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 if (Subtarget->is64Bit()) {
567 setExceptionPointerRegister(X86::RAX);
568 setExceptionSelectorRegister(X86::RDX);
570 setExceptionPointerRegister(X86::EAX);
571 setExceptionSelectorRegister(X86::EDX);
573 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
574 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
576 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
577 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
579 setOperationAction(ISD::TRAP, MVT::Other, Legal);
580 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
582 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
583 setOperationAction(ISD::VASTART , MVT::Other, Custom);
584 setOperationAction(ISD::VAEND , MVT::Other, Expand);
585 if (Subtarget->is64Bit()) {
586 setOperationAction(ISD::VAARG , MVT::Other, Custom);
587 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
589 setOperationAction(ISD::VAARG , MVT::Other, Expand);
590 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
593 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
594 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
596 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
597 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
598 MVT::i64 : MVT::i32, Custom);
599 else if (TM.Options.EnableSegmentedStacks)
600 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601 MVT::i64 : MVT::i32, Custom);
603 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604 MVT::i64 : MVT::i32, Expand);
606 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
607 // f32 and f64 use SSE.
608 // Set up the FP register classes.
609 addRegisterClass(MVT::f32, &X86::FR32RegClass);
610 addRegisterClass(MVT::f64, &X86::FR64RegClass);
612 // Use ANDPD to simulate FABS.
613 setOperationAction(ISD::FABS , MVT::f64, Custom);
614 setOperationAction(ISD::FABS , MVT::f32, Custom);
616 // Use XORP to simulate FNEG.
617 setOperationAction(ISD::FNEG , MVT::f64, Custom);
618 setOperationAction(ISD::FNEG , MVT::f32, Custom);
620 // Use ANDPD and ORPD to simulate FCOPYSIGN.
621 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
624 // Lower this to FGETSIGNx86 plus an AND.
625 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
626 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
628 // We don't support sin/cos/fmod
629 setOperationAction(ISD::FSIN , MVT::f64, Expand);
630 setOperationAction(ISD::FCOS , MVT::f64, Expand);
631 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
632 setOperationAction(ISD::FSIN , MVT::f32, Expand);
633 setOperationAction(ISD::FCOS , MVT::f32, Expand);
634 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
636 // Expand FP immediates into loads from the stack, except for the special
638 addLegalFPImmediate(APFloat(+0.0)); // xorpd
639 addLegalFPImmediate(APFloat(+0.0f)); // xorps
640 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
641 // Use SSE for f32, x87 for f64.
642 // Set up the FP register classes.
643 addRegisterClass(MVT::f32, &X86::FR32RegClass);
644 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
646 // Use ANDPS to simulate FABS.
647 setOperationAction(ISD::FABS , MVT::f32, Custom);
649 // Use XORP to simulate FNEG.
650 setOperationAction(ISD::FNEG , MVT::f32, Custom);
652 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
654 // Use ANDPS and ORPS to simulate FCOPYSIGN.
655 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
656 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658 // We don't support sin/cos/fmod
659 setOperationAction(ISD::FSIN , MVT::f32, Expand);
660 setOperationAction(ISD::FCOS , MVT::f32, Expand);
661 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
663 // Special cases we handle for FP constants.
664 addLegalFPImmediate(APFloat(+0.0f)); // xorps
665 addLegalFPImmediate(APFloat(+0.0)); // FLD0
666 addLegalFPImmediate(APFloat(+1.0)); // FLD1
667 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
668 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
670 if (!TM.Options.UnsafeFPMath) {
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675 } else if (!TM.Options.UseSoftFloat) {
676 // f32 and f64 in x87.
677 // Set up the FP register classes.
678 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
679 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
681 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
682 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
683 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
684 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
686 if (!TM.Options.UnsafeFPMath) {
687 setOperationAction(ISD::FSIN , MVT::f64, Expand);
688 setOperationAction(ISD::FSIN , MVT::f32, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FCOS , MVT::f32, Expand);
691 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
692 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694 addLegalFPImmediate(APFloat(+0.0)); // FLD0
695 addLegalFPImmediate(APFloat(+1.0)); // FLD1
696 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
697 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
698 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
699 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
700 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
701 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
704 // We don't support FMA.
705 setOperationAction(ISD::FMA, MVT::f64, Expand);
706 setOperationAction(ISD::FMA, MVT::f32, Expand);
708 // Long double always uses X87.
709 if (!TM.Options.UseSoftFloat) {
710 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
711 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
712 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
714 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
715 addLegalFPImmediate(TmpFlt); // FLD0
717 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
720 APFloat TmpFlt2(+1.0);
721 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
723 addLegalFPImmediate(TmpFlt2); // FLD1
724 TmpFlt2.changeSign();
725 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f80, Expand);
730 setOperationAction(ISD::FCOS , MVT::f80, Expand);
731 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
734 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
735 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
736 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
737 setOperationAction(ISD::FRINT, MVT::f80, Expand);
738 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
739 setOperationAction(ISD::FMA, MVT::f80, Expand);
742 // Always use a library call for pow.
743 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
744 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
745 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
747 setOperationAction(ISD::FLOG, MVT::f80, Expand);
748 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
749 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
750 setOperationAction(ISD::FEXP, MVT::f80, Expand);
751 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
753 // First set operation action for all vector types to either promote
754 // (for widening) or expand (for scalarization). Then we will selectively
755 // turn on ones that can be effectively codegen'd.
756 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
757 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
758 MVT VT = (MVT::SimpleValueType)i;
759 setOperationAction(ISD::ADD , VT, Expand);
760 setOperationAction(ISD::SUB , VT, Expand);
761 setOperationAction(ISD::FADD, VT, Expand);
762 setOperationAction(ISD::FNEG, VT, Expand);
763 setOperationAction(ISD::FSUB, VT, Expand);
764 setOperationAction(ISD::MUL , VT, Expand);
765 setOperationAction(ISD::FMUL, VT, Expand);
766 setOperationAction(ISD::SDIV, VT, Expand);
767 setOperationAction(ISD::UDIV, VT, Expand);
768 setOperationAction(ISD::FDIV, VT, Expand);
769 setOperationAction(ISD::SREM, VT, Expand);
770 setOperationAction(ISD::UREM, VT, Expand);
771 setOperationAction(ISD::LOAD, VT, Expand);
772 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
774 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
775 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
776 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
777 setOperationAction(ISD::FABS, VT, Expand);
778 setOperationAction(ISD::FSIN, VT, Expand);
779 setOperationAction(ISD::FSINCOS, VT, Expand);
780 setOperationAction(ISD::FCOS, VT, Expand);
781 setOperationAction(ISD::FSINCOS, VT, Expand);
782 setOperationAction(ISD::FREM, VT, Expand);
783 setOperationAction(ISD::FMA, VT, Expand);
784 setOperationAction(ISD::FPOWI, VT, Expand);
785 setOperationAction(ISD::FSQRT, VT, Expand);
786 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
787 setOperationAction(ISD::FFLOOR, VT, Expand);
788 setOperationAction(ISD::FCEIL, VT, Expand);
789 setOperationAction(ISD::FTRUNC, VT, Expand);
790 setOperationAction(ISD::FRINT, VT, Expand);
791 setOperationAction(ISD::FNEARBYINT, VT, Expand);
792 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
793 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
794 setOperationAction(ISD::SDIVREM, VT, Expand);
795 setOperationAction(ISD::UDIVREM, VT, Expand);
796 setOperationAction(ISD::FPOW, VT, Expand);
797 setOperationAction(ISD::CTPOP, VT, Expand);
798 setOperationAction(ISD::CTTZ, VT, Expand);
799 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
800 setOperationAction(ISD::CTLZ, VT, Expand);
801 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
802 setOperationAction(ISD::SHL, VT, Expand);
803 setOperationAction(ISD::SRA, VT, Expand);
804 setOperationAction(ISD::SRL, VT, Expand);
805 setOperationAction(ISD::ROTL, VT, Expand);
806 setOperationAction(ISD::ROTR, VT, Expand);
807 setOperationAction(ISD::BSWAP, VT, Expand);
808 setOperationAction(ISD::SETCC, VT, Expand);
809 setOperationAction(ISD::FLOG, VT, Expand);
810 setOperationAction(ISD::FLOG2, VT, Expand);
811 setOperationAction(ISD::FLOG10, VT, Expand);
812 setOperationAction(ISD::FEXP, VT, Expand);
813 setOperationAction(ISD::FEXP2, VT, Expand);
814 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
815 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
816 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
817 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
818 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
819 setOperationAction(ISD::TRUNCATE, VT, Expand);
820 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
821 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
822 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
823 setOperationAction(ISD::VSELECT, VT, Expand);
824 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
825 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
826 setTruncStoreAction(VT,
827 (MVT::SimpleValueType)InnerVT, Expand);
828 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
829 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
830 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
833 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
834 // with -msoft-float, disable use of MMX as well.
835 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
836 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
837 // No operations on x86mmx supported, everything uses intrinsics.
840 // MMX-sized vectors (other than x86mmx) are expected to be expanded
841 // into smaller operations.
842 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
843 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
844 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
845 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
846 setOperationAction(ISD::AND, MVT::v8i8, Expand);
847 setOperationAction(ISD::AND, MVT::v4i16, Expand);
848 setOperationAction(ISD::AND, MVT::v2i32, Expand);
849 setOperationAction(ISD::AND, MVT::v1i64, Expand);
850 setOperationAction(ISD::OR, MVT::v8i8, Expand);
851 setOperationAction(ISD::OR, MVT::v4i16, Expand);
852 setOperationAction(ISD::OR, MVT::v2i32, Expand);
853 setOperationAction(ISD::OR, MVT::v1i64, Expand);
854 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
855 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
856 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
857 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
860 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
861 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
863 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
864 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
865 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
866 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
867 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
868 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
869 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
870 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
872 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
873 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
875 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
876 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
877 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
878 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
879 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
880 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
881 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
882 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
884 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
885 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
886 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
889 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
890 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
892 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
893 // registers cannot be used even for integer operations.
894 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
895 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
896 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
897 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
899 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
900 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
901 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
902 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
903 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
904 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
905 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
906 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
907 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
908 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
909 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
910 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
911 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
912 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
913 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
914 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
915 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
916 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
918 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
919 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
920 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
921 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
923 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
924 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
925 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
926 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
927 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
929 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
930 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
931 MVT VT = (MVT::SimpleValueType)i;
932 // Do not attempt to custom lower non-power-of-2 vectors
933 if (!isPowerOf2_32(VT.getVectorNumElements()))
935 // Do not attempt to custom lower non-128-bit vectors
936 if (!VT.is128BitVector())
938 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
939 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
943 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
944 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
945 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
946 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
947 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
950 if (Subtarget->is64Bit()) {
951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
955 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
956 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
957 MVT VT = (MVT::SimpleValueType)i;
959 // Do not attempt to promote non-128-bit vectors
960 if (!VT.is128BitVector())
963 setOperationAction(ISD::AND, VT, Promote);
964 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
965 setOperationAction(ISD::OR, VT, Promote);
966 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
967 setOperationAction(ISD::XOR, VT, Promote);
968 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
969 setOperationAction(ISD::LOAD, VT, Promote);
970 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
971 setOperationAction(ISD::SELECT, VT, Promote);
972 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
975 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
977 // Custom lower v2i64 and v2f64 selects.
978 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
979 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
980 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
981 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
983 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
984 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
986 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
987 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
988 // As there is no 64-bit GPR available, we need build a special custom
989 // sequence to convert from v2i32 to v2f32.
990 if (!Subtarget->is64Bit())
991 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
993 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
994 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
996 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
999 if (Subtarget->hasSSE41()) {
1000 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1001 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1002 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1003 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1004 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1005 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1006 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1007 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1008 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1009 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1011 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1012 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1013 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1014 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1015 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1016 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1017 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1018 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1019 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1020 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1022 // FIXME: Do we need to handle scalar-to-vector here?
1023 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1025 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1026 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1027 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1028 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1029 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1031 // i8 and i16 vectors are custom , because the source register and source
1032 // source memory operand types are not the same width. f32 vectors are
1033 // custom since the immediate controlling the insert encodes additional
1035 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1036 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1037 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1040 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1041 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1042 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1043 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1045 // FIXME: these should be Legal but thats only for the case where
1046 // the index is constant. For now custom expand to deal with that.
1047 if (Subtarget->is64Bit()) {
1048 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1049 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1053 if (Subtarget->hasSSE2()) {
1054 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1055 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1057 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1058 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1060 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1061 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1063 // In the customized shift lowering, the legal cases in AVX2 will be
1065 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1066 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1068 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1069 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1071 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1073 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1074 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1077 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1078 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1079 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1080 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1081 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1082 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1083 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1085 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1086 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1087 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1089 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1090 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1091 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1092 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1093 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1094 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1095 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1096 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1097 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1098 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1099 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1100 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1102 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1103 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1104 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1105 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1106 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1107 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1109 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1110 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1112 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1113 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1115 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1116 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1118 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1120 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1121 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1122 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1123 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1125 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1126 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1127 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1129 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1131 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1132 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1134 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1135 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1137 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1138 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1140 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1142 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1143 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1144 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1145 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1147 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1148 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1149 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1151 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1153 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1154 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1156 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1157 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1158 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1159 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1160 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1161 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1163 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1164 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::f64, Legal);
1172 if (Subtarget->hasInt256()) {
1173 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1175 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1176 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1178 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1179 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1180 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1181 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1183 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1184 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1185 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1186 // Don't lower v32i8 because there is no 128-bit byte mul
1188 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1190 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1192 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1193 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1194 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1195 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1197 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1199 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1200 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1202 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1203 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1204 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1205 // Don't lower v32i8 because there is no 128-bit byte mul
1208 // In the customized shift lowering, the legal cases in AVX2 will be
1210 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1211 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1213 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1216 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1218 // Custom lower several nodes for 256-bit types.
1219 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1220 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1221 MVT VT = (MVT::SimpleValueType)i;
1223 // Extract subvector is special because the value type
1224 // (result) is 128-bit but the source is 256-bit wide.
1225 if (VT.is128BitVector())
1226 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228 // Do not attempt to custom lower other non-256-bit vectors
1229 if (!VT.is256BitVector())
1232 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1233 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1234 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1235 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1236 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1237 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1238 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1241 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1242 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1243 MVT VT = (MVT::SimpleValueType)i;
1245 // Do not attempt to promote non-256-bit vectors
1246 if (!VT.is256BitVector())
1249 setOperationAction(ISD::AND, VT, Promote);
1250 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1251 setOperationAction(ISD::OR, VT, Promote);
1252 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1253 setOperationAction(ISD::XOR, VT, Promote);
1254 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1255 setOperationAction(ISD::LOAD, VT, Promote);
1256 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1257 setOperationAction(ISD::SELECT, VT, Promote);
1258 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1262 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1263 // of this type with custom code.
1264 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1265 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1266 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1270 // We want to custom lower some of our intrinsics.
1271 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1272 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1274 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1275 // handle type legalization for these operations here.
1277 // FIXME: We really should do custom legalization for addition and
1278 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1279 // than generic legalization for 64-bit multiplication-with-overflow, though.
1280 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1281 // Add/Sub/Mul with overflow operations are custom lowered.
1283 setOperationAction(ISD::SADDO, VT, Custom);
1284 setOperationAction(ISD::UADDO, VT, Custom);
1285 setOperationAction(ISD::SSUBO, VT, Custom);
1286 setOperationAction(ISD::USUBO, VT, Custom);
1287 setOperationAction(ISD::SMULO, VT, Custom);
1288 setOperationAction(ISD::UMULO, VT, Custom);
1291 // There are no 8-bit 3-address imul/mul instructions
1292 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1293 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1295 if (!Subtarget->is64Bit()) {
1296 // These libcalls are not available in 32-bit.
1297 setLibcallName(RTLIB::SHL_I128, 0);
1298 setLibcallName(RTLIB::SRL_I128, 0);
1299 setLibcallName(RTLIB::SRA_I128, 0);
1302 // Combine sin / cos into one node or libcall if possible.
1303 if (Subtarget->hasSinCos()) {
1304 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1305 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1306 if (Subtarget->isTargetDarwin()) {
1307 // For MacOSX, we don't want to the normal expansion of a libcall to
1308 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1310 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1311 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1315 // We have target-specific dag combine patterns for the following nodes:
1316 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1317 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1318 setTargetDAGCombine(ISD::VSELECT);
1319 setTargetDAGCombine(ISD::SELECT);
1320 setTargetDAGCombine(ISD::SHL);
1321 setTargetDAGCombine(ISD::SRA);
1322 setTargetDAGCombine(ISD::SRL);
1323 setTargetDAGCombine(ISD::OR);
1324 setTargetDAGCombine(ISD::AND);
1325 setTargetDAGCombine(ISD::ADD);
1326 setTargetDAGCombine(ISD::FADD);
1327 setTargetDAGCombine(ISD::FSUB);
1328 setTargetDAGCombine(ISD::FMA);
1329 setTargetDAGCombine(ISD::SUB);
1330 setTargetDAGCombine(ISD::LOAD);
1331 setTargetDAGCombine(ISD::STORE);
1332 setTargetDAGCombine(ISD::ZERO_EXTEND);
1333 setTargetDAGCombine(ISD::ANY_EXTEND);
1334 setTargetDAGCombine(ISD::SIGN_EXTEND);
1335 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1336 setTargetDAGCombine(ISD::TRUNCATE);
1337 setTargetDAGCombine(ISD::SINT_TO_FP);
1338 setTargetDAGCombine(ISD::SETCC);
1339 if (Subtarget->is64Bit())
1340 setTargetDAGCombine(ISD::MUL);
1341 setTargetDAGCombine(ISD::XOR);
1343 computeRegisterProperties();
1345 // On Darwin, -Os means optimize for size without hurting performance,
1346 // do not reduce the limit.
1347 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1348 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1349 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1350 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1351 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1352 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1353 setPrefLoopAlignment(4); // 2^4 bytes.
1355 // Predictable cmov don't hurt on atom because it's in-order.
1356 PredictableSelectIsExpensive = !Subtarget->isAtom();
1358 setPrefFunctionAlignment(4); // 2^4 bytes.
1361 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1362 if (!VT.isVector()) return MVT::i8;
1363 return VT.changeVectorElementTypeToInteger();
1366 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1367 /// the desired ByVal argument alignment.
1368 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1371 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1372 if (VTy->getBitWidth() == 128)
1374 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1375 unsigned EltAlign = 0;
1376 getMaxByValAlign(ATy->getElementType(), EltAlign);
1377 if (EltAlign > MaxAlign)
1378 MaxAlign = EltAlign;
1379 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1380 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1381 unsigned EltAlign = 0;
1382 getMaxByValAlign(STy->getElementType(i), EltAlign);
1383 if (EltAlign > MaxAlign)
1384 MaxAlign = EltAlign;
1391 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1392 /// function arguments in the caller parameter area. For X86, aggregates
1393 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1394 /// are at 4-byte boundaries.
1395 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1396 if (Subtarget->is64Bit()) {
1397 // Max of 8 and alignment of type.
1398 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1405 if (Subtarget->hasSSE1())
1406 getMaxByValAlign(Ty, Align);
1410 /// getOptimalMemOpType - Returns the target specific optimal type for load
1411 /// and store operations as a result of memset, memcpy, and memmove
1412 /// lowering. If DstAlign is zero that means it's safe to destination
1413 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1414 /// means there isn't a need to check it against alignment requirement,
1415 /// probably because the source does not need to be loaded. If 'IsMemset' is
1416 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1417 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1418 /// source is constant so it does not need to be loaded.
1419 /// It returns EVT::Other if the type should be determined using generic
1420 /// target-independent logic.
1422 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1423 unsigned DstAlign, unsigned SrcAlign,
1424 bool IsMemset, bool ZeroMemset,
1426 MachineFunction &MF) const {
1427 const Function *F = MF.getFunction();
1428 if ((!IsMemset || ZeroMemset) &&
1429 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1430 Attribute::NoImplicitFloat)) {
1432 (Subtarget->isUnalignedMemAccessFast() ||
1433 ((DstAlign == 0 || DstAlign >= 16) &&
1434 (SrcAlign == 0 || SrcAlign >= 16)))) {
1436 if (Subtarget->hasInt256())
1438 if (Subtarget->hasFp256())
1441 if (Subtarget->hasSSE2())
1443 if (Subtarget->hasSSE1())
1445 } else if (!MemcpyStrSrc && Size >= 8 &&
1446 !Subtarget->is64Bit() &&
1447 Subtarget->hasSSE2()) {
1448 // Do not use f64 to lower memcpy if source is string constant. It's
1449 // better to use i32 to avoid the loads.
1453 if (Subtarget->is64Bit() && Size >= 8)
1458 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1460 return X86ScalarSSEf32;
1461 else if (VT == MVT::f64)
1462 return X86ScalarSSEf64;
1467 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1469 *Fast = Subtarget->isUnalignedMemAccessFast();
1473 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1474 /// current function. The returned value is a member of the
1475 /// MachineJumpTableInfo::JTEntryKind enum.
1476 unsigned X86TargetLowering::getJumpTableEncoding() const {
1477 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1479 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1480 Subtarget->isPICStyleGOT())
1481 return MachineJumpTableInfo::EK_Custom32;
1483 // Otherwise, use the normal jump table encoding heuristics.
1484 return TargetLowering::getJumpTableEncoding();
1488 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1489 const MachineBasicBlock *MBB,
1490 unsigned uid,MCContext &Ctx) const{
1491 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1492 Subtarget->isPICStyleGOT());
1493 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1495 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1496 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1499 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1501 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1502 SelectionDAG &DAG) const {
1503 if (!Subtarget->is64Bit())
1504 // This doesn't have SDLoc associated with it, but is not really the
1505 // same as a Register.
1506 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1510 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1511 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1513 const MCExpr *X86TargetLowering::
1514 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1515 MCContext &Ctx) const {
1516 // X86-64 uses RIP relative addressing based on the jump table label.
1517 if (Subtarget->isPICStyleRIPRel())
1518 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1520 // Otherwise, the reference is relative to the PIC base.
1521 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1524 // FIXME: Why this routine is here? Move to RegInfo!
1525 std::pair<const TargetRegisterClass*, uint8_t>
1526 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1527 const TargetRegisterClass *RRC = 0;
1529 switch (VT.SimpleTy) {
1531 return TargetLowering::findRepresentativeClass(VT);
1532 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1533 RRC = Subtarget->is64Bit() ?
1534 (const TargetRegisterClass*)&X86::GR64RegClass :
1535 (const TargetRegisterClass*)&X86::GR32RegClass;
1538 RRC = &X86::VR64RegClass;
1540 case MVT::f32: case MVT::f64:
1541 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1542 case MVT::v4f32: case MVT::v2f64:
1543 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1545 RRC = &X86::VR128RegClass;
1548 return std::make_pair(RRC, Cost);
1551 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1552 unsigned &Offset) const {
1553 if (!Subtarget->isTargetLinux())
1556 if (Subtarget->is64Bit()) {
1557 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1559 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1571 //===----------------------------------------------------------------------===//
1572 // Return Value Calling Convention Implementation
1573 //===----------------------------------------------------------------------===//
1575 #include "X86GenCallingConv.inc"
1578 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1579 MachineFunction &MF, bool isVarArg,
1580 const SmallVectorImpl<ISD::OutputArg> &Outs,
1581 LLVMContext &Context) const {
1582 SmallVector<CCValAssign, 16> RVLocs;
1583 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1585 return CCInfo.CheckReturn(Outs, RetCC_X86);
1589 X86TargetLowering::LowerReturn(SDValue Chain,
1590 CallingConv::ID CallConv, bool isVarArg,
1591 const SmallVectorImpl<ISD::OutputArg> &Outs,
1592 const SmallVectorImpl<SDValue> &OutVals,
1593 SDLoc dl, SelectionDAG &DAG) const {
1594 MachineFunction &MF = DAG.getMachineFunction();
1595 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1597 SmallVector<CCValAssign, 16> RVLocs;
1598 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1599 RVLocs, *DAG.getContext());
1600 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1603 SmallVector<SDValue, 6> RetOps;
1604 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1605 // Operand #1 = Bytes To Pop
1606 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1609 // Copy the result values into the output registers.
1610 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1611 CCValAssign &VA = RVLocs[i];
1612 assert(VA.isRegLoc() && "Can only return in registers!");
1613 SDValue ValToCopy = OutVals[i];
1614 EVT ValVT = ValToCopy.getValueType();
1616 // Promote values to the appropriate types
1617 if (VA.getLocInfo() == CCValAssign::SExt)
1618 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1619 else if (VA.getLocInfo() == CCValAssign::ZExt)
1620 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1621 else if (VA.getLocInfo() == CCValAssign::AExt)
1622 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1623 else if (VA.getLocInfo() == CCValAssign::BCvt)
1624 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1626 // If this is x86-64, and we disabled SSE, we can't return FP values,
1627 // or SSE or MMX vectors.
1628 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1629 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1630 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1631 report_fatal_error("SSE register return with SSE disabled");
1633 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1634 // llvm-gcc has never done it right and no one has noticed, so this
1635 // should be OK for now.
1636 if (ValVT == MVT::f64 &&
1637 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1638 report_fatal_error("SSE2 register return with SSE2 disabled");
1640 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1641 // the RET instruction and handled by the FP Stackifier.
1642 if (VA.getLocReg() == X86::ST0 ||
1643 VA.getLocReg() == X86::ST1) {
1644 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1645 // change the value to the FP stack register class.
1646 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1647 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1648 RetOps.push_back(ValToCopy);
1649 // Don't emit a copytoreg.
1653 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1654 // which is returned in RAX / RDX.
1655 if (Subtarget->is64Bit()) {
1656 if (ValVT == MVT::x86mmx) {
1657 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1658 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1659 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1661 // If we don't have SSE2 available, convert to v4f32 so the generated
1662 // register is legal.
1663 if (!Subtarget->hasSSE2())
1664 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1669 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1670 Flag = Chain.getValue(1);
1671 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1674 // The x86-64 ABIs require that for returning structs by value we copy
1675 // the sret argument into %rax/%eax (depending on ABI) for the return.
1676 // Win32 requires us to put the sret argument to %eax as well.
1677 // We saved the argument into a virtual register in the entry block,
1678 // so now we copy the value out and into %rax/%eax.
1679 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1680 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1681 MachineFunction &MF = DAG.getMachineFunction();
1682 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1683 unsigned Reg = FuncInfo->getSRetReturnReg();
1685 "SRetReturnReg should have been set in LowerFormalArguments().");
1686 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1689 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1690 X86::RAX : X86::EAX;
1691 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1692 Flag = Chain.getValue(1);
1694 // RAX/EAX now acts like a return value.
1695 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1698 RetOps[0] = Chain; // Update chain.
1700 // Add the flag if we have it.
1702 RetOps.push_back(Flag);
1704 return DAG.getNode(X86ISD::RET_FLAG, dl,
1705 MVT::Other, &RetOps[0], RetOps.size());
1708 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1709 if (N->getNumValues() != 1)
1711 if (!N->hasNUsesOfValue(1, 0))
1714 SDValue TCChain = Chain;
1715 SDNode *Copy = *N->use_begin();
1716 if (Copy->getOpcode() == ISD::CopyToReg) {
1717 // If the copy has a glue operand, we conservatively assume it isn't safe to
1718 // perform a tail call.
1719 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1721 TCChain = Copy->getOperand(0);
1722 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1725 bool HasRet = false;
1726 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1728 if (UI->getOpcode() != X86ISD::RET_FLAG)
1741 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1742 ISD::NodeType ExtendKind) const {
1744 // TODO: Is this also valid on 32-bit?
1745 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1746 ReturnMVT = MVT::i8;
1748 ReturnMVT = MVT::i32;
1750 MVT MinVT = getRegisterType(ReturnMVT);
1751 return VT.bitsLT(MinVT) ? MinVT : VT;
1754 /// LowerCallResult - Lower the result values of a call into the
1755 /// appropriate copies out of appropriate physical registers.
1758 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1759 CallingConv::ID CallConv, bool isVarArg,
1760 const SmallVectorImpl<ISD::InputArg> &Ins,
1761 SDLoc dl, SelectionDAG &DAG,
1762 SmallVectorImpl<SDValue> &InVals) const {
1764 // Assign locations to each value returned by this call.
1765 SmallVector<CCValAssign, 16> RVLocs;
1766 bool Is64Bit = Subtarget->is64Bit();
1767 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1768 getTargetMachine(), RVLocs, *DAG.getContext());
1769 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1771 // Copy all of the result registers out of their specified physreg.
1772 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1773 CCValAssign &VA = RVLocs[i];
1774 EVT CopyVT = VA.getValVT();
1776 // If this is x86-64, and we disabled SSE, we can't return FP values
1777 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1778 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1779 report_fatal_error("SSE register return with SSE disabled");
1784 // If this is a call to a function that returns an fp value on the floating
1785 // point stack, we must guarantee the value is popped from the stack, so
1786 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1787 // if the return value is not used. We use the FpPOP_RETVAL instruction
1789 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1790 // If we prefer to use the value in xmm registers, copy it out as f80 and
1791 // use a truncate to move it from fp stack reg to xmm reg.
1792 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1793 SDValue Ops[] = { Chain, InFlag };
1794 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1795 MVT::Other, MVT::Glue, Ops), 1);
1796 Val = Chain.getValue(0);
1798 // Round the f80 to the right size, which also moves it to the appropriate
1800 if (CopyVT != VA.getValVT())
1801 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1802 // This truncation won't change the value.
1803 DAG.getIntPtrConstant(1));
1805 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1806 CopyVT, InFlag).getValue(1);
1807 Val = Chain.getValue(0);
1809 InFlag = Chain.getValue(2);
1810 InVals.push_back(Val);
1816 //===----------------------------------------------------------------------===//
1817 // C & StdCall & Fast Calling Convention implementation
1818 //===----------------------------------------------------------------------===//
1819 // StdCall calling convention seems to be standard for many Windows' API
1820 // routines and around. It differs from C calling convention just a little:
1821 // callee should clean up the stack, not caller. Symbols should be also
1822 // decorated in some fancy way :) It doesn't support any vector arguments.
1823 // For info on fast calling convention see Fast Calling Convention (tail call)
1824 // implementation LowerX86_32FastCCCallTo.
1826 /// CallIsStructReturn - Determines whether a call uses struct return
1828 enum StructReturnType {
1833 static StructReturnType
1834 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1836 return NotStructReturn;
1838 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1839 if (!Flags.isSRet())
1840 return NotStructReturn;
1841 if (Flags.isInReg())
1842 return RegStructReturn;
1843 return StackStructReturn;
1846 /// ArgsAreStructReturn - Determines whether a function uses struct
1847 /// return semantics.
1848 static StructReturnType
1849 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1851 return NotStructReturn;
1853 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1854 if (!Flags.isSRet())
1855 return NotStructReturn;
1856 if (Flags.isInReg())
1857 return RegStructReturn;
1858 return StackStructReturn;
1861 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1862 /// by "Src" to address "Dst" with size and alignment information specified by
1863 /// the specific parameter attribute. The copy will be passed as a byval
1864 /// function parameter.
1866 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1867 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1869 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1871 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1872 /*isVolatile*/false, /*AlwaysInline=*/true,
1873 MachinePointerInfo(), MachinePointerInfo());
1876 /// IsTailCallConvention - Return true if the calling convention is one that
1877 /// supports tail call optimization.
1878 static bool IsTailCallConvention(CallingConv::ID CC) {
1879 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1880 CC == CallingConv::HiPE);
1883 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1884 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1888 CallingConv::ID CalleeCC = CS.getCallingConv();
1889 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1895 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1896 /// a tailcall target by changing its ABI.
1897 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1898 bool GuaranteedTailCallOpt) {
1899 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1903 X86TargetLowering::LowerMemArgument(SDValue Chain,
1904 CallingConv::ID CallConv,
1905 const SmallVectorImpl<ISD::InputArg> &Ins,
1906 SDLoc dl, SelectionDAG &DAG,
1907 const CCValAssign &VA,
1908 MachineFrameInfo *MFI,
1910 // Create the nodes corresponding to a load from this parameter slot.
1911 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1912 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1913 getTargetMachine().Options.GuaranteedTailCallOpt);
1914 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1917 // If value is passed by pointer we have address passed instead of the value
1919 if (VA.getLocInfo() == CCValAssign::Indirect)
1920 ValVT = VA.getLocVT();
1922 ValVT = VA.getValVT();
1924 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1925 // changed with more analysis.
1926 // In case of tail call optimization mark all arguments mutable. Since they
1927 // could be overwritten by lowering of arguments in case of a tail call.
1928 if (Flags.isByVal()) {
1929 unsigned Bytes = Flags.getByValSize();
1930 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1931 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1932 return DAG.getFrameIndex(FI, getPointerTy());
1934 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1935 VA.getLocMemOffset(), isImmutable);
1936 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1937 return DAG.getLoad(ValVT, dl, Chain, FIN,
1938 MachinePointerInfo::getFixedStack(FI),
1939 false, false, false, 0);
1944 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1945 CallingConv::ID CallConv,
1947 const SmallVectorImpl<ISD::InputArg> &Ins,
1950 SmallVectorImpl<SDValue> &InVals)
1952 MachineFunction &MF = DAG.getMachineFunction();
1953 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1955 const Function* Fn = MF.getFunction();
1956 if (Fn->hasExternalLinkage() &&
1957 Subtarget->isTargetCygMing() &&
1958 Fn->getName() == "main")
1959 FuncInfo->setForceFramePointer(true);
1961 MachineFrameInfo *MFI = MF.getFrameInfo();
1962 bool Is64Bit = Subtarget->is64Bit();
1963 bool IsWindows = Subtarget->isTargetWindows();
1964 bool IsWin64 = Subtarget->isTargetWin64();
1966 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1967 "Var args not supported with calling convention fastcc, ghc or hipe");
1969 // Assign locations to all of the incoming arguments.
1970 SmallVector<CCValAssign, 16> ArgLocs;
1971 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1972 ArgLocs, *DAG.getContext());
1974 // Allocate shadow area for Win64
1976 CCInfo.AllocateStack(32, 8);
1979 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1981 unsigned LastVal = ~0U;
1983 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1984 CCValAssign &VA = ArgLocs[i];
1985 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1987 assert(VA.getValNo() != LastVal &&
1988 "Don't support value assigned to multiple locs yet");
1990 LastVal = VA.getValNo();
1992 if (VA.isRegLoc()) {
1993 EVT RegVT = VA.getLocVT();
1994 const TargetRegisterClass *RC;
1995 if (RegVT == MVT::i32)
1996 RC = &X86::GR32RegClass;
1997 else if (Is64Bit && RegVT == MVT::i64)
1998 RC = &X86::GR64RegClass;
1999 else if (RegVT == MVT::f32)
2000 RC = &X86::FR32RegClass;
2001 else if (RegVT == MVT::f64)
2002 RC = &X86::FR64RegClass;
2003 else if (RegVT.is256BitVector())
2004 RC = &X86::VR256RegClass;
2005 else if (RegVT.is128BitVector())
2006 RC = &X86::VR128RegClass;
2007 else if (RegVT == MVT::x86mmx)
2008 RC = &X86::VR64RegClass;
2010 llvm_unreachable("Unknown argument type!");
2012 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2013 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2015 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2016 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2018 if (VA.getLocInfo() == CCValAssign::SExt)
2019 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2020 DAG.getValueType(VA.getValVT()));
2021 else if (VA.getLocInfo() == CCValAssign::ZExt)
2022 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2023 DAG.getValueType(VA.getValVT()));
2024 else if (VA.getLocInfo() == CCValAssign::BCvt)
2025 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2027 if (VA.isExtInLoc()) {
2028 // Handle MMX values passed in XMM regs.
2029 if (RegVT.isVector())
2030 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2032 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2035 assert(VA.isMemLoc());
2036 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2039 // If value is passed via pointer - do a load.
2040 if (VA.getLocInfo() == CCValAssign::Indirect)
2041 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2042 MachinePointerInfo(), false, false, false, 0);
2044 InVals.push_back(ArgValue);
2047 // The x86-64 ABIs require that for returning structs by value we copy
2048 // the sret argument into %rax/%eax (depending on ABI) for the return.
2049 // Win32 requires us to put the sret argument to %eax as well.
2050 // Save the argument into a virtual register so that we can access it
2051 // from the return points.
2052 if (MF.getFunction()->hasStructRetAttr() &&
2053 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2054 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2055 unsigned Reg = FuncInfo->getSRetReturnReg();
2057 MVT PtrTy = getPointerTy();
2058 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2059 FuncInfo->setSRetReturnReg(Reg);
2061 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2062 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2065 unsigned StackSize = CCInfo.getNextStackOffset();
2066 // Align stack specially for tail calls.
2067 if (FuncIsMadeTailCallSafe(CallConv,
2068 MF.getTarget().Options.GuaranteedTailCallOpt))
2069 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2071 // If the function takes variable number of arguments, make a frame index for
2072 // the start of the first vararg value... for expansion of llvm.va_start.
2074 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2075 CallConv != CallingConv::X86_ThisCall)) {
2076 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2079 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2081 // FIXME: We should really autogenerate these arrays
2082 static const uint16_t GPR64ArgRegsWin64[] = {
2083 X86::RCX, X86::RDX, X86::R8, X86::R9
2085 static const uint16_t GPR64ArgRegs64Bit[] = {
2086 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2088 static const uint16_t XMMArgRegs64Bit[] = {
2089 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2090 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2092 const uint16_t *GPR64ArgRegs;
2093 unsigned NumXMMRegs = 0;
2096 // The XMM registers which might contain var arg parameters are shadowed
2097 // in their paired GPR. So we only need to save the GPR to their home
2099 TotalNumIntRegs = 4;
2100 GPR64ArgRegs = GPR64ArgRegsWin64;
2102 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2103 GPR64ArgRegs = GPR64ArgRegs64Bit;
2105 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2108 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2111 bool NoImplicitFloatOps = Fn->getAttributes().
2112 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2113 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2114 "SSE register cannot be used when SSE is disabled!");
2115 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2116 NoImplicitFloatOps) &&
2117 "SSE register cannot be used when SSE is disabled!");
2118 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2119 !Subtarget->hasSSE1())
2120 // Kernel mode asks for SSE to be disabled, so don't push them
2122 TotalNumXMMRegs = 0;
2125 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2126 // Get to the caller-allocated home save location. Add 8 to account
2127 // for the return address.
2128 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2129 FuncInfo->setRegSaveFrameIndex(
2130 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2131 // Fixup to set vararg frame on shadow area (4 x i64).
2133 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2135 // For X86-64, if there are vararg parameters that are passed via
2136 // registers, then we must store them to their spots on the stack so
2137 // they may be loaded by deferencing the result of va_next.
2138 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2139 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2140 FuncInfo->setRegSaveFrameIndex(
2141 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2145 // Store the integer parameter registers.
2146 SmallVector<SDValue, 8> MemOps;
2147 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2149 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2150 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2151 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2152 DAG.getIntPtrConstant(Offset));
2153 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2154 &X86::GR64RegClass);
2155 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2157 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2158 MachinePointerInfo::getFixedStack(
2159 FuncInfo->getRegSaveFrameIndex(), Offset),
2161 MemOps.push_back(Store);
2165 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2166 // Now store the XMM (fp + vector) parameter registers.
2167 SmallVector<SDValue, 11> SaveXMMOps;
2168 SaveXMMOps.push_back(Chain);
2170 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2171 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2172 SaveXMMOps.push_back(ALVal);
2174 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2175 FuncInfo->getRegSaveFrameIndex()));
2176 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2177 FuncInfo->getVarArgsFPOffset()));
2179 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2180 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2181 &X86::VR128RegClass);
2182 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2183 SaveXMMOps.push_back(Val);
2185 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2187 &SaveXMMOps[0], SaveXMMOps.size()));
2190 if (!MemOps.empty())
2191 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2192 &MemOps[0], MemOps.size());
2196 // Some CCs need callee pop.
2197 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2198 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2199 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2201 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2202 // If this is an sret function, the return should pop the hidden pointer.
2203 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2204 argsAreStructReturn(Ins) == StackStructReturn)
2205 FuncInfo->setBytesToPopOnReturn(4);
2209 // RegSaveFrameIndex is X86-64 only.
2210 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2211 if (CallConv == CallingConv::X86_FastCall ||
2212 CallConv == CallingConv::X86_ThisCall)
2213 // fastcc functions can't have varargs.
2214 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2217 FuncInfo->setArgumentStackSize(StackSize);
2223 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2224 SDValue StackPtr, SDValue Arg,
2225 SDLoc dl, SelectionDAG &DAG,
2226 const CCValAssign &VA,
2227 ISD::ArgFlagsTy Flags) const {
2228 unsigned LocMemOffset = VA.getLocMemOffset();
2229 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2230 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2231 if (Flags.isByVal())
2232 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2234 return DAG.getStore(Chain, dl, Arg, PtrOff,
2235 MachinePointerInfo::getStack(LocMemOffset),
2239 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2240 /// optimization is performed and it is required.
2242 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2243 SDValue &OutRetAddr, SDValue Chain,
2244 bool IsTailCall, bool Is64Bit,
2245 int FPDiff, SDLoc dl) const {
2246 // Adjust the Return address stack slot.
2247 EVT VT = getPointerTy();
2248 OutRetAddr = getReturnAddressFrameIndex(DAG);
2250 // Load the "old" Return address.
2251 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2252 false, false, false, 0);
2253 return SDValue(OutRetAddr.getNode(), 1);
2256 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2257 /// optimization is performed and it is required (FPDiff!=0).
2259 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2260 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2261 unsigned SlotSize, int FPDiff, SDLoc dl) {
2262 // Store the return address to the appropriate stack slot.
2263 if (!FPDiff) return Chain;
2264 // Calculate the new stack slot for the return address.
2265 int NewReturnAddrFI =
2266 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2267 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2268 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2269 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2275 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2276 SmallVectorImpl<SDValue> &InVals) const {
2277 SelectionDAG &DAG = CLI.DAG;
2279 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2280 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2281 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2282 SDValue Chain = CLI.Chain;
2283 SDValue Callee = CLI.Callee;
2284 CallingConv::ID CallConv = CLI.CallConv;
2285 bool &isTailCall = CLI.IsTailCall;
2286 bool isVarArg = CLI.IsVarArg;
2288 MachineFunction &MF = DAG.getMachineFunction();
2289 bool Is64Bit = Subtarget->is64Bit();
2290 bool IsWin64 = Subtarget->isTargetWin64();
2291 bool IsWindows = Subtarget->isTargetWindows();
2292 StructReturnType SR = callIsStructReturn(Outs);
2293 bool IsSibcall = false;
2295 if (MF.getTarget().Options.DisableTailCalls)
2299 // Check if it's really possible to do a tail call.
2300 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2301 isVarArg, SR != NotStructReturn,
2302 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2303 Outs, OutVals, Ins, DAG);
2305 // Sibcalls are automatically detected tailcalls which do not require
2307 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2314 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2315 "Var args not supported with calling convention fastcc, ghc or hipe");
2317 // Analyze operands of the call, assigning locations to each operand.
2318 SmallVector<CCValAssign, 16> ArgLocs;
2319 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2320 ArgLocs, *DAG.getContext());
2322 // Allocate shadow area for Win64
2324 CCInfo.AllocateStack(32, 8);
2327 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2329 // Get a count of how many bytes are to be pushed on the stack.
2330 unsigned NumBytes = CCInfo.getNextStackOffset();
2332 // This is a sibcall. The memory operands are available in caller's
2333 // own caller's stack.
2335 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2336 IsTailCallConvention(CallConv))
2337 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2340 if (isTailCall && !IsSibcall) {
2341 // Lower arguments at fp - stackoffset + fpdiff.
2342 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2343 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2345 FPDiff = NumBytesCallerPushed - NumBytes;
2347 // Set the delta of movement of the returnaddr stackslot.
2348 // But only set if delta is greater than previous delta.
2349 if (FPDiff < X86Info->getTCReturnAddrDelta())
2350 X86Info->setTCReturnAddrDelta(FPDiff);
2354 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2357 SDValue RetAddrFrIdx;
2358 // Load return address for tail calls.
2359 if (isTailCall && FPDiff)
2360 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2361 Is64Bit, FPDiff, dl);
2363 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2364 SmallVector<SDValue, 8> MemOpChains;
2367 // Walk the register/memloc assignments, inserting copies/loads. In the case
2368 // of tail call optimization arguments are handle later.
2369 const X86RegisterInfo *RegInfo =
2370 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2371 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2372 CCValAssign &VA = ArgLocs[i];
2373 EVT RegVT = VA.getLocVT();
2374 SDValue Arg = OutVals[i];
2375 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2376 bool isByVal = Flags.isByVal();
2378 // Promote the value if needed.
2379 switch (VA.getLocInfo()) {
2380 default: llvm_unreachable("Unknown loc info!");
2381 case CCValAssign::Full: break;
2382 case CCValAssign::SExt:
2383 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2385 case CCValAssign::ZExt:
2386 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2388 case CCValAssign::AExt:
2389 if (RegVT.is128BitVector()) {
2390 // Special case: passing MMX values in XMM registers.
2391 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2392 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2393 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2395 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2397 case CCValAssign::BCvt:
2398 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2400 case CCValAssign::Indirect: {
2401 // Store the argument.
2402 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2403 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2404 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2405 MachinePointerInfo::getFixedStack(FI),
2412 if (VA.isRegLoc()) {
2413 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2414 if (isVarArg && IsWin64) {
2415 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2416 // shadow reg if callee is a varargs function.
2417 unsigned ShadowReg = 0;
2418 switch (VA.getLocReg()) {
2419 case X86::XMM0: ShadowReg = X86::RCX; break;
2420 case X86::XMM1: ShadowReg = X86::RDX; break;
2421 case X86::XMM2: ShadowReg = X86::R8; break;
2422 case X86::XMM3: ShadowReg = X86::R9; break;
2425 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2427 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2428 assert(VA.isMemLoc());
2429 if (StackPtr.getNode() == 0)
2430 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2432 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2433 dl, DAG, VA, Flags));
2437 if (!MemOpChains.empty())
2438 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2439 &MemOpChains[0], MemOpChains.size());
2441 if (Subtarget->isPICStyleGOT()) {
2442 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2445 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2446 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2448 // If we are tail calling and generating PIC/GOT style code load the
2449 // address of the callee into ECX. The value in ecx is used as target of
2450 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2451 // for tail calls on PIC/GOT architectures. Normally we would just put the
2452 // address of GOT into ebx and then call target@PLT. But for tail calls
2453 // ebx would be restored (since ebx is callee saved) before jumping to the
2456 // Note: The actual moving to ECX is done further down.
2457 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2458 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2459 !G->getGlobal()->hasProtectedVisibility())
2460 Callee = LowerGlobalAddress(Callee, DAG);
2461 else if (isa<ExternalSymbolSDNode>(Callee))
2462 Callee = LowerExternalSymbol(Callee, DAG);
2466 if (Is64Bit && isVarArg && !IsWin64) {
2467 // From AMD64 ABI document:
2468 // For calls that may call functions that use varargs or stdargs
2469 // (prototype-less calls or calls to functions containing ellipsis (...) in
2470 // the declaration) %al is used as hidden argument to specify the number
2471 // of SSE registers used. The contents of %al do not need to match exactly
2472 // the number of registers, but must be an ubound on the number of SSE
2473 // registers used and is in the range 0 - 8 inclusive.
2475 // Count the number of XMM registers allocated.
2476 static const uint16_t XMMArgRegs[] = {
2477 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2478 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2480 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2481 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2482 && "SSE registers cannot be used when SSE is disabled");
2484 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2485 DAG.getConstant(NumXMMRegs, MVT::i8)));
2488 // For tail calls lower the arguments to the 'real' stack slot.
2490 // Force all the incoming stack arguments to be loaded from the stack
2491 // before any new outgoing arguments are stored to the stack, because the
2492 // outgoing stack slots may alias the incoming argument stack slots, and
2493 // the alias isn't otherwise explicit. This is slightly more conservative
2494 // than necessary, because it means that each store effectively depends
2495 // on every argument instead of just those arguments it would clobber.
2496 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2498 SmallVector<SDValue, 8> MemOpChains2;
2501 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2502 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2503 CCValAssign &VA = ArgLocs[i];
2506 assert(VA.isMemLoc());
2507 SDValue Arg = OutVals[i];
2508 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2509 // Create frame index.
2510 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2511 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2512 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2513 FIN = DAG.getFrameIndex(FI, getPointerTy());
2515 if (Flags.isByVal()) {
2516 // Copy relative to framepointer.
2517 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2518 if (StackPtr.getNode() == 0)
2519 StackPtr = DAG.getCopyFromReg(Chain, dl,
2520 RegInfo->getStackRegister(),
2522 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2524 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2528 // Store relative to framepointer.
2529 MemOpChains2.push_back(
2530 DAG.getStore(ArgChain, dl, Arg, FIN,
2531 MachinePointerInfo::getFixedStack(FI),
2537 if (!MemOpChains2.empty())
2538 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2539 &MemOpChains2[0], MemOpChains2.size());
2541 // Store the return address to the appropriate stack slot.
2542 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2543 getPointerTy(), RegInfo->getSlotSize(),
2547 // Build a sequence of copy-to-reg nodes chained together with token chain
2548 // and flag operands which copy the outgoing args into registers.
2550 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2551 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2552 RegsToPass[i].second, InFlag);
2553 InFlag = Chain.getValue(1);
2556 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2557 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2558 // In the 64-bit large code model, we have to make all calls
2559 // through a register, since the call instruction's 32-bit
2560 // pc-relative offset may not be large enough to hold the whole
2562 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2563 // If the callee is a GlobalAddress node (quite common, every direct call
2564 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2567 // We should use extra load for direct calls to dllimported functions in
2569 const GlobalValue *GV = G->getGlobal();
2570 if (!GV->hasDLLImportLinkage()) {
2571 unsigned char OpFlags = 0;
2572 bool ExtraLoad = false;
2573 unsigned WrapperKind = ISD::DELETED_NODE;
2575 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2576 // external symbols most go through the PLT in PIC mode. If the symbol
2577 // has hidden or protected visibility, or if it is static or local, then
2578 // we don't need to use the PLT - we can directly call it.
2579 if (Subtarget->isTargetELF() &&
2580 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2581 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2582 OpFlags = X86II::MO_PLT;
2583 } else if (Subtarget->isPICStyleStubAny() &&
2584 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2585 (!Subtarget->getTargetTriple().isMacOSX() ||
2586 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2587 // PC-relative references to external symbols should go through $stub,
2588 // unless we're building with the leopard linker or later, which
2589 // automatically synthesizes these stubs.
2590 OpFlags = X86II::MO_DARWIN_STUB;
2591 } else if (Subtarget->isPICStyleRIPRel() &&
2592 isa<Function>(GV) &&
2593 cast<Function>(GV)->getAttributes().
2594 hasAttribute(AttributeSet::FunctionIndex,
2595 Attribute::NonLazyBind)) {
2596 // If the function is marked as non-lazy, generate an indirect call
2597 // which loads from the GOT directly. This avoids runtime overhead
2598 // at the cost of eager binding (and one extra byte of encoding).
2599 OpFlags = X86II::MO_GOTPCREL;
2600 WrapperKind = X86ISD::WrapperRIP;
2604 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2605 G->getOffset(), OpFlags);
2607 // Add a wrapper if needed.
2608 if (WrapperKind != ISD::DELETED_NODE)
2609 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2610 // Add extra indirection if needed.
2612 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2613 MachinePointerInfo::getGOT(),
2614 false, false, false, 0);
2616 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2617 unsigned char OpFlags = 0;
2619 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2620 // external symbols should go through the PLT.
2621 if (Subtarget->isTargetELF() &&
2622 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2623 OpFlags = X86II::MO_PLT;
2624 } else if (Subtarget->isPICStyleStubAny() &&
2625 (!Subtarget->getTargetTriple().isMacOSX() ||
2626 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2627 // PC-relative references to external symbols should go through $stub,
2628 // unless we're building with the leopard linker or later, which
2629 // automatically synthesizes these stubs.
2630 OpFlags = X86II::MO_DARWIN_STUB;
2633 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2637 // Returns a chain & a flag for retval copy to use.
2638 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2639 SmallVector<SDValue, 8> Ops;
2641 if (!IsSibcall && isTailCall) {
2642 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2643 DAG.getIntPtrConstant(0, true), InFlag, dl);
2644 InFlag = Chain.getValue(1);
2647 Ops.push_back(Chain);
2648 Ops.push_back(Callee);
2651 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2653 // Add argument registers to the end of the list so that they are known live
2655 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2656 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2657 RegsToPass[i].second.getValueType()));
2659 // Add a register mask operand representing the call-preserved registers.
2660 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2661 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2662 assert(Mask && "Missing call preserved mask for calling convention");
2663 Ops.push_back(DAG.getRegisterMask(Mask));
2665 if (InFlag.getNode())
2666 Ops.push_back(InFlag);
2670 //// If this is the first return lowered for this function, add the regs
2671 //// to the liveout set for the function.
2672 // This isn't right, although it's probably harmless on x86; liveouts
2673 // should be computed from returns not tail calls. Consider a void
2674 // function making a tail call to a function returning int.
2675 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2678 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2679 InFlag = Chain.getValue(1);
2681 // Create the CALLSEQ_END node.
2682 unsigned NumBytesForCalleeToPush;
2683 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2684 getTargetMachine().Options.GuaranteedTailCallOpt))
2685 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2686 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2687 SR == StackStructReturn)
2688 // If this is a call to a struct-return function, the callee
2689 // pops the hidden struct pointer, so we have to push it back.
2690 // This is common for Darwin/X86, Linux & Mingw32 targets.
2691 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2692 NumBytesForCalleeToPush = 4;
2694 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2696 // Returns a flag for retval copy to use.
2698 Chain = DAG.getCALLSEQ_END(Chain,
2699 DAG.getIntPtrConstant(NumBytes, true),
2700 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2703 InFlag = Chain.getValue(1);
2706 // Handle result values, copying them out of physregs into vregs that we
2708 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2709 Ins, dl, DAG, InVals);
2712 //===----------------------------------------------------------------------===//
2713 // Fast Calling Convention (tail call) implementation
2714 //===----------------------------------------------------------------------===//
2716 // Like std call, callee cleans arguments, convention except that ECX is
2717 // reserved for storing the tail called function address. Only 2 registers are
2718 // free for argument passing (inreg). Tail call optimization is performed
2720 // * tailcallopt is enabled
2721 // * caller/callee are fastcc
2722 // On X86_64 architecture with GOT-style position independent code only local
2723 // (within module) calls are supported at the moment.
2724 // To keep the stack aligned according to platform abi the function
2725 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2726 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2727 // If a tail called function callee has more arguments than the caller the
2728 // caller needs to make sure that there is room to move the RETADDR to. This is
2729 // achieved by reserving an area the size of the argument delta right after the
2730 // original REtADDR, but before the saved framepointer or the spilled registers
2731 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2743 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2744 /// for a 16 byte align requirement.
2746 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2747 SelectionDAG& DAG) const {
2748 MachineFunction &MF = DAG.getMachineFunction();
2749 const TargetMachine &TM = MF.getTarget();
2750 const X86RegisterInfo *RegInfo =
2751 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2752 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2753 unsigned StackAlignment = TFI.getStackAlignment();
2754 uint64_t AlignMask = StackAlignment - 1;
2755 int64_t Offset = StackSize;
2756 unsigned SlotSize = RegInfo->getSlotSize();
2757 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2758 // Number smaller than 12 so just add the difference.
2759 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2761 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2762 Offset = ((~AlignMask) & Offset) + StackAlignment +
2763 (StackAlignment-SlotSize);
2768 /// MatchingStackOffset - Return true if the given stack call argument is
2769 /// already available in the same position (relatively) of the caller's
2770 /// incoming argument stack.
2772 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2773 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2774 const X86InstrInfo *TII) {
2775 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2777 if (Arg.getOpcode() == ISD::CopyFromReg) {
2778 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2779 if (!TargetRegisterInfo::isVirtualRegister(VR))
2781 MachineInstr *Def = MRI->getVRegDef(VR);
2784 if (!Flags.isByVal()) {
2785 if (!TII->isLoadFromStackSlot(Def, FI))
2788 unsigned Opcode = Def->getOpcode();
2789 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2790 Def->getOperand(1).isFI()) {
2791 FI = Def->getOperand(1).getIndex();
2792 Bytes = Flags.getByValSize();
2796 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2797 if (Flags.isByVal())
2798 // ByVal argument is passed in as a pointer but it's now being
2799 // dereferenced. e.g.
2800 // define @foo(%struct.X* %A) {
2801 // tail call @bar(%struct.X* byval %A)
2804 SDValue Ptr = Ld->getBasePtr();
2805 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2808 FI = FINode->getIndex();
2809 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2810 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2811 FI = FINode->getIndex();
2812 Bytes = Flags.getByValSize();
2816 assert(FI != INT_MAX);
2817 if (!MFI->isFixedObjectIndex(FI))
2819 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2822 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2823 /// for tail call optimization. Targets which want to do tail call
2824 /// optimization should implement this function.
2826 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2827 CallingConv::ID CalleeCC,
2829 bool isCalleeStructRet,
2830 bool isCallerStructRet,
2832 const SmallVectorImpl<ISD::OutputArg> &Outs,
2833 const SmallVectorImpl<SDValue> &OutVals,
2834 const SmallVectorImpl<ISD::InputArg> &Ins,
2835 SelectionDAG &DAG) const {
2836 if (!IsTailCallConvention(CalleeCC) &&
2837 CalleeCC != CallingConv::C)
2840 // If -tailcallopt is specified, make fastcc functions tail-callable.
2841 const MachineFunction &MF = DAG.getMachineFunction();
2842 const Function *CallerF = DAG.getMachineFunction().getFunction();
2844 // If the function return type is x86_fp80 and the callee return type is not,
2845 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2846 // perform a tailcall optimization here.
2847 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2850 CallingConv::ID CallerCC = CallerF->getCallingConv();
2851 bool CCMatch = CallerCC == CalleeCC;
2853 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2854 if (IsTailCallConvention(CalleeCC) && CCMatch)
2859 // Look for obvious safe cases to perform tail call optimization that do not
2860 // require ABI changes. This is what gcc calls sibcall.
2862 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2863 // emit a special epilogue.
2864 const X86RegisterInfo *RegInfo =
2865 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2866 if (RegInfo->needsStackRealignment(MF))
2869 // Also avoid sibcall optimization if either caller or callee uses struct
2870 // return semantics.
2871 if (isCalleeStructRet || isCallerStructRet)
2874 // An stdcall caller is expected to clean up its arguments; the callee
2875 // isn't going to do that.
2876 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2879 // Do not sibcall optimize vararg calls unless all arguments are passed via
2881 if (isVarArg && !Outs.empty()) {
2883 // Optimizing for varargs on Win64 is unlikely to be safe without
2884 // additional testing.
2885 if (Subtarget->isTargetWin64())
2888 SmallVector<CCValAssign, 16> ArgLocs;
2889 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2890 getTargetMachine(), ArgLocs, *DAG.getContext());
2892 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2893 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2894 if (!ArgLocs[i].isRegLoc())
2898 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2899 // stack. Therefore, if it's not used by the call it is not safe to optimize
2900 // this into a sibcall.
2901 bool Unused = false;
2902 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2909 SmallVector<CCValAssign, 16> RVLocs;
2910 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2911 getTargetMachine(), RVLocs, *DAG.getContext());
2912 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2913 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2914 CCValAssign &VA = RVLocs[i];
2915 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2920 // If the calling conventions do not match, then we'd better make sure the
2921 // results are returned in the same way as what the caller expects.
2923 SmallVector<CCValAssign, 16> RVLocs1;
2924 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2925 getTargetMachine(), RVLocs1, *DAG.getContext());
2926 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2928 SmallVector<CCValAssign, 16> RVLocs2;
2929 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2930 getTargetMachine(), RVLocs2, *DAG.getContext());
2931 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2933 if (RVLocs1.size() != RVLocs2.size())
2935 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2936 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2938 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2940 if (RVLocs1[i].isRegLoc()) {
2941 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2944 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2950 // If the callee takes no arguments then go on to check the results of the
2952 if (!Outs.empty()) {
2953 // Check if stack adjustment is needed. For now, do not do this if any
2954 // argument is passed on the stack.
2955 SmallVector<CCValAssign, 16> ArgLocs;
2956 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2957 getTargetMachine(), ArgLocs, *DAG.getContext());
2959 // Allocate shadow area for Win64
2960 if (Subtarget->isTargetWin64()) {
2961 CCInfo.AllocateStack(32, 8);
2964 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2965 if (CCInfo.getNextStackOffset()) {
2966 MachineFunction &MF = DAG.getMachineFunction();
2967 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2970 // Check if the arguments are already laid out in the right way as
2971 // the caller's fixed stack objects.
2972 MachineFrameInfo *MFI = MF.getFrameInfo();
2973 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2974 const X86InstrInfo *TII =
2975 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2976 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2977 CCValAssign &VA = ArgLocs[i];
2978 SDValue Arg = OutVals[i];
2979 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2980 if (VA.getLocInfo() == CCValAssign::Indirect)
2982 if (!VA.isRegLoc()) {
2983 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2990 // If the tailcall address may be in a register, then make sure it's
2991 // possible to register allocate for it. In 32-bit, the call address can
2992 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2993 // callee-saved registers are restored. These happen to be the same
2994 // registers used to pass 'inreg' arguments so watch out for those.
2995 if (!Subtarget->is64Bit() &&
2996 ((!isa<GlobalAddressSDNode>(Callee) &&
2997 !isa<ExternalSymbolSDNode>(Callee)) ||
2998 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2999 unsigned NumInRegs = 0;
3000 // In PIC we need an extra register to formulate the address computation
3002 unsigned MaxInRegs =
3003 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3005 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3006 CCValAssign &VA = ArgLocs[i];
3009 unsigned Reg = VA.getLocReg();
3012 case X86::EAX: case X86::EDX: case X86::ECX:
3013 if (++NumInRegs == MaxInRegs)
3025 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3026 const TargetLibraryInfo *libInfo) const {
3027 return X86::createFastISel(funcInfo, libInfo);
3030 //===----------------------------------------------------------------------===//
3031 // Other Lowering Hooks
3032 //===----------------------------------------------------------------------===//
3034 static bool MayFoldLoad(SDValue Op) {
3035 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3038 static bool MayFoldIntoStore(SDValue Op) {
3039 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3042 static bool isTargetShuffle(unsigned Opcode) {
3044 default: return false;
3045 case X86ISD::PSHUFD:
3046 case X86ISD::PSHUFHW:
3047 case X86ISD::PSHUFLW:
3049 case X86ISD::PALIGNR:
3050 case X86ISD::MOVLHPS:
3051 case X86ISD::MOVLHPD:
3052 case X86ISD::MOVHLPS:
3053 case X86ISD::MOVLPS:
3054 case X86ISD::MOVLPD:
3055 case X86ISD::MOVSHDUP:
3056 case X86ISD::MOVSLDUP:
3057 case X86ISD::MOVDDUP:
3060 case X86ISD::UNPCKL:
3061 case X86ISD::UNPCKH:
3062 case X86ISD::VPERMILP:
3063 case X86ISD::VPERM2X128:
3064 case X86ISD::VPERMI:
3069 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3070 SDValue V1, SelectionDAG &DAG) {
3072 default: llvm_unreachable("Unknown x86 shuffle node");
3073 case X86ISD::MOVSHDUP:
3074 case X86ISD::MOVSLDUP:
3075 case X86ISD::MOVDDUP:
3076 return DAG.getNode(Opc, dl, VT, V1);
3080 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3081 SDValue V1, unsigned TargetMask,
3082 SelectionDAG &DAG) {
3084 default: llvm_unreachable("Unknown x86 shuffle node");
3085 case X86ISD::PSHUFD:
3086 case X86ISD::PSHUFHW:
3087 case X86ISD::PSHUFLW:
3088 case X86ISD::VPERMILP:
3089 case X86ISD::VPERMI:
3090 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3094 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3095 SDValue V1, SDValue V2, unsigned TargetMask,
3096 SelectionDAG &DAG) {
3098 default: llvm_unreachable("Unknown x86 shuffle node");
3099 case X86ISD::PALIGNR:
3101 case X86ISD::VPERM2X128:
3102 return DAG.getNode(Opc, dl, VT, V1, V2,
3103 DAG.getConstant(TargetMask, MVT::i8));
3107 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3108 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3110 default: llvm_unreachable("Unknown x86 shuffle node");
3111 case X86ISD::MOVLHPS:
3112 case X86ISD::MOVLHPD:
3113 case X86ISD::MOVHLPS:
3114 case X86ISD::MOVLPS:
3115 case X86ISD::MOVLPD:
3118 case X86ISD::UNPCKL:
3119 case X86ISD::UNPCKH:
3120 return DAG.getNode(Opc, dl, VT, V1, V2);
3124 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3125 MachineFunction &MF = DAG.getMachineFunction();
3126 const X86RegisterInfo *RegInfo =
3127 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3128 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3129 int ReturnAddrIndex = FuncInfo->getRAIndex();
3131 if (ReturnAddrIndex == 0) {
3132 // Set up a frame object for the return address.
3133 unsigned SlotSize = RegInfo->getSlotSize();
3134 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3136 FuncInfo->setRAIndex(ReturnAddrIndex);
3139 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3142 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3143 bool hasSymbolicDisplacement) {
3144 // Offset should fit into 32 bit immediate field.
3145 if (!isInt<32>(Offset))
3148 // If we don't have a symbolic displacement - we don't have any extra
3150 if (!hasSymbolicDisplacement)
3153 // FIXME: Some tweaks might be needed for medium code model.
3154 if (M != CodeModel::Small && M != CodeModel::Kernel)
3157 // For small code model we assume that latest object is 16MB before end of 31
3158 // bits boundary. We may also accept pretty large negative constants knowing
3159 // that all objects are in the positive half of address space.
3160 if (M == CodeModel::Small && Offset < 16*1024*1024)
3163 // For kernel code model we know that all object resist in the negative half
3164 // of 32bits address space. We may not accept negative offsets, since they may
3165 // be just off and we may accept pretty large positive ones.
3166 if (M == CodeModel::Kernel && Offset > 0)
3172 /// isCalleePop - Determines whether the callee is required to pop its
3173 /// own arguments. Callee pop is necessary to support tail calls.
3174 bool X86::isCalleePop(CallingConv::ID CallingConv,
3175 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3179 switch (CallingConv) {
3182 case CallingConv::X86_StdCall:
3184 case CallingConv::X86_FastCall:
3186 case CallingConv::X86_ThisCall:
3188 case CallingConv::Fast:
3190 case CallingConv::GHC:
3192 case CallingConv::HiPE:
3197 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3198 /// specific condition code, returning the condition code and the LHS/RHS of the
3199 /// comparison to make.
3200 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3201 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3203 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3204 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3205 // X > -1 -> X == 0, jump !sign.
3206 RHS = DAG.getConstant(0, RHS.getValueType());
3207 return X86::COND_NS;
3209 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3210 // X < 0 -> X == 0, jump on sign.
3213 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3215 RHS = DAG.getConstant(0, RHS.getValueType());
3216 return X86::COND_LE;
3220 switch (SetCCOpcode) {
3221 default: llvm_unreachable("Invalid integer condition!");
3222 case ISD::SETEQ: return X86::COND_E;
3223 case ISD::SETGT: return X86::COND_G;
3224 case ISD::SETGE: return X86::COND_GE;
3225 case ISD::SETLT: return X86::COND_L;
3226 case ISD::SETLE: return X86::COND_LE;
3227 case ISD::SETNE: return X86::COND_NE;
3228 case ISD::SETULT: return X86::COND_B;
3229 case ISD::SETUGT: return X86::COND_A;
3230 case ISD::SETULE: return X86::COND_BE;
3231 case ISD::SETUGE: return X86::COND_AE;
3235 // First determine if it is required or is profitable to flip the operands.
3237 // If LHS is a foldable load, but RHS is not, flip the condition.
3238 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3239 !ISD::isNON_EXTLoad(RHS.getNode())) {
3240 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3241 std::swap(LHS, RHS);
3244 switch (SetCCOpcode) {
3250 std::swap(LHS, RHS);
3254 // On a floating point condition, the flags are set as follows:
3256 // 0 | 0 | 0 | X > Y
3257 // 0 | 0 | 1 | X < Y
3258 // 1 | 0 | 0 | X == Y
3259 // 1 | 1 | 1 | unordered
3260 switch (SetCCOpcode) {
3261 default: llvm_unreachable("Condcode should be pre-legalized away");
3263 case ISD::SETEQ: return X86::COND_E;
3264 case ISD::SETOLT: // flipped
3266 case ISD::SETGT: return X86::COND_A;
3267 case ISD::SETOLE: // flipped
3269 case ISD::SETGE: return X86::COND_AE;
3270 case ISD::SETUGT: // flipped
3272 case ISD::SETLT: return X86::COND_B;
3273 case ISD::SETUGE: // flipped
3275 case ISD::SETLE: return X86::COND_BE;
3277 case ISD::SETNE: return X86::COND_NE;
3278 case ISD::SETUO: return X86::COND_P;
3279 case ISD::SETO: return X86::COND_NP;
3281 case ISD::SETUNE: return X86::COND_INVALID;
3285 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3286 /// code. Current x86 isa includes the following FP cmov instructions:
3287 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3288 static bool hasFPCMov(unsigned X86CC) {
3304 /// isFPImmLegal - Returns true if the target can instruction select the
3305 /// specified FP immediate natively. If false, the legalizer will
3306 /// materialize the FP immediate as a load from a constant pool.
3307 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3308 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3309 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3315 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3316 /// the specified range (L, H].
3317 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3318 return (Val < 0) || (Val >= Low && Val < Hi);
3321 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3322 /// specified value.
3323 static bool isUndefOrEqual(int Val, int CmpVal) {
3324 return (Val < 0 || Val == CmpVal);
3327 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3328 /// from position Pos and ending in Pos+Size, falls within the specified
3329 /// sequential range (L, L+Pos]. or is undef.
3330 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3331 unsigned Pos, unsigned Size, int Low) {
3332 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3333 if (!isUndefOrEqual(Mask[i], Low))
3338 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3339 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3340 /// the second operand.
3341 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3342 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3343 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3344 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3345 return (Mask[0] < 2 && Mask[1] < 2);
3349 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3350 /// is suitable for input to PSHUFHW.
3351 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3352 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3355 // Lower quadword copied in order or undef.
3356 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3359 // Upper quadword shuffled.
3360 for (unsigned i = 4; i != 8; ++i)
3361 if (!isUndefOrInRange(Mask[i], 4, 8))
3364 if (VT == MVT::v16i16) {
3365 // Lower quadword copied in order or undef.
3366 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3369 // Upper quadword shuffled.
3370 for (unsigned i = 12; i != 16; ++i)
3371 if (!isUndefOrInRange(Mask[i], 12, 16))
3378 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3379 /// is suitable for input to PSHUFLW.
3380 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3381 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3384 // Upper quadword copied in order.
3385 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3388 // Lower quadword shuffled.
3389 for (unsigned i = 0; i != 4; ++i)
3390 if (!isUndefOrInRange(Mask[i], 0, 4))
3393 if (VT == MVT::v16i16) {
3394 // Upper quadword copied in order.
3395 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3398 // Lower quadword shuffled.
3399 for (unsigned i = 8; i != 12; ++i)
3400 if (!isUndefOrInRange(Mask[i], 8, 12))
3407 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3408 /// is suitable for input to PALIGNR.
3409 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3410 const X86Subtarget *Subtarget) {
3411 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3412 (VT.is256BitVector() && !Subtarget->hasInt256()))
3415 unsigned NumElts = VT.getVectorNumElements();
3416 unsigned NumLanes = VT.getSizeInBits()/128;
3417 unsigned NumLaneElts = NumElts/NumLanes;
3419 // Do not handle 64-bit element shuffles with palignr.
3420 if (NumLaneElts == 2)
3423 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3425 for (i = 0; i != NumLaneElts; ++i) {
3430 // Lane is all undef, go to next lane
3431 if (i == NumLaneElts)
3434 int Start = Mask[i+l];
3436 // Make sure its in this lane in one of the sources
3437 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3438 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3441 // If not lane 0, then we must match lane 0
3442 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3445 // Correct second source to be contiguous with first source
3446 if (Start >= (int)NumElts)
3447 Start -= NumElts - NumLaneElts;
3449 // Make sure we're shifting in the right direction.
3450 if (Start <= (int)(i+l))
3455 // Check the rest of the elements to see if they are consecutive.
3456 for (++i; i != NumLaneElts; ++i) {
3457 int Idx = Mask[i+l];
3459 // Make sure its in this lane
3460 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3461 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3464 // If not lane 0, then we must match lane 0
3465 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3468 if (Idx >= (int)NumElts)
3469 Idx -= NumElts - NumLaneElts;
3471 if (!isUndefOrEqual(Idx, Start+i))
3480 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3481 /// the two vector operands have swapped position.
3482 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3483 unsigned NumElems) {
3484 for (unsigned i = 0; i != NumElems; ++i) {
3488 else if (idx < (int)NumElems)
3489 Mask[i] = idx + NumElems;
3491 Mask[i] = idx - NumElems;
3495 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3497 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3498 /// reverse of what x86 shuffles want.
3499 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3500 bool Commuted = false) {
3501 if (!HasFp256 && VT.is256BitVector())
3504 unsigned NumElems = VT.getVectorNumElements();
3505 unsigned NumLanes = VT.getSizeInBits()/128;
3506 unsigned NumLaneElems = NumElems/NumLanes;
3508 if (NumLaneElems != 2 && NumLaneElems != 4)
3511 // VSHUFPSY divides the resulting vector into 4 chunks.
3512 // The sources are also splitted into 4 chunks, and each destination
3513 // chunk must come from a different source chunk.
3515 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3516 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3518 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3519 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3521 // VSHUFPDY divides the resulting vector into 4 chunks.
3522 // The sources are also splitted into 4 chunks, and each destination
3523 // chunk must come from a different source chunk.
3525 // SRC1 => X3 X2 X1 X0
3526 // SRC2 => Y3 Y2 Y1 Y0
3528 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3530 unsigned HalfLaneElems = NumLaneElems/2;
3531 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3532 for (unsigned i = 0; i != NumLaneElems; ++i) {
3533 int Idx = Mask[i+l];
3534 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3535 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3537 // For VSHUFPSY, the mask of the second half must be the same as the
3538 // first but with the appropriate offsets. This works in the same way as
3539 // VPERMILPS works with masks.
3540 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3542 if (!isUndefOrEqual(Idx, Mask[i]+l))
3550 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3551 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3552 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3553 if (!VT.is128BitVector())
3556 unsigned NumElems = VT.getVectorNumElements();
3561 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3562 return isUndefOrEqual(Mask[0], 6) &&
3563 isUndefOrEqual(Mask[1], 7) &&
3564 isUndefOrEqual(Mask[2], 2) &&
3565 isUndefOrEqual(Mask[3], 3);
3568 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3569 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3571 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3572 if (!VT.is128BitVector())
3575 unsigned NumElems = VT.getVectorNumElements();
3580 return isUndefOrEqual(Mask[0], 2) &&
3581 isUndefOrEqual(Mask[1], 3) &&
3582 isUndefOrEqual(Mask[2], 2) &&
3583 isUndefOrEqual(Mask[3], 3);
3586 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3587 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3588 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3589 if (!VT.is128BitVector())
3592 unsigned NumElems = VT.getVectorNumElements();
3594 if (NumElems != 2 && NumElems != 4)
3597 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3598 if (!isUndefOrEqual(Mask[i], i + NumElems))
3601 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3602 if (!isUndefOrEqual(Mask[i], i))
3608 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3609 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3610 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3611 if (!VT.is128BitVector())
3614 unsigned NumElems = VT.getVectorNumElements();
3616 if (NumElems != 2 && NumElems != 4)
3619 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3620 if (!isUndefOrEqual(Mask[i], i))
3623 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3624 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3631 // Some special combinations that can be optimized.
3634 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3635 SelectionDAG &DAG) {
3636 MVT VT = SVOp->getValueType(0).getSimpleVT();
3639 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3642 ArrayRef<int> Mask = SVOp->getMask();
3644 // These are the special masks that may be optimized.
3645 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3646 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3647 bool MatchEvenMask = true;
3648 bool MatchOddMask = true;
3649 for (int i=0; i<8; ++i) {
3650 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3651 MatchEvenMask = false;
3652 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3653 MatchOddMask = false;
3656 if (!MatchEvenMask && !MatchOddMask)
3659 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3661 SDValue Op0 = SVOp->getOperand(0);
3662 SDValue Op1 = SVOp->getOperand(1);
3664 if (MatchEvenMask) {
3665 // Shift the second operand right to 32 bits.
3666 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3667 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3669 // Shift the first operand left to 32 bits.
3670 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3671 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3673 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3674 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3677 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3678 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3679 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3680 bool HasInt256, bool V2IsSplat = false) {
3681 unsigned NumElts = VT.getVectorNumElements();
3683 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3684 "Unsupported vector type for unpckh");
3686 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3687 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3690 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3691 // independently on 128-bit lanes.
3692 unsigned NumLanes = VT.getSizeInBits()/128;
3693 unsigned NumLaneElts = NumElts/NumLanes;
3695 for (unsigned l = 0; l != NumLanes; ++l) {
3696 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3697 i != (l+1)*NumLaneElts;
3700 int BitI1 = Mask[i+1];
3701 if (!isUndefOrEqual(BitI, j))
3704 if (!isUndefOrEqual(BitI1, NumElts))
3707 if (!isUndefOrEqual(BitI1, j + NumElts))
3716 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3717 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3718 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3719 bool HasInt256, bool V2IsSplat = false) {
3720 unsigned NumElts = VT.getVectorNumElements();
3722 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3723 "Unsupported vector type for unpckh");
3725 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3726 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3729 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3730 // independently on 128-bit lanes.
3731 unsigned NumLanes = VT.getSizeInBits()/128;
3732 unsigned NumLaneElts = NumElts/NumLanes;
3734 for (unsigned l = 0; l != NumLanes; ++l) {
3735 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3736 i != (l+1)*NumLaneElts; i += 2, ++j) {
3738 int BitI1 = Mask[i+1];
3739 if (!isUndefOrEqual(BitI, j))
3742 if (isUndefOrEqual(BitI1, NumElts))
3745 if (!isUndefOrEqual(BitI1, j+NumElts))
3753 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3754 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3756 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3757 unsigned NumElts = VT.getVectorNumElements();
3758 bool Is256BitVec = VT.is256BitVector();
3760 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3761 "Unsupported vector type for unpckh");
3763 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3764 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3767 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3768 // FIXME: Need a better way to get rid of this, there's no latency difference
3769 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3770 // the former later. We should also remove the "_undef" special mask.
3771 if (NumElts == 4 && Is256BitVec)
3774 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3775 // independently on 128-bit lanes.
3776 unsigned NumLanes = VT.getSizeInBits()/128;
3777 unsigned NumLaneElts = NumElts/NumLanes;
3779 for (unsigned l = 0; l != NumLanes; ++l) {
3780 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3781 i != (l+1)*NumLaneElts;
3784 int BitI1 = Mask[i+1];
3786 if (!isUndefOrEqual(BitI, j))
3788 if (!isUndefOrEqual(BitI1, j))
3796 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3797 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3799 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3800 unsigned NumElts = VT.getVectorNumElements();
3802 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3803 "Unsupported vector type for unpckh");
3805 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3806 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3809 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3810 // independently on 128-bit lanes.
3811 unsigned NumLanes = VT.getSizeInBits()/128;
3812 unsigned NumLaneElts = NumElts/NumLanes;
3814 for (unsigned l = 0; l != NumLanes; ++l) {
3815 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3816 i != (l+1)*NumLaneElts; i += 2, ++j) {
3818 int BitI1 = Mask[i+1];
3819 if (!isUndefOrEqual(BitI, j))
3821 if (!isUndefOrEqual(BitI1, j))
3828 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3829 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3830 /// MOVSD, and MOVD, i.e. setting the lowest element.
3831 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3832 if (VT.getVectorElementType().getSizeInBits() < 32)
3834 if (!VT.is128BitVector())
3837 unsigned NumElts = VT.getVectorNumElements();
3839 if (!isUndefOrEqual(Mask[0], NumElts))
3842 for (unsigned i = 1; i != NumElts; ++i)
3843 if (!isUndefOrEqual(Mask[i], i))
3849 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3850 /// as permutations between 128-bit chunks or halves. As an example: this
3852 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3853 /// The first half comes from the second half of V1 and the second half from the
3854 /// the second half of V2.
3855 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3856 if (!HasFp256 || !VT.is256BitVector())
3859 // The shuffle result is divided into half A and half B. In total the two
3860 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3861 // B must come from C, D, E or F.
3862 unsigned HalfSize = VT.getVectorNumElements()/2;
3863 bool MatchA = false, MatchB = false;
3865 // Check if A comes from one of C, D, E, F.
3866 for (unsigned Half = 0; Half != 4; ++Half) {
3867 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3873 // Check if B comes from one of C, D, E, F.
3874 for (unsigned Half = 0; Half != 4; ++Half) {
3875 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3881 return MatchA && MatchB;
3884 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3885 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3886 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3887 MVT VT = SVOp->getValueType(0).getSimpleVT();
3889 unsigned HalfSize = VT.getVectorNumElements()/2;
3891 unsigned FstHalf = 0, SndHalf = 0;
3892 for (unsigned i = 0; i < HalfSize; ++i) {
3893 if (SVOp->getMaskElt(i) > 0) {
3894 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3898 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3899 if (SVOp->getMaskElt(i) > 0) {
3900 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3905 return (FstHalf | (SndHalf << 4));
3908 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3910 /// Note that VPERMIL mask matching is different depending whether theunderlying
3911 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3912 /// to the same elements of the low, but to the higher half of the source.
3913 /// In VPERMILPD the two lanes could be shuffled independently of each other
3914 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3915 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3919 unsigned NumElts = VT.getVectorNumElements();
3920 // Only match 256-bit with 32/64-bit types
3921 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3924 unsigned NumLanes = VT.getSizeInBits()/128;
3925 unsigned LaneSize = NumElts/NumLanes;
3926 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3927 for (unsigned i = 0; i != LaneSize; ++i) {
3928 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3930 if (NumElts != 8 || l == 0)
3932 // VPERMILPS handling
3935 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3943 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3944 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3945 /// element of vector 2 and the other elements to come from vector 1 in order.
3946 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3947 bool V2IsSplat = false, bool V2IsUndef = false) {
3948 if (!VT.is128BitVector())
3951 unsigned NumOps = VT.getVectorNumElements();
3952 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3955 if (!isUndefOrEqual(Mask[0], 0))
3958 for (unsigned i = 1; i != NumOps; ++i)
3959 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3960 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3961 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3967 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3968 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3969 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3970 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3971 const X86Subtarget *Subtarget) {
3972 if (!Subtarget->hasSSE3())
3975 unsigned NumElems = VT.getVectorNumElements();
3977 if ((VT.is128BitVector() && NumElems != 4) ||
3978 (VT.is256BitVector() && NumElems != 8))
3981 // "i+1" is the value the indexed mask element must have
3982 for (unsigned i = 0; i != NumElems; i += 2)
3983 if (!isUndefOrEqual(Mask[i], i+1) ||
3984 !isUndefOrEqual(Mask[i+1], i+1))
3990 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3991 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3992 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3993 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3994 const X86Subtarget *Subtarget) {
3995 if (!Subtarget->hasSSE3())
3998 unsigned NumElems = VT.getVectorNumElements();
4000 if ((VT.is128BitVector() && NumElems != 4) ||
4001 (VT.is256BitVector() && NumElems != 8))
4004 // "i" is the value the indexed mask element must have
4005 for (unsigned i = 0; i != NumElems; i += 2)
4006 if (!isUndefOrEqual(Mask[i], i) ||
4007 !isUndefOrEqual(Mask[i+1], i))
4013 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4014 /// specifies a shuffle of elements that is suitable for input to 256-bit
4015 /// version of MOVDDUP.
4016 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4017 if (!HasFp256 || !VT.is256BitVector())
4020 unsigned NumElts = VT.getVectorNumElements();
4024 for (unsigned i = 0; i != NumElts/2; ++i)
4025 if (!isUndefOrEqual(Mask[i], 0))
4027 for (unsigned i = NumElts/2; i != NumElts; ++i)
4028 if (!isUndefOrEqual(Mask[i], NumElts/2))
4033 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4034 /// specifies a shuffle of elements that is suitable for input to 128-bit
4035 /// version of MOVDDUP.
4036 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4037 if (!VT.is128BitVector())
4040 unsigned e = VT.getVectorNumElements() / 2;
4041 for (unsigned i = 0; i != e; ++i)
4042 if (!isUndefOrEqual(Mask[i], i))
4044 for (unsigned i = 0; i != e; ++i)
4045 if (!isUndefOrEqual(Mask[e+i], i))
4050 /// isVEXTRACTF128Index - Return true if the specified
4051 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4052 /// suitable for input to VEXTRACTF128.
4053 bool X86::isVEXTRACTF128Index(SDNode *N) {
4054 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4057 // The index should be aligned on a 128-bit boundary.
4059 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4061 MVT VT = N->getValueType(0).getSimpleVT();
4062 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4063 bool Result = (Index * ElSize) % 128 == 0;
4068 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4069 /// operand specifies a subvector insert that is suitable for input to
4071 bool X86::isVINSERTF128Index(SDNode *N) {
4072 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4075 // The index should be aligned on a 128-bit boundary.
4077 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4079 MVT VT = N->getValueType(0).getSimpleVT();
4080 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4081 bool Result = (Index * ElSize) % 128 == 0;
4086 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4087 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4088 /// Handles 128-bit and 256-bit.
4089 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4090 MVT VT = N->getValueType(0).getSimpleVT();
4092 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4093 "Unsupported vector type for PSHUF/SHUFP");
4095 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4096 // independently on 128-bit lanes.
4097 unsigned NumElts = VT.getVectorNumElements();
4098 unsigned NumLanes = VT.getSizeInBits()/128;
4099 unsigned NumLaneElts = NumElts/NumLanes;
4101 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4102 "Only supports 2 or 4 elements per lane");
4104 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4106 for (unsigned i = 0; i != NumElts; ++i) {
4107 int Elt = N->getMaskElt(i);
4108 if (Elt < 0) continue;
4109 Elt &= NumLaneElts - 1;
4110 unsigned ShAmt = (i << Shift) % 8;
4111 Mask |= Elt << ShAmt;
4117 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4118 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4119 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4120 MVT VT = N->getValueType(0).getSimpleVT();
4122 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4123 "Unsupported vector type for PSHUFHW");
4125 unsigned NumElts = VT.getVectorNumElements();
4128 for (unsigned l = 0; l != NumElts; l += 8) {
4129 // 8 nodes per lane, but we only care about the last 4.
4130 for (unsigned i = 0; i < 4; ++i) {
4131 int Elt = N->getMaskElt(l+i+4);
4132 if (Elt < 0) continue;
4133 Elt &= 0x3; // only 2-bits.
4134 Mask |= Elt << (i * 2);
4141 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4142 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4143 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4144 MVT VT = N->getValueType(0).getSimpleVT();
4146 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4147 "Unsupported vector type for PSHUFHW");
4149 unsigned NumElts = VT.getVectorNumElements();
4152 for (unsigned l = 0; l != NumElts; l += 8) {
4153 // 8 nodes per lane, but we only care about the first 4.
4154 for (unsigned i = 0; i < 4; ++i) {
4155 int Elt = N->getMaskElt(l+i);
4156 if (Elt < 0) continue;
4157 Elt &= 0x3; // only 2-bits
4158 Mask |= Elt << (i * 2);
4165 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4166 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4167 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4168 MVT VT = SVOp->getValueType(0).getSimpleVT();
4169 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4171 unsigned NumElts = VT.getVectorNumElements();
4172 unsigned NumLanes = VT.getSizeInBits()/128;
4173 unsigned NumLaneElts = NumElts/NumLanes;
4177 for (i = 0; i != NumElts; ++i) {
4178 Val = SVOp->getMaskElt(i);
4182 if (Val >= (int)NumElts)
4183 Val -= NumElts - NumLaneElts;
4185 assert(Val - i > 0 && "PALIGNR imm should be positive");
4186 return (Val - i) * EltSize;
4189 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4190 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4192 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4193 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4194 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4197 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4199 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4200 MVT ElVT = VecVT.getVectorElementType();
4202 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4203 return Index / NumElemsPerChunk;
4206 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4207 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4209 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4210 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4211 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4214 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4216 MVT VecVT = N->getValueType(0).getSimpleVT();
4217 MVT ElVT = VecVT.getVectorElementType();
4219 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4220 return Index / NumElemsPerChunk;
4223 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4224 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4225 /// Handles 256-bit.
4226 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4227 MVT VT = N->getValueType(0).getSimpleVT();
4229 unsigned NumElts = VT.getVectorNumElements();
4231 assert((VT.is256BitVector() && NumElts == 4) &&
4232 "Unsupported vector type for VPERMQ/VPERMPD");
4235 for (unsigned i = 0; i != NumElts; ++i) {
4236 int Elt = N->getMaskElt(i);
4239 Mask |= Elt << (i*2);
4244 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4246 bool X86::isZeroNode(SDValue Elt) {
4247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4248 return CN->isNullValue();
4249 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4250 return CFP->getValueAPF().isPosZero();
4254 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4255 /// their permute mask.
4256 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4257 SelectionDAG &DAG) {
4258 MVT VT = SVOp->getValueType(0).getSimpleVT();
4259 unsigned NumElems = VT.getVectorNumElements();
4260 SmallVector<int, 8> MaskVec;
4262 for (unsigned i = 0; i != NumElems; ++i) {
4263 int Idx = SVOp->getMaskElt(i);
4265 if (Idx < (int)NumElems)
4270 MaskVec.push_back(Idx);
4272 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4273 SVOp->getOperand(0), &MaskVec[0]);
4276 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4277 /// match movhlps. The lower half elements should come from upper half of
4278 /// V1 (and in order), and the upper half elements should come from the upper
4279 /// half of V2 (and in order).
4280 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4281 if (!VT.is128BitVector())
4283 if (VT.getVectorNumElements() != 4)
4285 for (unsigned i = 0, e = 2; i != e; ++i)
4286 if (!isUndefOrEqual(Mask[i], i+2))
4288 for (unsigned i = 2; i != 4; ++i)
4289 if (!isUndefOrEqual(Mask[i], i+4))
4294 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4295 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4297 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4298 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4300 N = N->getOperand(0).getNode();
4301 if (!ISD::isNON_EXTLoad(N))
4304 *LD = cast<LoadSDNode>(N);
4308 // Test whether the given value is a vector value which will be legalized
4310 static bool WillBeConstantPoolLoad(SDNode *N) {
4311 if (N->getOpcode() != ISD::BUILD_VECTOR)
4314 // Check for any non-constant elements.
4315 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4316 switch (N->getOperand(i).getNode()->getOpcode()) {
4318 case ISD::ConstantFP:
4325 // Vectors of all-zeros and all-ones are materialized with special
4326 // instructions rather than being loaded.
4327 return !ISD::isBuildVectorAllZeros(N) &&
4328 !ISD::isBuildVectorAllOnes(N);
4331 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4332 /// match movlp{s|d}. The lower half elements should come from lower half of
4333 /// V1 (and in order), and the upper half elements should come from the upper
4334 /// half of V2 (and in order). And since V1 will become the source of the
4335 /// MOVLP, it must be either a vector load or a scalar load to vector.
4336 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4337 ArrayRef<int> Mask, EVT VT) {
4338 if (!VT.is128BitVector())
4341 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4343 // Is V2 is a vector load, don't do this transformation. We will try to use
4344 // load folding shufps op.
4345 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4348 unsigned NumElems = VT.getVectorNumElements();
4350 if (NumElems != 2 && NumElems != 4)
4352 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4353 if (!isUndefOrEqual(Mask[i], i))
4355 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4356 if (!isUndefOrEqual(Mask[i], i+NumElems))
4361 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4363 static bool isSplatVector(SDNode *N) {
4364 if (N->getOpcode() != ISD::BUILD_VECTOR)
4367 SDValue SplatValue = N->getOperand(0);
4368 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4369 if (N->getOperand(i) != SplatValue)
4374 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4375 /// to an zero vector.
4376 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4377 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4378 SDValue V1 = N->getOperand(0);
4379 SDValue V2 = N->getOperand(1);
4380 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4381 for (unsigned i = 0; i != NumElems; ++i) {
4382 int Idx = N->getMaskElt(i);
4383 if (Idx >= (int)NumElems) {
4384 unsigned Opc = V2.getOpcode();
4385 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4387 if (Opc != ISD::BUILD_VECTOR ||
4388 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4390 } else if (Idx >= 0) {
4391 unsigned Opc = V1.getOpcode();
4392 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4394 if (Opc != ISD::BUILD_VECTOR ||
4395 !X86::isZeroNode(V1.getOperand(Idx)))
4402 /// getZeroVector - Returns a vector of specified type with all zero elements.
4404 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4405 SelectionDAG &DAG, SDLoc dl) {
4406 assert(VT.isVector() && "Expected a vector type");
4408 // Always build SSE zero vectors as <4 x i32> bitcasted
4409 // to their dest type. This ensures they get CSE'd.
4411 if (VT.is128BitVector()) { // SSE
4412 if (Subtarget->hasSSE2()) { // SSE2
4413 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4414 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4416 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4417 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4419 } else if (VT.is256BitVector()) { // AVX
4420 if (Subtarget->hasInt256()) { // AVX2
4421 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4422 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4423 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4424 array_lengthof(Ops));
4426 // 256-bit logic and arithmetic instructions in AVX are all
4427 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4428 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4429 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4430 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4431 array_lengthof(Ops));
4434 llvm_unreachable("Unexpected vector type");
4436 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4439 /// getOnesVector - Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4445 assert(VT.isVector() && "Expected a vector type");
4447 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4449 if (VT.is256BitVector()) {
4450 if (HasInt256) { // AVX2
4451 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4453 array_lengthof(Ops));
4455 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4456 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4458 } else if (VT.is128BitVector()) {
4459 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4461 llvm_unreachable("Unexpected vector type");
4463 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4466 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4467 /// that point to V2 points to its first element.
4468 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4469 for (unsigned i = 0; i != NumElems; ++i) {
4470 if (Mask[i] > (int)NumElems) {
4476 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4477 /// operation of specified width.
4478 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4480 unsigned NumElems = VT.getVectorNumElements();
4481 SmallVector<int, 8> Mask;
4482 Mask.push_back(NumElems);
4483 for (unsigned i = 1; i != NumElems; ++i)
4485 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4488 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4489 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4491 unsigned NumElems = VT.getVectorNumElements();
4492 SmallVector<int, 8> Mask;
4493 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4495 Mask.push_back(i + NumElems);
4497 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4500 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4501 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4503 unsigned NumElems = VT.getVectorNumElements();
4504 SmallVector<int, 8> Mask;
4505 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4506 Mask.push_back(i + Half);
4507 Mask.push_back(i + NumElems + Half);
4509 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4512 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4513 // a generic shuffle instruction because the target has no such instructions.
4514 // Generate shuffles which repeat i16 and i8 several times until they can be
4515 // represented by v4f32 and then be manipulated by target suported shuffles.
4516 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4517 EVT VT = V.getValueType();
4518 int NumElems = VT.getVectorNumElements();
4521 while (NumElems > 4) {
4522 if (EltNo < NumElems/2) {
4523 V = getUnpackl(DAG, dl, VT, V, V);
4525 V = getUnpackh(DAG, dl, VT, V, V);
4526 EltNo -= NumElems/2;
4533 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4534 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4535 EVT VT = V.getValueType();
4538 if (VT.is128BitVector()) {
4539 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4540 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4541 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4543 } else if (VT.is256BitVector()) {
4544 // To use VPERMILPS to splat scalars, the second half of indicies must
4545 // refer to the higher part, which is a duplication of the lower one,
4546 // because VPERMILPS can only handle in-lane permutations.
4547 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4548 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4550 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4551 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4554 llvm_unreachable("Vector size not supported");
4556 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4559 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4560 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4561 EVT SrcVT = SV->getValueType(0);
4562 SDValue V1 = SV->getOperand(0);
4565 int EltNo = SV->getSplatIndex();
4566 int NumElems = SrcVT.getVectorNumElements();
4567 bool Is256BitVec = SrcVT.is256BitVector();
4569 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4570 "Unknown how to promote splat for type");
4572 // Extract the 128-bit part containing the splat element and update
4573 // the splat element index when it refers to the higher register.
4575 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4576 if (EltNo >= NumElems/2)
4577 EltNo -= NumElems/2;
4580 // All i16 and i8 vector types can't be used directly by a generic shuffle
4581 // instruction because the target has no such instruction. Generate shuffles
4582 // which repeat i16 and i8 several times until they fit in i32, and then can
4583 // be manipulated by target suported shuffles.
4584 EVT EltVT = SrcVT.getVectorElementType();
4585 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4586 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4588 // Recreate the 256-bit vector and place the same 128-bit vector
4589 // into the low and high part. This is necessary because we want
4590 // to use VPERM* to shuffle the vectors
4592 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4595 return getLegalSplat(DAG, V1, EltNo);
4598 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4599 /// vector of zero or undef vector. This produces a shuffle where the low
4600 /// element of V2 is swizzled into the zero/undef vector, landing at element
4601 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4602 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4604 const X86Subtarget *Subtarget,
4605 SelectionDAG &DAG) {
4606 EVT VT = V2.getValueType();
4608 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4609 unsigned NumElems = VT.getVectorNumElements();
4610 SmallVector<int, 16> MaskVec;
4611 for (unsigned i = 0; i != NumElems; ++i)
4612 // If this is the insertion idx, put the low elt of V2 here.
4613 MaskVec.push_back(i == Idx ? NumElems : i);
4614 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4617 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4618 /// target specific opcode. Returns true if the Mask could be calculated.
4619 /// Sets IsUnary to true if only uses one source.
4620 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4621 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4622 unsigned NumElems = VT.getVectorNumElements();
4626 switch(N->getOpcode()) {
4628 ImmN = N->getOperand(N->getNumOperands()-1);
4629 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4631 case X86ISD::UNPCKH:
4632 DecodeUNPCKHMask(VT, Mask);
4634 case X86ISD::UNPCKL:
4635 DecodeUNPCKLMask(VT, Mask);
4637 case X86ISD::MOVHLPS:
4638 DecodeMOVHLPSMask(NumElems, Mask);
4640 case X86ISD::MOVLHPS:
4641 DecodeMOVLHPSMask(NumElems, Mask);
4643 case X86ISD::PALIGNR:
4644 ImmN = N->getOperand(N->getNumOperands()-1);
4645 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4647 case X86ISD::PSHUFD:
4648 case X86ISD::VPERMILP:
4649 ImmN = N->getOperand(N->getNumOperands()-1);
4650 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4653 case X86ISD::PSHUFHW:
4654 ImmN = N->getOperand(N->getNumOperands()-1);
4655 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4658 case X86ISD::PSHUFLW:
4659 ImmN = N->getOperand(N->getNumOperands()-1);
4660 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4663 case X86ISD::VPERMI:
4664 ImmN = N->getOperand(N->getNumOperands()-1);
4665 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4669 case X86ISD::MOVSD: {
4670 // The index 0 always comes from the first element of the second source,
4671 // this is why MOVSS and MOVSD are used in the first place. The other
4672 // elements come from the other positions of the first source vector
4673 Mask.push_back(NumElems);
4674 for (unsigned i = 1; i != NumElems; ++i) {
4679 case X86ISD::VPERM2X128:
4680 ImmN = N->getOperand(N->getNumOperands()-1);
4681 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4682 if (Mask.empty()) return false;
4684 case X86ISD::MOVDDUP:
4685 case X86ISD::MOVLHPD:
4686 case X86ISD::MOVLPD:
4687 case X86ISD::MOVLPS:
4688 case X86ISD::MOVSHDUP:
4689 case X86ISD::MOVSLDUP:
4690 // Not yet implemented
4692 default: llvm_unreachable("unknown target shuffle node");
4698 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4699 /// element of the result of the vector shuffle.
4700 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4703 return SDValue(); // Limit search depth.
4705 SDValue V = SDValue(N, 0);
4706 EVT VT = V.getValueType();
4707 unsigned Opcode = V.getOpcode();
4709 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4710 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4711 int Elt = SV->getMaskElt(Index);
4714 return DAG.getUNDEF(VT.getVectorElementType());
4716 unsigned NumElems = VT.getVectorNumElements();
4717 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4718 : SV->getOperand(1);
4719 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4722 // Recurse into target specific vector shuffles to find scalars.
4723 if (isTargetShuffle(Opcode)) {
4724 MVT ShufVT = V.getValueType().getSimpleVT();
4725 unsigned NumElems = ShufVT.getVectorNumElements();
4726 SmallVector<int, 16> ShuffleMask;
4729 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4732 int Elt = ShuffleMask[Index];
4734 return DAG.getUNDEF(ShufVT.getVectorElementType());
4736 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4738 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4742 // Actual nodes that may contain scalar elements
4743 if (Opcode == ISD::BITCAST) {
4744 V = V.getOperand(0);
4745 EVT SrcVT = V.getValueType();
4746 unsigned NumElems = VT.getVectorNumElements();
4748 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4752 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4753 return (Index == 0) ? V.getOperand(0)
4754 : DAG.getUNDEF(VT.getVectorElementType());
4756 if (V.getOpcode() == ISD::BUILD_VECTOR)
4757 return V.getOperand(Index);
4762 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4763 /// shuffle operation which come from a consecutively from a zero. The
4764 /// search can start in two different directions, from left or right.
4765 /// We count undefs as zeros until PreferredNum is reached.
4766 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4767 unsigned NumElems, bool ZerosFromLeft,
4769 unsigned PreferredNum = -1U) {
4770 unsigned NumZeros = 0;
4771 for (unsigned i = 0; i != NumElems; ++i) {
4772 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4773 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4777 if (X86::isZeroNode(Elt))
4779 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4780 NumZeros = std::min(NumZeros + 1, PreferredNum);
4788 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4789 /// correspond consecutively to elements from one of the vector operands,
4790 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4792 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4793 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4794 unsigned NumElems, unsigned &OpNum) {
4795 bool SeenV1 = false;
4796 bool SeenV2 = false;
4798 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4799 int Idx = SVOp->getMaskElt(i);
4800 // Ignore undef indicies
4804 if (Idx < (int)NumElems)
4809 // Only accept consecutive elements from the same vector
4810 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4814 OpNum = SeenV1 ? 0 : 1;
4818 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4819 /// logical left shift of a vector.
4820 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4821 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4822 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4823 unsigned NumZeros = getNumOfConsecutiveZeros(
4824 SVOp, NumElems, false /* check zeros from right */, DAG,
4825 SVOp->getMaskElt(0));
4831 // Considering the elements in the mask that are not consecutive zeros,
4832 // check if they consecutively come from only one of the source vectors.
4834 // V1 = {X, A, B, C} 0
4836 // vector_shuffle V1, V2 <1, 2, 3, X>
4838 if (!isShuffleMaskConsecutive(SVOp,
4839 0, // Mask Start Index
4840 NumElems-NumZeros, // Mask End Index(exclusive)
4841 NumZeros, // Where to start looking in the src vector
4842 NumElems, // Number of elements in vector
4843 OpSrc)) // Which source operand ?
4848 ShVal = SVOp->getOperand(OpSrc);
4852 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4853 /// logical left shift of a vector.
4854 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4855 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4856 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4857 unsigned NumZeros = getNumOfConsecutiveZeros(
4858 SVOp, NumElems, true /* check zeros from left */, DAG,
4859 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4865 // Considering the elements in the mask that are not consecutive zeros,
4866 // check if they consecutively come from only one of the source vectors.
4868 // 0 { A, B, X, X } = V2
4870 // vector_shuffle V1, V2 <X, X, 4, 5>
4872 if (!isShuffleMaskConsecutive(SVOp,
4873 NumZeros, // Mask Start Index
4874 NumElems, // Mask End Index(exclusive)
4875 0, // Where to start looking in the src vector
4876 NumElems, // Number of elements in vector
4877 OpSrc)) // Which source operand ?
4882 ShVal = SVOp->getOperand(OpSrc);
4886 /// isVectorShift - Returns true if the shuffle can be implemented as a
4887 /// logical left or right shift of a vector.
4888 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4889 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4890 // Although the logic below support any bitwidth size, there are no
4891 // shift instructions which handle more than 128-bit vectors.
4892 if (!SVOp->getValueType(0).is128BitVector())
4895 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4896 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4902 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4904 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4905 unsigned NumNonZero, unsigned NumZero,
4907 const X86Subtarget* Subtarget,
4908 const TargetLowering &TLI) {
4915 for (unsigned i = 0; i < 16; ++i) {
4916 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4917 if (ThisIsNonZero && First) {
4919 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4921 V = DAG.getUNDEF(MVT::v8i16);
4926 SDValue ThisElt(0, 0), LastElt(0, 0);
4927 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4928 if (LastIsNonZero) {
4929 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4930 MVT::i16, Op.getOperand(i-1));
4932 if (ThisIsNonZero) {
4933 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4934 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4935 ThisElt, DAG.getConstant(8, MVT::i8));
4937 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4941 if (ThisElt.getNode())
4942 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4943 DAG.getIntPtrConstant(i/2));
4947 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4950 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4952 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4953 unsigned NumNonZero, unsigned NumZero,
4955 const X86Subtarget* Subtarget,
4956 const TargetLowering &TLI) {
4963 for (unsigned i = 0; i < 8; ++i) {
4964 bool isNonZero = (NonZeros & (1 << i)) != 0;
4968 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4970 V = DAG.getUNDEF(MVT::v8i16);
4973 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4974 MVT::v8i16, V, Op.getOperand(i),
4975 DAG.getIntPtrConstant(i));
4982 /// getVShift - Return a vector logical shift node.
4984 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4985 unsigned NumBits, SelectionDAG &DAG,
4986 const TargetLowering &TLI, SDLoc dl) {
4987 assert(VT.is128BitVector() && "Unknown type for VShift");
4988 EVT ShVT = MVT::v2i64;
4989 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4990 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4991 return DAG.getNode(ISD::BITCAST, dl, VT,
4992 DAG.getNode(Opc, dl, ShVT, SrcOp,
4993 DAG.getConstant(NumBits,
4994 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4998 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
4999 SelectionDAG &DAG) const {
5001 // Check if the scalar load can be widened into a vector load. And if
5002 // the address is "base + cst" see if the cst can be "absorbed" into
5003 // the shuffle mask.
5004 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5005 SDValue Ptr = LD->getBasePtr();
5006 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5008 EVT PVT = LD->getValueType(0);
5009 if (PVT != MVT::i32 && PVT != MVT::f32)
5014 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5015 FI = FINode->getIndex();
5017 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5018 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5019 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5020 Offset = Ptr.getConstantOperandVal(1);
5021 Ptr = Ptr.getOperand(0);
5026 // FIXME: 256-bit vector instructions don't require a strict alignment,
5027 // improve this code to support it better.
5028 unsigned RequiredAlign = VT.getSizeInBits()/8;
5029 SDValue Chain = LD->getChain();
5030 // Make sure the stack object alignment is at least 16 or 32.
5031 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5032 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5033 if (MFI->isFixedObjectIndex(FI)) {
5034 // Can't change the alignment. FIXME: It's possible to compute
5035 // the exact stack offset and reference FI + adjust offset instead.
5036 // If someone *really* cares about this. That's the way to implement it.
5039 MFI->setObjectAlignment(FI, RequiredAlign);
5043 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5044 // Ptr + (Offset & ~15).
5047 if ((Offset % RequiredAlign) & 3)
5049 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5051 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5052 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5054 int EltNo = (Offset - StartOffset) >> 2;
5055 unsigned NumElems = VT.getVectorNumElements();
5057 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5058 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5059 LD->getPointerInfo().getWithOffset(StartOffset),
5060 false, false, false, 0);
5062 SmallVector<int, 8> Mask;
5063 for (unsigned i = 0; i != NumElems; ++i)
5064 Mask.push_back(EltNo);
5066 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5072 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5073 /// vector of type 'VT', see if the elements can be replaced by a single large
5074 /// load which has the same value as a build_vector whose operands are 'elts'.
5076 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5078 /// FIXME: we'd also like to handle the case where the last elements are zero
5079 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5080 /// There's even a handy isZeroNode for that purpose.
5081 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5082 SDLoc &DL, SelectionDAG &DAG) {
5083 EVT EltVT = VT.getVectorElementType();
5084 unsigned NumElems = Elts.size();
5086 LoadSDNode *LDBase = NULL;
5087 unsigned LastLoadedElt = -1U;
5089 // For each element in the initializer, see if we've found a load or an undef.
5090 // If we don't find an initial load element, or later load elements are
5091 // non-consecutive, bail out.
5092 for (unsigned i = 0; i < NumElems; ++i) {
5093 SDValue Elt = Elts[i];
5095 if (!Elt.getNode() ||
5096 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5099 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5101 LDBase = cast<LoadSDNode>(Elt.getNode());
5105 if (Elt.getOpcode() == ISD::UNDEF)
5108 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5109 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5114 // If we have found an entire vector of loads and undefs, then return a large
5115 // load of the entire vector width starting at the base pointer. If we found
5116 // consecutive loads for the low half, generate a vzext_load node.
5117 if (LastLoadedElt == NumElems - 1) {
5118 SDValue NewLd = SDValue();
5119 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5120 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5121 LDBase->getPointerInfo(),
5122 LDBase->isVolatile(), LDBase->isNonTemporal(),
5123 LDBase->isInvariant(), 0);
5124 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5125 LDBase->getPointerInfo(),
5126 LDBase->isVolatile(), LDBase->isNonTemporal(),
5127 LDBase->isInvariant(), LDBase->getAlignment());
5129 if (LDBase->hasAnyUseOfValue(1)) {
5130 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5132 SDValue(NewLd.getNode(), 1));
5133 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5134 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5135 SDValue(NewLd.getNode(), 1));
5140 if (NumElems == 4 && LastLoadedElt == 1 &&
5141 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5142 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5143 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5145 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5146 array_lengthof(Ops), MVT::i64,
5147 LDBase->getPointerInfo(),
5148 LDBase->getAlignment(),
5149 false/*isVolatile*/, true/*ReadMem*/,
5152 // Make sure the newly-created LOAD is in the same position as LDBase in
5153 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5154 // update uses of LDBase's output chain to use the TokenFactor.
5155 if (LDBase->hasAnyUseOfValue(1)) {
5156 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5157 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5158 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5159 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5160 SDValue(ResNode.getNode(), 1));
5163 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5168 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5169 /// to generate a splat value for the following cases:
5170 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5171 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5172 /// a scalar load, or a constant.
5173 /// The VBROADCAST node is returned when a pattern is found,
5174 /// or SDValue() otherwise.
5176 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5177 if (!Subtarget->hasFp256())
5180 MVT VT = Op.getValueType().getSimpleVT();
5183 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5184 "Unsupported vector type for broadcast.");
5189 switch (Op.getOpcode()) {
5191 // Unknown pattern found.
5194 case ISD::BUILD_VECTOR: {
5195 // The BUILD_VECTOR node must be a splat.
5196 if (!isSplatVector(Op.getNode()))
5199 Ld = Op.getOperand(0);
5200 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5201 Ld.getOpcode() == ISD::ConstantFP);
5203 // The suspected load node has several users. Make sure that all
5204 // of its users are from the BUILD_VECTOR node.
5205 // Constants may have multiple users.
5206 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5211 case ISD::VECTOR_SHUFFLE: {
5212 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5214 // Shuffles must have a splat mask where the first element is
5216 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5219 SDValue Sc = Op.getOperand(0);
5220 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5221 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5223 if (!Subtarget->hasInt256())
5226 // Use the register form of the broadcast instruction available on AVX2.
5227 if (VT.is256BitVector())
5228 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5229 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5232 Ld = Sc.getOperand(0);
5233 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5234 Ld.getOpcode() == ISD::ConstantFP);
5236 // The scalar_to_vector node and the suspected
5237 // load node must have exactly one user.
5238 // Constants may have multiple users.
5239 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5245 bool Is256 = VT.is256BitVector();
5247 // Handle the broadcasting a single constant scalar from the constant pool
5248 // into a vector. On Sandybridge it is still better to load a constant vector
5249 // from the constant pool and not to broadcast it from a scalar.
5250 if (ConstSplatVal && Subtarget->hasInt256()) {
5251 EVT CVT = Ld.getValueType();
5252 assert(!CVT.isVector() && "Must not broadcast a vector type");
5253 unsigned ScalarSize = CVT.getSizeInBits();
5255 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5256 const Constant *C = 0;
5257 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5258 C = CI->getConstantIntValue();
5259 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5260 C = CF->getConstantFPValue();
5262 assert(C && "Invalid constant type");
5264 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5265 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5266 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5267 MachinePointerInfo::getConstantPool(),
5268 false, false, false, Alignment);
5270 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5274 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5275 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5277 // Handle AVX2 in-register broadcasts.
5278 if (!IsLoad && Subtarget->hasInt256() &&
5279 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5280 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5282 // The scalar source must be a normal load.
5286 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5287 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5289 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5290 // double since there is no vbroadcastsd xmm
5291 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5292 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5293 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5296 // Unsupported broadcast.
5301 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5302 EVT VT = Op.getValueType();
5304 // Skip if insert_vec_elt is not supported.
5305 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5309 unsigned NumElems = Op.getNumOperands();
5313 SmallVector<unsigned, 4> InsertIndices;
5314 SmallVector<int, 8> Mask(NumElems, -1);
5316 for (unsigned i = 0; i != NumElems; ++i) {
5317 unsigned Opc = Op.getOperand(i).getOpcode();
5319 if (Opc == ISD::UNDEF)
5322 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5323 // Quit if more than 1 elements need inserting.
5324 if (InsertIndices.size() > 1)
5327 InsertIndices.push_back(i);
5331 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5332 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5334 // Quit if extracted from vector of different type.
5335 if (ExtractedFromVec.getValueType() != VT)
5338 // Quit if non-constant index.
5339 if (!isa<ConstantSDNode>(ExtIdx))
5342 if (VecIn1.getNode() == 0)
5343 VecIn1 = ExtractedFromVec;
5344 else if (VecIn1 != ExtractedFromVec) {
5345 if (VecIn2.getNode() == 0)
5346 VecIn2 = ExtractedFromVec;
5347 else if (VecIn2 != ExtractedFromVec)
5348 // Quit if more than 2 vectors to shuffle
5352 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5354 if (ExtractedFromVec == VecIn1)
5356 else if (ExtractedFromVec == VecIn2)
5357 Mask[i] = Idx + NumElems;
5360 if (VecIn1.getNode() == 0)
5363 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5364 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5365 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5366 unsigned Idx = InsertIndices[i];
5367 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5368 DAG.getIntPtrConstant(Idx));
5375 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5378 MVT VT = Op.getValueType().getSimpleVT();
5379 MVT ExtVT = VT.getVectorElementType();
5380 unsigned NumElems = Op.getNumOperands();
5382 // Vectors containing all zeros can be matched by pxor and xorps later
5383 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5384 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5385 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5386 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5389 return getZeroVector(VT, Subtarget, DAG, dl);
5392 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5393 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5394 // vpcmpeqd on 256-bit vectors.
5395 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5396 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5399 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5402 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5403 if (Broadcast.getNode())
5406 unsigned EVTBits = ExtVT.getSizeInBits();
5408 unsigned NumZero = 0;
5409 unsigned NumNonZero = 0;
5410 unsigned NonZeros = 0;
5411 bool IsAllConstants = true;
5412 SmallSet<SDValue, 8> Values;
5413 for (unsigned i = 0; i < NumElems; ++i) {
5414 SDValue Elt = Op.getOperand(i);
5415 if (Elt.getOpcode() == ISD::UNDEF)
5418 if (Elt.getOpcode() != ISD::Constant &&
5419 Elt.getOpcode() != ISD::ConstantFP)
5420 IsAllConstants = false;
5421 if (X86::isZeroNode(Elt))
5424 NonZeros |= (1 << i);
5429 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5430 if (NumNonZero == 0)
5431 return DAG.getUNDEF(VT);
5433 // Special case for single non-zero, non-undef, element.
5434 if (NumNonZero == 1) {
5435 unsigned Idx = countTrailingZeros(NonZeros);
5436 SDValue Item = Op.getOperand(Idx);
5438 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5439 // the value are obviously zero, truncate the value to i32 and do the
5440 // insertion that way. Only do this if the value is non-constant or if the
5441 // value is a constant being inserted into element 0. It is cheaper to do
5442 // a constant pool load than it is to do a movd + shuffle.
5443 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5444 (!IsAllConstants || Idx == 0)) {
5445 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5447 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5448 EVT VecVT = MVT::v4i32;
5449 unsigned VecElts = 4;
5451 // Truncate the value (which may itself be a constant) to i32, and
5452 // convert it to a vector with movd (S2V+shuffle to zero extend).
5453 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5454 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5455 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5457 // Now we have our 32-bit value zero extended in the low element of
5458 // a vector. If Idx != 0, swizzle it into place.
5460 SmallVector<int, 4> Mask;
5461 Mask.push_back(Idx);
5462 for (unsigned i = 1; i != VecElts; ++i)
5464 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5467 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5471 // If we have a constant or non-constant insertion into the low element of
5472 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5473 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5474 // depending on what the source datatype is.
5477 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5479 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5480 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5481 if (VT.is256BitVector()) {
5482 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5483 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5484 Item, DAG.getIntPtrConstant(0));
5486 assert(VT.is128BitVector() && "Expected an SSE value type!");
5487 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5488 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5489 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5492 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5493 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5494 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5495 if (VT.is256BitVector()) {
5496 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5497 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5499 assert(VT.is128BitVector() && "Expected an SSE value type!");
5500 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5502 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5506 // Is it a vector logical left shift?
5507 if (NumElems == 2 && Idx == 1 &&
5508 X86::isZeroNode(Op.getOperand(0)) &&
5509 !X86::isZeroNode(Op.getOperand(1))) {
5510 unsigned NumBits = VT.getSizeInBits();
5511 return getVShift(true, VT,
5512 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5513 VT, Op.getOperand(1)),
5514 NumBits/2, DAG, *this, dl);
5517 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5520 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5521 // is a non-constant being inserted into an element other than the low one,
5522 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5523 // movd/movss) to move this into the low element, then shuffle it into
5525 if (EVTBits == 32) {
5526 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5528 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5529 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5530 SmallVector<int, 8> MaskVec;
5531 for (unsigned i = 0; i != NumElems; ++i)
5532 MaskVec.push_back(i == Idx ? 0 : 1);
5533 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5537 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5538 if (Values.size() == 1) {
5539 if (EVTBits == 32) {
5540 // Instead of a shuffle like this:
5541 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5542 // Check if it's possible to issue this instead.
5543 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5544 unsigned Idx = countTrailingZeros(NonZeros);
5545 SDValue Item = Op.getOperand(Idx);
5546 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5547 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5552 // A vector full of immediates; various special cases are already
5553 // handled, so this is best done with a single constant-pool load.
5557 // For AVX-length vectors, build the individual 128-bit pieces and use
5558 // shuffles to put them in place.
5559 if (VT.is256BitVector()) {
5560 SmallVector<SDValue, 32> V;
5561 for (unsigned i = 0; i != NumElems; ++i)
5562 V.push_back(Op.getOperand(i));
5564 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5566 // Build both the lower and upper subvector.
5567 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5568 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5571 // Recreate the wider vector with the lower and upper part.
5572 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5575 // Let legalizer expand 2-wide build_vectors.
5576 if (EVTBits == 64) {
5577 if (NumNonZero == 1) {
5578 // One half is zero or undef.
5579 unsigned Idx = countTrailingZeros(NonZeros);
5580 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5581 Op.getOperand(Idx));
5582 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5587 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5588 if (EVTBits == 8 && NumElems == 16) {
5589 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5591 if (V.getNode()) return V;
5594 if (EVTBits == 16 && NumElems == 8) {
5595 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5597 if (V.getNode()) return V;
5600 // If element VT is == 32 bits, turn it into a number of shuffles.
5601 SmallVector<SDValue, 8> V(NumElems);
5602 if (NumElems == 4 && NumZero > 0) {
5603 for (unsigned i = 0; i < 4; ++i) {
5604 bool isZero = !(NonZeros & (1 << i));
5606 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5608 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5611 for (unsigned i = 0; i < 2; ++i) {
5612 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5615 V[i] = V[i*2]; // Must be a zero vector.
5618 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5621 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5624 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5629 bool Reverse1 = (NonZeros & 0x3) == 2;
5630 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5634 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5635 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5637 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5640 if (Values.size() > 1 && VT.is128BitVector()) {
5641 // Check for a build vector of consecutive loads.
5642 for (unsigned i = 0; i < NumElems; ++i)
5643 V[i] = Op.getOperand(i);
5645 // Check for elements which are consecutive loads.
5646 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5650 // Check for a build vector from mostly shuffle plus few inserting.
5651 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5655 // For SSE 4.1, use insertps to put the high elements into the low element.
5656 if (getSubtarget()->hasSSE41()) {
5658 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5659 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5661 Result = DAG.getUNDEF(VT);
5663 for (unsigned i = 1; i < NumElems; ++i) {
5664 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5665 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5666 Op.getOperand(i), DAG.getIntPtrConstant(i));
5671 // Otherwise, expand into a number of unpckl*, start by extending each of
5672 // our (non-undef) elements to the full vector width with the element in the
5673 // bottom slot of the vector (which generates no code for SSE).
5674 for (unsigned i = 0; i < NumElems; ++i) {
5675 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5676 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5678 V[i] = DAG.getUNDEF(VT);
5681 // Next, we iteratively mix elements, e.g. for v4f32:
5682 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5683 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5684 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5685 unsigned EltStride = NumElems >> 1;
5686 while (EltStride != 0) {
5687 for (unsigned i = 0; i < EltStride; ++i) {
5688 // If V[i+EltStride] is undef and this is the first round of mixing,
5689 // then it is safe to just drop this shuffle: V[i] is already in the
5690 // right place, the one element (since it's the first round) being
5691 // inserted as undef can be dropped. This isn't safe for successive
5692 // rounds because they will permute elements within both vectors.
5693 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5694 EltStride == NumElems/2)
5697 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5706 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5707 // to create 256-bit vectors from two other 128-bit ones.
5708 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5710 MVT ResVT = Op.getValueType().getSimpleVT();
5712 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5714 SDValue V1 = Op.getOperand(0);
5715 SDValue V2 = Op.getOperand(1);
5716 unsigned NumElems = ResVT.getVectorNumElements();
5718 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5721 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5722 assert(Op.getNumOperands() == 2);
5724 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5725 // from two other 128-bit ones.
5726 return LowerAVXCONCAT_VECTORS(Op, DAG);
5729 // Try to lower a shuffle node into a simple blend instruction.
5731 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5732 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5733 SDValue V1 = SVOp->getOperand(0);
5734 SDValue V2 = SVOp->getOperand(1);
5736 MVT VT = SVOp->getValueType(0).getSimpleVT();
5737 MVT EltVT = VT.getVectorElementType();
5738 unsigned NumElems = VT.getVectorNumElements();
5740 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5742 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5745 // Check the mask for BLEND and build the value.
5746 unsigned MaskValue = 0;
5747 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5748 unsigned NumLanes = (NumElems-1)/8 + 1;
5749 unsigned NumElemsInLane = NumElems / NumLanes;
5751 // Blend for v16i16 should be symetric for the both lanes.
5752 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5754 int SndLaneEltIdx = (NumLanes == 2) ?
5755 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5756 int EltIdx = SVOp->getMaskElt(i);
5758 if ((EltIdx < 0 || EltIdx == (int)i) &&
5759 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5762 if (((unsigned)EltIdx == (i + NumElems)) &&
5763 (SndLaneEltIdx < 0 ||
5764 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5765 MaskValue |= (1<<i);
5770 // Convert i32 vectors to floating point if it is not AVX2.
5771 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5773 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5774 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5776 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5777 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5780 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5781 DAG.getConstant(MaskValue, MVT::i32));
5782 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5785 // v8i16 shuffles - Prefer shuffles in the following order:
5786 // 1. [all] pshuflw, pshufhw, optional move
5787 // 2. [ssse3] 1 x pshufb
5788 // 3. [ssse3] 2 x pshufb + 1 x por
5789 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5791 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5792 SelectionDAG &DAG) {
5793 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5794 SDValue V1 = SVOp->getOperand(0);
5795 SDValue V2 = SVOp->getOperand(1);
5797 SmallVector<int, 8> MaskVals;
5799 // Determine if more than 1 of the words in each of the low and high quadwords
5800 // of the result come from the same quadword of one of the two inputs. Undef
5801 // mask values count as coming from any quadword, for better codegen.
5802 unsigned LoQuad[] = { 0, 0, 0, 0 };
5803 unsigned HiQuad[] = { 0, 0, 0, 0 };
5804 std::bitset<4> InputQuads;
5805 for (unsigned i = 0; i < 8; ++i) {
5806 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5807 int EltIdx = SVOp->getMaskElt(i);
5808 MaskVals.push_back(EltIdx);
5817 InputQuads.set(EltIdx / 4);
5820 int BestLoQuad = -1;
5821 unsigned MaxQuad = 1;
5822 for (unsigned i = 0; i < 4; ++i) {
5823 if (LoQuad[i] > MaxQuad) {
5825 MaxQuad = LoQuad[i];
5829 int BestHiQuad = -1;
5831 for (unsigned i = 0; i < 4; ++i) {
5832 if (HiQuad[i] > MaxQuad) {
5834 MaxQuad = HiQuad[i];
5838 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5839 // of the two input vectors, shuffle them into one input vector so only a
5840 // single pshufb instruction is necessary. If There are more than 2 input
5841 // quads, disable the next transformation since it does not help SSSE3.
5842 bool V1Used = InputQuads[0] || InputQuads[1];
5843 bool V2Used = InputQuads[2] || InputQuads[3];
5844 if (Subtarget->hasSSSE3()) {
5845 if (InputQuads.count() == 2 && V1Used && V2Used) {
5846 BestLoQuad = InputQuads[0] ? 0 : 1;
5847 BestHiQuad = InputQuads[2] ? 2 : 3;
5849 if (InputQuads.count() > 2) {
5855 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5856 // the shuffle mask. If a quad is scored as -1, that means that it contains
5857 // words from all 4 input quadwords.
5859 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5861 BestLoQuad < 0 ? 0 : BestLoQuad,
5862 BestHiQuad < 0 ? 1 : BestHiQuad
5864 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5865 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5866 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5867 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5869 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5870 // source words for the shuffle, to aid later transformations.
5871 bool AllWordsInNewV = true;
5872 bool InOrder[2] = { true, true };
5873 for (unsigned i = 0; i != 8; ++i) {
5874 int idx = MaskVals[i];
5876 InOrder[i/4] = false;
5877 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5879 AllWordsInNewV = false;
5883 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5884 if (AllWordsInNewV) {
5885 for (int i = 0; i != 8; ++i) {
5886 int idx = MaskVals[i];
5889 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5890 if ((idx != i) && idx < 4)
5892 if ((idx != i) && idx > 3)
5901 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5902 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5903 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5904 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5905 unsigned TargetMask = 0;
5906 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5907 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5908 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5909 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5910 getShufflePSHUFLWImmediate(SVOp);
5911 V1 = NewV.getOperand(0);
5912 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5916 // Promote splats to a larger type which usually leads to more efficient code.
5917 // FIXME: Is this true if pshufb is available?
5918 if (SVOp->isSplat())
5919 return PromoteSplat(SVOp, DAG);
5921 // If we have SSSE3, and all words of the result are from 1 input vector,
5922 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5923 // is present, fall back to case 4.
5924 if (Subtarget->hasSSSE3()) {
5925 SmallVector<SDValue,16> pshufbMask;
5927 // If we have elements from both input vectors, set the high bit of the
5928 // shuffle mask element to zero out elements that come from V2 in the V1
5929 // mask, and elements that come from V1 in the V2 mask, so that the two
5930 // results can be OR'd together.
5931 bool TwoInputs = V1Used && V2Used;
5932 for (unsigned i = 0; i != 8; ++i) {
5933 int EltIdx = MaskVals[i] * 2;
5934 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5935 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5936 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5937 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5939 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5940 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5941 DAG.getNode(ISD::BUILD_VECTOR, dl,
5942 MVT::v16i8, &pshufbMask[0], 16));
5944 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5946 // Calculate the shuffle mask for the second input, shuffle it, and
5947 // OR it with the first shuffled input.
5949 for (unsigned i = 0; i != 8; ++i) {
5950 int EltIdx = MaskVals[i] * 2;
5951 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5952 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5953 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5954 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5956 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5957 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5958 DAG.getNode(ISD::BUILD_VECTOR, dl,
5959 MVT::v16i8, &pshufbMask[0], 16));
5960 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5961 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5964 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5965 // and update MaskVals with new element order.
5966 std::bitset<8> InOrder;
5967 if (BestLoQuad >= 0) {
5968 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5969 for (int i = 0; i != 4; ++i) {
5970 int idx = MaskVals[i];
5973 } else if ((idx / 4) == BestLoQuad) {
5978 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5981 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5983 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5985 getShufflePSHUFLWImmediate(SVOp), DAG);
5989 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5990 // and update MaskVals with the new element order.
5991 if (BestHiQuad >= 0) {
5992 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5993 for (unsigned i = 4; i != 8; ++i) {
5994 int idx = MaskVals[i];
5997 } else if ((idx / 4) == BestHiQuad) {
5998 MaskV[i] = (idx & 3) + 4;
6002 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6005 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6006 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6007 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6009 getShufflePSHUFHWImmediate(SVOp), DAG);
6013 // In case BestHi & BestLo were both -1, which means each quadword has a word
6014 // from each of the four input quadwords, calculate the InOrder bitvector now
6015 // before falling through to the insert/extract cleanup.
6016 if (BestLoQuad == -1 && BestHiQuad == -1) {
6018 for (int i = 0; i != 8; ++i)
6019 if (MaskVals[i] < 0 || MaskVals[i] == i)
6023 // The other elements are put in the right place using pextrw and pinsrw.
6024 for (unsigned i = 0; i != 8; ++i) {
6027 int EltIdx = MaskVals[i];
6030 SDValue ExtOp = (EltIdx < 8) ?
6031 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6032 DAG.getIntPtrConstant(EltIdx)) :
6033 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6034 DAG.getIntPtrConstant(EltIdx - 8));
6035 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6036 DAG.getIntPtrConstant(i));
6041 // v16i8 shuffles - Prefer shuffles in the following order:
6042 // 1. [ssse3] 1 x pshufb
6043 // 2. [ssse3] 2 x pshufb + 1 x por
6044 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6046 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6048 const X86TargetLowering &TLI) {
6049 SDValue V1 = SVOp->getOperand(0);
6050 SDValue V2 = SVOp->getOperand(1);
6052 ArrayRef<int> MaskVals = SVOp->getMask();
6054 // Promote splats to a larger type which usually leads to more efficient code.
6055 // FIXME: Is this true if pshufb is available?
6056 if (SVOp->isSplat())
6057 return PromoteSplat(SVOp, DAG);
6059 // If we have SSSE3, case 1 is generated when all result bytes come from
6060 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6061 // present, fall back to case 3.
6063 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6064 if (TLI.getSubtarget()->hasSSSE3()) {
6065 SmallVector<SDValue,16> pshufbMask;
6067 // If all result elements are from one input vector, then only translate
6068 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6070 // Otherwise, we have elements from both input vectors, and must zero out
6071 // elements that come from V2 in the first mask, and V1 in the second mask
6072 // so that we can OR them together.
6073 for (unsigned i = 0; i != 16; ++i) {
6074 int EltIdx = MaskVals[i];
6075 if (EltIdx < 0 || EltIdx >= 16)
6077 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6079 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6080 DAG.getNode(ISD::BUILD_VECTOR, dl,
6081 MVT::v16i8, &pshufbMask[0], 16));
6083 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6084 // the 2nd operand if it's undefined or zero.
6085 if (V2.getOpcode() == ISD::UNDEF ||
6086 ISD::isBuildVectorAllZeros(V2.getNode()))
6089 // Calculate the shuffle mask for the second input, shuffle it, and
6090 // OR it with the first shuffled input.
6092 for (unsigned i = 0; i != 16; ++i) {
6093 int EltIdx = MaskVals[i];
6094 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6095 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6097 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6098 DAG.getNode(ISD::BUILD_VECTOR, dl,
6099 MVT::v16i8, &pshufbMask[0], 16));
6100 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6103 // No SSSE3 - Calculate in place words and then fix all out of place words
6104 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6105 // the 16 different words that comprise the two doublequadword input vectors.
6106 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6107 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6109 for (int i = 0; i != 8; ++i) {
6110 int Elt0 = MaskVals[i*2];
6111 int Elt1 = MaskVals[i*2+1];
6113 // This word of the result is all undef, skip it.
6114 if (Elt0 < 0 && Elt1 < 0)
6117 // This word of the result is already in the correct place, skip it.
6118 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6121 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6122 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6125 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6126 // using a single extract together, load it and store it.
6127 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6128 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6129 DAG.getIntPtrConstant(Elt1 / 2));
6130 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6131 DAG.getIntPtrConstant(i));
6135 // If Elt1 is defined, extract it from the appropriate source. If the
6136 // source byte is not also odd, shift the extracted word left 8 bits
6137 // otherwise clear the bottom 8 bits if we need to do an or.
6139 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6140 DAG.getIntPtrConstant(Elt1 / 2));
6141 if ((Elt1 & 1) == 0)
6142 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6144 TLI.getShiftAmountTy(InsElt.getValueType())));
6146 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6147 DAG.getConstant(0xFF00, MVT::i16));
6149 // If Elt0 is defined, extract it from the appropriate source. If the
6150 // source byte is not also even, shift the extracted word right 8 bits. If
6151 // Elt1 was also defined, OR the extracted values together before
6152 // inserting them in the result.
6154 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6155 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6156 if ((Elt0 & 1) != 0)
6157 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6159 TLI.getShiftAmountTy(InsElt0.getValueType())));
6161 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6162 DAG.getConstant(0x00FF, MVT::i16));
6163 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6166 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6167 DAG.getIntPtrConstant(i));
6169 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6172 // v32i8 shuffles - Translate to VPSHUFB if possible.
6174 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6175 const X86Subtarget *Subtarget,
6176 SelectionDAG &DAG) {
6177 MVT VT = SVOp->getValueType(0).getSimpleVT();
6178 SDValue V1 = SVOp->getOperand(0);
6179 SDValue V2 = SVOp->getOperand(1);
6181 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6183 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6184 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6185 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6187 // VPSHUFB may be generated if
6188 // (1) one of input vector is undefined or zeroinitializer.
6189 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6190 // And (2) the mask indexes don't cross the 128-bit lane.
6191 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6192 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6195 if (V1IsAllZero && !V2IsAllZero) {
6196 CommuteVectorShuffleMask(MaskVals, 32);
6199 SmallVector<SDValue, 32> pshufbMask;
6200 for (unsigned i = 0; i != 32; i++) {
6201 int EltIdx = MaskVals[i];
6202 if (EltIdx < 0 || EltIdx >= 32)
6205 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6206 // Cross lane is not allowed.
6210 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6212 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6213 DAG.getNode(ISD::BUILD_VECTOR, dl,
6214 MVT::v32i8, &pshufbMask[0], 32));
6217 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6218 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6219 /// done when every pair / quad of shuffle mask elements point to elements in
6220 /// the right sequence. e.g.
6221 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6223 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6224 SelectionDAG &DAG) {
6225 MVT VT = SVOp->getValueType(0).getSimpleVT();
6227 unsigned NumElems = VT.getVectorNumElements();
6230 switch (VT.SimpleTy) {
6231 default: llvm_unreachable("Unexpected!");
6232 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6233 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6234 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6235 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6236 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6237 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6240 SmallVector<int, 8> MaskVec;
6241 for (unsigned i = 0; i != NumElems; i += Scale) {
6243 for (unsigned j = 0; j != Scale; ++j) {
6244 int EltIdx = SVOp->getMaskElt(i+j);
6248 StartIdx = (EltIdx / Scale);
6249 if (EltIdx != (int)(StartIdx*Scale + j))
6252 MaskVec.push_back(StartIdx);
6255 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6256 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6257 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6260 /// getVZextMovL - Return a zero-extending vector move low node.
6262 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6263 SDValue SrcOp, SelectionDAG &DAG,
6264 const X86Subtarget *Subtarget, SDLoc dl) {
6265 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6266 LoadSDNode *LD = NULL;
6267 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6268 LD = dyn_cast<LoadSDNode>(SrcOp);
6270 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6272 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6273 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6274 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6275 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6276 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6278 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6279 return DAG.getNode(ISD::BITCAST, dl, VT,
6280 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6281 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6289 return DAG.getNode(ISD::BITCAST, dl, VT,
6290 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6291 DAG.getNode(ISD::BITCAST, dl,
6295 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6296 /// which could not be matched by any known target speficic shuffle
6298 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6300 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6301 if (NewOp.getNode())
6304 MVT VT = SVOp->getValueType(0).getSimpleVT();
6306 unsigned NumElems = VT.getVectorNumElements();
6307 unsigned NumLaneElems = NumElems / 2;
6310 MVT EltVT = VT.getVectorElementType();
6311 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6314 SmallVector<int, 16> Mask;
6315 for (unsigned l = 0; l < 2; ++l) {
6316 // Build a shuffle mask for the output, discovering on the fly which
6317 // input vectors to use as shuffle operands (recorded in InputUsed).
6318 // If building a suitable shuffle vector proves too hard, then bail
6319 // out with UseBuildVector set.
6320 bool UseBuildVector = false;
6321 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6322 unsigned LaneStart = l * NumLaneElems;
6323 for (unsigned i = 0; i != NumLaneElems; ++i) {
6324 // The mask element. This indexes into the input.
6325 int Idx = SVOp->getMaskElt(i+LaneStart);
6327 // the mask element does not index into any input vector.
6332 // The input vector this mask element indexes into.
6333 int Input = Idx / NumLaneElems;
6335 // Turn the index into an offset from the start of the input vector.
6336 Idx -= Input * NumLaneElems;
6338 // Find or create a shuffle vector operand to hold this input.
6340 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6341 if (InputUsed[OpNo] == Input)
6342 // This input vector is already an operand.
6344 if (InputUsed[OpNo] < 0) {
6345 // Create a new operand for this input vector.
6346 InputUsed[OpNo] = Input;
6351 if (OpNo >= array_lengthof(InputUsed)) {
6352 // More than two input vectors used! Give up on trying to create a
6353 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6354 UseBuildVector = true;
6358 // Add the mask index for the new shuffle vector.
6359 Mask.push_back(Idx + OpNo * NumLaneElems);
6362 if (UseBuildVector) {
6363 SmallVector<SDValue, 16> SVOps;
6364 for (unsigned i = 0; i != NumLaneElems; ++i) {
6365 // The mask element. This indexes into the input.
6366 int Idx = SVOp->getMaskElt(i+LaneStart);
6368 SVOps.push_back(DAG.getUNDEF(EltVT));
6372 // The input vector this mask element indexes into.
6373 int Input = Idx / NumElems;
6375 // Turn the index into an offset from the start of the input vector.
6376 Idx -= Input * NumElems;
6378 // Extract the vector element by hand.
6379 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6380 SVOp->getOperand(Input),
6381 DAG.getIntPtrConstant(Idx)));
6384 // Construct the output using a BUILD_VECTOR.
6385 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6387 } else if (InputUsed[0] < 0) {
6388 // No input vectors were used! The result is undefined.
6389 Output[l] = DAG.getUNDEF(NVT);
6391 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6392 (InputUsed[0] % 2) * NumLaneElems,
6394 // If only one input was used, use an undefined vector for the other.
6395 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6396 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6397 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6398 // At least one input vector was used. Create a new shuffle vector.
6399 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6405 // Concatenate the result back
6406 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6409 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6410 /// 4 elements, and match them with several different shuffle types.
6412 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6413 SDValue V1 = SVOp->getOperand(0);
6414 SDValue V2 = SVOp->getOperand(1);
6416 MVT VT = SVOp->getValueType(0).getSimpleVT();
6418 assert(VT.is128BitVector() && "Unsupported vector size");
6420 std::pair<int, int> Locs[4];
6421 int Mask1[] = { -1, -1, -1, -1 };
6422 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6426 for (unsigned i = 0; i != 4; ++i) {
6427 int Idx = PermMask[i];
6429 Locs[i] = std::make_pair(-1, -1);
6431 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6433 Locs[i] = std::make_pair(0, NumLo);
6437 Locs[i] = std::make_pair(1, NumHi);
6439 Mask1[2+NumHi] = Idx;
6445 if (NumLo <= 2 && NumHi <= 2) {
6446 // If no more than two elements come from either vector. This can be
6447 // implemented with two shuffles. First shuffle gather the elements.
6448 // The second shuffle, which takes the first shuffle as both of its
6449 // vector operands, put the elements into the right order.
6450 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6452 int Mask2[] = { -1, -1, -1, -1 };
6454 for (unsigned i = 0; i != 4; ++i)
6455 if (Locs[i].first != -1) {
6456 unsigned Idx = (i < 2) ? 0 : 4;
6457 Idx += Locs[i].first * 2 + Locs[i].second;
6461 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6464 if (NumLo == 3 || NumHi == 3) {
6465 // Otherwise, we must have three elements from one vector, call it X, and
6466 // one element from the other, call it Y. First, use a shufps to build an
6467 // intermediate vector with the one element from Y and the element from X
6468 // that will be in the same half in the final destination (the indexes don't
6469 // matter). Then, use a shufps to build the final vector, taking the half
6470 // containing the element from Y from the intermediate, and the other half
6473 // Normalize it so the 3 elements come from V1.
6474 CommuteVectorShuffleMask(PermMask, 4);
6478 // Find the element from V2.
6480 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6481 int Val = PermMask[HiIndex];
6488 Mask1[0] = PermMask[HiIndex];
6490 Mask1[2] = PermMask[HiIndex^1];
6492 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6495 Mask1[0] = PermMask[0];
6496 Mask1[1] = PermMask[1];
6497 Mask1[2] = HiIndex & 1 ? 6 : 4;
6498 Mask1[3] = HiIndex & 1 ? 4 : 6;
6499 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6502 Mask1[0] = HiIndex & 1 ? 2 : 0;
6503 Mask1[1] = HiIndex & 1 ? 0 : 2;
6504 Mask1[2] = PermMask[2];
6505 Mask1[3] = PermMask[3];
6510 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6513 // Break it into (shuffle shuffle_hi, shuffle_lo).
6514 int LoMask[] = { -1, -1, -1, -1 };
6515 int HiMask[] = { -1, -1, -1, -1 };
6517 int *MaskPtr = LoMask;
6518 unsigned MaskIdx = 0;
6521 for (unsigned i = 0; i != 4; ++i) {
6528 int Idx = PermMask[i];
6530 Locs[i] = std::make_pair(-1, -1);
6531 } else if (Idx < 4) {
6532 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6533 MaskPtr[LoIdx] = Idx;
6536 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6537 MaskPtr[HiIdx] = Idx;
6542 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6543 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6544 int MaskOps[] = { -1, -1, -1, -1 };
6545 for (unsigned i = 0; i != 4; ++i)
6546 if (Locs[i].first != -1)
6547 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6548 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6551 static bool MayFoldVectorLoad(SDValue V) {
6552 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6553 V = V.getOperand(0);
6555 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6556 V = V.getOperand(0);
6557 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6558 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6559 // BUILD_VECTOR (load), undef
6560 V = V.getOperand(0);
6562 return MayFoldLoad(V);
6566 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6567 EVT VT = Op.getValueType();
6569 // Canonizalize to v2f64.
6570 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6571 return DAG.getNode(ISD::BITCAST, dl, VT,
6572 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6577 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6579 SDValue V1 = Op.getOperand(0);
6580 SDValue V2 = Op.getOperand(1);
6581 EVT VT = Op.getValueType();
6583 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6585 if (HasSSE2 && VT == MVT::v2f64)
6586 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6588 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6589 return DAG.getNode(ISD::BITCAST, dl, VT,
6590 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6591 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6592 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6596 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6597 SDValue V1 = Op.getOperand(0);
6598 SDValue V2 = Op.getOperand(1);
6599 EVT VT = Op.getValueType();
6601 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6602 "unsupported shuffle type");
6604 if (V2.getOpcode() == ISD::UNDEF)
6608 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6612 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6613 SDValue V1 = Op.getOperand(0);
6614 SDValue V2 = Op.getOperand(1);
6615 EVT VT = Op.getValueType();
6616 unsigned NumElems = VT.getVectorNumElements();
6618 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6619 // operand of these instructions is only memory, so check if there's a
6620 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6622 bool CanFoldLoad = false;
6624 // Trivial case, when V2 comes from a load.
6625 if (MayFoldVectorLoad(V2))
6628 // When V1 is a load, it can be folded later into a store in isel, example:
6629 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6631 // (MOVLPSmr addr:$src1, VR128:$src2)
6632 // So, recognize this potential and also use MOVLPS or MOVLPD
6633 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6638 if (HasSSE2 && NumElems == 2)
6639 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6642 // If we don't care about the second element, proceed to use movss.
6643 if (SVOp->getMaskElt(1) != -1)
6644 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6647 // movl and movlp will both match v2i64, but v2i64 is never matched by
6648 // movl earlier because we make it strict to avoid messing with the movlp load
6649 // folding logic (see the code above getMOVLP call). Match it here then,
6650 // this is horrible, but will stay like this until we move all shuffle
6651 // matching to x86 specific nodes. Note that for the 1st condition all
6652 // types are matched with movsd.
6654 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6655 // as to remove this logic from here, as much as possible
6656 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6657 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6658 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6661 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6663 // Invert the operand order and use SHUFPS to match it.
6664 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6665 getShuffleSHUFImmediate(SVOp), DAG);
6668 // Reduce a vector shuffle to zext.
6670 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6671 // PMOVZX is only available from SSE41.
6672 if (!Subtarget->hasSSE41())
6675 EVT VT = Op.getValueType();
6677 // Only AVX2 support 256-bit vector integer extending.
6678 if (!Subtarget->hasInt256() && VT.is256BitVector())
6681 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6683 SDValue V1 = Op.getOperand(0);
6684 SDValue V2 = Op.getOperand(1);
6685 unsigned NumElems = VT.getVectorNumElements();
6687 // Extending is an unary operation and the element type of the source vector
6688 // won't be equal to or larger than i64.
6689 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6690 VT.getVectorElementType() == MVT::i64)
6693 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6694 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6695 while ((1U << Shift) < NumElems) {
6696 if (SVOp->getMaskElt(1U << Shift) == 1)
6699 // The maximal ratio is 8, i.e. from i8 to i64.
6704 // Check the shuffle mask.
6705 unsigned Mask = (1U << Shift) - 1;
6706 for (unsigned i = 0; i != NumElems; ++i) {
6707 int EltIdx = SVOp->getMaskElt(i);
6708 if ((i & Mask) != 0 && EltIdx != -1)
6710 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6714 LLVMContext *Context = DAG.getContext();
6715 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6716 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6717 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6719 if (!isTypeLegal(NVT))
6722 // Simplify the operand as it's prepared to be fed into shuffle.
6723 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6724 if (V1.getOpcode() == ISD::BITCAST &&
6725 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6726 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6728 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6729 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6730 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6731 ConstantSDNode *CIdx =
6732 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6733 // If it's foldable, i.e. normal load with single use, we will let code
6734 // selection to fold it. Otherwise, we will short the conversion sequence.
6735 if (CIdx && CIdx->getZExtValue() == 0 &&
6736 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6737 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6738 // The "ext_vec_elt" node is wider than the result node.
6739 // In this case we should extract subvector from V.
6740 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6741 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6742 EVT FullVT = V.getValueType();
6743 EVT SubVecVT = EVT::getVectorVT(*Context,
6744 FullVT.getVectorElementType(),
6745 FullVT.getVectorNumElements()/Ratio);
6746 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6747 DAG.getIntPtrConstant(0));
6749 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6753 return DAG.getNode(ISD::BITCAST, DL, VT,
6754 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6758 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6759 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6760 MVT VT = Op.getValueType().getSimpleVT();
6762 SDValue V1 = Op.getOperand(0);
6763 SDValue V2 = Op.getOperand(1);
6765 if (isZeroShuffle(SVOp))
6766 return getZeroVector(VT, Subtarget, DAG, dl);
6768 // Handle splat operations
6769 if (SVOp->isSplat()) {
6770 // Use vbroadcast whenever the splat comes from a foldable load
6771 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6772 if (Broadcast.getNode())
6776 // Check integer expanding shuffles.
6777 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6778 if (NewOp.getNode())
6781 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6783 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6784 VT == MVT::v16i16 || VT == MVT::v32i8) {
6785 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6786 if (NewOp.getNode())
6787 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6788 } else if ((VT == MVT::v4i32 ||
6789 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6790 // FIXME: Figure out a cleaner way to do this.
6791 // Try to make use of movq to zero out the top part.
6792 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6793 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6794 if (NewOp.getNode()) {
6795 MVT NewVT = NewOp.getValueType().getSimpleVT();
6796 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6797 NewVT, true, false))
6798 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6799 DAG, Subtarget, dl);
6801 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6802 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6803 if (NewOp.getNode()) {
6804 MVT NewVT = NewOp.getValueType().getSimpleVT();
6805 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6806 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6807 DAG, Subtarget, dl);
6815 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6816 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6817 SDValue V1 = Op.getOperand(0);
6818 SDValue V2 = Op.getOperand(1);
6819 MVT VT = Op.getValueType().getSimpleVT();
6821 unsigned NumElems = VT.getVectorNumElements();
6822 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6823 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6824 bool V1IsSplat = false;
6825 bool V2IsSplat = false;
6826 bool HasSSE2 = Subtarget->hasSSE2();
6827 bool HasFp256 = Subtarget->hasFp256();
6828 bool HasInt256 = Subtarget->hasInt256();
6829 MachineFunction &MF = DAG.getMachineFunction();
6830 bool OptForSize = MF.getFunction()->getAttributes().
6831 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6833 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6835 if (V1IsUndef && V2IsUndef)
6836 return DAG.getUNDEF(VT);
6838 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6840 // Vector shuffle lowering takes 3 steps:
6842 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6843 // narrowing and commutation of operands should be handled.
6844 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6846 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6847 // so the shuffle can be broken into other shuffles and the legalizer can
6848 // try the lowering again.
6850 // The general idea is that no vector_shuffle operation should be left to
6851 // be matched during isel, all of them must be converted to a target specific
6854 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6855 // narrowing and commutation of operands should be handled. The actual code
6856 // doesn't include all of those, work in progress...
6857 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6858 if (NewOp.getNode())
6861 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6863 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6864 // unpckh_undef). Only use pshufd if speed is more important than size.
6865 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6866 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6867 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6868 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6870 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6871 V2IsUndef && MayFoldVectorLoad(V1))
6872 return getMOVDDup(Op, dl, V1, DAG);
6874 if (isMOVHLPS_v_undef_Mask(M, VT))
6875 return getMOVHighToLow(Op, dl, DAG);
6877 // Use to match splats
6878 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6879 (VT == MVT::v2f64 || VT == MVT::v2i64))
6880 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6882 if (isPSHUFDMask(M, VT)) {
6883 // The actual implementation will match the mask in the if above and then
6884 // during isel it can match several different instructions, not only pshufd
6885 // as its name says, sad but true, emulate the behavior for now...
6886 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6887 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6889 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6891 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6892 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6894 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6895 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6898 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6902 if (isPALIGNRMask(M, VT, Subtarget))
6903 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6904 getShufflePALIGNRImmediate(SVOp),
6907 // Check if this can be converted into a logical shift.
6908 bool isLeft = false;
6911 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6912 if (isShift && ShVal.hasOneUse()) {
6913 // If the shifted value has multiple uses, it may be cheaper to use
6914 // v_set0 + movlhps or movhlps, etc.
6915 MVT EltVT = VT.getVectorElementType();
6916 ShAmt *= EltVT.getSizeInBits();
6917 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6920 if (isMOVLMask(M, VT)) {
6921 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6922 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6923 if (!isMOVLPMask(M, VT)) {
6924 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6925 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6927 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6928 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6932 // FIXME: fold these into legal mask.
6933 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6934 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6936 if (isMOVHLPSMask(M, VT))
6937 return getMOVHighToLow(Op, dl, DAG);
6939 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6940 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6942 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6943 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6945 if (isMOVLPMask(M, VT))
6946 return getMOVLP(Op, dl, DAG, HasSSE2);
6948 if (ShouldXformToMOVHLPS(M, VT) ||
6949 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6950 return CommuteVectorShuffle(SVOp, DAG);
6953 // No better options. Use a vshldq / vsrldq.
6954 MVT EltVT = VT.getVectorElementType();
6955 ShAmt *= EltVT.getSizeInBits();
6956 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6959 bool Commuted = false;
6960 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6961 // 1,1,1,1 -> v8i16 though.
6962 V1IsSplat = isSplatVector(V1.getNode());
6963 V2IsSplat = isSplatVector(V2.getNode());
6965 // Canonicalize the splat or undef, if present, to be on the RHS.
6966 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6967 CommuteVectorShuffleMask(M, NumElems);
6969 std::swap(V1IsSplat, V2IsSplat);
6973 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6974 // Shuffling low element of v1 into undef, just return v1.
6977 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6978 // the instruction selector will not match, so get a canonical MOVL with
6979 // swapped operands to undo the commute.
6980 return getMOVL(DAG, dl, VT, V2, V1);
6983 if (isUNPCKLMask(M, VT, HasInt256))
6984 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6986 if (isUNPCKHMask(M, VT, HasInt256))
6987 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6990 // Normalize mask so all entries that point to V2 points to its first
6991 // element then try to match unpck{h|l} again. If match, return a
6992 // new vector_shuffle with the corrected mask.p
6993 SmallVector<int, 8> NewMask(M.begin(), M.end());
6994 NormalizeMask(NewMask, NumElems);
6995 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6996 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6997 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6998 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7002 // Commute is back and try unpck* again.
7003 // FIXME: this seems wrong.
7004 CommuteVectorShuffleMask(M, NumElems);
7006 std::swap(V1IsSplat, V2IsSplat);
7009 if (isUNPCKLMask(M, VT, HasInt256))
7010 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7012 if (isUNPCKHMask(M, VT, HasInt256))
7013 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7016 // Normalize the node to match x86 shuffle ops if needed
7017 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7018 return CommuteVectorShuffle(SVOp, DAG);
7020 // The checks below are all present in isShuffleMaskLegal, but they are
7021 // inlined here right now to enable us to directly emit target specific
7022 // nodes, and remove one by one until they don't return Op anymore.
7024 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7025 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7026 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7027 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7030 if (isPSHUFHWMask(M, VT, HasInt256))
7031 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7032 getShufflePSHUFHWImmediate(SVOp),
7035 if (isPSHUFLWMask(M, VT, HasInt256))
7036 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7037 getShufflePSHUFLWImmediate(SVOp),
7040 if (isSHUFPMask(M, VT, HasFp256))
7041 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7042 getShuffleSHUFImmediate(SVOp), DAG);
7044 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7045 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7046 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7047 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7049 //===--------------------------------------------------------------------===//
7050 // Generate target specific nodes for 128 or 256-bit shuffles only
7051 // supported in the AVX instruction set.
7054 // Handle VMOVDDUPY permutations
7055 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7056 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7058 // Handle VPERMILPS/D* permutations
7059 if (isVPERMILPMask(M, VT, HasFp256)) {
7060 if (HasInt256 && VT == MVT::v8i32)
7061 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7062 getShuffleSHUFImmediate(SVOp), DAG);
7063 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7064 getShuffleSHUFImmediate(SVOp), DAG);
7067 // Handle VPERM2F128/VPERM2I128 permutations
7068 if (isVPERM2X128Mask(M, VT, HasFp256))
7069 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7070 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7072 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7073 if (BlendOp.getNode())
7076 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7077 SmallVector<SDValue, 8> permclMask;
7078 for (unsigned i = 0; i != 8; ++i) {
7079 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7081 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7083 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7084 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7085 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7088 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7089 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7090 getShuffleCLImmediate(SVOp), DAG);
7092 //===--------------------------------------------------------------------===//
7093 // Since no target specific shuffle was selected for this generic one,
7094 // lower it into other known shuffles. FIXME: this isn't true yet, but
7095 // this is the plan.
7098 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7099 if (VT == MVT::v8i16) {
7100 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7101 if (NewOp.getNode())
7105 if (VT == MVT::v16i8) {
7106 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7107 if (NewOp.getNode())
7111 if (VT == MVT::v32i8) {
7112 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7113 if (NewOp.getNode())
7117 // Handle all 128-bit wide vectors with 4 elements, and match them with
7118 // several different shuffle types.
7119 if (NumElems == 4 && VT.is128BitVector())
7120 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7122 // Handle general 256-bit shuffles
7123 if (VT.is256BitVector())
7124 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7129 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7130 MVT VT = Op.getValueType().getSimpleVT();
7133 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7136 if (VT.getSizeInBits() == 8) {
7137 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7138 Op.getOperand(0), Op.getOperand(1));
7139 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7140 DAG.getValueType(VT));
7141 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7144 if (VT.getSizeInBits() == 16) {
7145 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7146 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7148 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7149 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7150 DAG.getNode(ISD::BITCAST, dl,
7154 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7155 Op.getOperand(0), Op.getOperand(1));
7156 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7157 DAG.getValueType(VT));
7158 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7161 if (VT == MVT::f32) {
7162 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7163 // the result back to FR32 register. It's only worth matching if the
7164 // result has a single use which is a store or a bitcast to i32. And in
7165 // the case of a store, it's not worth it if the index is a constant 0,
7166 // because a MOVSSmr can be used instead, which is smaller and faster.
7167 if (!Op.hasOneUse())
7169 SDNode *User = *Op.getNode()->use_begin();
7170 if ((User->getOpcode() != ISD::STORE ||
7171 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7172 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7173 (User->getOpcode() != ISD::BITCAST ||
7174 User->getValueType(0) != MVT::i32))
7176 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7177 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7180 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7183 if (VT == MVT::i32 || VT == MVT::i64) {
7184 // ExtractPS/pextrq works with constant index.
7185 if (isa<ConstantSDNode>(Op.getOperand(1)))
7192 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7193 SelectionDAG &DAG) const {
7194 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7197 SDValue Vec = Op.getOperand(0);
7198 MVT VecVT = Vec.getValueType().getSimpleVT();
7200 // If this is a 256-bit vector result, first extract the 128-bit vector and
7201 // then extract the element from the 128-bit vector.
7202 if (VecVT.is256BitVector()) {
7203 SDLoc dl(Op.getNode());
7204 unsigned NumElems = VecVT.getVectorNumElements();
7205 SDValue Idx = Op.getOperand(1);
7206 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7208 // Get the 128-bit vector.
7209 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7211 if (IdxVal >= NumElems/2)
7212 IdxVal -= NumElems/2;
7213 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7214 DAG.getConstant(IdxVal, MVT::i32));
7217 assert(VecVT.is128BitVector() && "Unexpected vector length");
7219 if (Subtarget->hasSSE41()) {
7220 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7225 MVT VT = Op.getValueType().getSimpleVT();
7227 // TODO: handle v16i8.
7228 if (VT.getSizeInBits() == 16) {
7229 SDValue Vec = Op.getOperand(0);
7230 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7232 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7233 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7234 DAG.getNode(ISD::BITCAST, dl,
7237 // Transform it so it match pextrw which produces a 32-bit result.
7238 MVT EltVT = MVT::i32;
7239 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7240 Op.getOperand(0), Op.getOperand(1));
7241 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7242 DAG.getValueType(VT));
7243 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7246 if (VT.getSizeInBits() == 32) {
7247 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7251 // SHUFPS the element to the lowest double word, then movss.
7252 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7253 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7254 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7255 DAG.getUNDEF(VVT), Mask);
7256 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7257 DAG.getIntPtrConstant(0));
7260 if (VT.getSizeInBits() == 64) {
7261 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7262 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7263 // to match extract_elt for f64.
7264 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7268 // UNPCKHPD the element to the lowest double word, then movsd.
7269 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7270 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7271 int Mask[2] = { 1, -1 };
7272 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7273 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7274 DAG.getUNDEF(VVT), Mask);
7275 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7276 DAG.getIntPtrConstant(0));
7282 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7283 MVT VT = Op.getValueType().getSimpleVT();
7284 MVT EltVT = VT.getVectorElementType();
7287 SDValue N0 = Op.getOperand(0);
7288 SDValue N1 = Op.getOperand(1);
7289 SDValue N2 = Op.getOperand(2);
7291 if (!VT.is128BitVector())
7294 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7295 isa<ConstantSDNode>(N2)) {
7297 if (VT == MVT::v8i16)
7298 Opc = X86ISD::PINSRW;
7299 else if (VT == MVT::v16i8)
7300 Opc = X86ISD::PINSRB;
7302 Opc = X86ISD::PINSRB;
7304 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7306 if (N1.getValueType() != MVT::i32)
7307 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7308 if (N2.getValueType() != MVT::i32)
7309 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7310 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7313 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7314 // Bits [7:6] of the constant are the source select. This will always be
7315 // zero here. The DAG Combiner may combine an extract_elt index into these
7316 // bits. For example (insert (extract, 3), 2) could be matched by putting
7317 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7318 // Bits [5:4] of the constant are the destination select. This is the
7319 // value of the incoming immediate.
7320 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7321 // combine either bitwise AND or insert of float 0.0 to set these bits.
7322 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7323 // Create this as a scalar to vector..
7324 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7325 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7328 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7329 // PINSR* works with constant index.
7336 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7337 MVT VT = Op.getValueType().getSimpleVT();
7338 MVT EltVT = VT.getVectorElementType();
7341 SDValue N0 = Op.getOperand(0);
7342 SDValue N1 = Op.getOperand(1);
7343 SDValue N2 = Op.getOperand(2);
7345 // If this is a 256-bit vector result, first extract the 128-bit vector,
7346 // insert the element into the extracted half and then place it back.
7347 if (VT.is256BitVector()) {
7348 if (!isa<ConstantSDNode>(N2))
7351 // Get the desired 128-bit vector half.
7352 unsigned NumElems = VT.getVectorNumElements();
7353 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7354 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7356 // Insert the element into the desired half.
7357 bool Upper = IdxVal >= NumElems/2;
7358 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7359 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7361 // Insert the changed part back to the 256-bit vector
7362 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7365 if (Subtarget->hasSSE41())
7366 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7368 if (EltVT == MVT::i8)
7371 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7372 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7373 // as its second argument.
7374 if (N1.getValueType() != MVT::i32)
7375 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7376 if (N2.getValueType() != MVT::i32)
7377 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7378 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7383 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7384 LLVMContext *Context = DAG.getContext();
7386 MVT OpVT = Op.getValueType().getSimpleVT();
7388 // If this is a 256-bit vector result, first insert into a 128-bit
7389 // vector and then insert into the 256-bit vector.
7390 if (!OpVT.is128BitVector()) {
7391 // Insert into a 128-bit vector.
7392 EVT VT128 = EVT::getVectorVT(*Context,
7393 OpVT.getVectorElementType(),
7394 OpVT.getVectorNumElements() / 2);
7396 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7398 // Insert the 128-bit vector.
7399 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7402 if (OpVT == MVT::v1i64 &&
7403 Op.getOperand(0).getValueType() == MVT::i64)
7404 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7406 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7407 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7408 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7409 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7412 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7413 // a simple subregister reference or explicit instructions to grab
7414 // upper bits of a vector.
7415 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7416 SelectionDAG &DAG) {
7417 if (Subtarget->hasFp256()) {
7418 SDLoc dl(Op.getNode());
7419 SDValue Vec = Op.getNode()->getOperand(0);
7420 SDValue Idx = Op.getNode()->getOperand(1);
7422 if (Op.getNode()->getValueType(0).is128BitVector() &&
7423 Vec.getNode()->getValueType(0).is256BitVector() &&
7424 isa<ConstantSDNode>(Idx)) {
7425 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7426 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7432 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7433 // simple superregister reference or explicit instructions to insert
7434 // the upper bits of a vector.
7435 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7436 SelectionDAG &DAG) {
7437 if (Subtarget->hasFp256()) {
7438 SDLoc dl(Op.getNode());
7439 SDValue Vec = Op.getNode()->getOperand(0);
7440 SDValue SubVec = Op.getNode()->getOperand(1);
7441 SDValue Idx = Op.getNode()->getOperand(2);
7443 if (Op.getNode()->getValueType(0).is256BitVector() &&
7444 SubVec.getNode()->getValueType(0).is128BitVector() &&
7445 isa<ConstantSDNode>(Idx)) {
7446 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7447 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7453 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7454 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7455 // one of the above mentioned nodes. It has to be wrapped because otherwise
7456 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7457 // be used to form addressing mode. These wrapped nodes will be selected
7460 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7461 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7463 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7465 unsigned char OpFlag = 0;
7466 unsigned WrapperKind = X86ISD::Wrapper;
7467 CodeModel::Model M = getTargetMachine().getCodeModel();
7469 if (Subtarget->isPICStyleRIPRel() &&
7470 (M == CodeModel::Small || M == CodeModel::Kernel))
7471 WrapperKind = X86ISD::WrapperRIP;
7472 else if (Subtarget->isPICStyleGOT())
7473 OpFlag = X86II::MO_GOTOFF;
7474 else if (Subtarget->isPICStyleStubPIC())
7475 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7477 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7479 CP->getOffset(), OpFlag);
7481 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7482 // With PIC, the address is actually $g + Offset.
7484 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7485 DAG.getNode(X86ISD::GlobalBaseReg,
7486 SDLoc(), getPointerTy()),
7493 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7494 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7496 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7498 unsigned char OpFlag = 0;
7499 unsigned WrapperKind = X86ISD::Wrapper;
7500 CodeModel::Model M = getTargetMachine().getCodeModel();
7502 if (Subtarget->isPICStyleRIPRel() &&
7503 (M == CodeModel::Small || M == CodeModel::Kernel))
7504 WrapperKind = X86ISD::WrapperRIP;
7505 else if (Subtarget->isPICStyleGOT())
7506 OpFlag = X86II::MO_GOTOFF;
7507 else if (Subtarget->isPICStyleStubPIC())
7508 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7510 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7513 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7515 // With PIC, the address is actually $g + Offset.
7517 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7518 DAG.getNode(X86ISD::GlobalBaseReg,
7519 SDLoc(), getPointerTy()),
7526 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7527 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7529 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7531 unsigned char OpFlag = 0;
7532 unsigned WrapperKind = X86ISD::Wrapper;
7533 CodeModel::Model M = getTargetMachine().getCodeModel();
7535 if (Subtarget->isPICStyleRIPRel() &&
7536 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7537 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7538 OpFlag = X86II::MO_GOTPCREL;
7539 WrapperKind = X86ISD::WrapperRIP;
7540 } else if (Subtarget->isPICStyleGOT()) {
7541 OpFlag = X86II::MO_GOT;
7542 } else if (Subtarget->isPICStyleStubPIC()) {
7543 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7544 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7545 OpFlag = X86II::MO_DARWIN_NONLAZY;
7548 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7551 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7553 // With PIC, the address is actually $g + Offset.
7554 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7555 !Subtarget->is64Bit()) {
7556 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7557 DAG.getNode(X86ISD::GlobalBaseReg,
7558 SDLoc(), getPointerTy()),
7562 // For symbols that require a load from a stub to get the address, emit the
7564 if (isGlobalStubReference(OpFlag))
7565 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7566 MachinePointerInfo::getGOT(), false, false, false, 0);
7572 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7573 // Create the TargetBlockAddressAddress node.
7574 unsigned char OpFlags =
7575 Subtarget->ClassifyBlockAddressReference();
7576 CodeModel::Model M = getTargetMachine().getCodeModel();
7577 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7578 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7580 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7583 if (Subtarget->isPICStyleRIPRel() &&
7584 (M == CodeModel::Small || M == CodeModel::Kernel))
7585 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7587 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7589 // With PIC, the address is actually $g + Offset.
7590 if (isGlobalRelativeToPICBase(OpFlags)) {
7591 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7592 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7600 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7601 int64_t Offset, SelectionDAG &DAG) const {
7602 // Create the TargetGlobalAddress node, folding in the constant
7603 // offset if it is legal.
7604 unsigned char OpFlags =
7605 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7606 CodeModel::Model M = getTargetMachine().getCodeModel();
7608 if (OpFlags == X86II::MO_NO_FLAG &&
7609 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7610 // A direct static reference to a global.
7611 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7614 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7617 if (Subtarget->isPICStyleRIPRel() &&
7618 (M == CodeModel::Small || M == CodeModel::Kernel))
7619 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7621 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7623 // With PIC, the address is actually $g + Offset.
7624 if (isGlobalRelativeToPICBase(OpFlags)) {
7625 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7626 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7630 // For globals that require a load from a stub to get the address, emit the
7632 if (isGlobalStubReference(OpFlags))
7633 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7634 MachinePointerInfo::getGOT(), false, false, false, 0);
7636 // If there was a non-zero offset that we didn't fold, create an explicit
7639 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7640 DAG.getConstant(Offset, getPointerTy()));
7646 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7647 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7648 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7649 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7653 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7654 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7655 unsigned char OperandFlags, bool LocalDynamic = false) {
7656 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7659 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7660 GA->getValueType(0),
7664 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7668 SDValue Ops[] = { Chain, TGA, *InFlag };
7669 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7671 SDValue Ops[] = { Chain, TGA };
7672 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7675 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7676 MFI->setAdjustsStack(true);
7678 SDValue Flag = Chain.getValue(1);
7679 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7682 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7684 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7687 SDLoc dl(GA); // ? function entry point might be better
7688 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7689 DAG.getNode(X86ISD::GlobalBaseReg,
7690 SDLoc(), PtrVT), InFlag);
7691 InFlag = Chain.getValue(1);
7693 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7696 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7698 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7700 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7701 X86::RAX, X86II::MO_TLSGD);
7704 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7710 // Get the start address of the TLS block for this module.
7711 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7712 .getInfo<X86MachineFunctionInfo>();
7713 MFI->incNumLocalDynamicTLSAccesses();
7717 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7718 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7721 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7722 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7723 InFlag = Chain.getValue(1);
7724 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7725 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7728 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7732 unsigned char OperandFlags = X86II::MO_DTPOFF;
7733 unsigned WrapperKind = X86ISD::Wrapper;
7734 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7735 GA->getValueType(0),
7736 GA->getOffset(), OperandFlags);
7737 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7739 // Add x@dtpoff with the base.
7740 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7743 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7744 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7745 const EVT PtrVT, TLSModel::Model model,
7746 bool is64Bit, bool isPIC) {
7749 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7750 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7751 is64Bit ? 257 : 256));
7753 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7754 DAG.getIntPtrConstant(0),
7755 MachinePointerInfo(Ptr),
7756 false, false, false, 0);
7758 unsigned char OperandFlags = 0;
7759 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7761 unsigned WrapperKind = X86ISD::Wrapper;
7762 if (model == TLSModel::LocalExec) {
7763 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7764 } else if (model == TLSModel::InitialExec) {
7766 OperandFlags = X86II::MO_GOTTPOFF;
7767 WrapperKind = X86ISD::WrapperRIP;
7769 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7772 llvm_unreachable("Unexpected model");
7775 // emit "addl x@ntpoff,%eax" (local exec)
7776 // or "addl x@indntpoff,%eax" (initial exec)
7777 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7778 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7779 GA->getValueType(0),
7780 GA->getOffset(), OperandFlags);
7781 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7783 if (model == TLSModel::InitialExec) {
7784 if (isPIC && !is64Bit) {
7785 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7786 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
7790 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7791 MachinePointerInfo::getGOT(), false, false, false,
7795 // The address of the thread local variable is the add of the thread
7796 // pointer with the offset of the variable.
7797 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7801 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7803 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7804 const GlobalValue *GV = GA->getGlobal();
7806 if (Subtarget->isTargetELF()) {
7807 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7810 case TLSModel::GeneralDynamic:
7811 if (Subtarget->is64Bit())
7812 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7813 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7814 case TLSModel::LocalDynamic:
7815 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7816 Subtarget->is64Bit());
7817 case TLSModel::InitialExec:
7818 case TLSModel::LocalExec:
7819 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7820 Subtarget->is64Bit(),
7821 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7823 llvm_unreachable("Unknown TLS model.");
7826 if (Subtarget->isTargetDarwin()) {
7827 // Darwin only has one model of TLS. Lower to that.
7828 unsigned char OpFlag = 0;
7829 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7830 X86ISD::WrapperRIP : X86ISD::Wrapper;
7832 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7834 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7835 !Subtarget->is64Bit();
7837 OpFlag = X86II::MO_TLVP_PIC_BASE;
7839 OpFlag = X86II::MO_TLVP;
7841 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7842 GA->getValueType(0),
7843 GA->getOffset(), OpFlag);
7844 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7846 // With PIC32, the address is actually $g + Offset.
7848 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7849 DAG.getNode(X86ISD::GlobalBaseReg,
7850 SDLoc(), getPointerTy()),
7853 // Lowering the machine isd will make sure everything is in the right
7855 SDValue Chain = DAG.getEntryNode();
7856 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7857 SDValue Args[] = { Chain, Offset };
7858 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7860 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7861 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7862 MFI->setAdjustsStack(true);
7864 // And our return value (tls address) is in the standard call return value
7866 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7867 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7871 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7872 // Just use the implicit TLS architecture
7873 // Need to generate someting similar to:
7874 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7876 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7877 // mov rcx, qword [rdx+rcx*8]
7878 // mov eax, .tls$:tlsvar
7879 // [rax+rcx] contains the address
7880 // Windows 64bit: gs:0x58
7881 // Windows 32bit: fs:__tls_array
7883 // If GV is an alias then use the aliasee for determining
7884 // thread-localness.
7885 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7886 GV = GA->resolveAliasedGlobal(false);
7888 SDValue Chain = DAG.getEntryNode();
7890 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7891 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7892 // use its literal value of 0x2C.
7893 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7894 ? Type::getInt8PtrTy(*DAG.getContext(),
7896 : Type::getInt32PtrTy(*DAG.getContext(),
7899 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7900 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7901 DAG.getExternalSymbol("_tls_array", getPointerTy()));
7903 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7904 MachinePointerInfo(Ptr),
7905 false, false, false, 0);
7907 // Load the _tls_index variable
7908 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7909 if (Subtarget->is64Bit())
7910 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7911 IDX, MachinePointerInfo(), MVT::i32,
7914 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7915 false, false, false, 0);
7917 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7919 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7921 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7922 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7923 false, false, false, 0);
7925 // Get the offset of start of .tls section
7926 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7927 GA->getValueType(0),
7928 GA->getOffset(), X86II::MO_SECREL);
7929 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7931 // The address of the thread local variable is the add of the thread
7932 // pointer with the offset of the variable.
7933 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7936 llvm_unreachable("TLS not implemented for this target.");
7939 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7940 /// and take a 2 x i32 value to shift plus a shift amount.
7941 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7942 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7943 EVT VT = Op.getValueType();
7944 unsigned VTBits = VT.getSizeInBits();
7946 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7947 SDValue ShOpLo = Op.getOperand(0);
7948 SDValue ShOpHi = Op.getOperand(1);
7949 SDValue ShAmt = Op.getOperand(2);
7950 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7951 DAG.getConstant(VTBits - 1, MVT::i8))
7952 : DAG.getConstant(0, VT);
7955 if (Op.getOpcode() == ISD::SHL_PARTS) {
7956 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7957 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7959 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7960 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7963 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7964 DAG.getConstant(VTBits, MVT::i8));
7965 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7966 AndNode, DAG.getConstant(0, MVT::i8));
7969 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7970 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7971 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7973 if (Op.getOpcode() == ISD::SHL_PARTS) {
7974 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7975 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7977 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7978 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7981 SDValue Ops[2] = { Lo, Hi };
7982 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7985 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7986 SelectionDAG &DAG) const {
7987 EVT SrcVT = Op.getOperand(0).getValueType();
7989 if (SrcVT.isVector())
7992 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7993 "Unknown SINT_TO_FP to lower!");
7995 // These are really Legal; return the operand so the caller accepts it as
7997 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7999 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8000 Subtarget->is64Bit()) {
8005 unsigned Size = SrcVT.getSizeInBits()/8;
8006 MachineFunction &MF = DAG.getMachineFunction();
8007 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8008 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8009 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8011 MachinePointerInfo::getFixedStack(SSFI),
8013 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8016 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8018 SelectionDAG &DAG) const {
8022 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8024 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8026 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8028 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8030 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8031 MachineMemOperand *MMO;
8033 int SSFI = FI->getIndex();
8035 DAG.getMachineFunction()
8036 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8037 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8039 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8040 StackSlot = StackSlot.getOperand(1);
8042 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8043 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8045 Tys, Ops, array_lengthof(Ops),
8049 Chain = Result.getValue(1);
8050 SDValue InFlag = Result.getValue(2);
8052 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8053 // shouldn't be necessary except that RFP cannot be live across
8054 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8055 MachineFunction &MF = DAG.getMachineFunction();
8056 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8057 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8058 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8059 Tys = DAG.getVTList(MVT::Other);
8061 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8063 MachineMemOperand *MMO =
8064 DAG.getMachineFunction()
8065 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8066 MachineMemOperand::MOStore, SSFISize, SSFISize);
8068 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8069 Ops, array_lengthof(Ops),
8070 Op.getValueType(), MMO);
8071 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8072 MachinePointerInfo::getFixedStack(SSFI),
8073 false, false, false, 0);
8079 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8080 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8081 SelectionDAG &DAG) const {
8082 // This algorithm is not obvious. Here it is what we're trying to output:
8085 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8086 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8090 pshufd $0x4e, %xmm0, %xmm1
8096 LLVMContext *Context = DAG.getContext();
8098 // Build some magic constants.
8099 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8100 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8101 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8103 SmallVector<Constant*,2> CV1;
8105 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8106 APInt(64, 0x4330000000000000ULL))));
8108 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8109 APInt(64, 0x4530000000000000ULL))));
8110 Constant *C1 = ConstantVector::get(CV1);
8111 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8113 // Load the 64-bit value into an XMM register.
8114 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8116 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8117 MachinePointerInfo::getConstantPool(),
8118 false, false, false, 16);
8119 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8120 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8123 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8124 MachinePointerInfo::getConstantPool(),
8125 false, false, false, 16);
8126 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8127 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8130 if (Subtarget->hasSSE3()) {
8131 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8132 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8134 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8135 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8137 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8138 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8142 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8143 DAG.getIntPtrConstant(0));
8146 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8147 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8148 SelectionDAG &DAG) const {
8150 // FP constant to bias correct the final result.
8151 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8154 // Load the 32-bit value into an XMM register.
8155 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8158 // Zero out the upper parts of the register.
8159 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8161 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8162 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8163 DAG.getIntPtrConstant(0));
8165 // Or the load with the bias.
8166 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8167 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8168 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8170 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8171 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8172 MVT::v2f64, Bias)));
8173 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8174 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8175 DAG.getIntPtrConstant(0));
8177 // Subtract the bias.
8178 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8180 // Handle final rounding.
8181 EVT DestVT = Op.getValueType();
8183 if (DestVT.bitsLT(MVT::f64))
8184 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8185 DAG.getIntPtrConstant(0));
8186 if (DestVT.bitsGT(MVT::f64))
8187 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8189 // Handle final rounding.
8193 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8194 SelectionDAG &DAG) const {
8195 SDValue N0 = Op.getOperand(0);
8196 EVT SVT = N0.getValueType();
8199 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8200 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8201 "Custom UINT_TO_FP is not supported!");
8203 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8204 SVT.getVectorNumElements());
8205 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8206 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8209 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8210 SelectionDAG &DAG) const {
8211 SDValue N0 = Op.getOperand(0);
8214 if (Op.getValueType().isVector())
8215 return lowerUINT_TO_FP_vec(Op, DAG);
8217 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8218 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8219 // the optimization here.
8220 if (DAG.SignBitIsZero(N0))
8221 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8223 EVT SrcVT = N0.getValueType();
8224 EVT DstVT = Op.getValueType();
8225 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8226 return LowerUINT_TO_FP_i64(Op, DAG);
8227 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8228 return LowerUINT_TO_FP_i32(Op, DAG);
8229 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8232 // Make a 64-bit buffer, and use it to build an FILD.
8233 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8234 if (SrcVT == MVT::i32) {
8235 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8236 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8237 getPointerTy(), StackSlot, WordOff);
8238 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8239 StackSlot, MachinePointerInfo(),
8241 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8242 OffsetSlot, MachinePointerInfo(),
8244 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8248 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8249 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8250 StackSlot, MachinePointerInfo(),
8252 // For i64 source, we need to add the appropriate power of 2 if the input
8253 // was negative. This is the same as the optimization in
8254 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8255 // we must be careful to do the computation in x87 extended precision, not
8256 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8257 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8258 MachineMemOperand *MMO =
8259 DAG.getMachineFunction()
8260 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8261 MachineMemOperand::MOLoad, 8, 8);
8263 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8264 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8265 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8266 array_lengthof(Ops), MVT::i64, MMO);
8268 APInt FF(32, 0x5F800000ULL);
8270 // Check whether the sign bit is set.
8271 SDValue SignSet = DAG.getSetCC(dl,
8272 getSetCCResultType(*DAG.getContext(), MVT::i64),
8273 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8276 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8277 SDValue FudgePtr = DAG.getConstantPool(
8278 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8281 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8282 SDValue Zero = DAG.getIntPtrConstant(0);
8283 SDValue Four = DAG.getIntPtrConstant(4);
8284 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8286 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8288 // Load the value out, extending it from f32 to f80.
8289 // FIXME: Avoid the extend by constructing the right constant pool?
8290 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8291 FudgePtr, MachinePointerInfo::getConstantPool(),
8292 MVT::f32, false, false, 4);
8293 // Extend everything to 80 bits to force it to be done on x87.
8294 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8295 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8298 std::pair<SDValue,SDValue>
8299 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8300 bool IsSigned, bool IsReplace) const {
8303 EVT DstTy = Op.getValueType();
8305 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8306 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8310 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8311 DstTy.getSimpleVT() >= MVT::i16 &&
8312 "Unknown FP_TO_INT to lower!");
8314 // These are really Legal.
8315 if (DstTy == MVT::i32 &&
8316 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8317 return std::make_pair(SDValue(), SDValue());
8318 if (Subtarget->is64Bit() &&
8319 DstTy == MVT::i64 &&
8320 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8321 return std::make_pair(SDValue(), SDValue());
8323 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8324 // stack slot, or into the FTOL runtime function.
8325 MachineFunction &MF = DAG.getMachineFunction();
8326 unsigned MemSize = DstTy.getSizeInBits()/8;
8327 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8328 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8331 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8332 Opc = X86ISD::WIN_FTOL;
8334 switch (DstTy.getSimpleVT().SimpleTy) {
8335 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8336 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8337 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8338 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8341 SDValue Chain = DAG.getEntryNode();
8342 SDValue Value = Op.getOperand(0);
8343 EVT TheVT = Op.getOperand(0).getValueType();
8344 // FIXME This causes a redundant load/store if the SSE-class value is already
8345 // in memory, such as if it is on the callstack.
8346 if (isScalarFPTypeInSSEReg(TheVT)) {
8347 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8348 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8349 MachinePointerInfo::getFixedStack(SSFI),
8351 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8353 Chain, StackSlot, DAG.getValueType(TheVT)
8356 MachineMemOperand *MMO =
8357 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8358 MachineMemOperand::MOLoad, MemSize, MemSize);
8359 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8360 array_lengthof(Ops), DstTy, MMO);
8361 Chain = Value.getValue(1);
8362 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8363 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8366 MachineMemOperand *MMO =
8367 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8368 MachineMemOperand::MOStore, MemSize, MemSize);
8370 if (Opc != X86ISD::WIN_FTOL) {
8371 // Build the FP_TO_INT*_IN_MEM
8372 SDValue Ops[] = { Chain, Value, StackSlot };
8373 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8374 Ops, array_lengthof(Ops), DstTy,
8376 return std::make_pair(FIST, StackSlot);
8378 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8379 DAG.getVTList(MVT::Other, MVT::Glue),
8381 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8382 MVT::i32, ftol.getValue(1));
8383 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8384 MVT::i32, eax.getValue(2));
8385 SDValue Ops[] = { eax, edx };
8386 SDValue pair = IsReplace
8387 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8388 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8389 return std::make_pair(pair, SDValue());
8393 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8394 const X86Subtarget *Subtarget) {
8395 MVT VT = Op->getValueType(0).getSimpleVT();
8396 SDValue In = Op->getOperand(0);
8397 MVT InVT = In.getValueType().getSimpleVT();
8400 // Optimize vectors in AVX mode:
8403 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8404 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8405 // Concat upper and lower parts.
8408 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8409 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8410 // Concat upper and lower parts.
8413 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8414 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8417 if (Subtarget->hasInt256())
8418 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8420 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8421 SDValue Undef = DAG.getUNDEF(InVT);
8422 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8423 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8424 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8426 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8427 VT.getVectorNumElements()/2);
8429 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8430 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8432 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8435 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8436 SelectionDAG &DAG) const {
8437 if (Subtarget->hasFp256()) {
8438 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8445 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8446 SelectionDAG &DAG) const {
8448 MVT VT = Op.getValueType().getSimpleVT();
8449 SDValue In = Op.getOperand(0);
8450 MVT SVT = In.getValueType().getSimpleVT();
8452 if (Subtarget->hasFp256()) {
8453 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8458 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8459 VT.getVectorNumElements() != SVT.getVectorNumElements())
8462 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8464 // AVX2 has better support of integer extending.
8465 if (Subtarget->hasInt256())
8466 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8468 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8469 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8470 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8471 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8472 DAG.getUNDEF(MVT::v8i16),
8475 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8478 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8480 MVT VT = Op.getValueType().getSimpleVT();
8481 SDValue In = Op.getOperand(0);
8482 MVT SVT = In.getValueType().getSimpleVT();
8484 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8485 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8486 if (Subtarget->hasInt256()) {
8487 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8488 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8489 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8491 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8492 DAG.getIntPtrConstant(0));
8495 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8496 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8497 DAG.getIntPtrConstant(0));
8498 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8499 DAG.getIntPtrConstant(2));
8501 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8502 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8505 static const int ShufMask1[] = {0, 2, 0, 0};
8506 SDValue Undef = DAG.getUNDEF(VT);
8507 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8508 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8510 // The MOVLHPS mask:
8511 static const int ShufMask2[] = {0, 1, 4, 5};
8512 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8515 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8516 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8517 if (Subtarget->hasInt256()) {
8518 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8520 SmallVector<SDValue,32> pshufbMask;
8521 for (unsigned i = 0; i < 2; ++i) {
8522 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8523 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8524 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8525 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8526 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8527 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8528 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8529 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8530 for (unsigned j = 0; j < 8; ++j)
8531 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8533 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8534 &pshufbMask[0], 32);
8535 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8536 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8538 static const int ShufMask[] = {0, 2, -1, -1};
8539 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8541 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8542 DAG.getIntPtrConstant(0));
8543 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8546 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8547 DAG.getIntPtrConstant(0));
8549 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8550 DAG.getIntPtrConstant(4));
8552 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8553 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8556 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8557 -1, -1, -1, -1, -1, -1, -1, -1};
8559 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8560 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8561 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8563 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8564 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8566 // The MOVLHPS Mask:
8567 static const int ShufMask2[] = {0, 1, 4, 5};
8568 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8569 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8572 // Handle truncation of V256 to V128 using shuffles.
8573 if (!VT.is128BitVector() || !SVT.is256BitVector())
8576 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8578 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8580 unsigned NumElems = VT.getVectorNumElements();
8581 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8584 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8585 // Prepare truncation shuffle mask
8586 for (unsigned i = 0; i != NumElems; ++i)
8588 SDValue V = DAG.getVectorShuffle(NVT, DL,
8589 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8590 DAG.getUNDEF(NVT), &MaskVec[0]);
8591 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8592 DAG.getIntPtrConstant(0));
8595 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8596 SelectionDAG &DAG) const {
8597 MVT VT = Op.getValueType().getSimpleVT();
8598 if (VT.isVector()) {
8599 if (VT == MVT::v8i16)
8600 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8601 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8602 MVT::v8i32, Op.getOperand(0)));
8606 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8607 /*IsSigned=*/ true, /*IsReplace=*/ false);
8608 SDValue FIST = Vals.first, StackSlot = Vals.second;
8609 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8610 if (FIST.getNode() == 0) return Op;
8612 if (StackSlot.getNode())
8614 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8615 FIST, StackSlot, MachinePointerInfo(),
8616 false, false, false, 0);
8618 // The node is the result.
8622 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8623 SelectionDAG &DAG) const {
8624 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8625 /*IsSigned=*/ false, /*IsReplace=*/ false);
8626 SDValue FIST = Vals.first, StackSlot = Vals.second;
8627 assert(FIST.getNode() && "Unexpected failure");
8629 if (StackSlot.getNode())
8631 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8632 FIST, StackSlot, MachinePointerInfo(),
8633 false, false, false, 0);
8635 // The node is the result.
8639 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8641 MVT VT = Op.getValueType().getSimpleVT();
8642 SDValue In = Op.getOperand(0);
8643 MVT SVT = In.getValueType().getSimpleVT();
8645 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8647 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8648 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8649 In, DAG.getUNDEF(SVT)));
8652 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8653 LLVMContext *Context = DAG.getContext();
8655 MVT VT = Op.getValueType().getSimpleVT();
8657 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8658 if (VT.isVector()) {
8659 EltVT = VT.getVectorElementType();
8660 NumElts = VT.getVectorNumElements();
8663 if (EltVT == MVT::f64)
8664 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8665 APInt(64, ~(1ULL << 63))));
8667 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8668 APInt(32, ~(1U << 31))));
8669 C = ConstantVector::getSplat(NumElts, C);
8670 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8671 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8672 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8673 MachinePointerInfo::getConstantPool(),
8674 false, false, false, Alignment);
8675 if (VT.isVector()) {
8676 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8677 return DAG.getNode(ISD::BITCAST, dl, VT,
8678 DAG.getNode(ISD::AND, dl, ANDVT,
8679 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8681 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8683 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8686 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8687 LLVMContext *Context = DAG.getContext();
8689 MVT VT = Op.getValueType().getSimpleVT();
8691 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8692 if (VT.isVector()) {
8693 EltVT = VT.getVectorElementType();
8694 NumElts = VT.getVectorNumElements();
8697 if (EltVT == MVT::f64)
8698 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8699 APInt(64, 1ULL << 63)));
8701 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8702 APInt(32, 1U << 31)));
8703 C = ConstantVector::getSplat(NumElts, C);
8704 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8705 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8706 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8707 MachinePointerInfo::getConstantPool(),
8708 false, false, false, Alignment);
8709 if (VT.isVector()) {
8710 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8711 return DAG.getNode(ISD::BITCAST, dl, VT,
8712 DAG.getNode(ISD::XOR, dl, XORVT,
8713 DAG.getNode(ISD::BITCAST, dl, XORVT,
8715 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8718 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8721 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8722 LLVMContext *Context = DAG.getContext();
8723 SDValue Op0 = Op.getOperand(0);
8724 SDValue Op1 = Op.getOperand(1);
8726 MVT VT = Op.getValueType().getSimpleVT();
8727 MVT SrcVT = Op1.getValueType().getSimpleVT();
8729 // If second operand is smaller, extend it first.
8730 if (SrcVT.bitsLT(VT)) {
8731 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8734 // And if it is bigger, shrink it first.
8735 if (SrcVT.bitsGT(VT)) {
8736 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8740 // At this point the operands and the result should have the same
8741 // type, and that won't be f80 since that is not custom lowered.
8743 // First get the sign bit of second operand.
8744 SmallVector<Constant*,4> CV;
8745 if (SrcVT == MVT::f64) {
8746 const fltSemantics &Sem = APFloat::IEEEdouble;
8747 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8748 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8750 const fltSemantics &Sem = APFloat::IEEEsingle;
8751 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8752 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8753 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8754 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8756 Constant *C = ConstantVector::get(CV);
8757 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8758 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8759 MachinePointerInfo::getConstantPool(),
8760 false, false, false, 16);
8761 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8763 // Shift sign bit right or left if the two operands have different types.
8764 if (SrcVT.bitsGT(VT)) {
8765 // Op0 is MVT::f32, Op1 is MVT::f64.
8766 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8767 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8768 DAG.getConstant(32, MVT::i32));
8769 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8770 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8771 DAG.getIntPtrConstant(0));
8774 // Clear first operand sign bit.
8776 if (VT == MVT::f64) {
8777 const fltSemantics &Sem = APFloat::IEEEdouble;
8778 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8779 APInt(64, ~(1ULL << 63)))));
8780 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8782 const fltSemantics &Sem = APFloat::IEEEsingle;
8783 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8784 APInt(32, ~(1U << 31)))));
8785 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8786 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8787 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8789 C = ConstantVector::get(CV);
8790 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8791 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8792 MachinePointerInfo::getConstantPool(),
8793 false, false, false, 16);
8794 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8796 // Or the value with the sign bit.
8797 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8800 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8801 SDValue N0 = Op.getOperand(0);
8803 MVT VT = Op.getValueType().getSimpleVT();
8805 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8806 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8807 DAG.getConstant(1, VT));
8808 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8811 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8813 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8814 SelectionDAG &DAG) const {
8815 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8817 if (!Subtarget->hasSSE41())
8820 if (!Op->hasOneUse())
8823 SDNode *N = Op.getNode();
8826 SmallVector<SDValue, 8> Opnds;
8827 DenseMap<SDValue, unsigned> VecInMap;
8828 EVT VT = MVT::Other;
8830 // Recognize a special case where a vector is casted into wide integer to
8832 Opnds.push_back(N->getOperand(0));
8833 Opnds.push_back(N->getOperand(1));
8835 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8836 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
8837 // BFS traverse all OR'd operands.
8838 if (I->getOpcode() == ISD::OR) {
8839 Opnds.push_back(I->getOperand(0));
8840 Opnds.push_back(I->getOperand(1));
8841 // Re-evaluate the number of nodes to be traversed.
8842 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8846 // Quit if a non-EXTRACT_VECTOR_ELT
8847 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8850 // Quit if without a constant index.
8851 SDValue Idx = I->getOperand(1);
8852 if (!isa<ConstantSDNode>(Idx))
8855 SDValue ExtractedFromVec = I->getOperand(0);
8856 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8857 if (M == VecInMap.end()) {
8858 VT = ExtractedFromVec.getValueType();
8859 // Quit if not 128/256-bit vector.
8860 if (!VT.is128BitVector() && !VT.is256BitVector())
8862 // Quit if not the same type.
8863 if (VecInMap.begin() != VecInMap.end() &&
8864 VT != VecInMap.begin()->first.getValueType())
8866 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8868 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8871 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8872 "Not extracted from 128-/256-bit vector.");
8874 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8875 SmallVector<SDValue, 8> VecIns;
8877 for (DenseMap<SDValue, unsigned>::const_iterator
8878 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8879 // Quit if not all elements are used.
8880 if (I->second != FullMask)
8882 VecIns.push_back(I->first);
8885 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8887 // Cast all vectors into TestVT for PTEST.
8888 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8889 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8891 // If more than one full vectors are evaluated, OR them first before PTEST.
8892 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8893 // Each iteration will OR 2 nodes and append the result until there is only
8894 // 1 node left, i.e. the final OR'd value of all vectors.
8895 SDValue LHS = VecIns[Slot];
8896 SDValue RHS = VecIns[Slot + 1];
8897 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8900 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8901 VecIns.back(), VecIns.back());
8904 /// Emit nodes that will be selected as "test Op0,Op0", or something
8906 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8907 SelectionDAG &DAG) const {
8910 // CF and OF aren't always set the way we want. Determine which
8911 // of these we need.
8912 bool NeedCF = false;
8913 bool NeedOF = false;
8916 case X86::COND_A: case X86::COND_AE:
8917 case X86::COND_B: case X86::COND_BE:
8920 case X86::COND_G: case X86::COND_GE:
8921 case X86::COND_L: case X86::COND_LE:
8922 case X86::COND_O: case X86::COND_NO:
8927 // See if we can use the EFLAGS value from the operand instead of
8928 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8929 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8930 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8931 // Emit a CMP with 0, which is the TEST pattern.
8932 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8933 DAG.getConstant(0, Op.getValueType()));
8935 unsigned Opcode = 0;
8936 unsigned NumOperands = 0;
8938 // Truncate operations may prevent the merge of the SETCC instruction
8939 // and the arithmetic intruction before it. Attempt to truncate the operands
8940 // of the arithmetic instruction and use a reduced bit-width instruction.
8941 bool NeedTruncation = false;
8942 SDValue ArithOp = Op;
8943 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8944 SDValue Arith = Op->getOperand(0);
8945 // Both the trunc and the arithmetic op need to have one user each.
8946 if (Arith->hasOneUse())
8947 switch (Arith.getOpcode()) {
8954 NeedTruncation = true;
8960 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8961 // which may be the result of a CAST. We use the variable 'Op', which is the
8962 // non-casted variable when we check for possible users.
8963 switch (ArithOp.getOpcode()) {
8965 // Due to an isel shortcoming, be conservative if this add is likely to be
8966 // selected as part of a load-modify-store instruction. When the root node
8967 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8968 // uses of other nodes in the match, such as the ADD in this case. This
8969 // leads to the ADD being left around and reselected, with the result being
8970 // two adds in the output. Alas, even if none our users are stores, that
8971 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8972 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8973 // climbing the DAG back to the root, and it doesn't seem to be worth the
8975 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8976 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8977 if (UI->getOpcode() != ISD::CopyToReg &&
8978 UI->getOpcode() != ISD::SETCC &&
8979 UI->getOpcode() != ISD::STORE)
8982 if (ConstantSDNode *C =
8983 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8984 // An add of one will be selected as an INC.
8985 if (C->getAPIntValue() == 1) {
8986 Opcode = X86ISD::INC;
8991 // An add of negative one (subtract of one) will be selected as a DEC.
8992 if (C->getAPIntValue().isAllOnesValue()) {
8993 Opcode = X86ISD::DEC;
8999 // Otherwise use a regular EFLAGS-setting add.
9000 Opcode = X86ISD::ADD;
9004 // If the primary and result isn't used, don't bother using X86ISD::AND,
9005 // because a TEST instruction will be better.
9006 bool NonFlagUse = false;
9007 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9008 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9010 unsigned UOpNo = UI.getOperandNo();
9011 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9012 // Look pass truncate.
9013 UOpNo = User->use_begin().getOperandNo();
9014 User = *User->use_begin();
9017 if (User->getOpcode() != ISD::BRCOND &&
9018 User->getOpcode() != ISD::SETCC &&
9019 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9032 // Due to the ISEL shortcoming noted above, be conservative if this op is
9033 // likely to be selected as part of a load-modify-store instruction.
9034 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9035 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9036 if (UI->getOpcode() == ISD::STORE)
9039 // Otherwise use a regular EFLAGS-setting instruction.
9040 switch (ArithOp.getOpcode()) {
9041 default: llvm_unreachable("unexpected operator!");
9042 case ISD::SUB: Opcode = X86ISD::SUB; break;
9043 case ISD::XOR: Opcode = X86ISD::XOR; break;
9044 case ISD::AND: Opcode = X86ISD::AND; break;
9046 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9047 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9048 if (EFLAGS.getNode())
9051 Opcode = X86ISD::OR;
9065 return SDValue(Op.getNode(), 1);
9071 // If we found that truncation is beneficial, perform the truncation and
9073 if (NeedTruncation) {
9074 EVT VT = Op.getValueType();
9075 SDValue WideVal = Op->getOperand(0);
9076 EVT WideVT = WideVal.getValueType();
9077 unsigned ConvertedOp = 0;
9078 // Use a target machine opcode to prevent further DAGCombine
9079 // optimizations that may separate the arithmetic operations
9080 // from the setcc node.
9081 switch (WideVal.getOpcode()) {
9083 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9084 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9085 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9086 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9087 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9091 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9092 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9093 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9094 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9095 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9101 // Emit a CMP with 0, which is the TEST pattern.
9102 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9103 DAG.getConstant(0, Op.getValueType()));
9105 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9106 SmallVector<SDValue, 4> Ops;
9107 for (unsigned i = 0; i != NumOperands; ++i)
9108 Ops.push_back(Op.getOperand(i));
9110 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9111 DAG.ReplaceAllUsesWith(Op, New);
9112 return SDValue(New.getNode(), 1);
9115 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9117 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9118 SelectionDAG &DAG) const {
9119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9120 if (C->getAPIntValue() == 0)
9121 return EmitTest(Op0, X86CC, DAG);
9124 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9125 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9126 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9127 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9128 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9130 return SDValue(Sub.getNode(), 1);
9132 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9135 /// Convert a comparison if required by the subtarget.
9136 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9137 SelectionDAG &DAG) const {
9138 // If the subtarget does not support the FUCOMI instruction, floating-point
9139 // comparisons have to be converted.
9140 if (Subtarget->hasCMov() ||
9141 Cmp.getOpcode() != X86ISD::CMP ||
9142 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9143 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9146 // The instruction selector will select an FUCOM instruction instead of
9147 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9148 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9149 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9151 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9152 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9153 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9154 DAG.getConstant(8, MVT::i8));
9155 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9156 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9159 static bool isAllOnes(SDValue V) {
9160 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9161 return C && C->isAllOnesValue();
9164 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9165 /// if it's possible.
9166 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9167 SDLoc dl, SelectionDAG &DAG) const {
9168 SDValue Op0 = And.getOperand(0);
9169 SDValue Op1 = And.getOperand(1);
9170 if (Op0.getOpcode() == ISD::TRUNCATE)
9171 Op0 = Op0.getOperand(0);
9172 if (Op1.getOpcode() == ISD::TRUNCATE)
9173 Op1 = Op1.getOperand(0);
9176 if (Op1.getOpcode() == ISD::SHL)
9177 std::swap(Op0, Op1);
9178 if (Op0.getOpcode() == ISD::SHL) {
9179 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9180 if (And00C->getZExtValue() == 1) {
9181 // If we looked past a truncate, check that it's only truncating away
9183 unsigned BitWidth = Op0.getValueSizeInBits();
9184 unsigned AndBitWidth = And.getValueSizeInBits();
9185 if (BitWidth > AndBitWidth) {
9187 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9188 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9192 RHS = Op0.getOperand(1);
9194 } else if (Op1.getOpcode() == ISD::Constant) {
9195 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9196 uint64_t AndRHSVal = AndRHS->getZExtValue();
9197 SDValue AndLHS = Op0;
9199 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9200 LHS = AndLHS.getOperand(0);
9201 RHS = AndLHS.getOperand(1);
9204 // Use BT if the immediate can't be encoded in a TEST instruction.
9205 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9207 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9211 if (LHS.getNode()) {
9212 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9213 // instruction. Since the shift amount is in-range-or-undefined, we know
9214 // that doing a bittest on the i32 value is ok. We extend to i32 because
9215 // the encoding for the i16 version is larger than the i32 version.
9216 // Also promote i16 to i32 for performance / code size reason.
9217 if (LHS.getValueType() == MVT::i8 ||
9218 LHS.getValueType() == MVT::i16)
9219 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9221 // If the operand types disagree, extend the shift amount to match. Since
9222 // BT ignores high bits (like shifts) we can use anyextend.
9223 if (LHS.getValueType() != RHS.getValueType())
9224 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9226 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9227 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9228 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9229 DAG.getConstant(Cond, MVT::i8), BT);
9235 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9236 // ones, and then concatenate the result back.
9237 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9238 MVT VT = Op.getValueType().getSimpleVT();
9240 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9241 "Unsupported value type for operation");
9243 unsigned NumElems = VT.getVectorNumElements();
9245 SDValue CC = Op.getOperand(2);
9247 // Extract the LHS vectors
9248 SDValue LHS = Op.getOperand(0);
9249 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9250 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9252 // Extract the RHS vectors
9253 SDValue RHS = Op.getOperand(1);
9254 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9255 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9257 // Issue the operation on the smaller types and concatenate the result back
9258 MVT EltVT = VT.getVectorElementType();
9259 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9260 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9261 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9262 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9265 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9266 SelectionDAG &DAG) {
9268 SDValue Op0 = Op.getOperand(0);
9269 SDValue Op1 = Op.getOperand(1);
9270 SDValue CC = Op.getOperand(2);
9271 MVT VT = Op.getValueType().getSimpleVT();
9272 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9273 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9278 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9279 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9285 // SSE Condition code mapping:
9294 switch (SetCCOpcode) {
9295 default: llvm_unreachable("Unexpected SETCC condition");
9297 case ISD::SETEQ: SSECC = 0; break;
9299 case ISD::SETGT: Swap = true; // Fallthrough
9301 case ISD::SETOLT: SSECC = 1; break;
9303 case ISD::SETGE: Swap = true; // Fallthrough
9305 case ISD::SETOLE: SSECC = 2; break;
9306 case ISD::SETUO: SSECC = 3; break;
9308 case ISD::SETNE: SSECC = 4; break;
9309 case ISD::SETULE: Swap = true; // Fallthrough
9310 case ISD::SETUGE: SSECC = 5; break;
9311 case ISD::SETULT: Swap = true; // Fallthrough
9312 case ISD::SETUGT: SSECC = 6; break;
9313 case ISD::SETO: SSECC = 7; break;
9315 case ISD::SETONE: SSECC = 8; break;
9318 std::swap(Op0, Op1);
9320 // In the two special cases we can't handle, emit two comparisons.
9323 unsigned CombineOpc;
9324 if (SetCCOpcode == ISD::SETUEQ) {
9325 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9327 assert(SetCCOpcode == ISD::SETONE);
9328 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9331 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9332 DAG.getConstant(CC0, MVT::i8));
9333 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9334 DAG.getConstant(CC1, MVT::i8));
9335 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9337 // Handle all other FP comparisons here.
9338 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9339 DAG.getConstant(SSECC, MVT::i8));
9342 // Break 256-bit integer vector compare into smaller ones.
9343 if (VT.is256BitVector() && !Subtarget->hasInt256())
9344 return Lower256IntVSETCC(Op, DAG);
9346 // We are handling one of the integer comparisons here. Since SSE only has
9347 // GT and EQ comparisons for integer, swapping operands and multiple
9348 // operations may be required for some comparisons.
9350 bool Swap = false, Invert = false, FlipSigns = false;
9352 switch (SetCCOpcode) {
9353 default: llvm_unreachable("Unexpected SETCC condition");
9354 case ISD::SETNE: Invert = true;
9355 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9356 case ISD::SETLT: Swap = true;
9357 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9358 case ISD::SETGE: Swap = true;
9359 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9360 case ISD::SETULT: Swap = true;
9361 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9362 case ISD::SETUGE: Swap = true;
9363 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9366 std::swap(Op0, Op1);
9368 // Check that the operation in question is available (most are plain SSE2,
9369 // but PCMPGTQ and PCMPEQQ have different requirements).
9370 if (VT == MVT::v2i64) {
9371 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9372 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9374 // First cast everything to the right type.
9375 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9376 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9378 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9379 // bits of the inputs before performing those operations. The lower
9380 // compare is always unsigned.
9383 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9385 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9386 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9387 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9388 Sign, Zero, Sign, Zero);
9390 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9391 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9393 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9394 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9395 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9397 // Create masks for only the low parts/high parts of the 64 bit integers.
9398 const int MaskHi[] = { 1, 1, 3, 3 };
9399 const int MaskLo[] = { 0, 0, 2, 2 };
9400 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9401 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9402 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9404 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9405 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9408 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9410 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9413 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9414 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9415 // pcmpeqd + pshufd + pand.
9416 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9418 // First cast everything to the right type.
9419 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9420 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9423 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9425 // Make sure the lower and upper halves are both all-ones.
9426 const int Mask[] = { 1, 0, 3, 2 };
9427 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9428 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9431 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9433 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9437 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9438 // bits of the inputs before performing those operations.
9440 EVT EltVT = VT.getVectorElementType();
9441 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9442 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9443 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9446 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9448 // If the logical-not of the result is required, perform that now.
9450 Result = DAG.getNOT(dl, Result, VT);
9455 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9457 MVT VT = Op.getValueType().getSimpleVT();
9459 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9461 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9462 SDValue Op0 = Op.getOperand(0);
9463 SDValue Op1 = Op.getOperand(1);
9465 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9467 // Optimize to BT if possible.
9468 // Lower (X & (1 << N)) == 0 to BT(X, N).
9469 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9470 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9471 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9472 Op1.getOpcode() == ISD::Constant &&
9473 cast<ConstantSDNode>(Op1)->isNullValue() &&
9474 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9475 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9476 if (NewSetCC.getNode())
9480 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9482 if (Op1.getOpcode() == ISD::Constant &&
9483 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9484 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9485 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9487 // If the input is a setcc, then reuse the input setcc or use a new one with
9488 // the inverted condition.
9489 if (Op0.getOpcode() == X86ISD::SETCC) {
9490 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9491 bool Invert = (CC == ISD::SETNE) ^
9492 cast<ConstantSDNode>(Op1)->isNullValue();
9493 if (!Invert) return Op0;
9495 CCode = X86::GetOppositeBranchCondition(CCode);
9496 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9497 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9501 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9502 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9503 if (X86CC == X86::COND_INVALID)
9506 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9507 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9508 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9509 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9512 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9513 static bool isX86LogicalCmp(SDValue Op) {
9514 unsigned Opc = Op.getNode()->getOpcode();
9515 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9516 Opc == X86ISD::SAHF)
9518 if (Op.getResNo() == 1 &&
9519 (Opc == X86ISD::ADD ||
9520 Opc == X86ISD::SUB ||
9521 Opc == X86ISD::ADC ||
9522 Opc == X86ISD::SBB ||
9523 Opc == X86ISD::SMUL ||
9524 Opc == X86ISD::UMUL ||
9525 Opc == X86ISD::INC ||
9526 Opc == X86ISD::DEC ||
9527 Opc == X86ISD::OR ||
9528 Opc == X86ISD::XOR ||
9529 Opc == X86ISD::AND))
9532 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9538 static bool isZero(SDValue V) {
9539 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9540 return C && C->isNullValue();
9543 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9544 if (V.getOpcode() != ISD::TRUNCATE)
9547 SDValue VOp0 = V.getOperand(0);
9548 unsigned InBits = VOp0.getValueSizeInBits();
9549 unsigned Bits = V.getValueSizeInBits();
9550 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9553 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9554 bool addTest = true;
9555 SDValue Cond = Op.getOperand(0);
9556 SDValue Op1 = Op.getOperand(1);
9557 SDValue Op2 = Op.getOperand(2);
9561 if (Cond.getOpcode() == ISD::SETCC) {
9562 SDValue NewCond = LowerSETCC(Cond, DAG);
9563 if (NewCond.getNode())
9567 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9568 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9569 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9570 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9571 if (Cond.getOpcode() == X86ISD::SETCC &&
9572 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9573 isZero(Cond.getOperand(1).getOperand(1))) {
9574 SDValue Cmp = Cond.getOperand(1);
9576 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9578 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9579 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9580 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9582 SDValue CmpOp0 = Cmp.getOperand(0);
9583 // Apply further optimizations for special cases
9584 // (select (x != 0), -1, 0) -> neg & sbb
9585 // (select (x == 0), 0, -1) -> neg & sbb
9586 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9587 if (YC->isNullValue() &&
9588 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9589 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9590 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9591 DAG.getConstant(0, CmpOp0.getValueType()),
9593 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9594 DAG.getConstant(X86::COND_B, MVT::i8),
9595 SDValue(Neg.getNode(), 1));
9599 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9600 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9601 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9603 SDValue Res = // Res = 0 or -1.
9604 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9605 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9607 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9608 Res = DAG.getNOT(DL, Res, Res.getValueType());
9610 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9611 if (N2C == 0 || !N2C->isNullValue())
9612 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9617 // Look past (and (setcc_carry (cmp ...)), 1).
9618 if (Cond.getOpcode() == ISD::AND &&
9619 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9621 if (C && C->getAPIntValue() == 1)
9622 Cond = Cond.getOperand(0);
9625 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9626 // setting operand in place of the X86ISD::SETCC.
9627 unsigned CondOpcode = Cond.getOpcode();
9628 if (CondOpcode == X86ISD::SETCC ||
9629 CondOpcode == X86ISD::SETCC_CARRY) {
9630 CC = Cond.getOperand(0);
9632 SDValue Cmp = Cond.getOperand(1);
9633 unsigned Opc = Cmp.getOpcode();
9634 MVT VT = Op.getValueType().getSimpleVT();
9636 bool IllegalFPCMov = false;
9637 if (VT.isFloatingPoint() && !VT.isVector() &&
9638 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9639 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9641 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9642 Opc == X86ISD::BT) { // FIXME
9646 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9647 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9648 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9649 Cond.getOperand(0).getValueType() != MVT::i8)) {
9650 SDValue LHS = Cond.getOperand(0);
9651 SDValue RHS = Cond.getOperand(1);
9655 switch (CondOpcode) {
9656 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9657 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9658 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9659 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9660 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9661 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9662 default: llvm_unreachable("unexpected overflowing operator");
9664 if (CondOpcode == ISD::UMULO)
9665 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9668 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9670 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9672 if (CondOpcode == ISD::UMULO)
9673 Cond = X86Op.getValue(2);
9675 Cond = X86Op.getValue(1);
9677 CC = DAG.getConstant(X86Cond, MVT::i8);
9682 // Look pass the truncate if the high bits are known zero.
9683 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9684 Cond = Cond.getOperand(0);
9686 // We know the result of AND is compared against zero. Try to match
9688 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9689 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9690 if (NewSetCC.getNode()) {
9691 CC = NewSetCC.getOperand(0);
9692 Cond = NewSetCC.getOperand(1);
9699 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9700 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9703 // a < b ? -1 : 0 -> RES = ~setcc_carry
9704 // a < b ? 0 : -1 -> RES = setcc_carry
9705 // a >= b ? -1 : 0 -> RES = setcc_carry
9706 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9707 if (Cond.getOpcode() == X86ISD::SUB) {
9708 Cond = ConvertCmpIfNecessary(Cond, DAG);
9709 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9711 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9712 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9713 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9714 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9715 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9716 return DAG.getNOT(DL, Res, Res.getValueType());
9721 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9722 // widen the cmov and push the truncate through. This avoids introducing a new
9723 // branch during isel and doesn't add any extensions.
9724 if (Op.getValueType() == MVT::i8 &&
9725 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9726 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9727 if (T1.getValueType() == T2.getValueType() &&
9728 // Blacklist CopyFromReg to avoid partial register stalls.
9729 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9730 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9731 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9732 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9736 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9737 // condition is true.
9738 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9739 SDValue Ops[] = { Op2, Op1, CC, Cond };
9740 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9743 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9744 SelectionDAG &DAG) const {
9745 MVT VT = Op->getValueType(0).getSimpleVT();
9746 SDValue In = Op->getOperand(0);
9747 MVT InVT = In.getValueType().getSimpleVT();
9750 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9751 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9754 if (Subtarget->hasInt256())
9755 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9757 // Optimize vectors in AVX mode
9758 // Sign extend v8i16 to v8i32 and
9761 // Divide input vector into two parts
9762 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9763 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9764 // concat the vectors to original VT
9766 unsigned NumElems = InVT.getVectorNumElements();
9767 SDValue Undef = DAG.getUNDEF(InVT);
9769 SmallVector<int,8> ShufMask1(NumElems, -1);
9770 for (unsigned i = 0; i != NumElems/2; ++i)
9773 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9775 SmallVector<int,8> ShufMask2(NumElems, -1);
9776 for (unsigned i = 0; i != NumElems/2; ++i)
9777 ShufMask2[i] = i + NumElems/2;
9779 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9781 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9782 VT.getVectorNumElements()/2);
9784 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9785 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9787 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9790 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9791 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9792 // from the AND / OR.
9793 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9794 Opc = Op.getOpcode();
9795 if (Opc != ISD::OR && Opc != ISD::AND)
9797 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9798 Op.getOperand(0).hasOneUse() &&
9799 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9800 Op.getOperand(1).hasOneUse());
9803 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9804 // 1 and that the SETCC node has a single use.
9805 static bool isXor1OfSetCC(SDValue Op) {
9806 if (Op.getOpcode() != ISD::XOR)
9808 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9809 if (N1C && N1C->getAPIntValue() == 1) {
9810 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9811 Op.getOperand(0).hasOneUse();
9816 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9817 bool addTest = true;
9818 SDValue Chain = Op.getOperand(0);
9819 SDValue Cond = Op.getOperand(1);
9820 SDValue Dest = Op.getOperand(2);
9823 bool Inverted = false;
9825 if (Cond.getOpcode() == ISD::SETCC) {
9826 // Check for setcc([su]{add,sub,mul}o == 0).
9827 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9828 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9829 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9830 Cond.getOperand(0).getResNo() == 1 &&
9831 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9832 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9833 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9834 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9835 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9836 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9838 Cond = Cond.getOperand(0);
9840 SDValue NewCond = LowerSETCC(Cond, DAG);
9841 if (NewCond.getNode())
9846 // FIXME: LowerXALUO doesn't handle these!!
9847 else if (Cond.getOpcode() == X86ISD::ADD ||
9848 Cond.getOpcode() == X86ISD::SUB ||
9849 Cond.getOpcode() == X86ISD::SMUL ||
9850 Cond.getOpcode() == X86ISD::UMUL)
9851 Cond = LowerXALUO(Cond, DAG);
9854 // Look pass (and (setcc_carry (cmp ...)), 1).
9855 if (Cond.getOpcode() == ISD::AND &&
9856 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9857 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9858 if (C && C->getAPIntValue() == 1)
9859 Cond = Cond.getOperand(0);
9862 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9863 // setting operand in place of the X86ISD::SETCC.
9864 unsigned CondOpcode = Cond.getOpcode();
9865 if (CondOpcode == X86ISD::SETCC ||
9866 CondOpcode == X86ISD::SETCC_CARRY) {
9867 CC = Cond.getOperand(0);
9869 SDValue Cmp = Cond.getOperand(1);
9870 unsigned Opc = Cmp.getOpcode();
9871 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9872 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9876 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9880 // These can only come from an arithmetic instruction with overflow,
9881 // e.g. SADDO, UADDO.
9882 Cond = Cond.getNode()->getOperand(1);
9888 CondOpcode = Cond.getOpcode();
9889 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9890 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9891 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9892 Cond.getOperand(0).getValueType() != MVT::i8)) {
9893 SDValue LHS = Cond.getOperand(0);
9894 SDValue RHS = Cond.getOperand(1);
9898 switch (CondOpcode) {
9899 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9900 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9901 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9902 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9903 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9904 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9905 default: llvm_unreachable("unexpected overflowing operator");
9908 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9909 if (CondOpcode == ISD::UMULO)
9910 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9913 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9915 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9917 if (CondOpcode == ISD::UMULO)
9918 Cond = X86Op.getValue(2);
9920 Cond = X86Op.getValue(1);
9922 CC = DAG.getConstant(X86Cond, MVT::i8);
9926 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9927 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9928 if (CondOpc == ISD::OR) {
9929 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9930 // two branches instead of an explicit OR instruction with a
9932 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9933 isX86LogicalCmp(Cmp)) {
9934 CC = Cond.getOperand(0).getOperand(0);
9935 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9936 Chain, Dest, CC, Cmp);
9937 CC = Cond.getOperand(1).getOperand(0);
9941 } else { // ISD::AND
9942 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9943 // two branches instead of an explicit AND instruction with a
9944 // separate test. However, we only do this if this block doesn't
9945 // have a fall-through edge, because this requires an explicit
9946 // jmp when the condition is false.
9947 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9948 isX86LogicalCmp(Cmp) &&
9949 Op.getNode()->hasOneUse()) {
9950 X86::CondCode CCode =
9951 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9952 CCode = X86::GetOppositeBranchCondition(CCode);
9953 CC = DAG.getConstant(CCode, MVT::i8);
9954 SDNode *User = *Op.getNode()->use_begin();
9955 // Look for an unconditional branch following this conditional branch.
9956 // We need this because we need to reverse the successors in order
9957 // to implement FCMP_OEQ.
9958 if (User->getOpcode() == ISD::BR) {
9959 SDValue FalseBB = User->getOperand(1);
9961 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9962 assert(NewBR == User);
9966 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9967 Chain, Dest, CC, Cmp);
9968 X86::CondCode CCode =
9969 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9970 CCode = X86::GetOppositeBranchCondition(CCode);
9971 CC = DAG.getConstant(CCode, MVT::i8);
9977 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9978 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9979 // It should be transformed during dag combiner except when the condition
9980 // is set by a arithmetics with overflow node.
9981 X86::CondCode CCode =
9982 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9983 CCode = X86::GetOppositeBranchCondition(CCode);
9984 CC = DAG.getConstant(CCode, MVT::i8);
9985 Cond = Cond.getOperand(0).getOperand(1);
9987 } else if (Cond.getOpcode() == ISD::SETCC &&
9988 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9989 // For FCMP_OEQ, we can emit
9990 // two branches instead of an explicit AND instruction with a
9991 // separate test. However, we only do this if this block doesn't
9992 // have a fall-through edge, because this requires an explicit
9993 // jmp when the condition is false.
9994 if (Op.getNode()->hasOneUse()) {
9995 SDNode *User = *Op.getNode()->use_begin();
9996 // Look for an unconditional branch following this conditional branch.
9997 // We need this because we need to reverse the successors in order
9998 // to implement FCMP_OEQ.
9999 if (User->getOpcode() == ISD::BR) {
10000 SDValue FalseBB = User->getOperand(1);
10002 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10003 assert(NewBR == User);
10007 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10008 Cond.getOperand(0), Cond.getOperand(1));
10009 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10010 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10011 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10012 Chain, Dest, CC, Cmp);
10013 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10018 } else if (Cond.getOpcode() == ISD::SETCC &&
10019 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10020 // For FCMP_UNE, we can emit
10021 // two branches instead of an explicit AND instruction with a
10022 // separate test. However, we only do this if this block doesn't
10023 // have a fall-through edge, because this requires an explicit
10024 // jmp when the condition is false.
10025 if (Op.getNode()->hasOneUse()) {
10026 SDNode *User = *Op.getNode()->use_begin();
10027 // Look for an unconditional branch following this conditional branch.
10028 // We need this because we need to reverse the successors in order
10029 // to implement FCMP_UNE.
10030 if (User->getOpcode() == ISD::BR) {
10031 SDValue FalseBB = User->getOperand(1);
10033 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10034 assert(NewBR == User);
10037 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10038 Cond.getOperand(0), Cond.getOperand(1));
10039 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10040 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10041 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10042 Chain, Dest, CC, Cmp);
10043 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10053 // Look pass the truncate if the high bits are known zero.
10054 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10055 Cond = Cond.getOperand(0);
10057 // We know the result of AND is compared against zero. Try to match
10059 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10060 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10061 if (NewSetCC.getNode()) {
10062 CC = NewSetCC.getOperand(0);
10063 Cond = NewSetCC.getOperand(1);
10070 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10071 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10073 Cond = ConvertCmpIfNecessary(Cond, DAG);
10074 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10075 Chain, Dest, CC, Cond);
10078 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10079 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10080 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10081 // that the guard pages used by the OS virtual memory manager are allocated in
10082 // correct sequence.
10084 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10085 SelectionDAG &DAG) const {
10086 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10087 getTargetMachine().Options.EnableSegmentedStacks) &&
10088 "This should be used only on Windows targets or when segmented stacks "
10090 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10094 SDValue Chain = Op.getOperand(0);
10095 SDValue Size = Op.getOperand(1);
10096 // FIXME: Ensure alignment here
10098 bool Is64Bit = Subtarget->is64Bit();
10099 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10101 if (getTargetMachine().Options.EnableSegmentedStacks) {
10102 MachineFunction &MF = DAG.getMachineFunction();
10103 MachineRegisterInfo &MRI = MF.getRegInfo();
10106 // The 64 bit implementation of segmented stacks needs to clobber both r10
10107 // r11. This makes it impossible to use it along with nested parameters.
10108 const Function *F = MF.getFunction();
10110 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10112 if (I->hasNestAttr())
10113 report_fatal_error("Cannot use segmented stacks with functions that "
10114 "have nested arguments.");
10117 const TargetRegisterClass *AddrRegClass =
10118 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10119 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10120 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10121 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10122 DAG.getRegister(Vreg, SPTy));
10123 SDValue Ops1[2] = { Value, Chain };
10124 return DAG.getMergeValues(Ops1, 2, dl);
10127 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10129 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10130 Flag = Chain.getValue(1);
10131 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10133 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10134 Flag = Chain.getValue(1);
10136 const X86RegisterInfo *RegInfo =
10137 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10138 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10141 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10142 return DAG.getMergeValues(Ops1, 2, dl);
10146 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10147 MachineFunction &MF = DAG.getMachineFunction();
10148 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10150 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10153 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10154 // vastart just stores the address of the VarArgsFrameIndex slot into the
10155 // memory location argument.
10156 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10158 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10159 MachinePointerInfo(SV), false, false, 0);
10163 // gp_offset (0 - 6 * 8)
10164 // fp_offset (48 - 48 + 8 * 16)
10165 // overflow_arg_area (point to parameters coming in memory).
10167 SmallVector<SDValue, 8> MemOps;
10168 SDValue FIN = Op.getOperand(1);
10170 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10171 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10173 FIN, MachinePointerInfo(SV), false, false, 0);
10174 MemOps.push_back(Store);
10177 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10178 FIN, DAG.getIntPtrConstant(4));
10179 Store = DAG.getStore(Op.getOperand(0), DL,
10180 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10182 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10183 MemOps.push_back(Store);
10185 // Store ptr to overflow_arg_area
10186 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10187 FIN, DAG.getIntPtrConstant(4));
10188 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10190 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10191 MachinePointerInfo(SV, 8),
10193 MemOps.push_back(Store);
10195 // Store ptr to reg_save_area.
10196 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10197 FIN, DAG.getIntPtrConstant(8));
10198 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10200 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10201 MachinePointerInfo(SV, 16), false, false, 0);
10202 MemOps.push_back(Store);
10203 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10204 &MemOps[0], MemOps.size());
10207 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10208 assert(Subtarget->is64Bit() &&
10209 "LowerVAARG only handles 64-bit va_arg!");
10210 assert((Subtarget->isTargetLinux() ||
10211 Subtarget->isTargetDarwin()) &&
10212 "Unhandled target in LowerVAARG");
10213 assert(Op.getNode()->getNumOperands() == 4);
10214 SDValue Chain = Op.getOperand(0);
10215 SDValue SrcPtr = Op.getOperand(1);
10216 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10217 unsigned Align = Op.getConstantOperandVal(3);
10220 EVT ArgVT = Op.getNode()->getValueType(0);
10221 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10222 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10225 // Decide which area this value should be read from.
10226 // TODO: Implement the AMD64 ABI in its entirety. This simple
10227 // selection mechanism works only for the basic types.
10228 if (ArgVT == MVT::f80) {
10229 llvm_unreachable("va_arg for f80 not yet implemented");
10230 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10231 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10232 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10233 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10235 llvm_unreachable("Unhandled argument type in LowerVAARG");
10238 if (ArgMode == 2) {
10239 // Sanity Check: Make sure using fp_offset makes sense.
10240 assert(!getTargetMachine().Options.UseSoftFloat &&
10241 !(DAG.getMachineFunction()
10242 .getFunction()->getAttributes()
10243 .hasAttribute(AttributeSet::FunctionIndex,
10244 Attribute::NoImplicitFloat)) &&
10245 Subtarget->hasSSE1());
10248 // Insert VAARG_64 node into the DAG
10249 // VAARG_64 returns two values: Variable Argument Address, Chain
10250 SmallVector<SDValue, 11> InstOps;
10251 InstOps.push_back(Chain);
10252 InstOps.push_back(SrcPtr);
10253 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10254 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10255 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10256 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10257 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10258 VTs, &InstOps[0], InstOps.size(),
10260 MachinePointerInfo(SV),
10262 /*Volatile=*/false,
10264 /*WriteMem=*/true);
10265 Chain = VAARG.getValue(1);
10267 // Load the next argument and return it
10268 return DAG.getLoad(ArgVT, dl,
10271 MachinePointerInfo(),
10272 false, false, false, 0);
10275 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10276 SelectionDAG &DAG) {
10277 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10278 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10279 SDValue Chain = Op.getOperand(0);
10280 SDValue DstPtr = Op.getOperand(1);
10281 SDValue SrcPtr = Op.getOperand(2);
10282 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10283 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10286 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10287 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10289 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10292 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10293 // may or may not be a constant. Takes immediate version of shift as input.
10294 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10295 SDValue SrcOp, SDValue ShAmt,
10296 SelectionDAG &DAG) {
10297 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10299 if (isa<ConstantSDNode>(ShAmt)) {
10300 // Constant may be a TargetConstant. Use a regular constant.
10301 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10303 default: llvm_unreachable("Unknown target vector shift node");
10304 case X86ISD::VSHLI:
10305 case X86ISD::VSRLI:
10306 case X86ISD::VSRAI:
10307 return DAG.getNode(Opc, dl, VT, SrcOp,
10308 DAG.getConstant(ShiftAmt, MVT::i32));
10312 // Change opcode to non-immediate version
10314 default: llvm_unreachable("Unknown target vector shift node");
10315 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10316 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10317 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10320 // Need to build a vector containing shift amount
10321 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10324 ShOps[1] = DAG.getConstant(0, MVT::i32);
10325 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10326 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10328 // The return type has to be a 128-bit type with the same element
10329 // type as the input type.
10330 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10331 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10333 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10334 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10337 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10339 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10341 default: return SDValue(); // Don't custom lower most intrinsics.
10342 // Comparison intrinsics.
10343 case Intrinsic::x86_sse_comieq_ss:
10344 case Intrinsic::x86_sse_comilt_ss:
10345 case Intrinsic::x86_sse_comile_ss:
10346 case Intrinsic::x86_sse_comigt_ss:
10347 case Intrinsic::x86_sse_comige_ss:
10348 case Intrinsic::x86_sse_comineq_ss:
10349 case Intrinsic::x86_sse_ucomieq_ss:
10350 case Intrinsic::x86_sse_ucomilt_ss:
10351 case Intrinsic::x86_sse_ucomile_ss:
10352 case Intrinsic::x86_sse_ucomigt_ss:
10353 case Intrinsic::x86_sse_ucomige_ss:
10354 case Intrinsic::x86_sse_ucomineq_ss:
10355 case Intrinsic::x86_sse2_comieq_sd:
10356 case Intrinsic::x86_sse2_comilt_sd:
10357 case Intrinsic::x86_sse2_comile_sd:
10358 case Intrinsic::x86_sse2_comigt_sd:
10359 case Intrinsic::x86_sse2_comige_sd:
10360 case Intrinsic::x86_sse2_comineq_sd:
10361 case Intrinsic::x86_sse2_ucomieq_sd:
10362 case Intrinsic::x86_sse2_ucomilt_sd:
10363 case Intrinsic::x86_sse2_ucomile_sd:
10364 case Intrinsic::x86_sse2_ucomigt_sd:
10365 case Intrinsic::x86_sse2_ucomige_sd:
10366 case Intrinsic::x86_sse2_ucomineq_sd: {
10370 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10371 case Intrinsic::x86_sse_comieq_ss:
10372 case Intrinsic::x86_sse2_comieq_sd:
10373 Opc = X86ISD::COMI;
10376 case Intrinsic::x86_sse_comilt_ss:
10377 case Intrinsic::x86_sse2_comilt_sd:
10378 Opc = X86ISD::COMI;
10381 case Intrinsic::x86_sse_comile_ss:
10382 case Intrinsic::x86_sse2_comile_sd:
10383 Opc = X86ISD::COMI;
10386 case Intrinsic::x86_sse_comigt_ss:
10387 case Intrinsic::x86_sse2_comigt_sd:
10388 Opc = X86ISD::COMI;
10391 case Intrinsic::x86_sse_comige_ss:
10392 case Intrinsic::x86_sse2_comige_sd:
10393 Opc = X86ISD::COMI;
10396 case Intrinsic::x86_sse_comineq_ss:
10397 case Intrinsic::x86_sse2_comineq_sd:
10398 Opc = X86ISD::COMI;
10401 case Intrinsic::x86_sse_ucomieq_ss:
10402 case Intrinsic::x86_sse2_ucomieq_sd:
10403 Opc = X86ISD::UCOMI;
10406 case Intrinsic::x86_sse_ucomilt_ss:
10407 case Intrinsic::x86_sse2_ucomilt_sd:
10408 Opc = X86ISD::UCOMI;
10411 case Intrinsic::x86_sse_ucomile_ss:
10412 case Intrinsic::x86_sse2_ucomile_sd:
10413 Opc = X86ISD::UCOMI;
10416 case Intrinsic::x86_sse_ucomigt_ss:
10417 case Intrinsic::x86_sse2_ucomigt_sd:
10418 Opc = X86ISD::UCOMI;
10421 case Intrinsic::x86_sse_ucomige_ss:
10422 case Intrinsic::x86_sse2_ucomige_sd:
10423 Opc = X86ISD::UCOMI;
10426 case Intrinsic::x86_sse_ucomineq_ss:
10427 case Intrinsic::x86_sse2_ucomineq_sd:
10428 Opc = X86ISD::UCOMI;
10433 SDValue LHS = Op.getOperand(1);
10434 SDValue RHS = Op.getOperand(2);
10435 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10436 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10437 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10438 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10439 DAG.getConstant(X86CC, MVT::i8), Cond);
10440 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10443 // Arithmetic intrinsics.
10444 case Intrinsic::x86_sse2_pmulu_dq:
10445 case Intrinsic::x86_avx2_pmulu_dq:
10446 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10447 Op.getOperand(1), Op.getOperand(2));
10449 // SSE2/AVX2 sub with unsigned saturation intrinsics
10450 case Intrinsic::x86_sse2_psubus_b:
10451 case Intrinsic::x86_sse2_psubus_w:
10452 case Intrinsic::x86_avx2_psubus_b:
10453 case Intrinsic::x86_avx2_psubus_w:
10454 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10455 Op.getOperand(1), Op.getOperand(2));
10457 // SSE3/AVX horizontal add/sub intrinsics
10458 case Intrinsic::x86_sse3_hadd_ps:
10459 case Intrinsic::x86_sse3_hadd_pd:
10460 case Intrinsic::x86_avx_hadd_ps_256:
10461 case Intrinsic::x86_avx_hadd_pd_256:
10462 case Intrinsic::x86_sse3_hsub_ps:
10463 case Intrinsic::x86_sse3_hsub_pd:
10464 case Intrinsic::x86_avx_hsub_ps_256:
10465 case Intrinsic::x86_avx_hsub_pd_256:
10466 case Intrinsic::x86_ssse3_phadd_w_128:
10467 case Intrinsic::x86_ssse3_phadd_d_128:
10468 case Intrinsic::x86_avx2_phadd_w:
10469 case Intrinsic::x86_avx2_phadd_d:
10470 case Intrinsic::x86_ssse3_phsub_w_128:
10471 case Intrinsic::x86_ssse3_phsub_d_128:
10472 case Intrinsic::x86_avx2_phsub_w:
10473 case Intrinsic::x86_avx2_phsub_d: {
10476 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10477 case Intrinsic::x86_sse3_hadd_ps:
10478 case Intrinsic::x86_sse3_hadd_pd:
10479 case Intrinsic::x86_avx_hadd_ps_256:
10480 case Intrinsic::x86_avx_hadd_pd_256:
10481 Opcode = X86ISD::FHADD;
10483 case Intrinsic::x86_sse3_hsub_ps:
10484 case Intrinsic::x86_sse3_hsub_pd:
10485 case Intrinsic::x86_avx_hsub_ps_256:
10486 case Intrinsic::x86_avx_hsub_pd_256:
10487 Opcode = X86ISD::FHSUB;
10489 case Intrinsic::x86_ssse3_phadd_w_128:
10490 case Intrinsic::x86_ssse3_phadd_d_128:
10491 case Intrinsic::x86_avx2_phadd_w:
10492 case Intrinsic::x86_avx2_phadd_d:
10493 Opcode = X86ISD::HADD;
10495 case Intrinsic::x86_ssse3_phsub_w_128:
10496 case Intrinsic::x86_ssse3_phsub_d_128:
10497 case Intrinsic::x86_avx2_phsub_w:
10498 case Intrinsic::x86_avx2_phsub_d:
10499 Opcode = X86ISD::HSUB;
10502 return DAG.getNode(Opcode, dl, Op.getValueType(),
10503 Op.getOperand(1), Op.getOperand(2));
10506 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10507 case Intrinsic::x86_sse2_pmaxu_b:
10508 case Intrinsic::x86_sse41_pmaxuw:
10509 case Intrinsic::x86_sse41_pmaxud:
10510 case Intrinsic::x86_avx2_pmaxu_b:
10511 case Intrinsic::x86_avx2_pmaxu_w:
10512 case Intrinsic::x86_avx2_pmaxu_d:
10513 case Intrinsic::x86_sse2_pminu_b:
10514 case Intrinsic::x86_sse41_pminuw:
10515 case Intrinsic::x86_sse41_pminud:
10516 case Intrinsic::x86_avx2_pminu_b:
10517 case Intrinsic::x86_avx2_pminu_w:
10518 case Intrinsic::x86_avx2_pminu_d:
10519 case Intrinsic::x86_sse41_pmaxsb:
10520 case Intrinsic::x86_sse2_pmaxs_w:
10521 case Intrinsic::x86_sse41_pmaxsd:
10522 case Intrinsic::x86_avx2_pmaxs_b:
10523 case Intrinsic::x86_avx2_pmaxs_w:
10524 case Intrinsic::x86_avx2_pmaxs_d:
10525 case Intrinsic::x86_sse41_pminsb:
10526 case Intrinsic::x86_sse2_pmins_w:
10527 case Intrinsic::x86_sse41_pminsd:
10528 case Intrinsic::x86_avx2_pmins_b:
10529 case Intrinsic::x86_avx2_pmins_w:
10530 case Intrinsic::x86_avx2_pmins_d: {
10533 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10534 case Intrinsic::x86_sse2_pmaxu_b:
10535 case Intrinsic::x86_sse41_pmaxuw:
10536 case Intrinsic::x86_sse41_pmaxud:
10537 case Intrinsic::x86_avx2_pmaxu_b:
10538 case Intrinsic::x86_avx2_pmaxu_w:
10539 case Intrinsic::x86_avx2_pmaxu_d:
10540 Opcode = X86ISD::UMAX;
10542 case Intrinsic::x86_sse2_pminu_b:
10543 case Intrinsic::x86_sse41_pminuw:
10544 case Intrinsic::x86_sse41_pminud:
10545 case Intrinsic::x86_avx2_pminu_b:
10546 case Intrinsic::x86_avx2_pminu_w:
10547 case Intrinsic::x86_avx2_pminu_d:
10548 Opcode = X86ISD::UMIN;
10550 case Intrinsic::x86_sse41_pmaxsb:
10551 case Intrinsic::x86_sse2_pmaxs_w:
10552 case Intrinsic::x86_sse41_pmaxsd:
10553 case Intrinsic::x86_avx2_pmaxs_b:
10554 case Intrinsic::x86_avx2_pmaxs_w:
10555 case Intrinsic::x86_avx2_pmaxs_d:
10556 Opcode = X86ISD::SMAX;
10558 case Intrinsic::x86_sse41_pminsb:
10559 case Intrinsic::x86_sse2_pmins_w:
10560 case Intrinsic::x86_sse41_pminsd:
10561 case Intrinsic::x86_avx2_pmins_b:
10562 case Intrinsic::x86_avx2_pmins_w:
10563 case Intrinsic::x86_avx2_pmins_d:
10564 Opcode = X86ISD::SMIN;
10567 return DAG.getNode(Opcode, dl, Op.getValueType(),
10568 Op.getOperand(1), Op.getOperand(2));
10571 // SSE/SSE2/AVX floating point max/min intrinsics.
10572 case Intrinsic::x86_sse_max_ps:
10573 case Intrinsic::x86_sse2_max_pd:
10574 case Intrinsic::x86_avx_max_ps_256:
10575 case Intrinsic::x86_avx_max_pd_256:
10576 case Intrinsic::x86_sse_min_ps:
10577 case Intrinsic::x86_sse2_min_pd:
10578 case Intrinsic::x86_avx_min_ps_256:
10579 case Intrinsic::x86_avx_min_pd_256: {
10582 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10583 case Intrinsic::x86_sse_max_ps:
10584 case Intrinsic::x86_sse2_max_pd:
10585 case Intrinsic::x86_avx_max_ps_256:
10586 case Intrinsic::x86_avx_max_pd_256:
10587 Opcode = X86ISD::FMAX;
10589 case Intrinsic::x86_sse_min_ps:
10590 case Intrinsic::x86_sse2_min_pd:
10591 case Intrinsic::x86_avx_min_ps_256:
10592 case Intrinsic::x86_avx_min_pd_256:
10593 Opcode = X86ISD::FMIN;
10596 return DAG.getNode(Opcode, dl, Op.getValueType(),
10597 Op.getOperand(1), Op.getOperand(2));
10600 // AVX2 variable shift intrinsics
10601 case Intrinsic::x86_avx2_psllv_d:
10602 case Intrinsic::x86_avx2_psllv_q:
10603 case Intrinsic::x86_avx2_psllv_d_256:
10604 case Intrinsic::x86_avx2_psllv_q_256:
10605 case Intrinsic::x86_avx2_psrlv_d:
10606 case Intrinsic::x86_avx2_psrlv_q:
10607 case Intrinsic::x86_avx2_psrlv_d_256:
10608 case Intrinsic::x86_avx2_psrlv_q_256:
10609 case Intrinsic::x86_avx2_psrav_d:
10610 case Intrinsic::x86_avx2_psrav_d_256: {
10613 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10614 case Intrinsic::x86_avx2_psllv_d:
10615 case Intrinsic::x86_avx2_psllv_q:
10616 case Intrinsic::x86_avx2_psllv_d_256:
10617 case Intrinsic::x86_avx2_psllv_q_256:
10620 case Intrinsic::x86_avx2_psrlv_d:
10621 case Intrinsic::x86_avx2_psrlv_q:
10622 case Intrinsic::x86_avx2_psrlv_d_256:
10623 case Intrinsic::x86_avx2_psrlv_q_256:
10626 case Intrinsic::x86_avx2_psrav_d:
10627 case Intrinsic::x86_avx2_psrav_d_256:
10631 return DAG.getNode(Opcode, dl, Op.getValueType(),
10632 Op.getOperand(1), Op.getOperand(2));
10635 case Intrinsic::x86_ssse3_pshuf_b_128:
10636 case Intrinsic::x86_avx2_pshuf_b:
10637 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10638 Op.getOperand(1), Op.getOperand(2));
10640 case Intrinsic::x86_ssse3_psign_b_128:
10641 case Intrinsic::x86_ssse3_psign_w_128:
10642 case Intrinsic::x86_ssse3_psign_d_128:
10643 case Intrinsic::x86_avx2_psign_b:
10644 case Intrinsic::x86_avx2_psign_w:
10645 case Intrinsic::x86_avx2_psign_d:
10646 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10647 Op.getOperand(1), Op.getOperand(2));
10649 case Intrinsic::x86_sse41_insertps:
10650 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10651 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10653 case Intrinsic::x86_avx_vperm2f128_ps_256:
10654 case Intrinsic::x86_avx_vperm2f128_pd_256:
10655 case Intrinsic::x86_avx_vperm2f128_si_256:
10656 case Intrinsic::x86_avx2_vperm2i128:
10657 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10658 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10660 case Intrinsic::x86_avx2_permd:
10661 case Intrinsic::x86_avx2_permps:
10662 // Operands intentionally swapped. Mask is last operand to intrinsic,
10663 // but second operand for node/intruction.
10664 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10665 Op.getOperand(2), Op.getOperand(1));
10667 case Intrinsic::x86_sse_sqrt_ps:
10668 case Intrinsic::x86_sse2_sqrt_pd:
10669 case Intrinsic::x86_avx_sqrt_ps_256:
10670 case Intrinsic::x86_avx_sqrt_pd_256:
10671 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10673 // ptest and testp intrinsics. The intrinsic these come from are designed to
10674 // return an integer value, not just an instruction so lower it to the ptest
10675 // or testp pattern and a setcc for the result.
10676 case Intrinsic::x86_sse41_ptestz:
10677 case Intrinsic::x86_sse41_ptestc:
10678 case Intrinsic::x86_sse41_ptestnzc:
10679 case Intrinsic::x86_avx_ptestz_256:
10680 case Intrinsic::x86_avx_ptestc_256:
10681 case Intrinsic::x86_avx_ptestnzc_256:
10682 case Intrinsic::x86_avx_vtestz_ps:
10683 case Intrinsic::x86_avx_vtestc_ps:
10684 case Intrinsic::x86_avx_vtestnzc_ps:
10685 case Intrinsic::x86_avx_vtestz_pd:
10686 case Intrinsic::x86_avx_vtestc_pd:
10687 case Intrinsic::x86_avx_vtestnzc_pd:
10688 case Intrinsic::x86_avx_vtestz_ps_256:
10689 case Intrinsic::x86_avx_vtestc_ps_256:
10690 case Intrinsic::x86_avx_vtestnzc_ps_256:
10691 case Intrinsic::x86_avx_vtestz_pd_256:
10692 case Intrinsic::x86_avx_vtestc_pd_256:
10693 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10694 bool IsTestPacked = false;
10697 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10698 case Intrinsic::x86_avx_vtestz_ps:
10699 case Intrinsic::x86_avx_vtestz_pd:
10700 case Intrinsic::x86_avx_vtestz_ps_256:
10701 case Intrinsic::x86_avx_vtestz_pd_256:
10702 IsTestPacked = true; // Fallthrough
10703 case Intrinsic::x86_sse41_ptestz:
10704 case Intrinsic::x86_avx_ptestz_256:
10706 X86CC = X86::COND_E;
10708 case Intrinsic::x86_avx_vtestc_ps:
10709 case Intrinsic::x86_avx_vtestc_pd:
10710 case Intrinsic::x86_avx_vtestc_ps_256:
10711 case Intrinsic::x86_avx_vtestc_pd_256:
10712 IsTestPacked = true; // Fallthrough
10713 case Intrinsic::x86_sse41_ptestc:
10714 case Intrinsic::x86_avx_ptestc_256:
10716 X86CC = X86::COND_B;
10718 case Intrinsic::x86_avx_vtestnzc_ps:
10719 case Intrinsic::x86_avx_vtestnzc_pd:
10720 case Intrinsic::x86_avx_vtestnzc_ps_256:
10721 case Intrinsic::x86_avx_vtestnzc_pd_256:
10722 IsTestPacked = true; // Fallthrough
10723 case Intrinsic::x86_sse41_ptestnzc:
10724 case Intrinsic::x86_avx_ptestnzc_256:
10726 X86CC = X86::COND_A;
10730 SDValue LHS = Op.getOperand(1);
10731 SDValue RHS = Op.getOperand(2);
10732 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10733 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10734 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10735 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10736 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10739 // SSE/AVX shift intrinsics
10740 case Intrinsic::x86_sse2_psll_w:
10741 case Intrinsic::x86_sse2_psll_d:
10742 case Intrinsic::x86_sse2_psll_q:
10743 case Intrinsic::x86_avx2_psll_w:
10744 case Intrinsic::x86_avx2_psll_d:
10745 case Intrinsic::x86_avx2_psll_q:
10746 case Intrinsic::x86_sse2_psrl_w:
10747 case Intrinsic::x86_sse2_psrl_d:
10748 case Intrinsic::x86_sse2_psrl_q:
10749 case Intrinsic::x86_avx2_psrl_w:
10750 case Intrinsic::x86_avx2_psrl_d:
10751 case Intrinsic::x86_avx2_psrl_q:
10752 case Intrinsic::x86_sse2_psra_w:
10753 case Intrinsic::x86_sse2_psra_d:
10754 case Intrinsic::x86_avx2_psra_w:
10755 case Intrinsic::x86_avx2_psra_d: {
10758 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10759 case Intrinsic::x86_sse2_psll_w:
10760 case Intrinsic::x86_sse2_psll_d:
10761 case Intrinsic::x86_sse2_psll_q:
10762 case Intrinsic::x86_avx2_psll_w:
10763 case Intrinsic::x86_avx2_psll_d:
10764 case Intrinsic::x86_avx2_psll_q:
10765 Opcode = X86ISD::VSHL;
10767 case Intrinsic::x86_sse2_psrl_w:
10768 case Intrinsic::x86_sse2_psrl_d:
10769 case Intrinsic::x86_sse2_psrl_q:
10770 case Intrinsic::x86_avx2_psrl_w:
10771 case Intrinsic::x86_avx2_psrl_d:
10772 case Intrinsic::x86_avx2_psrl_q:
10773 Opcode = X86ISD::VSRL;
10775 case Intrinsic::x86_sse2_psra_w:
10776 case Intrinsic::x86_sse2_psra_d:
10777 case Intrinsic::x86_avx2_psra_w:
10778 case Intrinsic::x86_avx2_psra_d:
10779 Opcode = X86ISD::VSRA;
10782 return DAG.getNode(Opcode, dl, Op.getValueType(),
10783 Op.getOperand(1), Op.getOperand(2));
10786 // SSE/AVX immediate shift intrinsics
10787 case Intrinsic::x86_sse2_pslli_w:
10788 case Intrinsic::x86_sse2_pslli_d:
10789 case Intrinsic::x86_sse2_pslli_q:
10790 case Intrinsic::x86_avx2_pslli_w:
10791 case Intrinsic::x86_avx2_pslli_d:
10792 case Intrinsic::x86_avx2_pslli_q:
10793 case Intrinsic::x86_sse2_psrli_w:
10794 case Intrinsic::x86_sse2_psrli_d:
10795 case Intrinsic::x86_sse2_psrli_q:
10796 case Intrinsic::x86_avx2_psrli_w:
10797 case Intrinsic::x86_avx2_psrli_d:
10798 case Intrinsic::x86_avx2_psrli_q:
10799 case Intrinsic::x86_sse2_psrai_w:
10800 case Intrinsic::x86_sse2_psrai_d:
10801 case Intrinsic::x86_avx2_psrai_w:
10802 case Intrinsic::x86_avx2_psrai_d: {
10805 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10806 case Intrinsic::x86_sse2_pslli_w:
10807 case Intrinsic::x86_sse2_pslli_d:
10808 case Intrinsic::x86_sse2_pslli_q:
10809 case Intrinsic::x86_avx2_pslli_w:
10810 case Intrinsic::x86_avx2_pslli_d:
10811 case Intrinsic::x86_avx2_pslli_q:
10812 Opcode = X86ISD::VSHLI;
10814 case Intrinsic::x86_sse2_psrli_w:
10815 case Intrinsic::x86_sse2_psrli_d:
10816 case Intrinsic::x86_sse2_psrli_q:
10817 case Intrinsic::x86_avx2_psrli_w:
10818 case Intrinsic::x86_avx2_psrli_d:
10819 case Intrinsic::x86_avx2_psrli_q:
10820 Opcode = X86ISD::VSRLI;
10822 case Intrinsic::x86_sse2_psrai_w:
10823 case Intrinsic::x86_sse2_psrai_d:
10824 case Intrinsic::x86_avx2_psrai_w:
10825 case Intrinsic::x86_avx2_psrai_d:
10826 Opcode = X86ISD::VSRAI;
10829 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10830 Op.getOperand(1), Op.getOperand(2), DAG);
10833 case Intrinsic::x86_sse42_pcmpistria128:
10834 case Intrinsic::x86_sse42_pcmpestria128:
10835 case Intrinsic::x86_sse42_pcmpistric128:
10836 case Intrinsic::x86_sse42_pcmpestric128:
10837 case Intrinsic::x86_sse42_pcmpistrio128:
10838 case Intrinsic::x86_sse42_pcmpestrio128:
10839 case Intrinsic::x86_sse42_pcmpistris128:
10840 case Intrinsic::x86_sse42_pcmpestris128:
10841 case Intrinsic::x86_sse42_pcmpistriz128:
10842 case Intrinsic::x86_sse42_pcmpestriz128: {
10846 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10847 case Intrinsic::x86_sse42_pcmpistria128:
10848 Opcode = X86ISD::PCMPISTRI;
10849 X86CC = X86::COND_A;
10851 case Intrinsic::x86_sse42_pcmpestria128:
10852 Opcode = X86ISD::PCMPESTRI;
10853 X86CC = X86::COND_A;
10855 case Intrinsic::x86_sse42_pcmpistric128:
10856 Opcode = X86ISD::PCMPISTRI;
10857 X86CC = X86::COND_B;
10859 case Intrinsic::x86_sse42_pcmpestric128:
10860 Opcode = X86ISD::PCMPESTRI;
10861 X86CC = X86::COND_B;
10863 case Intrinsic::x86_sse42_pcmpistrio128:
10864 Opcode = X86ISD::PCMPISTRI;
10865 X86CC = X86::COND_O;
10867 case Intrinsic::x86_sse42_pcmpestrio128:
10868 Opcode = X86ISD::PCMPESTRI;
10869 X86CC = X86::COND_O;
10871 case Intrinsic::x86_sse42_pcmpistris128:
10872 Opcode = X86ISD::PCMPISTRI;
10873 X86CC = X86::COND_S;
10875 case Intrinsic::x86_sse42_pcmpestris128:
10876 Opcode = X86ISD::PCMPESTRI;
10877 X86CC = X86::COND_S;
10879 case Intrinsic::x86_sse42_pcmpistriz128:
10880 Opcode = X86ISD::PCMPISTRI;
10881 X86CC = X86::COND_E;
10883 case Intrinsic::x86_sse42_pcmpestriz128:
10884 Opcode = X86ISD::PCMPESTRI;
10885 X86CC = X86::COND_E;
10888 SmallVector<SDValue, 5> NewOps;
10889 NewOps.append(Op->op_begin()+1, Op->op_end());
10890 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10891 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10892 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10893 DAG.getConstant(X86CC, MVT::i8),
10894 SDValue(PCMP.getNode(), 1));
10895 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10898 case Intrinsic::x86_sse42_pcmpistri128:
10899 case Intrinsic::x86_sse42_pcmpestri128: {
10901 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10902 Opcode = X86ISD::PCMPISTRI;
10904 Opcode = X86ISD::PCMPESTRI;
10906 SmallVector<SDValue, 5> NewOps;
10907 NewOps.append(Op->op_begin()+1, Op->op_end());
10908 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10909 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10911 case Intrinsic::x86_fma_vfmadd_ps:
10912 case Intrinsic::x86_fma_vfmadd_pd:
10913 case Intrinsic::x86_fma_vfmsub_ps:
10914 case Intrinsic::x86_fma_vfmsub_pd:
10915 case Intrinsic::x86_fma_vfnmadd_ps:
10916 case Intrinsic::x86_fma_vfnmadd_pd:
10917 case Intrinsic::x86_fma_vfnmsub_ps:
10918 case Intrinsic::x86_fma_vfnmsub_pd:
10919 case Intrinsic::x86_fma_vfmaddsub_ps:
10920 case Intrinsic::x86_fma_vfmaddsub_pd:
10921 case Intrinsic::x86_fma_vfmsubadd_ps:
10922 case Intrinsic::x86_fma_vfmsubadd_pd:
10923 case Intrinsic::x86_fma_vfmadd_ps_256:
10924 case Intrinsic::x86_fma_vfmadd_pd_256:
10925 case Intrinsic::x86_fma_vfmsub_ps_256:
10926 case Intrinsic::x86_fma_vfmsub_pd_256:
10927 case Intrinsic::x86_fma_vfnmadd_ps_256:
10928 case Intrinsic::x86_fma_vfnmadd_pd_256:
10929 case Intrinsic::x86_fma_vfnmsub_ps_256:
10930 case Intrinsic::x86_fma_vfnmsub_pd_256:
10931 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10932 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10933 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10934 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10937 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10938 case Intrinsic::x86_fma_vfmadd_ps:
10939 case Intrinsic::x86_fma_vfmadd_pd:
10940 case Intrinsic::x86_fma_vfmadd_ps_256:
10941 case Intrinsic::x86_fma_vfmadd_pd_256:
10942 Opc = X86ISD::FMADD;
10944 case Intrinsic::x86_fma_vfmsub_ps:
10945 case Intrinsic::x86_fma_vfmsub_pd:
10946 case Intrinsic::x86_fma_vfmsub_ps_256:
10947 case Intrinsic::x86_fma_vfmsub_pd_256:
10948 Opc = X86ISD::FMSUB;
10950 case Intrinsic::x86_fma_vfnmadd_ps:
10951 case Intrinsic::x86_fma_vfnmadd_pd:
10952 case Intrinsic::x86_fma_vfnmadd_ps_256:
10953 case Intrinsic::x86_fma_vfnmadd_pd_256:
10954 Opc = X86ISD::FNMADD;
10956 case Intrinsic::x86_fma_vfnmsub_ps:
10957 case Intrinsic::x86_fma_vfnmsub_pd:
10958 case Intrinsic::x86_fma_vfnmsub_ps_256:
10959 case Intrinsic::x86_fma_vfnmsub_pd_256:
10960 Opc = X86ISD::FNMSUB;
10962 case Intrinsic::x86_fma_vfmaddsub_ps:
10963 case Intrinsic::x86_fma_vfmaddsub_pd:
10964 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10965 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10966 Opc = X86ISD::FMADDSUB;
10968 case Intrinsic::x86_fma_vfmsubadd_ps:
10969 case Intrinsic::x86_fma_vfmsubadd_pd:
10970 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10971 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10972 Opc = X86ISD::FMSUBADD;
10976 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10977 Op.getOperand(2), Op.getOperand(3));
10982 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10984 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10986 default: return SDValue(); // Don't custom lower most intrinsics.
10988 // RDRAND/RDSEED intrinsics.
10989 case Intrinsic::x86_rdrand_16:
10990 case Intrinsic::x86_rdrand_32:
10991 case Intrinsic::x86_rdrand_64:
10992 case Intrinsic::x86_rdseed_16:
10993 case Intrinsic::x86_rdseed_32:
10994 case Intrinsic::x86_rdseed_64: {
10995 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10996 IntNo == Intrinsic::x86_rdseed_32 ||
10997 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10999 // Emit the node with the right value type.
11000 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11001 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11003 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11004 // Otherwise return the value from Rand, which is always 0, casted to i32.
11005 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11006 DAG.getConstant(1, Op->getValueType(1)),
11007 DAG.getConstant(X86::COND_B, MVT::i32),
11008 SDValue(Result.getNode(), 1) };
11009 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11010 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11011 Ops, array_lengthof(Ops));
11013 // Return { result, isValid, chain }.
11014 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11015 SDValue(Result.getNode(), 2));
11018 // XTEST intrinsics.
11019 case Intrinsic::x86_xtest: {
11020 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11021 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11022 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11023 DAG.getConstant(X86::COND_NE, MVT::i8),
11025 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11026 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11027 Ret, SDValue(InTrans.getNode(), 1));
11032 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11033 SelectionDAG &DAG) const {
11034 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11035 MFI->setReturnAddressIsTaken(true);
11037 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11039 EVT PtrVT = getPointerTy();
11042 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11043 const X86RegisterInfo *RegInfo =
11044 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11045 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11046 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11047 DAG.getNode(ISD::ADD, dl, PtrVT,
11048 FrameAddr, Offset),
11049 MachinePointerInfo(), false, false, false, 0);
11052 // Just load the return address.
11053 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11054 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11055 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11058 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11059 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11060 MFI->setFrameAddressIsTaken(true);
11062 EVT VT = Op.getValueType();
11063 SDLoc dl(Op); // FIXME probably not meaningful
11064 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11065 const X86RegisterInfo *RegInfo =
11066 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11067 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11068 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11069 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11070 "Invalid Frame Register!");
11071 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11073 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11074 MachinePointerInfo(),
11075 false, false, false, 0);
11079 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11080 SelectionDAG &DAG) const {
11081 const X86RegisterInfo *RegInfo =
11082 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11083 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11086 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11087 SDValue Chain = Op.getOperand(0);
11088 SDValue Offset = Op.getOperand(1);
11089 SDValue Handler = Op.getOperand(2);
11092 EVT PtrVT = getPointerTy();
11093 const X86RegisterInfo *RegInfo =
11094 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11095 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11096 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11097 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11098 "Invalid Frame Register!");
11099 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11100 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11102 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11103 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11104 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11105 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11107 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11109 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11110 DAG.getRegister(StoreAddrReg, PtrVT));
11113 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11114 SelectionDAG &DAG) const {
11116 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11117 DAG.getVTList(MVT::i32, MVT::Other),
11118 Op.getOperand(0), Op.getOperand(1));
11121 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11122 SelectionDAG &DAG) const {
11124 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11125 Op.getOperand(0), Op.getOperand(1));
11128 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11129 return Op.getOperand(0);
11132 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11133 SelectionDAG &DAG) const {
11134 SDValue Root = Op.getOperand(0);
11135 SDValue Trmp = Op.getOperand(1); // trampoline
11136 SDValue FPtr = Op.getOperand(2); // nested function
11137 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11140 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11141 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11143 if (Subtarget->is64Bit()) {
11144 SDValue OutChains[6];
11146 // Large code-model.
11147 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11148 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11150 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11151 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11153 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11155 // Load the pointer to the nested function into R11.
11156 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11157 SDValue Addr = Trmp;
11158 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11159 Addr, MachinePointerInfo(TrmpAddr),
11162 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11163 DAG.getConstant(2, MVT::i64));
11164 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11165 MachinePointerInfo(TrmpAddr, 2),
11168 // Load the 'nest' parameter value into R10.
11169 // R10 is specified in X86CallingConv.td
11170 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11171 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11172 DAG.getConstant(10, MVT::i64));
11173 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11174 Addr, MachinePointerInfo(TrmpAddr, 10),
11177 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11178 DAG.getConstant(12, MVT::i64));
11179 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11180 MachinePointerInfo(TrmpAddr, 12),
11183 // Jump to the nested function.
11184 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11185 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11186 DAG.getConstant(20, MVT::i64));
11187 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11188 Addr, MachinePointerInfo(TrmpAddr, 20),
11191 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11192 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11193 DAG.getConstant(22, MVT::i64));
11194 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11195 MachinePointerInfo(TrmpAddr, 22),
11198 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11200 const Function *Func =
11201 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11202 CallingConv::ID CC = Func->getCallingConv();
11207 llvm_unreachable("Unsupported calling convention");
11208 case CallingConv::C:
11209 case CallingConv::X86_StdCall: {
11210 // Pass 'nest' parameter in ECX.
11211 // Must be kept in sync with X86CallingConv.td
11212 NestReg = X86::ECX;
11214 // Check that ECX wasn't needed by an 'inreg' parameter.
11215 FunctionType *FTy = Func->getFunctionType();
11216 const AttributeSet &Attrs = Func->getAttributes();
11218 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11219 unsigned InRegCount = 0;
11222 for (FunctionType::param_iterator I = FTy->param_begin(),
11223 E = FTy->param_end(); I != E; ++I, ++Idx)
11224 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11225 // FIXME: should only count parameters that are lowered to integers.
11226 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11228 if (InRegCount > 2) {
11229 report_fatal_error("Nest register in use - reduce number of inreg"
11235 case CallingConv::X86_FastCall:
11236 case CallingConv::X86_ThisCall:
11237 case CallingConv::Fast:
11238 // Pass 'nest' parameter in EAX.
11239 // Must be kept in sync with X86CallingConv.td
11240 NestReg = X86::EAX;
11244 SDValue OutChains[4];
11245 SDValue Addr, Disp;
11247 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11248 DAG.getConstant(10, MVT::i32));
11249 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11251 // This is storing the opcode for MOV32ri.
11252 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11253 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11254 OutChains[0] = DAG.getStore(Root, dl,
11255 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11256 Trmp, MachinePointerInfo(TrmpAddr),
11259 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11260 DAG.getConstant(1, MVT::i32));
11261 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11262 MachinePointerInfo(TrmpAddr, 1),
11265 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11266 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11267 DAG.getConstant(5, MVT::i32));
11268 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11269 MachinePointerInfo(TrmpAddr, 5),
11272 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11273 DAG.getConstant(6, MVT::i32));
11274 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11275 MachinePointerInfo(TrmpAddr, 6),
11278 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11282 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11283 SelectionDAG &DAG) const {
11285 The rounding mode is in bits 11:10 of FPSR, and has the following
11287 00 Round to nearest
11292 FLT_ROUNDS, on the other hand, expects the following:
11299 To perform the conversion, we do:
11300 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11303 MachineFunction &MF = DAG.getMachineFunction();
11304 const TargetMachine &TM = MF.getTarget();
11305 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11306 unsigned StackAlignment = TFI.getStackAlignment();
11307 EVT VT = Op.getValueType();
11310 // Save FP Control Word to stack slot
11311 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11312 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11314 MachineMemOperand *MMO =
11315 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11316 MachineMemOperand::MOStore, 2, 2);
11318 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11319 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11320 DAG.getVTList(MVT::Other),
11321 Ops, array_lengthof(Ops), MVT::i16,
11324 // Load FP Control Word from stack slot
11325 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11326 MachinePointerInfo(), false, false, false, 0);
11328 // Transform as necessary
11330 DAG.getNode(ISD::SRL, DL, MVT::i16,
11331 DAG.getNode(ISD::AND, DL, MVT::i16,
11332 CWD, DAG.getConstant(0x800, MVT::i16)),
11333 DAG.getConstant(11, MVT::i8));
11335 DAG.getNode(ISD::SRL, DL, MVT::i16,
11336 DAG.getNode(ISD::AND, DL, MVT::i16,
11337 CWD, DAG.getConstant(0x400, MVT::i16)),
11338 DAG.getConstant(9, MVT::i8));
11341 DAG.getNode(ISD::AND, DL, MVT::i16,
11342 DAG.getNode(ISD::ADD, DL, MVT::i16,
11343 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11344 DAG.getConstant(1, MVT::i16)),
11345 DAG.getConstant(3, MVT::i16));
11347 return DAG.getNode((VT.getSizeInBits() < 16 ?
11348 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11351 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11352 EVT VT = Op.getValueType();
11354 unsigned NumBits = VT.getSizeInBits();
11357 Op = Op.getOperand(0);
11358 if (VT == MVT::i8) {
11359 // Zero extend to i32 since there is not an i8 bsr.
11361 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11364 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11365 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11366 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11368 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11371 DAG.getConstant(NumBits+NumBits-1, OpVT),
11372 DAG.getConstant(X86::COND_E, MVT::i8),
11375 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11377 // Finally xor with NumBits-1.
11378 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11381 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11385 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11386 EVT VT = Op.getValueType();
11388 unsigned NumBits = VT.getSizeInBits();
11391 Op = Op.getOperand(0);
11392 if (VT == MVT::i8) {
11393 // Zero extend to i32 since there is not an i8 bsr.
11395 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11398 // Issue a bsr (scan bits in reverse).
11399 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11400 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11402 // And xor with NumBits-1.
11403 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11406 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11410 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11411 EVT VT = Op.getValueType();
11412 unsigned NumBits = VT.getSizeInBits();
11414 Op = Op.getOperand(0);
11416 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11417 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11418 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11420 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11423 DAG.getConstant(NumBits, VT),
11424 DAG.getConstant(X86::COND_E, MVT::i8),
11427 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11430 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11431 // ones, and then concatenate the result back.
11432 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11433 EVT VT = Op.getValueType();
11435 assert(VT.is256BitVector() && VT.isInteger() &&
11436 "Unsupported value type for operation");
11438 unsigned NumElems = VT.getVectorNumElements();
11441 // Extract the LHS vectors
11442 SDValue LHS = Op.getOperand(0);
11443 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11444 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11446 // Extract the RHS vectors
11447 SDValue RHS = Op.getOperand(1);
11448 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11449 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11451 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11452 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11454 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11455 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11456 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11459 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11460 assert(Op.getValueType().is256BitVector() &&
11461 Op.getValueType().isInteger() &&
11462 "Only handle AVX 256-bit vector integer operation");
11463 return Lower256IntArith(Op, DAG);
11466 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11467 assert(Op.getValueType().is256BitVector() &&
11468 Op.getValueType().isInteger() &&
11469 "Only handle AVX 256-bit vector integer operation");
11470 return Lower256IntArith(Op, DAG);
11473 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11474 SelectionDAG &DAG) {
11476 EVT VT = Op.getValueType();
11478 // Decompose 256-bit ops into smaller 128-bit ops.
11479 if (VT.is256BitVector() && !Subtarget->hasInt256())
11480 return Lower256IntArith(Op, DAG);
11482 SDValue A = Op.getOperand(0);
11483 SDValue B = Op.getOperand(1);
11485 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11486 if (VT == MVT::v4i32) {
11487 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11488 "Should not custom lower when pmuldq is available!");
11490 // Extract the odd parts.
11491 const int UnpackMask[] = { 1, -1, 3, -1 };
11492 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11493 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11495 // Multiply the even parts.
11496 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11497 // Now multiply odd parts.
11498 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11500 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11501 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11503 // Merge the two vectors back together with a shuffle. This expands into 2
11505 const int ShufMask[] = { 0, 4, 2, 6 };
11506 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11509 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11510 "Only know how to lower V2I64/V4I64 multiply");
11512 // Ahi = psrlqi(a, 32);
11513 // Bhi = psrlqi(b, 32);
11515 // AloBlo = pmuludq(a, b);
11516 // AloBhi = pmuludq(a, Bhi);
11517 // AhiBlo = pmuludq(Ahi, b);
11519 // AloBhi = psllqi(AloBhi, 32);
11520 // AhiBlo = psllqi(AhiBlo, 32);
11521 // return AloBlo + AloBhi + AhiBlo;
11523 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11525 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11526 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11528 // Bit cast to 32-bit vectors for MULUDQ
11529 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11530 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11531 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11532 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11533 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11535 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11536 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11537 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11539 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11540 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11542 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11543 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11546 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11547 EVT VT = Op.getValueType();
11548 EVT EltTy = VT.getVectorElementType();
11549 unsigned NumElts = VT.getVectorNumElements();
11550 SDValue N0 = Op.getOperand(0);
11553 // Lower sdiv X, pow2-const.
11554 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11558 APInt SplatValue, SplatUndef;
11559 unsigned SplatBitSize;
11561 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11563 EltTy.getSizeInBits() < SplatBitSize)
11566 if ((SplatValue != 0) &&
11567 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11568 unsigned lg2 = SplatValue.countTrailingZeros();
11569 // Splat the sign bit.
11570 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11571 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11572 // Add (N0 < 0) ? abs2 - 1 : 0;
11573 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11574 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11575 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11576 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11577 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11579 // If we're dividing by a positive value, we're done. Otherwise, we must
11580 // negate the result.
11581 if (SplatValue.isNonNegative())
11584 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11585 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11586 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11591 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11592 const X86Subtarget *Subtarget) {
11593 EVT VT = Op.getValueType();
11595 SDValue R = Op.getOperand(0);
11596 SDValue Amt = Op.getOperand(1);
11598 // Optimize shl/srl/sra with constant shift amount.
11599 if (isSplatVector(Amt.getNode())) {
11600 SDValue SclrAmt = Amt->getOperand(0);
11601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11602 uint64_t ShiftAmt = C->getZExtValue();
11604 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11605 (Subtarget->hasInt256() &&
11606 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11607 if (Op.getOpcode() == ISD::SHL)
11608 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11609 DAG.getConstant(ShiftAmt, MVT::i32));
11610 if (Op.getOpcode() == ISD::SRL)
11611 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11612 DAG.getConstant(ShiftAmt, MVT::i32));
11613 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11614 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11615 DAG.getConstant(ShiftAmt, MVT::i32));
11618 if (VT == MVT::v16i8) {
11619 if (Op.getOpcode() == ISD::SHL) {
11620 // Make a large shift.
11621 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11622 DAG.getConstant(ShiftAmt, MVT::i32));
11623 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11624 // Zero out the rightmost bits.
11625 SmallVector<SDValue, 16> V(16,
11626 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11628 return DAG.getNode(ISD::AND, dl, VT, SHL,
11629 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11631 if (Op.getOpcode() == ISD::SRL) {
11632 // Make a large shift.
11633 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11634 DAG.getConstant(ShiftAmt, MVT::i32));
11635 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11636 // Zero out the leftmost bits.
11637 SmallVector<SDValue, 16> V(16,
11638 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11640 return DAG.getNode(ISD::AND, dl, VT, SRL,
11641 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11643 if (Op.getOpcode() == ISD::SRA) {
11644 if (ShiftAmt == 7) {
11645 // R s>> 7 === R s< 0
11646 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11647 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11650 // R s>> a === ((R u>> a) ^ m) - m
11651 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11652 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11654 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11655 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11656 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11659 llvm_unreachable("Unknown shift opcode.");
11662 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11663 if (Op.getOpcode() == ISD::SHL) {
11664 // Make a large shift.
11665 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11666 DAG.getConstant(ShiftAmt, MVT::i32));
11667 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11668 // Zero out the rightmost bits.
11669 SmallVector<SDValue, 32> V(32,
11670 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11672 return DAG.getNode(ISD::AND, dl, VT, SHL,
11673 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11675 if (Op.getOpcode() == ISD::SRL) {
11676 // Make a large shift.
11677 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11678 DAG.getConstant(ShiftAmt, MVT::i32));
11679 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11680 // Zero out the leftmost bits.
11681 SmallVector<SDValue, 32> V(32,
11682 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11684 return DAG.getNode(ISD::AND, dl, VT, SRL,
11685 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11687 if (Op.getOpcode() == ISD::SRA) {
11688 if (ShiftAmt == 7) {
11689 // R s>> 7 === R s< 0
11690 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11691 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11694 // R s>> a === ((R u>> a) ^ m) - m
11695 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11696 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11698 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11699 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11700 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11703 llvm_unreachable("Unknown shift opcode.");
11708 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11709 if (!Subtarget->is64Bit() &&
11710 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11711 Amt.getOpcode() == ISD::BITCAST &&
11712 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11713 Amt = Amt.getOperand(0);
11714 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11715 VT.getVectorNumElements();
11716 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11717 uint64_t ShiftAmt = 0;
11718 for (unsigned i = 0; i != Ratio; ++i) {
11719 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11723 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11725 // Check remaining shift amounts.
11726 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11727 uint64_t ShAmt = 0;
11728 for (unsigned j = 0; j != Ratio; ++j) {
11729 ConstantSDNode *C =
11730 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11734 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11736 if (ShAmt != ShiftAmt)
11739 switch (Op.getOpcode()) {
11741 llvm_unreachable("Unknown shift opcode!");
11743 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11744 DAG.getConstant(ShiftAmt, MVT::i32));
11746 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11747 DAG.getConstant(ShiftAmt, MVT::i32));
11749 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11750 DAG.getConstant(ShiftAmt, MVT::i32));
11757 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11758 const X86Subtarget* Subtarget) {
11759 EVT VT = Op.getValueType();
11761 SDValue R = Op.getOperand(0);
11762 SDValue Amt = Op.getOperand(1);
11764 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11765 VT == MVT::v4i32 || VT == MVT::v8i16 ||
11766 (Subtarget->hasInt256() &&
11767 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11768 VT == MVT::v8i32 || VT == MVT::v16i16))) {
11770 EVT EltVT = VT.getVectorElementType();
11772 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11773 unsigned NumElts = VT.getVectorNumElements();
11775 for (i = 0; i != NumElts; ++i) {
11776 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11780 for (j = i; j != NumElts; ++j) {
11781 SDValue Arg = Amt.getOperand(j);
11782 if (Arg.getOpcode() == ISD::UNDEF) continue;
11783 if (Arg != Amt.getOperand(i))
11786 if (i != NumElts && j == NumElts)
11787 BaseShAmt = Amt.getOperand(i);
11789 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11790 Amt = Amt.getOperand(0);
11791 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11792 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11793 SDValue InVec = Amt.getOperand(0);
11794 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11795 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11797 for (; i != NumElts; ++i) {
11798 SDValue Arg = InVec.getOperand(i);
11799 if (Arg.getOpcode() == ISD::UNDEF) continue;
11803 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11804 if (ConstantSDNode *C =
11805 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11806 unsigned SplatIdx =
11807 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11808 if (C->getZExtValue() == SplatIdx)
11809 BaseShAmt = InVec.getOperand(1);
11812 if (BaseShAmt.getNode() == 0)
11813 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11814 DAG.getIntPtrConstant(0));
11818 if (BaseShAmt.getNode()) {
11819 if (EltVT.bitsGT(MVT::i32))
11820 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11821 else if (EltVT.bitsLT(MVT::i32))
11822 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11824 switch (Op.getOpcode()) {
11826 llvm_unreachable("Unknown shift opcode!");
11828 switch (VT.getSimpleVT().SimpleTy) {
11829 default: return SDValue();
11836 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11839 switch (VT.getSimpleVT().SimpleTy) {
11840 default: return SDValue();
11845 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11848 switch (VT.getSimpleVT().SimpleTy) {
11849 default: return SDValue();
11856 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11862 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11863 if (!Subtarget->is64Bit() &&
11864 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11865 Amt.getOpcode() == ISD::BITCAST &&
11866 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11867 Amt = Amt.getOperand(0);
11868 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11869 VT.getVectorNumElements();
11870 std::vector<SDValue> Vals(Ratio);
11871 for (unsigned i = 0; i != Ratio; ++i)
11872 Vals[i] = Amt.getOperand(i);
11873 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11874 for (unsigned j = 0; j != Ratio; ++j)
11875 if (Vals[j] != Amt.getOperand(i + j))
11878 switch (Op.getOpcode()) {
11880 llvm_unreachable("Unknown shift opcode!");
11882 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11884 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11886 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11893 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11895 EVT VT = Op.getValueType();
11897 SDValue R = Op.getOperand(0);
11898 SDValue Amt = Op.getOperand(1);
11901 if (!Subtarget->hasSSE2())
11904 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11908 V = LowerScalarVariableShift(Op, DAG, Subtarget);
11912 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11913 if (Subtarget->hasInt256()) {
11914 if (Op.getOpcode() == ISD::SRL &&
11915 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11916 VT == MVT::v4i64 || VT == MVT::v8i32))
11918 if (Op.getOpcode() == ISD::SHL &&
11919 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11920 VT == MVT::v4i64 || VT == MVT::v8i32))
11922 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11926 // Lower SHL with variable shift amount.
11927 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11928 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11930 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11931 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11932 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11933 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11935 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11936 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11939 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11940 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11942 // Turn 'a' into a mask suitable for VSELECT
11943 SDValue VSelM = DAG.getConstant(0x80, VT);
11944 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11945 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11947 SDValue CM1 = DAG.getConstant(0x0f, VT);
11948 SDValue CM2 = DAG.getConstant(0x3f, VT);
11950 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11951 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11952 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11953 DAG.getConstant(4, MVT::i32), DAG);
11954 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11955 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11958 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11959 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11960 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11962 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11963 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11964 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11965 DAG.getConstant(2, MVT::i32), DAG);
11966 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11967 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11970 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11971 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11972 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11974 // return VSELECT(r, r+r, a);
11975 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11976 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11980 // Decompose 256-bit shifts into smaller 128-bit shifts.
11981 if (VT.is256BitVector()) {
11982 unsigned NumElems = VT.getVectorNumElements();
11983 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11984 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11986 // Extract the two vectors
11987 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11988 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11990 // Recreate the shift amount vectors
11991 SDValue Amt1, Amt2;
11992 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11993 // Constant shift amount
11994 SmallVector<SDValue, 4> Amt1Csts;
11995 SmallVector<SDValue, 4> Amt2Csts;
11996 for (unsigned i = 0; i != NumElems/2; ++i)
11997 Amt1Csts.push_back(Amt->getOperand(i));
11998 for (unsigned i = NumElems/2; i != NumElems; ++i)
11999 Amt2Csts.push_back(Amt->getOperand(i));
12001 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12002 &Amt1Csts[0], NumElems/2);
12003 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12004 &Amt2Csts[0], NumElems/2);
12006 // Variable shift amount
12007 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12008 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12011 // Issue new vector shifts for the smaller types
12012 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12013 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12015 // Concatenate the result back
12016 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12022 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12023 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12024 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12025 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12026 // has only one use.
12027 SDNode *N = Op.getNode();
12028 SDValue LHS = N->getOperand(0);
12029 SDValue RHS = N->getOperand(1);
12030 unsigned BaseOp = 0;
12033 switch (Op.getOpcode()) {
12034 default: llvm_unreachable("Unknown ovf instruction!");
12036 // A subtract of one will be selected as a INC. Note that INC doesn't
12037 // set CF, so we can't do this for UADDO.
12038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12040 BaseOp = X86ISD::INC;
12041 Cond = X86::COND_O;
12044 BaseOp = X86ISD::ADD;
12045 Cond = X86::COND_O;
12048 BaseOp = X86ISD::ADD;
12049 Cond = X86::COND_B;
12052 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12053 // set CF, so we can't do this for USUBO.
12054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12056 BaseOp = X86ISD::DEC;
12057 Cond = X86::COND_O;
12060 BaseOp = X86ISD::SUB;
12061 Cond = X86::COND_O;
12064 BaseOp = X86ISD::SUB;
12065 Cond = X86::COND_B;
12068 BaseOp = X86ISD::SMUL;
12069 Cond = X86::COND_O;
12071 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12072 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12074 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12077 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12078 DAG.getConstant(X86::COND_O, MVT::i32),
12079 SDValue(Sum.getNode(), 2));
12081 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12085 // Also sets EFLAGS.
12086 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12087 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12090 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12091 DAG.getConstant(Cond, MVT::i32),
12092 SDValue(Sum.getNode(), 1));
12094 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12097 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12098 SelectionDAG &DAG) const {
12100 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12101 EVT VT = Op.getValueType();
12103 if (!Subtarget->hasSSE2() || !VT.isVector())
12106 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12107 ExtraVT.getScalarType().getSizeInBits();
12108 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12110 switch (VT.getSimpleVT().SimpleTy) {
12111 default: return SDValue();
12114 if (!Subtarget->hasFp256())
12116 if (!Subtarget->hasInt256()) {
12117 // needs to be split
12118 unsigned NumElems = VT.getVectorNumElements();
12120 // Extract the LHS vectors
12121 SDValue LHS = Op.getOperand(0);
12122 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12123 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12125 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12126 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12128 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12129 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12130 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12132 SDValue Extra = DAG.getValueType(ExtraVT);
12134 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12135 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12137 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12142 // (sext (vzext x)) -> (vsext x)
12143 SDValue Op0 = Op.getOperand(0);
12144 SDValue Op00 = Op0.getOperand(0);
12146 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12147 if (Op0.getOpcode() == ISD::BITCAST &&
12148 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12149 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12150 if (Tmp1.getNode()) {
12151 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12152 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12153 "This optimization is invalid without a VZEXT.");
12154 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12157 // If the above didn't work, then just use Shift-Left + Shift-Right.
12158 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12159 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12164 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12165 SelectionDAG &DAG) {
12167 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12168 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12169 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12170 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12172 // The only fence that needs an instruction is a sequentially-consistent
12173 // cross-thread fence.
12174 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12175 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12176 // no-sse2). There isn't any reason to disable it if the target processor
12178 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12179 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12181 SDValue Chain = Op.getOperand(0);
12182 SDValue Zero = DAG.getConstant(0, MVT::i32);
12184 DAG.getRegister(X86::ESP, MVT::i32), // Base
12185 DAG.getTargetConstant(1, MVT::i8), // Scale
12186 DAG.getRegister(0, MVT::i32), // Index
12187 DAG.getTargetConstant(0, MVT::i32), // Disp
12188 DAG.getRegister(0, MVT::i32), // Segment.
12192 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12193 return SDValue(Res, 0);
12196 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12197 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12200 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12201 SelectionDAG &DAG) {
12202 EVT T = Op.getValueType();
12206 switch(T.getSimpleVT().SimpleTy) {
12207 default: llvm_unreachable("Invalid value type!");
12208 case MVT::i8: Reg = X86::AL; size = 1; break;
12209 case MVT::i16: Reg = X86::AX; size = 2; break;
12210 case MVT::i32: Reg = X86::EAX; size = 4; break;
12212 assert(Subtarget->is64Bit() && "Node not type legal!");
12213 Reg = X86::RAX; size = 8;
12216 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12217 Op.getOperand(2), SDValue());
12218 SDValue Ops[] = { cpIn.getValue(0),
12221 DAG.getTargetConstant(size, MVT::i8),
12222 cpIn.getValue(1) };
12223 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12224 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12225 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12226 Ops, array_lengthof(Ops), T, MMO);
12228 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12232 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12233 SelectionDAG &DAG) {
12234 assert(Subtarget->is64Bit() && "Result not type legalized?");
12235 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12236 SDValue TheChain = Op.getOperand(0);
12238 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12239 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12240 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12242 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12243 DAG.getConstant(32, MVT::i8));
12245 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12248 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12251 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12252 EVT SrcVT = Op.getOperand(0).getValueType();
12253 EVT DstVT = Op.getValueType();
12254 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12255 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12256 assert((DstVT == MVT::i64 ||
12257 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12258 "Unexpected custom BITCAST");
12259 // i64 <=> MMX conversions are Legal.
12260 if (SrcVT==MVT::i64 && DstVT.isVector())
12262 if (DstVT==MVT::i64 && SrcVT.isVector())
12264 // MMX <=> MMX conversions are Legal.
12265 if (SrcVT.isVector() && DstVT.isVector())
12267 // All other conversions need to be expanded.
12271 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12272 SDNode *Node = Op.getNode();
12274 EVT T = Node->getValueType(0);
12275 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12276 DAG.getConstant(0, T), Node->getOperand(2));
12277 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12278 cast<AtomicSDNode>(Node)->getMemoryVT(),
12279 Node->getOperand(0),
12280 Node->getOperand(1), negOp,
12281 cast<AtomicSDNode>(Node)->getSrcValue(),
12282 cast<AtomicSDNode>(Node)->getAlignment(),
12283 cast<AtomicSDNode>(Node)->getOrdering(),
12284 cast<AtomicSDNode>(Node)->getSynchScope());
12287 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12288 SDNode *Node = Op.getNode();
12290 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12292 // Convert seq_cst store -> xchg
12293 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12294 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12295 // (The only way to get a 16-byte store is cmpxchg16b)
12296 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12297 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12298 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12299 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12300 cast<AtomicSDNode>(Node)->getMemoryVT(),
12301 Node->getOperand(0),
12302 Node->getOperand(1), Node->getOperand(2),
12303 cast<AtomicSDNode>(Node)->getMemOperand(),
12304 cast<AtomicSDNode>(Node)->getOrdering(),
12305 cast<AtomicSDNode>(Node)->getSynchScope());
12306 return Swap.getValue(1);
12308 // Other atomic stores have a simple pattern.
12312 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12313 EVT VT = Op.getNode()->getValueType(0);
12315 // Let legalize expand this if it isn't a legal type yet.
12316 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12319 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12322 bool ExtraOp = false;
12323 switch (Op.getOpcode()) {
12324 default: llvm_unreachable("Invalid code");
12325 case ISD::ADDC: Opc = X86ISD::ADD; break;
12326 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12327 case ISD::SUBC: Opc = X86ISD::SUB; break;
12328 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12332 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12334 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12335 Op.getOperand(1), Op.getOperand(2));
12338 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12339 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12341 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12342 // which returns the values as { float, float } (in XMM0) or
12343 // { double, double } (which is returned in XMM0, XMM1).
12345 SDValue Arg = Op.getOperand(0);
12346 EVT ArgVT = Arg.getValueType();
12347 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12350 ArgListEntry Entry;
12354 Entry.isSExt = false;
12355 Entry.isZExt = false;
12356 Args.push_back(Entry);
12358 bool isF64 = ArgVT == MVT::f64;
12359 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12360 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12361 // the results are returned via SRet in memory.
12362 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12363 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12365 Type *RetTy = isF64
12366 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12367 : (Type*)VectorType::get(ArgTy, 4);
12369 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12370 false, false, false, false, 0,
12371 CallingConv::C, /*isTaillCall=*/false,
12372 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12373 Callee, Args, DAG, dl);
12374 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12377 // Returned in xmm0 and xmm1.
12378 return CallResult.first;
12380 // Returned in bits 0:31 and 32:64 xmm0.
12381 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12382 CallResult.first, DAG.getIntPtrConstant(0));
12383 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12384 CallResult.first, DAG.getIntPtrConstant(1));
12385 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12386 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12389 /// LowerOperation - Provide custom lowering hooks for some operations.
12391 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12392 switch (Op.getOpcode()) {
12393 default: llvm_unreachable("Should not custom lower this!");
12394 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12395 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12396 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12397 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12398 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12399 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12400 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12401 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12402 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12403 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12404 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12405 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12406 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12407 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12408 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12409 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12410 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12411 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12412 case ISD::SHL_PARTS:
12413 case ISD::SRA_PARTS:
12414 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12415 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12416 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12417 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12418 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12419 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12420 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12421 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12422 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12423 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12424 case ISD::FABS: return LowerFABS(Op, DAG);
12425 case ISD::FNEG: return LowerFNEG(Op, DAG);
12426 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12427 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12428 case ISD::SETCC: return LowerSETCC(Op, DAG);
12429 case ISD::SELECT: return LowerSELECT(Op, DAG);
12430 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12431 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12432 case ISD::VASTART: return LowerVASTART(Op, DAG);
12433 case ISD::VAARG: return LowerVAARG(Op, DAG);
12434 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12435 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12436 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12437 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12438 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12439 case ISD::FRAME_TO_ARGS_OFFSET:
12440 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12441 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12442 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12443 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12444 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12445 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12446 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12447 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12448 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12449 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12450 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12451 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12454 case ISD::SHL: return LowerShift(Op, DAG);
12460 case ISD::UMULO: return LowerXALUO(Op, DAG);
12461 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12462 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12466 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12467 case ISD::ADD: return LowerADD(Op, DAG);
12468 case ISD::SUB: return LowerSUB(Op, DAG);
12469 case ISD::SDIV: return LowerSDIV(Op, DAG);
12470 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12474 static void ReplaceATOMIC_LOAD(SDNode *Node,
12475 SmallVectorImpl<SDValue> &Results,
12476 SelectionDAG &DAG) {
12478 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12480 // Convert wide load -> cmpxchg8b/cmpxchg16b
12481 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12482 // (The only way to get a 16-byte load is cmpxchg16b)
12483 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12484 SDValue Zero = DAG.getConstant(0, VT);
12485 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12486 Node->getOperand(0),
12487 Node->getOperand(1), Zero, Zero,
12488 cast<AtomicSDNode>(Node)->getMemOperand(),
12489 cast<AtomicSDNode>(Node)->getOrdering(),
12490 cast<AtomicSDNode>(Node)->getSynchScope());
12491 Results.push_back(Swap.getValue(0));
12492 Results.push_back(Swap.getValue(1));
12496 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12497 SelectionDAG &DAG, unsigned NewOp) {
12499 assert (Node->getValueType(0) == MVT::i64 &&
12500 "Only know how to expand i64 atomics");
12502 SDValue Chain = Node->getOperand(0);
12503 SDValue In1 = Node->getOperand(1);
12504 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12505 Node->getOperand(2), DAG.getIntPtrConstant(0));
12506 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12507 Node->getOperand(2), DAG.getIntPtrConstant(1));
12508 SDValue Ops[] = { Chain, In1, In2L, In2H };
12509 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12511 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12512 cast<MemSDNode>(Node)->getMemOperand());
12513 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12514 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12515 Results.push_back(Result.getValue(2));
12518 /// ReplaceNodeResults - Replace a node with an illegal result type
12519 /// with a new node built out of custom code.
12520 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12521 SmallVectorImpl<SDValue>&Results,
12522 SelectionDAG &DAG) const {
12524 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12525 switch (N->getOpcode()) {
12527 llvm_unreachable("Do not know how to custom type legalize this operation!");
12528 case ISD::SIGN_EXTEND_INREG:
12533 // We don't want to expand or promote these.
12535 case ISD::FP_TO_SINT:
12536 case ISD::FP_TO_UINT: {
12537 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12539 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12542 std::pair<SDValue,SDValue> Vals =
12543 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12544 SDValue FIST = Vals.first, StackSlot = Vals.second;
12545 if (FIST.getNode() != 0) {
12546 EVT VT = N->getValueType(0);
12547 // Return a load from the stack slot.
12548 if (StackSlot.getNode() != 0)
12549 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12550 MachinePointerInfo(),
12551 false, false, false, 0));
12553 Results.push_back(FIST);
12557 case ISD::UINT_TO_FP: {
12558 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12559 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12560 N->getValueType(0) != MVT::v2f32)
12562 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12564 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12566 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12567 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12568 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12569 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12570 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12571 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12574 case ISD::FP_ROUND: {
12575 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12577 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12578 Results.push_back(V);
12581 case ISD::READCYCLECOUNTER: {
12582 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12583 SDValue TheChain = N->getOperand(0);
12584 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12585 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12587 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12589 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12590 SDValue Ops[] = { eax, edx };
12591 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12592 array_lengthof(Ops)));
12593 Results.push_back(edx.getValue(1));
12596 case ISD::ATOMIC_CMP_SWAP: {
12597 EVT T = N->getValueType(0);
12598 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12599 bool Regs64bit = T == MVT::i128;
12600 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12601 SDValue cpInL, cpInH;
12602 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12603 DAG.getConstant(0, HalfT));
12604 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12605 DAG.getConstant(1, HalfT));
12606 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12607 Regs64bit ? X86::RAX : X86::EAX,
12609 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12610 Regs64bit ? X86::RDX : X86::EDX,
12611 cpInH, cpInL.getValue(1));
12612 SDValue swapInL, swapInH;
12613 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12614 DAG.getConstant(0, HalfT));
12615 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12616 DAG.getConstant(1, HalfT));
12617 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12618 Regs64bit ? X86::RBX : X86::EBX,
12619 swapInL, cpInH.getValue(1));
12620 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12621 Regs64bit ? X86::RCX : X86::ECX,
12622 swapInH, swapInL.getValue(1));
12623 SDValue Ops[] = { swapInH.getValue(0),
12625 swapInH.getValue(1) };
12626 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12627 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12628 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12629 X86ISD::LCMPXCHG8_DAG;
12630 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12631 Ops, array_lengthof(Ops), T, MMO);
12632 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12633 Regs64bit ? X86::RAX : X86::EAX,
12634 HalfT, Result.getValue(1));
12635 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12636 Regs64bit ? X86::RDX : X86::EDX,
12637 HalfT, cpOutL.getValue(2));
12638 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12639 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12640 Results.push_back(cpOutH.getValue(1));
12643 case ISD::ATOMIC_LOAD_ADD:
12644 case ISD::ATOMIC_LOAD_AND:
12645 case ISD::ATOMIC_LOAD_NAND:
12646 case ISD::ATOMIC_LOAD_OR:
12647 case ISD::ATOMIC_LOAD_SUB:
12648 case ISD::ATOMIC_LOAD_XOR:
12649 case ISD::ATOMIC_LOAD_MAX:
12650 case ISD::ATOMIC_LOAD_MIN:
12651 case ISD::ATOMIC_LOAD_UMAX:
12652 case ISD::ATOMIC_LOAD_UMIN:
12653 case ISD::ATOMIC_SWAP: {
12655 switch (N->getOpcode()) {
12656 default: llvm_unreachable("Unexpected opcode");
12657 case ISD::ATOMIC_LOAD_ADD:
12658 Opc = X86ISD::ATOMADD64_DAG;
12660 case ISD::ATOMIC_LOAD_AND:
12661 Opc = X86ISD::ATOMAND64_DAG;
12663 case ISD::ATOMIC_LOAD_NAND:
12664 Opc = X86ISD::ATOMNAND64_DAG;
12666 case ISD::ATOMIC_LOAD_OR:
12667 Opc = X86ISD::ATOMOR64_DAG;
12669 case ISD::ATOMIC_LOAD_SUB:
12670 Opc = X86ISD::ATOMSUB64_DAG;
12672 case ISD::ATOMIC_LOAD_XOR:
12673 Opc = X86ISD::ATOMXOR64_DAG;
12675 case ISD::ATOMIC_LOAD_MAX:
12676 Opc = X86ISD::ATOMMAX64_DAG;
12678 case ISD::ATOMIC_LOAD_MIN:
12679 Opc = X86ISD::ATOMMIN64_DAG;
12681 case ISD::ATOMIC_LOAD_UMAX:
12682 Opc = X86ISD::ATOMUMAX64_DAG;
12684 case ISD::ATOMIC_LOAD_UMIN:
12685 Opc = X86ISD::ATOMUMIN64_DAG;
12687 case ISD::ATOMIC_SWAP:
12688 Opc = X86ISD::ATOMSWAP64_DAG;
12691 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12694 case ISD::ATOMIC_LOAD:
12695 ReplaceATOMIC_LOAD(N, Results, DAG);
12699 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12701 default: return NULL;
12702 case X86ISD::BSF: return "X86ISD::BSF";
12703 case X86ISD::BSR: return "X86ISD::BSR";
12704 case X86ISD::SHLD: return "X86ISD::SHLD";
12705 case X86ISD::SHRD: return "X86ISD::SHRD";
12706 case X86ISD::FAND: return "X86ISD::FAND";
12707 case X86ISD::FOR: return "X86ISD::FOR";
12708 case X86ISD::FXOR: return "X86ISD::FXOR";
12709 case X86ISD::FSRL: return "X86ISD::FSRL";
12710 case X86ISD::FILD: return "X86ISD::FILD";
12711 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12712 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12713 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12714 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12715 case X86ISD::FLD: return "X86ISD::FLD";
12716 case X86ISD::FST: return "X86ISD::FST";
12717 case X86ISD::CALL: return "X86ISD::CALL";
12718 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12719 case X86ISD::BT: return "X86ISD::BT";
12720 case X86ISD::CMP: return "X86ISD::CMP";
12721 case X86ISD::COMI: return "X86ISD::COMI";
12722 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12723 case X86ISD::SETCC: return "X86ISD::SETCC";
12724 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12725 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12726 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12727 case X86ISD::CMOV: return "X86ISD::CMOV";
12728 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12729 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12730 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12731 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12732 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12733 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12734 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12735 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12736 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12737 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12738 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12739 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12740 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12741 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12742 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12743 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12744 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12745 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12746 case X86ISD::HADD: return "X86ISD::HADD";
12747 case X86ISD::HSUB: return "X86ISD::HSUB";
12748 case X86ISD::FHADD: return "X86ISD::FHADD";
12749 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12750 case X86ISD::UMAX: return "X86ISD::UMAX";
12751 case X86ISD::UMIN: return "X86ISD::UMIN";
12752 case X86ISD::SMAX: return "X86ISD::SMAX";
12753 case X86ISD::SMIN: return "X86ISD::SMIN";
12754 case X86ISD::FMAX: return "X86ISD::FMAX";
12755 case X86ISD::FMIN: return "X86ISD::FMIN";
12756 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12757 case X86ISD::FMINC: return "X86ISD::FMINC";
12758 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12759 case X86ISD::FRCP: return "X86ISD::FRCP";
12760 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12761 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12762 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12763 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12764 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12765 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12766 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12767 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12768 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12769 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12770 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12771 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12772 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12773 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12774 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12775 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12776 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12777 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12778 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12779 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12780 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12781 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12782 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12783 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12784 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12785 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12786 case X86ISD::VSHL: return "X86ISD::VSHL";
12787 case X86ISD::VSRL: return "X86ISD::VSRL";
12788 case X86ISD::VSRA: return "X86ISD::VSRA";
12789 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12790 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12791 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12792 case X86ISD::CMPP: return "X86ISD::CMPP";
12793 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12794 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12795 case X86ISD::ADD: return "X86ISD::ADD";
12796 case X86ISD::SUB: return "X86ISD::SUB";
12797 case X86ISD::ADC: return "X86ISD::ADC";
12798 case X86ISD::SBB: return "X86ISD::SBB";
12799 case X86ISD::SMUL: return "X86ISD::SMUL";
12800 case X86ISD::UMUL: return "X86ISD::UMUL";
12801 case X86ISD::INC: return "X86ISD::INC";
12802 case X86ISD::DEC: return "X86ISD::DEC";
12803 case X86ISD::OR: return "X86ISD::OR";
12804 case X86ISD::XOR: return "X86ISD::XOR";
12805 case X86ISD::AND: return "X86ISD::AND";
12806 case X86ISD::BLSI: return "X86ISD::BLSI";
12807 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12808 case X86ISD::BLSR: return "X86ISD::BLSR";
12809 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12810 case X86ISD::PTEST: return "X86ISD::PTEST";
12811 case X86ISD::TESTP: return "X86ISD::TESTP";
12812 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
12813 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12814 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12815 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12816 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12817 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12818 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12819 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12820 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12821 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12822 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12823 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12824 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12825 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12826 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12827 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12828 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12829 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12830 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12831 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12832 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12833 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12834 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12835 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12836 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12837 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12838 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12839 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12840 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12841 case X86ISD::SAHF: return "X86ISD::SAHF";
12842 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12843 case X86ISD::RDSEED: return "X86ISD::RDSEED";
12844 case X86ISD::FMADD: return "X86ISD::FMADD";
12845 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12846 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12847 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12848 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12849 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12850 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12851 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12852 case X86ISD::XTEST: return "X86ISD::XTEST";
12856 // isLegalAddressingMode - Return true if the addressing mode represented
12857 // by AM is legal for this target, for a load/store of the specified type.
12858 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12860 // X86 supports extremely general addressing modes.
12861 CodeModel::Model M = getTargetMachine().getCodeModel();
12862 Reloc::Model R = getTargetMachine().getRelocationModel();
12864 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12865 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12870 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12872 // If a reference to this global requires an extra load, we can't fold it.
12873 if (isGlobalStubReference(GVFlags))
12876 // If BaseGV requires a register for the PIC base, we cannot also have a
12877 // BaseReg specified.
12878 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12881 // If lower 4G is not available, then we must use rip-relative addressing.
12882 if ((M != CodeModel::Small || R != Reloc::Static) &&
12883 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12887 switch (AM.Scale) {
12893 // These scales always work.
12898 // These scales are formed with basereg+scalereg. Only accept if there is
12903 default: // Other stuff never works.
12910 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12911 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12913 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12914 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12915 return NumBits1 > NumBits2;
12918 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12919 return isInt<32>(Imm);
12922 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12923 // Can also use sub to handle negated immediates.
12924 return isInt<32>(Imm);
12927 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12928 if (!VT1.isInteger() || !VT2.isInteger())
12930 unsigned NumBits1 = VT1.getSizeInBits();
12931 unsigned NumBits2 = VT2.getSizeInBits();
12932 return NumBits1 > NumBits2;
12935 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12936 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12937 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12940 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12941 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12942 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12945 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12946 EVT VT1 = Val.getValueType();
12947 if (isZExtFree(VT1, VT2))
12950 if (Val.getOpcode() != ISD::LOAD)
12953 if (!VT1.isSimple() || !VT1.isInteger() ||
12954 !VT2.isSimple() || !VT2.isInteger())
12957 switch (VT1.getSimpleVT().SimpleTy) {
12962 // X86 has 8, 16, and 32-bit zero-extending loads.
12969 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12970 // i16 instructions are longer (0x66 prefix) and potentially slower.
12971 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12974 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12975 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12976 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12977 /// are assumed to be legal.
12979 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12981 // Very little shuffling can be done for 64-bit vectors right now.
12982 if (VT.getSizeInBits() == 64)
12985 // FIXME: pshufb, blends, shifts.
12986 return (VT.getVectorNumElements() == 2 ||
12987 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12988 isMOVLMask(M, VT) ||
12989 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12990 isPSHUFDMask(M, VT) ||
12991 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12992 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12993 isPALIGNRMask(M, VT, Subtarget) ||
12994 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12995 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12996 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12997 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13001 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13003 unsigned NumElts = VT.getVectorNumElements();
13004 // FIXME: This collection of masks seems suspect.
13007 if (NumElts == 4 && VT.is128BitVector()) {
13008 return (isMOVLMask(Mask, VT) ||
13009 isCommutedMOVLMask(Mask, VT, true) ||
13010 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13011 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13016 //===----------------------------------------------------------------------===//
13017 // X86 Scheduler Hooks
13018 //===----------------------------------------------------------------------===//
13020 /// Utility function to emit xbegin specifying the start of an RTM region.
13021 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13022 const TargetInstrInfo *TII) {
13023 DebugLoc DL = MI->getDebugLoc();
13025 const BasicBlock *BB = MBB->getBasicBlock();
13026 MachineFunction::iterator I = MBB;
13029 // For the v = xbegin(), we generate
13040 MachineBasicBlock *thisMBB = MBB;
13041 MachineFunction *MF = MBB->getParent();
13042 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13043 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13044 MF->insert(I, mainMBB);
13045 MF->insert(I, sinkMBB);
13047 // Transfer the remainder of BB and its successor edges to sinkMBB.
13048 sinkMBB->splice(sinkMBB->begin(), MBB,
13049 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13050 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13054 // # fallthrough to mainMBB
13055 // # abortion to sinkMBB
13056 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13057 thisMBB->addSuccessor(mainMBB);
13058 thisMBB->addSuccessor(sinkMBB);
13062 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13063 mainMBB->addSuccessor(sinkMBB);
13066 // EAX is live into the sinkMBB
13067 sinkMBB->addLiveIn(X86::EAX);
13068 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13069 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13072 MI->eraseFromParent();
13076 // Get CMPXCHG opcode for the specified data type.
13077 static unsigned getCmpXChgOpcode(EVT VT) {
13078 switch (VT.getSimpleVT().SimpleTy) {
13079 case MVT::i8: return X86::LCMPXCHG8;
13080 case MVT::i16: return X86::LCMPXCHG16;
13081 case MVT::i32: return X86::LCMPXCHG32;
13082 case MVT::i64: return X86::LCMPXCHG64;
13086 llvm_unreachable("Invalid operand size!");
13089 // Get LOAD opcode for the specified data type.
13090 static unsigned getLoadOpcode(EVT VT) {
13091 switch (VT.getSimpleVT().SimpleTy) {
13092 case MVT::i8: return X86::MOV8rm;
13093 case MVT::i16: return X86::MOV16rm;
13094 case MVT::i32: return X86::MOV32rm;
13095 case MVT::i64: return X86::MOV64rm;
13099 llvm_unreachable("Invalid operand size!");
13102 // Get opcode of the non-atomic one from the specified atomic instruction.
13103 static unsigned getNonAtomicOpcode(unsigned Opc) {
13105 case X86::ATOMAND8: return X86::AND8rr;
13106 case X86::ATOMAND16: return X86::AND16rr;
13107 case X86::ATOMAND32: return X86::AND32rr;
13108 case X86::ATOMAND64: return X86::AND64rr;
13109 case X86::ATOMOR8: return X86::OR8rr;
13110 case X86::ATOMOR16: return X86::OR16rr;
13111 case X86::ATOMOR32: return X86::OR32rr;
13112 case X86::ATOMOR64: return X86::OR64rr;
13113 case X86::ATOMXOR8: return X86::XOR8rr;
13114 case X86::ATOMXOR16: return X86::XOR16rr;
13115 case X86::ATOMXOR32: return X86::XOR32rr;
13116 case X86::ATOMXOR64: return X86::XOR64rr;
13118 llvm_unreachable("Unhandled atomic-load-op opcode!");
13121 // Get opcode of the non-atomic one from the specified atomic instruction with
13123 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13124 unsigned &ExtraOpc) {
13126 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13127 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13128 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13129 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13130 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13131 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13132 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13133 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13134 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13135 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13136 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13137 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13138 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13139 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13140 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13141 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13142 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13143 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13144 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13145 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13147 llvm_unreachable("Unhandled atomic-load-op opcode!");
13150 // Get opcode of the non-atomic one from the specified atomic instruction for
13151 // 64-bit data type on 32-bit target.
13152 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13154 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13155 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13156 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13157 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13158 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13159 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13160 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13161 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13162 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13163 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13165 llvm_unreachable("Unhandled atomic-load-op opcode!");
13168 // Get opcode of the non-atomic one from the specified atomic instruction for
13169 // 64-bit data type on 32-bit target with extra opcode.
13170 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13172 unsigned &ExtraOpc) {
13174 case X86::ATOMNAND6432:
13175 ExtraOpc = X86::NOT32r;
13176 HiOpc = X86::AND32rr;
13177 return X86::AND32rr;
13179 llvm_unreachable("Unhandled atomic-load-op opcode!");
13182 // Get pseudo CMOV opcode from the specified data type.
13183 static unsigned getPseudoCMOVOpc(EVT VT) {
13184 switch (VT.getSimpleVT().SimpleTy) {
13185 case MVT::i8: return X86::CMOV_GR8;
13186 case MVT::i16: return X86::CMOV_GR16;
13187 case MVT::i32: return X86::CMOV_GR32;
13191 llvm_unreachable("Unknown CMOV opcode!");
13194 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13195 // They will be translated into a spin-loop or compare-exchange loop from
13198 // dst = atomic-fetch-op MI.addr, MI.val
13204 // t1 = LOAD MI.addr
13206 // t4 = phi(t1, t3 / loop)
13207 // t2 = OP MI.val, t4
13209 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13215 MachineBasicBlock *
13216 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13217 MachineBasicBlock *MBB) const {
13218 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13219 DebugLoc DL = MI->getDebugLoc();
13221 MachineFunction *MF = MBB->getParent();
13222 MachineRegisterInfo &MRI = MF->getRegInfo();
13224 const BasicBlock *BB = MBB->getBasicBlock();
13225 MachineFunction::iterator I = MBB;
13228 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13229 "Unexpected number of operands");
13231 assert(MI->hasOneMemOperand() &&
13232 "Expected atomic-load-op to have one memoperand");
13234 // Memory Reference
13235 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13236 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13238 unsigned DstReg, SrcReg;
13239 unsigned MemOpndSlot;
13241 unsigned CurOp = 0;
13243 DstReg = MI->getOperand(CurOp++).getReg();
13244 MemOpndSlot = CurOp;
13245 CurOp += X86::AddrNumOperands;
13246 SrcReg = MI->getOperand(CurOp++).getReg();
13248 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13249 MVT::SimpleValueType VT = *RC->vt_begin();
13250 unsigned t1 = MRI.createVirtualRegister(RC);
13251 unsigned t2 = MRI.createVirtualRegister(RC);
13252 unsigned t3 = MRI.createVirtualRegister(RC);
13253 unsigned t4 = MRI.createVirtualRegister(RC);
13254 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13256 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13257 unsigned LOADOpc = getLoadOpcode(VT);
13259 // For the atomic load-arith operator, we generate
13262 // t1 = LOAD [MI.addr]
13264 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13265 // t1 = OP MI.val, EAX
13267 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13273 MachineBasicBlock *thisMBB = MBB;
13274 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13275 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13276 MF->insert(I, mainMBB);
13277 MF->insert(I, sinkMBB);
13279 MachineInstrBuilder MIB;
13281 // Transfer the remainder of BB and its successor edges to sinkMBB.
13282 sinkMBB->splice(sinkMBB->begin(), MBB,
13283 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13284 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13287 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13288 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13289 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13291 NewMO.setIsKill(false);
13292 MIB.addOperand(NewMO);
13294 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13295 unsigned flags = (*MMOI)->getFlags();
13296 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13297 MachineMemOperand *MMO =
13298 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13299 (*MMOI)->getSize(),
13300 (*MMOI)->getBaseAlignment(),
13301 (*MMOI)->getTBAAInfo(),
13302 (*MMOI)->getRanges());
13303 MIB.addMemOperand(MMO);
13306 thisMBB->addSuccessor(mainMBB);
13309 MachineBasicBlock *origMainMBB = mainMBB;
13312 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13313 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13315 unsigned Opc = MI->getOpcode();
13318 llvm_unreachable("Unhandled atomic-load-op opcode!");
13319 case X86::ATOMAND8:
13320 case X86::ATOMAND16:
13321 case X86::ATOMAND32:
13322 case X86::ATOMAND64:
13324 case X86::ATOMOR16:
13325 case X86::ATOMOR32:
13326 case X86::ATOMOR64:
13327 case X86::ATOMXOR8:
13328 case X86::ATOMXOR16:
13329 case X86::ATOMXOR32:
13330 case X86::ATOMXOR64: {
13331 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13332 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13336 case X86::ATOMNAND8:
13337 case X86::ATOMNAND16:
13338 case X86::ATOMNAND32:
13339 case X86::ATOMNAND64: {
13340 unsigned Tmp = MRI.createVirtualRegister(RC);
13342 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13343 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13345 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13348 case X86::ATOMMAX8:
13349 case X86::ATOMMAX16:
13350 case X86::ATOMMAX32:
13351 case X86::ATOMMAX64:
13352 case X86::ATOMMIN8:
13353 case X86::ATOMMIN16:
13354 case X86::ATOMMIN32:
13355 case X86::ATOMMIN64:
13356 case X86::ATOMUMAX8:
13357 case X86::ATOMUMAX16:
13358 case X86::ATOMUMAX32:
13359 case X86::ATOMUMAX64:
13360 case X86::ATOMUMIN8:
13361 case X86::ATOMUMIN16:
13362 case X86::ATOMUMIN32:
13363 case X86::ATOMUMIN64: {
13365 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13367 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13371 if (Subtarget->hasCMov()) {
13372 if (VT != MVT::i8) {
13374 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13378 // Promote i8 to i32 to use CMOV32
13379 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13380 const TargetRegisterClass *RC32 =
13381 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13382 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13383 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13384 unsigned Tmp = MRI.createVirtualRegister(RC32);
13386 unsigned Undef = MRI.createVirtualRegister(RC32);
13387 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13389 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13392 .addImm(X86::sub_8bit);
13393 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13396 .addImm(X86::sub_8bit);
13398 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13402 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13403 .addReg(Tmp, 0, X86::sub_8bit);
13406 // Use pseudo select and lower them.
13407 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13408 "Invalid atomic-load-op transformation!");
13409 unsigned SelOpc = getPseudoCMOVOpc(VT);
13410 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13411 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13412 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13413 .addReg(SrcReg).addReg(t4)
13415 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13416 // Replace the original PHI node as mainMBB is changed after CMOV
13418 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13419 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13420 Phi->eraseFromParent();
13426 // Copy PhyReg back from virtual register.
13427 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13430 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13431 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13432 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13434 NewMO.setIsKill(false);
13435 MIB.addOperand(NewMO);
13438 MIB.setMemRefs(MMOBegin, MMOEnd);
13440 // Copy PhyReg back to virtual register.
13441 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13444 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13446 mainMBB->addSuccessor(origMainMBB);
13447 mainMBB->addSuccessor(sinkMBB);
13450 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13451 TII->get(TargetOpcode::COPY), DstReg)
13454 MI->eraseFromParent();
13458 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13459 // instructions. They will be translated into a spin-loop or compare-exchange
13463 // dst = atomic-fetch-op MI.addr, MI.val
13469 // t1L = LOAD [MI.addr + 0]
13470 // t1H = LOAD [MI.addr + 4]
13472 // t4L = phi(t1L, t3L / loop)
13473 // t4H = phi(t1H, t3H / loop)
13474 // t2L = OP MI.val.lo, t4L
13475 // t2H = OP MI.val.hi, t4H
13480 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13488 MachineBasicBlock *
13489 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13490 MachineBasicBlock *MBB) const {
13491 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13492 DebugLoc DL = MI->getDebugLoc();
13494 MachineFunction *MF = MBB->getParent();
13495 MachineRegisterInfo &MRI = MF->getRegInfo();
13497 const BasicBlock *BB = MBB->getBasicBlock();
13498 MachineFunction::iterator I = MBB;
13501 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13502 "Unexpected number of operands");
13504 assert(MI->hasOneMemOperand() &&
13505 "Expected atomic-load-op32 to have one memoperand");
13507 // Memory Reference
13508 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13509 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13511 unsigned DstLoReg, DstHiReg;
13512 unsigned SrcLoReg, SrcHiReg;
13513 unsigned MemOpndSlot;
13515 unsigned CurOp = 0;
13517 DstLoReg = MI->getOperand(CurOp++).getReg();
13518 DstHiReg = MI->getOperand(CurOp++).getReg();
13519 MemOpndSlot = CurOp;
13520 CurOp += X86::AddrNumOperands;
13521 SrcLoReg = MI->getOperand(CurOp++).getReg();
13522 SrcHiReg = MI->getOperand(CurOp++).getReg();
13524 const TargetRegisterClass *RC = &X86::GR32RegClass;
13525 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13527 unsigned t1L = MRI.createVirtualRegister(RC);
13528 unsigned t1H = MRI.createVirtualRegister(RC);
13529 unsigned t2L = MRI.createVirtualRegister(RC);
13530 unsigned t2H = MRI.createVirtualRegister(RC);
13531 unsigned t3L = MRI.createVirtualRegister(RC);
13532 unsigned t3H = MRI.createVirtualRegister(RC);
13533 unsigned t4L = MRI.createVirtualRegister(RC);
13534 unsigned t4H = MRI.createVirtualRegister(RC);
13536 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13537 unsigned LOADOpc = X86::MOV32rm;
13539 // For the atomic load-arith operator, we generate
13542 // t1L = LOAD [MI.addr + 0]
13543 // t1H = LOAD [MI.addr + 4]
13545 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
13546 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
13547 // t2L = OP MI.val.lo, t4L
13548 // t2H = OP MI.val.hi, t4H
13551 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13559 MachineBasicBlock *thisMBB = MBB;
13560 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13561 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13562 MF->insert(I, mainMBB);
13563 MF->insert(I, sinkMBB);
13565 MachineInstrBuilder MIB;
13567 // Transfer the remainder of BB and its successor edges to sinkMBB.
13568 sinkMBB->splice(sinkMBB->begin(), MBB,
13569 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13570 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13574 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13575 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13576 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13578 NewMO.setIsKill(false);
13579 MIB.addOperand(NewMO);
13581 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13582 unsigned flags = (*MMOI)->getFlags();
13583 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13584 MachineMemOperand *MMO =
13585 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13586 (*MMOI)->getSize(),
13587 (*MMOI)->getBaseAlignment(),
13588 (*MMOI)->getTBAAInfo(),
13589 (*MMOI)->getRanges());
13590 MIB.addMemOperand(MMO);
13592 MachineInstr *LowMI = MIB;
13595 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13596 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13597 if (i == X86::AddrDisp) {
13598 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13600 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13602 NewMO.setIsKill(false);
13603 MIB.addOperand(NewMO);
13606 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13608 thisMBB->addSuccessor(mainMBB);
13611 MachineBasicBlock *origMainMBB = mainMBB;
13614 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13615 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13616 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13617 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13619 unsigned Opc = MI->getOpcode();
13622 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13623 case X86::ATOMAND6432:
13624 case X86::ATOMOR6432:
13625 case X86::ATOMXOR6432:
13626 case X86::ATOMADD6432:
13627 case X86::ATOMSUB6432: {
13629 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13630 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13632 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13636 case X86::ATOMNAND6432: {
13637 unsigned HiOpc, NOTOpc;
13638 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13639 unsigned TmpL = MRI.createVirtualRegister(RC);
13640 unsigned TmpH = MRI.createVirtualRegister(RC);
13641 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13643 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13645 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13646 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13649 case X86::ATOMMAX6432:
13650 case X86::ATOMMIN6432:
13651 case X86::ATOMUMAX6432:
13652 case X86::ATOMUMIN6432: {
13654 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13655 unsigned cL = MRI.createVirtualRegister(RC8);
13656 unsigned cH = MRI.createVirtualRegister(RC8);
13657 unsigned cL32 = MRI.createVirtualRegister(RC);
13658 unsigned cH32 = MRI.createVirtualRegister(RC);
13659 unsigned cc = MRI.createVirtualRegister(RC);
13660 // cl := cmp src_lo, lo
13661 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13662 .addReg(SrcLoReg).addReg(t4L);
13663 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13664 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13665 // ch := cmp src_hi, hi
13666 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13667 .addReg(SrcHiReg).addReg(t4H);
13668 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13669 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13670 // cc := if (src_hi == hi) ? cl : ch;
13671 if (Subtarget->hasCMov()) {
13672 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13673 .addReg(cH32).addReg(cL32);
13675 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13676 .addReg(cH32).addReg(cL32)
13677 .addImm(X86::COND_E);
13678 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13680 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13681 if (Subtarget->hasCMov()) {
13682 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13683 .addReg(SrcLoReg).addReg(t4L);
13684 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13685 .addReg(SrcHiReg).addReg(t4H);
13687 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13688 .addReg(SrcLoReg).addReg(t4L)
13689 .addImm(X86::COND_NE);
13690 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13691 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13692 // 2nd CMOV lowering.
13693 mainMBB->addLiveIn(X86::EFLAGS);
13694 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13695 .addReg(SrcHiReg).addReg(t4H)
13696 .addImm(X86::COND_NE);
13697 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13698 // Replace the original PHI node as mainMBB is changed after CMOV
13700 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13701 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13702 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13703 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13704 PhiL->eraseFromParent();
13705 PhiH->eraseFromParent();
13709 case X86::ATOMSWAP6432: {
13711 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13712 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13713 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13718 // Copy EDX:EAX back from HiReg:LoReg
13719 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13720 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13721 // Copy ECX:EBX from t1H:t1L
13722 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13723 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13725 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13726 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13727 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13729 NewMO.setIsKill(false);
13730 MIB.addOperand(NewMO);
13732 MIB.setMemRefs(MMOBegin, MMOEnd);
13734 // Copy EDX:EAX back to t3H:t3L
13735 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13736 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13738 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13740 mainMBB->addSuccessor(origMainMBB);
13741 mainMBB->addSuccessor(sinkMBB);
13744 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13745 TII->get(TargetOpcode::COPY), DstLoReg)
13747 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13748 TII->get(TargetOpcode::COPY), DstHiReg)
13751 MI->eraseFromParent();
13755 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13756 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13757 // in the .td file.
13758 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13759 const TargetInstrInfo *TII) {
13761 switch (MI->getOpcode()) {
13762 default: llvm_unreachable("illegal opcode!");
13763 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13764 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13765 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13766 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13767 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13768 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13769 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13770 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13773 DebugLoc dl = MI->getDebugLoc();
13774 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13776 unsigned NumArgs = MI->getNumOperands();
13777 for (unsigned i = 1; i < NumArgs; ++i) {
13778 MachineOperand &Op = MI->getOperand(i);
13779 if (!(Op.isReg() && Op.isImplicit()))
13780 MIB.addOperand(Op);
13782 if (MI->hasOneMemOperand())
13783 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13785 BuildMI(*BB, MI, dl,
13786 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13787 .addReg(X86::XMM0);
13789 MI->eraseFromParent();
13793 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13794 // defs in an instruction pattern
13795 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13796 const TargetInstrInfo *TII) {
13798 switch (MI->getOpcode()) {
13799 default: llvm_unreachable("illegal opcode!");
13800 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13801 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13802 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13803 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13804 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13805 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13806 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13807 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13810 DebugLoc dl = MI->getDebugLoc();
13811 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13813 unsigned NumArgs = MI->getNumOperands(); // remove the results
13814 for (unsigned i = 1; i < NumArgs; ++i) {
13815 MachineOperand &Op = MI->getOperand(i);
13816 if (!(Op.isReg() && Op.isImplicit()))
13817 MIB.addOperand(Op);
13819 if (MI->hasOneMemOperand())
13820 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13822 BuildMI(*BB, MI, dl,
13823 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13826 MI->eraseFromParent();
13830 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13831 const TargetInstrInfo *TII,
13832 const X86Subtarget* Subtarget) {
13833 DebugLoc dl = MI->getDebugLoc();
13835 // Address into RAX/EAX, other two args into ECX, EDX.
13836 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13837 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13838 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13839 for (int i = 0; i < X86::AddrNumOperands; ++i)
13840 MIB.addOperand(MI->getOperand(i));
13842 unsigned ValOps = X86::AddrNumOperands;
13843 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13844 .addReg(MI->getOperand(ValOps).getReg());
13845 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13846 .addReg(MI->getOperand(ValOps+1).getReg());
13848 // The instruction doesn't actually take any operands though.
13849 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13851 MI->eraseFromParent(); // The pseudo is gone now.
13855 MachineBasicBlock *
13856 X86TargetLowering::EmitVAARG64WithCustomInserter(
13858 MachineBasicBlock *MBB) const {
13859 // Emit va_arg instruction on X86-64.
13861 // Operands to this pseudo-instruction:
13862 // 0 ) Output : destination address (reg)
13863 // 1-5) Input : va_list address (addr, i64mem)
13864 // 6 ) ArgSize : Size (in bytes) of vararg type
13865 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13866 // 8 ) Align : Alignment of type
13867 // 9 ) EFLAGS (implicit-def)
13869 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13870 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13872 unsigned DestReg = MI->getOperand(0).getReg();
13873 MachineOperand &Base = MI->getOperand(1);
13874 MachineOperand &Scale = MI->getOperand(2);
13875 MachineOperand &Index = MI->getOperand(3);
13876 MachineOperand &Disp = MI->getOperand(4);
13877 MachineOperand &Segment = MI->getOperand(5);
13878 unsigned ArgSize = MI->getOperand(6).getImm();
13879 unsigned ArgMode = MI->getOperand(7).getImm();
13880 unsigned Align = MI->getOperand(8).getImm();
13882 // Memory Reference
13883 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13884 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13885 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13887 // Machine Information
13888 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13889 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13890 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13891 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13892 DebugLoc DL = MI->getDebugLoc();
13894 // struct va_list {
13897 // i64 overflow_area (address)
13898 // i64 reg_save_area (address)
13900 // sizeof(va_list) = 24
13901 // alignment(va_list) = 8
13903 unsigned TotalNumIntRegs = 6;
13904 unsigned TotalNumXMMRegs = 8;
13905 bool UseGPOffset = (ArgMode == 1);
13906 bool UseFPOffset = (ArgMode == 2);
13907 unsigned MaxOffset = TotalNumIntRegs * 8 +
13908 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13910 /* Align ArgSize to a multiple of 8 */
13911 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13912 bool NeedsAlign = (Align > 8);
13914 MachineBasicBlock *thisMBB = MBB;
13915 MachineBasicBlock *overflowMBB;
13916 MachineBasicBlock *offsetMBB;
13917 MachineBasicBlock *endMBB;
13919 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13920 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13921 unsigned OffsetReg = 0;
13923 if (!UseGPOffset && !UseFPOffset) {
13924 // If we only pull from the overflow region, we don't create a branch.
13925 // We don't need to alter control flow.
13926 OffsetDestReg = 0; // unused
13927 OverflowDestReg = DestReg;
13930 overflowMBB = thisMBB;
13933 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13934 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13935 // If not, pull from overflow_area. (branch to overflowMBB)
13940 // offsetMBB overflowMBB
13945 // Registers for the PHI in endMBB
13946 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13947 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13949 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13950 MachineFunction *MF = MBB->getParent();
13951 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13952 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13953 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13955 MachineFunction::iterator MBBIter = MBB;
13958 // Insert the new basic blocks
13959 MF->insert(MBBIter, offsetMBB);
13960 MF->insert(MBBIter, overflowMBB);
13961 MF->insert(MBBIter, endMBB);
13963 // Transfer the remainder of MBB and its successor edges to endMBB.
13964 endMBB->splice(endMBB->begin(), thisMBB,
13965 llvm::next(MachineBasicBlock::iterator(MI)),
13967 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13969 // Make offsetMBB and overflowMBB successors of thisMBB
13970 thisMBB->addSuccessor(offsetMBB);
13971 thisMBB->addSuccessor(overflowMBB);
13973 // endMBB is a successor of both offsetMBB and overflowMBB
13974 offsetMBB->addSuccessor(endMBB);
13975 overflowMBB->addSuccessor(endMBB);
13977 // Load the offset value into a register
13978 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13979 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13983 .addDisp(Disp, UseFPOffset ? 4 : 0)
13984 .addOperand(Segment)
13985 .setMemRefs(MMOBegin, MMOEnd);
13987 // Check if there is enough room left to pull this argument.
13988 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13990 .addImm(MaxOffset + 8 - ArgSizeA8);
13992 // Branch to "overflowMBB" if offset >= max
13993 // Fall through to "offsetMBB" otherwise
13994 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13995 .addMBB(overflowMBB);
13998 // In offsetMBB, emit code to use the reg_save_area.
14000 assert(OffsetReg != 0);
14002 // Read the reg_save_area address.
14003 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14004 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14009 .addOperand(Segment)
14010 .setMemRefs(MMOBegin, MMOEnd);
14012 // Zero-extend the offset
14013 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14014 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14017 .addImm(X86::sub_32bit);
14019 // Add the offset to the reg_save_area to get the final address.
14020 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14021 .addReg(OffsetReg64)
14022 .addReg(RegSaveReg);
14024 // Compute the offset for the next argument
14025 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14026 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14028 .addImm(UseFPOffset ? 16 : 8);
14030 // Store it back into the va_list.
14031 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14035 .addDisp(Disp, UseFPOffset ? 4 : 0)
14036 .addOperand(Segment)
14037 .addReg(NextOffsetReg)
14038 .setMemRefs(MMOBegin, MMOEnd);
14041 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14046 // Emit code to use overflow area
14049 // Load the overflow_area address into a register.
14050 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14051 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14056 .addOperand(Segment)
14057 .setMemRefs(MMOBegin, MMOEnd);
14059 // If we need to align it, do so. Otherwise, just copy the address
14060 // to OverflowDestReg.
14062 // Align the overflow address
14063 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14064 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14066 // aligned_addr = (addr + (align-1)) & ~(align-1)
14067 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14068 .addReg(OverflowAddrReg)
14071 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14073 .addImm(~(uint64_t)(Align-1));
14075 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14076 .addReg(OverflowAddrReg);
14079 // Compute the next overflow address after this argument.
14080 // (the overflow address should be kept 8-byte aligned)
14081 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14082 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14083 .addReg(OverflowDestReg)
14084 .addImm(ArgSizeA8);
14086 // Store the new overflow address.
14087 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14092 .addOperand(Segment)
14093 .addReg(NextAddrReg)
14094 .setMemRefs(MMOBegin, MMOEnd);
14096 // If we branched, emit the PHI to the front of endMBB.
14098 BuildMI(*endMBB, endMBB->begin(), DL,
14099 TII->get(X86::PHI), DestReg)
14100 .addReg(OffsetDestReg).addMBB(offsetMBB)
14101 .addReg(OverflowDestReg).addMBB(overflowMBB);
14104 // Erase the pseudo instruction
14105 MI->eraseFromParent();
14110 MachineBasicBlock *
14111 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14113 MachineBasicBlock *MBB) const {
14114 // Emit code to save XMM registers to the stack. The ABI says that the
14115 // number of registers to save is given in %al, so it's theoretically
14116 // possible to do an indirect jump trick to avoid saving all of them,
14117 // however this code takes a simpler approach and just executes all
14118 // of the stores if %al is non-zero. It's less code, and it's probably
14119 // easier on the hardware branch predictor, and stores aren't all that
14120 // expensive anyway.
14122 // Create the new basic blocks. One block contains all the XMM stores,
14123 // and one block is the final destination regardless of whether any
14124 // stores were performed.
14125 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14126 MachineFunction *F = MBB->getParent();
14127 MachineFunction::iterator MBBIter = MBB;
14129 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14130 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14131 F->insert(MBBIter, XMMSaveMBB);
14132 F->insert(MBBIter, EndMBB);
14134 // Transfer the remainder of MBB and its successor edges to EndMBB.
14135 EndMBB->splice(EndMBB->begin(), MBB,
14136 llvm::next(MachineBasicBlock::iterator(MI)),
14138 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14140 // The original block will now fall through to the XMM save block.
14141 MBB->addSuccessor(XMMSaveMBB);
14142 // The XMMSaveMBB will fall through to the end block.
14143 XMMSaveMBB->addSuccessor(EndMBB);
14145 // Now add the instructions.
14146 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14147 DebugLoc DL = MI->getDebugLoc();
14149 unsigned CountReg = MI->getOperand(0).getReg();
14150 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14151 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14153 if (!Subtarget->isTargetWin64()) {
14154 // If %al is 0, branch around the XMM save block.
14155 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14156 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14157 MBB->addSuccessor(EndMBB);
14160 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14161 // In the XMM save block, save all the XMM argument registers.
14162 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14163 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14164 MachineMemOperand *MMO =
14165 F->getMachineMemOperand(
14166 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14167 MachineMemOperand::MOStore,
14168 /*Size=*/16, /*Align=*/16);
14169 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14170 .addFrameIndex(RegSaveFrameIndex)
14171 .addImm(/*Scale=*/1)
14172 .addReg(/*IndexReg=*/0)
14173 .addImm(/*Disp=*/Offset)
14174 .addReg(/*Segment=*/0)
14175 .addReg(MI->getOperand(i).getReg())
14176 .addMemOperand(MMO);
14179 MI->eraseFromParent(); // The pseudo instruction is gone now.
14184 // The EFLAGS operand of SelectItr might be missing a kill marker
14185 // because there were multiple uses of EFLAGS, and ISel didn't know
14186 // which to mark. Figure out whether SelectItr should have had a
14187 // kill marker, and set it if it should. Returns the correct kill
14189 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14190 MachineBasicBlock* BB,
14191 const TargetRegisterInfo* TRI) {
14192 // Scan forward through BB for a use/def of EFLAGS.
14193 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14194 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14195 const MachineInstr& mi = *miI;
14196 if (mi.readsRegister(X86::EFLAGS))
14198 if (mi.definesRegister(X86::EFLAGS))
14199 break; // Should have kill-flag - update below.
14202 // If we hit the end of the block, check whether EFLAGS is live into a
14204 if (miI == BB->end()) {
14205 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14206 sEnd = BB->succ_end();
14207 sItr != sEnd; ++sItr) {
14208 MachineBasicBlock* succ = *sItr;
14209 if (succ->isLiveIn(X86::EFLAGS))
14214 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14215 // out. SelectMI should have a kill flag on EFLAGS.
14216 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14220 MachineBasicBlock *
14221 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14222 MachineBasicBlock *BB) const {
14223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14224 DebugLoc DL = MI->getDebugLoc();
14226 // To "insert" a SELECT_CC instruction, we actually have to insert the
14227 // diamond control-flow pattern. The incoming instruction knows the
14228 // destination vreg to set, the condition code register to branch on, the
14229 // true/false values to select between, and a branch opcode to use.
14230 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14231 MachineFunction::iterator It = BB;
14237 // cmpTY ccX, r1, r2
14239 // fallthrough --> copy0MBB
14240 MachineBasicBlock *thisMBB = BB;
14241 MachineFunction *F = BB->getParent();
14242 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14243 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14244 F->insert(It, copy0MBB);
14245 F->insert(It, sinkMBB);
14247 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14248 // live into the sink and copy blocks.
14249 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14250 if (!MI->killsRegister(X86::EFLAGS) &&
14251 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14252 copy0MBB->addLiveIn(X86::EFLAGS);
14253 sinkMBB->addLiveIn(X86::EFLAGS);
14256 // Transfer the remainder of BB and its successor edges to sinkMBB.
14257 sinkMBB->splice(sinkMBB->begin(), BB,
14258 llvm::next(MachineBasicBlock::iterator(MI)),
14260 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14262 // Add the true and fallthrough blocks as its successors.
14263 BB->addSuccessor(copy0MBB);
14264 BB->addSuccessor(sinkMBB);
14266 // Create the conditional branch instruction.
14268 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14269 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14272 // %FalseValue = ...
14273 // # fallthrough to sinkMBB
14274 copy0MBB->addSuccessor(sinkMBB);
14277 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14279 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14280 TII->get(X86::PHI), MI->getOperand(0).getReg())
14281 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14282 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14284 MI->eraseFromParent(); // The pseudo instruction is gone now.
14288 MachineBasicBlock *
14289 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14290 bool Is64Bit) const {
14291 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14292 DebugLoc DL = MI->getDebugLoc();
14293 MachineFunction *MF = BB->getParent();
14294 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14296 assert(getTargetMachine().Options.EnableSegmentedStacks);
14298 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14299 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14302 // ... [Till the alloca]
14303 // If stacklet is not large enough, jump to mallocMBB
14306 // Allocate by subtracting from RSP
14307 // Jump to continueMBB
14310 // Allocate by call to runtime
14314 // [rest of original BB]
14317 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14318 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14319 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14321 MachineRegisterInfo &MRI = MF->getRegInfo();
14322 const TargetRegisterClass *AddrRegClass =
14323 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14325 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14326 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14327 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14328 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14329 sizeVReg = MI->getOperand(1).getReg(),
14330 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14332 MachineFunction::iterator MBBIter = BB;
14335 MF->insert(MBBIter, bumpMBB);
14336 MF->insert(MBBIter, mallocMBB);
14337 MF->insert(MBBIter, continueMBB);
14339 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14340 (MachineBasicBlock::iterator(MI)), BB->end());
14341 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14343 // Add code to the main basic block to check if the stack limit has been hit,
14344 // and if so, jump to mallocMBB otherwise to bumpMBB.
14345 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14346 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14347 .addReg(tmpSPVReg).addReg(sizeVReg);
14348 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14349 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14350 .addReg(SPLimitVReg);
14351 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14353 // bumpMBB simply decreases the stack pointer, since we know the current
14354 // stacklet has enough space.
14355 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14356 .addReg(SPLimitVReg);
14357 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14358 .addReg(SPLimitVReg);
14359 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14361 // Calls into a routine in libgcc to allocate more space from the heap.
14362 const uint32_t *RegMask =
14363 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14365 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14367 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14368 .addExternalSymbol("__morestack_allocate_stack_space")
14369 .addRegMask(RegMask)
14370 .addReg(X86::RDI, RegState::Implicit)
14371 .addReg(X86::RAX, RegState::ImplicitDefine);
14373 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14375 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14376 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14377 .addExternalSymbol("__morestack_allocate_stack_space")
14378 .addRegMask(RegMask)
14379 .addReg(X86::EAX, RegState::ImplicitDefine);
14383 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14386 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14387 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14388 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14390 // Set up the CFG correctly.
14391 BB->addSuccessor(bumpMBB);
14392 BB->addSuccessor(mallocMBB);
14393 mallocMBB->addSuccessor(continueMBB);
14394 bumpMBB->addSuccessor(continueMBB);
14396 // Take care of the PHI nodes.
14397 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14398 MI->getOperand(0).getReg())
14399 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14400 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14402 // Delete the original pseudo instruction.
14403 MI->eraseFromParent();
14406 return continueMBB;
14409 MachineBasicBlock *
14410 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14411 MachineBasicBlock *BB) const {
14412 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14413 DebugLoc DL = MI->getDebugLoc();
14415 assert(!Subtarget->isTargetEnvMacho());
14417 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14418 // non-trivial part is impdef of ESP.
14420 if (Subtarget->isTargetWin64()) {
14421 if (Subtarget->isTargetCygMing()) {
14422 // ___chkstk(Mingw64):
14423 // Clobbers R10, R11, RAX and EFLAGS.
14425 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14426 .addExternalSymbol("___chkstk")
14427 .addReg(X86::RAX, RegState::Implicit)
14428 .addReg(X86::RSP, RegState::Implicit)
14429 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14430 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14431 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14433 // __chkstk(MSVCRT): does not update stack pointer.
14434 // Clobbers R10, R11 and EFLAGS.
14435 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14436 .addExternalSymbol("__chkstk")
14437 .addReg(X86::RAX, RegState::Implicit)
14438 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14439 // RAX has the offset to be subtracted from RSP.
14440 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14445 const char *StackProbeSymbol =
14446 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14448 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14449 .addExternalSymbol(StackProbeSymbol)
14450 .addReg(X86::EAX, RegState::Implicit)
14451 .addReg(X86::ESP, RegState::Implicit)
14452 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14453 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14454 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14457 MI->eraseFromParent(); // The pseudo instruction is gone now.
14461 MachineBasicBlock *
14462 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14463 MachineBasicBlock *BB) const {
14464 // This is pretty easy. We're taking the value that we received from
14465 // our load from the relocation, sticking it in either RDI (x86-64)
14466 // or EAX and doing an indirect call. The return value will then
14467 // be in the normal return register.
14468 const X86InstrInfo *TII
14469 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14470 DebugLoc DL = MI->getDebugLoc();
14471 MachineFunction *F = BB->getParent();
14473 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14474 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14476 // Get a register mask for the lowered call.
14477 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14478 // proper register mask.
14479 const uint32_t *RegMask =
14480 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14481 if (Subtarget->is64Bit()) {
14482 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14483 TII->get(X86::MOV64rm), X86::RDI)
14485 .addImm(0).addReg(0)
14486 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14487 MI->getOperand(3).getTargetFlags())
14489 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14490 addDirectMem(MIB, X86::RDI);
14491 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14492 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14493 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14494 TII->get(X86::MOV32rm), X86::EAX)
14496 .addImm(0).addReg(0)
14497 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14498 MI->getOperand(3).getTargetFlags())
14500 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14501 addDirectMem(MIB, X86::EAX);
14502 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14504 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14505 TII->get(X86::MOV32rm), X86::EAX)
14506 .addReg(TII->getGlobalBaseReg(F))
14507 .addImm(0).addReg(0)
14508 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14509 MI->getOperand(3).getTargetFlags())
14511 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14512 addDirectMem(MIB, X86::EAX);
14513 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14516 MI->eraseFromParent(); // The pseudo instruction is gone now.
14520 MachineBasicBlock *
14521 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14522 MachineBasicBlock *MBB) const {
14523 DebugLoc DL = MI->getDebugLoc();
14524 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14526 MachineFunction *MF = MBB->getParent();
14527 MachineRegisterInfo &MRI = MF->getRegInfo();
14529 const BasicBlock *BB = MBB->getBasicBlock();
14530 MachineFunction::iterator I = MBB;
14533 // Memory Reference
14534 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14535 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14538 unsigned MemOpndSlot = 0;
14540 unsigned CurOp = 0;
14542 DstReg = MI->getOperand(CurOp++).getReg();
14543 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14544 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14545 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14546 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14548 MemOpndSlot = CurOp;
14550 MVT PVT = getPointerTy();
14551 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14552 "Invalid Pointer Size!");
14554 // For v = setjmp(buf), we generate
14557 // buf[LabelOffset] = restoreMBB
14558 // SjLjSetup restoreMBB
14564 // v = phi(main, restore)
14569 MachineBasicBlock *thisMBB = MBB;
14570 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14571 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14572 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14573 MF->insert(I, mainMBB);
14574 MF->insert(I, sinkMBB);
14575 MF->push_back(restoreMBB);
14577 MachineInstrBuilder MIB;
14579 // Transfer the remainder of BB and its successor edges to sinkMBB.
14580 sinkMBB->splice(sinkMBB->begin(), MBB,
14581 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14582 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14585 unsigned PtrStoreOpc = 0;
14586 unsigned LabelReg = 0;
14587 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14588 Reloc::Model RM = getTargetMachine().getRelocationModel();
14589 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14590 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14592 // Prepare IP either in reg or imm.
14593 if (!UseImmLabel) {
14594 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14595 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14596 LabelReg = MRI.createVirtualRegister(PtrRC);
14597 if (Subtarget->is64Bit()) {
14598 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14602 .addMBB(restoreMBB)
14605 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14606 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14607 .addReg(XII->getGlobalBaseReg(MF))
14610 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14614 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14616 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14617 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14618 if (i == X86::AddrDisp)
14619 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14621 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14624 MIB.addReg(LabelReg);
14626 MIB.addMBB(restoreMBB);
14627 MIB.setMemRefs(MMOBegin, MMOEnd);
14629 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14630 .addMBB(restoreMBB);
14632 const X86RegisterInfo *RegInfo =
14633 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14634 MIB.addRegMask(RegInfo->getNoPreservedMask());
14635 thisMBB->addSuccessor(mainMBB);
14636 thisMBB->addSuccessor(restoreMBB);
14640 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14641 mainMBB->addSuccessor(sinkMBB);
14644 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14645 TII->get(X86::PHI), DstReg)
14646 .addReg(mainDstReg).addMBB(mainMBB)
14647 .addReg(restoreDstReg).addMBB(restoreMBB);
14650 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14651 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14652 restoreMBB->addSuccessor(sinkMBB);
14654 MI->eraseFromParent();
14658 MachineBasicBlock *
14659 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14660 MachineBasicBlock *MBB) const {
14661 DebugLoc DL = MI->getDebugLoc();
14662 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14664 MachineFunction *MF = MBB->getParent();
14665 MachineRegisterInfo &MRI = MF->getRegInfo();
14667 // Memory Reference
14668 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14669 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14671 MVT PVT = getPointerTy();
14672 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14673 "Invalid Pointer Size!");
14675 const TargetRegisterClass *RC =
14676 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14677 unsigned Tmp = MRI.createVirtualRegister(RC);
14678 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14679 const X86RegisterInfo *RegInfo =
14680 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14681 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14682 unsigned SP = RegInfo->getStackRegister();
14684 MachineInstrBuilder MIB;
14686 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14687 const int64_t SPOffset = 2 * PVT.getStoreSize();
14689 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14690 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14693 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14694 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14695 MIB.addOperand(MI->getOperand(i));
14696 MIB.setMemRefs(MMOBegin, MMOEnd);
14698 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14699 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14700 if (i == X86::AddrDisp)
14701 MIB.addDisp(MI->getOperand(i), LabelOffset);
14703 MIB.addOperand(MI->getOperand(i));
14705 MIB.setMemRefs(MMOBegin, MMOEnd);
14707 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14708 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14709 if (i == X86::AddrDisp)
14710 MIB.addDisp(MI->getOperand(i), SPOffset);
14712 MIB.addOperand(MI->getOperand(i));
14714 MIB.setMemRefs(MMOBegin, MMOEnd);
14716 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14718 MI->eraseFromParent();
14722 MachineBasicBlock *
14723 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14724 MachineBasicBlock *BB) const {
14725 switch (MI->getOpcode()) {
14726 default: llvm_unreachable("Unexpected instr type to insert");
14727 case X86::TAILJMPd64:
14728 case X86::TAILJMPr64:
14729 case X86::TAILJMPm64:
14730 llvm_unreachable("TAILJMP64 would not be touched here.");
14731 case X86::TCRETURNdi64:
14732 case X86::TCRETURNri64:
14733 case X86::TCRETURNmi64:
14735 case X86::WIN_ALLOCA:
14736 return EmitLoweredWinAlloca(MI, BB);
14737 case X86::SEG_ALLOCA_32:
14738 return EmitLoweredSegAlloca(MI, BB, false);
14739 case X86::SEG_ALLOCA_64:
14740 return EmitLoweredSegAlloca(MI, BB, true);
14741 case X86::TLSCall_32:
14742 case X86::TLSCall_64:
14743 return EmitLoweredTLSCall(MI, BB);
14744 case X86::CMOV_GR8:
14745 case X86::CMOV_FR32:
14746 case X86::CMOV_FR64:
14747 case X86::CMOV_V4F32:
14748 case X86::CMOV_V2F64:
14749 case X86::CMOV_V2I64:
14750 case X86::CMOV_V8F32:
14751 case X86::CMOV_V4F64:
14752 case X86::CMOV_V4I64:
14753 case X86::CMOV_GR16:
14754 case X86::CMOV_GR32:
14755 case X86::CMOV_RFP32:
14756 case X86::CMOV_RFP64:
14757 case X86::CMOV_RFP80:
14758 return EmitLoweredSelect(MI, BB);
14760 case X86::FP32_TO_INT16_IN_MEM:
14761 case X86::FP32_TO_INT32_IN_MEM:
14762 case X86::FP32_TO_INT64_IN_MEM:
14763 case X86::FP64_TO_INT16_IN_MEM:
14764 case X86::FP64_TO_INT32_IN_MEM:
14765 case X86::FP64_TO_INT64_IN_MEM:
14766 case X86::FP80_TO_INT16_IN_MEM:
14767 case X86::FP80_TO_INT32_IN_MEM:
14768 case X86::FP80_TO_INT64_IN_MEM: {
14769 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14770 DebugLoc DL = MI->getDebugLoc();
14772 // Change the floating point control register to use "round towards zero"
14773 // mode when truncating to an integer value.
14774 MachineFunction *F = BB->getParent();
14775 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14776 addFrameReference(BuildMI(*BB, MI, DL,
14777 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14779 // Load the old value of the high byte of the control word...
14781 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14782 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14785 // Set the high part to be round to zero...
14786 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14789 // Reload the modified control word now...
14790 addFrameReference(BuildMI(*BB, MI, DL,
14791 TII->get(X86::FLDCW16m)), CWFrameIdx);
14793 // Restore the memory image of control word to original value
14794 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14797 // Get the X86 opcode to use.
14799 switch (MI->getOpcode()) {
14800 default: llvm_unreachable("illegal opcode!");
14801 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14802 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14803 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14804 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14805 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14806 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14807 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14808 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14809 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14813 MachineOperand &Op = MI->getOperand(0);
14815 AM.BaseType = X86AddressMode::RegBase;
14816 AM.Base.Reg = Op.getReg();
14818 AM.BaseType = X86AddressMode::FrameIndexBase;
14819 AM.Base.FrameIndex = Op.getIndex();
14821 Op = MI->getOperand(1);
14823 AM.Scale = Op.getImm();
14824 Op = MI->getOperand(2);
14826 AM.IndexReg = Op.getImm();
14827 Op = MI->getOperand(3);
14828 if (Op.isGlobal()) {
14829 AM.GV = Op.getGlobal();
14831 AM.Disp = Op.getImm();
14833 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14834 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14836 // Reload the original control word now.
14837 addFrameReference(BuildMI(*BB, MI, DL,
14838 TII->get(X86::FLDCW16m)), CWFrameIdx);
14840 MI->eraseFromParent(); // The pseudo instruction is gone now.
14843 // String/text processing lowering.
14844 case X86::PCMPISTRM128REG:
14845 case X86::VPCMPISTRM128REG:
14846 case X86::PCMPISTRM128MEM:
14847 case X86::VPCMPISTRM128MEM:
14848 case X86::PCMPESTRM128REG:
14849 case X86::VPCMPESTRM128REG:
14850 case X86::PCMPESTRM128MEM:
14851 case X86::VPCMPESTRM128MEM:
14852 assert(Subtarget->hasSSE42() &&
14853 "Target must have SSE4.2 or AVX features enabled");
14854 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14856 // String/text processing lowering.
14857 case X86::PCMPISTRIREG:
14858 case X86::VPCMPISTRIREG:
14859 case X86::PCMPISTRIMEM:
14860 case X86::VPCMPISTRIMEM:
14861 case X86::PCMPESTRIREG:
14862 case X86::VPCMPESTRIREG:
14863 case X86::PCMPESTRIMEM:
14864 case X86::VPCMPESTRIMEM:
14865 assert(Subtarget->hasSSE42() &&
14866 "Target must have SSE4.2 or AVX features enabled");
14867 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14869 // Thread synchronization.
14871 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14875 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14877 // Atomic Lowering.
14878 case X86::ATOMAND8:
14879 case X86::ATOMAND16:
14880 case X86::ATOMAND32:
14881 case X86::ATOMAND64:
14884 case X86::ATOMOR16:
14885 case X86::ATOMOR32:
14886 case X86::ATOMOR64:
14888 case X86::ATOMXOR16:
14889 case X86::ATOMXOR8:
14890 case X86::ATOMXOR32:
14891 case X86::ATOMXOR64:
14893 case X86::ATOMNAND8:
14894 case X86::ATOMNAND16:
14895 case X86::ATOMNAND32:
14896 case X86::ATOMNAND64:
14898 case X86::ATOMMAX8:
14899 case X86::ATOMMAX16:
14900 case X86::ATOMMAX32:
14901 case X86::ATOMMAX64:
14903 case X86::ATOMMIN8:
14904 case X86::ATOMMIN16:
14905 case X86::ATOMMIN32:
14906 case X86::ATOMMIN64:
14908 case X86::ATOMUMAX8:
14909 case X86::ATOMUMAX16:
14910 case X86::ATOMUMAX32:
14911 case X86::ATOMUMAX64:
14913 case X86::ATOMUMIN8:
14914 case X86::ATOMUMIN16:
14915 case X86::ATOMUMIN32:
14916 case X86::ATOMUMIN64:
14917 return EmitAtomicLoadArith(MI, BB);
14919 // This group does 64-bit operations on a 32-bit host.
14920 case X86::ATOMAND6432:
14921 case X86::ATOMOR6432:
14922 case X86::ATOMXOR6432:
14923 case X86::ATOMNAND6432:
14924 case X86::ATOMADD6432:
14925 case X86::ATOMSUB6432:
14926 case X86::ATOMMAX6432:
14927 case X86::ATOMMIN6432:
14928 case X86::ATOMUMAX6432:
14929 case X86::ATOMUMIN6432:
14930 case X86::ATOMSWAP6432:
14931 return EmitAtomicLoadArith6432(MI, BB);
14933 case X86::VASTART_SAVE_XMM_REGS:
14934 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14936 case X86::VAARG_64:
14937 return EmitVAARG64WithCustomInserter(MI, BB);
14939 case X86::EH_SjLj_SetJmp32:
14940 case X86::EH_SjLj_SetJmp64:
14941 return emitEHSjLjSetJmp(MI, BB);
14943 case X86::EH_SjLj_LongJmp32:
14944 case X86::EH_SjLj_LongJmp64:
14945 return emitEHSjLjLongJmp(MI, BB);
14949 //===----------------------------------------------------------------------===//
14950 // X86 Optimization Hooks
14951 //===----------------------------------------------------------------------===//
14953 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14956 const SelectionDAG &DAG,
14957 unsigned Depth) const {
14958 unsigned BitWidth = KnownZero.getBitWidth();
14959 unsigned Opc = Op.getOpcode();
14960 assert((Opc >= ISD::BUILTIN_OP_END ||
14961 Opc == ISD::INTRINSIC_WO_CHAIN ||
14962 Opc == ISD::INTRINSIC_W_CHAIN ||
14963 Opc == ISD::INTRINSIC_VOID) &&
14964 "Should use MaskedValueIsZero if you don't know whether Op"
14965 " is a target node!");
14967 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14981 // These nodes' second result is a boolean.
14982 if (Op.getResNo() == 0)
14985 case X86ISD::SETCC:
14986 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14988 case ISD::INTRINSIC_WO_CHAIN: {
14989 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14990 unsigned NumLoBits = 0;
14993 case Intrinsic::x86_sse_movmsk_ps:
14994 case Intrinsic::x86_avx_movmsk_ps_256:
14995 case Intrinsic::x86_sse2_movmsk_pd:
14996 case Intrinsic::x86_avx_movmsk_pd_256:
14997 case Intrinsic::x86_mmx_pmovmskb:
14998 case Intrinsic::x86_sse2_pmovmskb_128:
14999 case Intrinsic::x86_avx2_pmovmskb: {
15000 // High bits of movmskp{s|d}, pmovmskb are known zero.
15002 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15003 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15004 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15005 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15006 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15007 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15008 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15009 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15011 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15020 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15021 unsigned Depth) const {
15022 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15023 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15024 return Op.getValueType().getScalarType().getSizeInBits();
15030 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15031 /// node is a GlobalAddress + offset.
15032 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15033 const GlobalValue* &GA,
15034 int64_t &Offset) const {
15035 if (N->getOpcode() == X86ISD::Wrapper) {
15036 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15037 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15038 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15042 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15045 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15046 /// same as extracting the high 128-bit part of 256-bit vector and then
15047 /// inserting the result into the low part of a new 256-bit vector
15048 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15049 EVT VT = SVOp->getValueType(0);
15050 unsigned NumElems = VT.getVectorNumElements();
15052 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15053 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15054 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15055 SVOp->getMaskElt(j) >= 0)
15061 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15062 /// same as extracting the low 128-bit part of 256-bit vector and then
15063 /// inserting the result into the high part of a new 256-bit vector
15064 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15065 EVT VT = SVOp->getValueType(0);
15066 unsigned NumElems = VT.getVectorNumElements();
15068 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15069 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15070 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15071 SVOp->getMaskElt(j) >= 0)
15077 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15078 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15079 TargetLowering::DAGCombinerInfo &DCI,
15080 const X86Subtarget* Subtarget) {
15082 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15083 SDValue V1 = SVOp->getOperand(0);
15084 SDValue V2 = SVOp->getOperand(1);
15085 EVT VT = SVOp->getValueType(0);
15086 unsigned NumElems = VT.getVectorNumElements();
15088 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15089 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15093 // V UNDEF BUILD_VECTOR UNDEF
15095 // CONCAT_VECTOR CONCAT_VECTOR
15098 // RESULT: V + zero extended
15100 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15101 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15102 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15105 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15108 // To match the shuffle mask, the first half of the mask should
15109 // be exactly the first vector, and all the rest a splat with the
15110 // first element of the second one.
15111 for (unsigned i = 0; i != NumElems/2; ++i)
15112 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15113 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15116 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15117 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15118 if (Ld->hasNUsesOfValue(1, 0)) {
15119 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15120 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15122 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15123 array_lengthof(Ops),
15125 Ld->getPointerInfo(),
15126 Ld->getAlignment(),
15127 false/*isVolatile*/, true/*ReadMem*/,
15128 false/*WriteMem*/);
15130 // Make sure the newly-created LOAD is in the same position as Ld in
15131 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15132 // and update uses of Ld's output chain to use the TokenFactor.
15133 if (Ld->hasAnyUseOfValue(1)) {
15134 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15135 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15136 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15137 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15138 SDValue(ResNode.getNode(), 1));
15141 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15145 // Emit a zeroed vector and insert the desired subvector on its
15147 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15148 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15149 return DCI.CombineTo(N, InsV);
15152 //===--------------------------------------------------------------------===//
15153 // Combine some shuffles into subvector extracts and inserts:
15156 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15157 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15158 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15159 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15160 return DCI.CombineTo(N, InsV);
15163 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15164 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15165 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15166 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15167 return DCI.CombineTo(N, InsV);
15173 /// PerformShuffleCombine - Performs several different shuffle combines.
15174 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15175 TargetLowering::DAGCombinerInfo &DCI,
15176 const X86Subtarget *Subtarget) {
15178 EVT VT = N->getValueType(0);
15180 // Don't create instructions with illegal types after legalize types has run.
15181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15182 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15185 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15186 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15187 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15188 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15190 // Only handle 128 wide vector from here on.
15191 if (!VT.is128BitVector())
15194 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15195 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15196 // consecutive, non-overlapping, and in the right order.
15197 SmallVector<SDValue, 16> Elts;
15198 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15199 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15201 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15204 /// PerformTruncateCombine - Converts truncate operation to
15205 /// a sequence of vector shuffle operations.
15206 /// It is possible when we truncate 256-bit vector to 128-bit vector
15207 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15208 TargetLowering::DAGCombinerInfo &DCI,
15209 const X86Subtarget *Subtarget) {
15213 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15214 /// specific shuffle of a load can be folded into a single element load.
15215 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15216 /// shuffles have been customed lowered so we need to handle those here.
15217 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15218 TargetLowering::DAGCombinerInfo &DCI) {
15219 if (DCI.isBeforeLegalizeOps())
15222 SDValue InVec = N->getOperand(0);
15223 SDValue EltNo = N->getOperand(1);
15225 if (!isa<ConstantSDNode>(EltNo))
15228 EVT VT = InVec.getValueType();
15230 bool HasShuffleIntoBitcast = false;
15231 if (InVec.getOpcode() == ISD::BITCAST) {
15232 // Don't duplicate a load with other uses.
15233 if (!InVec.hasOneUse())
15235 EVT BCVT = InVec.getOperand(0).getValueType();
15236 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15238 InVec = InVec.getOperand(0);
15239 HasShuffleIntoBitcast = true;
15242 if (!isTargetShuffle(InVec.getOpcode()))
15245 // Don't duplicate a load with other uses.
15246 if (!InVec.hasOneUse())
15249 SmallVector<int, 16> ShuffleMask;
15251 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15255 // Select the input vector, guarding against out of range extract vector.
15256 unsigned NumElems = VT.getVectorNumElements();
15257 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15258 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15259 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15260 : InVec.getOperand(1);
15262 // If inputs to shuffle are the same for both ops, then allow 2 uses
15263 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15265 if (LdNode.getOpcode() == ISD::BITCAST) {
15266 // Don't duplicate a load with other uses.
15267 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15270 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15271 LdNode = LdNode.getOperand(0);
15274 if (!ISD::isNormalLoad(LdNode.getNode()))
15277 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15279 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15282 if (HasShuffleIntoBitcast) {
15283 // If there's a bitcast before the shuffle, check if the load type and
15284 // alignment is valid.
15285 unsigned Align = LN0->getAlignment();
15286 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15287 unsigned NewAlign = TLI.getDataLayout()->
15288 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15290 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15294 // All checks match so transform back to vector_shuffle so that DAG combiner
15295 // can finish the job
15298 // Create shuffle node taking into account the case that its a unary shuffle
15299 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15300 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15301 InVec.getOperand(0), Shuffle,
15303 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15304 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15308 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15309 /// generation and convert it from being a bunch of shuffles and extracts
15310 /// to a simple store and scalar loads to extract the elements.
15311 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15312 TargetLowering::DAGCombinerInfo &DCI) {
15313 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15314 if (NewOp.getNode())
15317 SDValue InputVector = N->getOperand(0);
15318 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15319 // from mmx to v2i32 has a single usage.
15320 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15321 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15322 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15323 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15324 N->getValueType(0),
15325 InputVector.getNode()->getOperand(0));
15327 // Only operate on vectors of 4 elements, where the alternative shuffling
15328 // gets to be more expensive.
15329 if (InputVector.getValueType() != MVT::v4i32)
15332 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15333 // single use which is a sign-extend or zero-extend, and all elements are
15335 SmallVector<SDNode *, 4> Uses;
15336 unsigned ExtractedElements = 0;
15337 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15338 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15339 if (UI.getUse().getResNo() != InputVector.getResNo())
15342 SDNode *Extract = *UI;
15343 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15346 if (Extract->getValueType(0) != MVT::i32)
15348 if (!Extract->hasOneUse())
15350 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15351 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15353 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15356 // Record which element was extracted.
15357 ExtractedElements |=
15358 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15360 Uses.push_back(Extract);
15363 // If not all the elements were used, this may not be worthwhile.
15364 if (ExtractedElements != 15)
15367 // Ok, we've now decided to do the transformation.
15368 SDLoc dl(InputVector);
15370 // Store the value to a temporary stack slot.
15371 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15372 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15373 MachinePointerInfo(), false, false, 0);
15375 // Replace each use (extract) with a load of the appropriate element.
15376 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15377 UE = Uses.end(); UI != UE; ++UI) {
15378 SDNode *Extract = *UI;
15380 // cOMpute the element's address.
15381 SDValue Idx = Extract->getOperand(1);
15383 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15384 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15386 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15388 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15389 StackPtr, OffsetVal);
15391 // Load the scalar.
15392 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15393 ScalarAddr, MachinePointerInfo(),
15394 false, false, false, 0);
15396 // Replace the exact with the load.
15397 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15400 // The replacement was made in place; don't return anything.
15404 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15405 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15406 SDValue RHS, SelectionDAG &DAG,
15407 const X86Subtarget *Subtarget) {
15408 if (!VT.isVector())
15411 switch (VT.getSimpleVT().SimpleTy) {
15416 if (!Subtarget->hasAVX2())
15421 if (!Subtarget->hasSSE2())
15425 // SSE2 has only a small subset of the operations.
15426 bool hasUnsigned = Subtarget->hasSSE41() ||
15427 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15428 bool hasSigned = Subtarget->hasSSE41() ||
15429 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15431 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15433 // Check for x CC y ? x : y.
15434 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15435 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15440 return hasUnsigned ? X86ISD::UMIN : 0;
15443 return hasUnsigned ? X86ISD::UMAX : 0;
15446 return hasSigned ? X86ISD::SMIN : 0;
15449 return hasSigned ? X86ISD::SMAX : 0;
15451 // Check for x CC y ? y : x -- a min/max with reversed arms.
15452 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15453 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15458 return hasUnsigned ? X86ISD::UMAX : 0;
15461 return hasUnsigned ? X86ISD::UMIN : 0;
15464 return hasSigned ? X86ISD::SMAX : 0;
15467 return hasSigned ? X86ISD::SMIN : 0;
15474 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15476 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15477 TargetLowering::DAGCombinerInfo &DCI,
15478 const X86Subtarget *Subtarget) {
15480 SDValue Cond = N->getOperand(0);
15481 // Get the LHS/RHS of the select.
15482 SDValue LHS = N->getOperand(1);
15483 SDValue RHS = N->getOperand(2);
15484 EVT VT = LHS.getValueType();
15486 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15487 // instructions match the semantics of the common C idiom x<y?x:y but not
15488 // x<=y?x:y, because of how they handle negative zero (which can be
15489 // ignored in unsafe-math mode).
15490 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15491 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15492 (Subtarget->hasSSE2() ||
15493 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15494 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15496 unsigned Opcode = 0;
15497 // Check for x CC y ? x : y.
15498 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15499 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15503 // Converting this to a min would handle NaNs incorrectly, and swapping
15504 // the operands would cause it to handle comparisons between positive
15505 // and negative zero incorrectly.
15506 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15507 if (!DAG.getTarget().Options.UnsafeFPMath &&
15508 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15510 std::swap(LHS, RHS);
15512 Opcode = X86ISD::FMIN;
15515 // Converting this to a min would handle comparisons between positive
15516 // and negative zero incorrectly.
15517 if (!DAG.getTarget().Options.UnsafeFPMath &&
15518 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15520 Opcode = X86ISD::FMIN;
15523 // Converting this to a min would handle both negative zeros and NaNs
15524 // incorrectly, but we can swap the operands to fix both.
15525 std::swap(LHS, RHS);
15529 Opcode = X86ISD::FMIN;
15533 // Converting this to a max would handle comparisons between positive
15534 // and negative zero incorrectly.
15535 if (!DAG.getTarget().Options.UnsafeFPMath &&
15536 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15538 Opcode = X86ISD::FMAX;
15541 // Converting this to a max would handle NaNs incorrectly, and swapping
15542 // the operands would cause it to handle comparisons between positive
15543 // and negative zero incorrectly.
15544 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15545 if (!DAG.getTarget().Options.UnsafeFPMath &&
15546 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15548 std::swap(LHS, RHS);
15550 Opcode = X86ISD::FMAX;
15553 // Converting this to a max would handle both negative zeros and NaNs
15554 // incorrectly, but we can swap the operands to fix both.
15555 std::swap(LHS, RHS);
15559 Opcode = X86ISD::FMAX;
15562 // Check for x CC y ? y : x -- a min/max with reversed arms.
15563 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15564 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15568 // Converting this to a min would handle comparisons between positive
15569 // and negative zero incorrectly, and swapping the operands would
15570 // cause it to handle NaNs incorrectly.
15571 if (!DAG.getTarget().Options.UnsafeFPMath &&
15572 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15573 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15575 std::swap(LHS, RHS);
15577 Opcode = X86ISD::FMIN;
15580 // Converting this to a min would handle NaNs incorrectly.
15581 if (!DAG.getTarget().Options.UnsafeFPMath &&
15582 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15584 Opcode = X86ISD::FMIN;
15587 // Converting this to a min would handle both negative zeros and NaNs
15588 // incorrectly, but we can swap the operands to fix both.
15589 std::swap(LHS, RHS);
15593 Opcode = X86ISD::FMIN;
15597 // Converting this to a max would handle NaNs incorrectly.
15598 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15600 Opcode = X86ISD::FMAX;
15603 // Converting this to a max would handle comparisons between positive
15604 // and negative zero incorrectly, and swapping the operands would
15605 // cause it to handle NaNs incorrectly.
15606 if (!DAG.getTarget().Options.UnsafeFPMath &&
15607 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15608 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15610 std::swap(LHS, RHS);
15612 Opcode = X86ISD::FMAX;
15615 // Converting this to a max would handle both negative zeros and NaNs
15616 // incorrectly, but we can swap the operands to fix both.
15617 std::swap(LHS, RHS);
15621 Opcode = X86ISD::FMAX;
15627 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15630 // If this is a select between two integer constants, try to do some
15632 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15633 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15634 // Don't do this for crazy integer types.
15635 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15636 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15637 // so that TrueC (the true value) is larger than FalseC.
15638 bool NeedsCondInvert = false;
15640 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15641 // Efficiently invertible.
15642 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15643 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15644 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15645 NeedsCondInvert = true;
15646 std::swap(TrueC, FalseC);
15649 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15650 if (FalseC->getAPIntValue() == 0 &&
15651 TrueC->getAPIntValue().isPowerOf2()) {
15652 if (NeedsCondInvert) // Invert the condition if needed.
15653 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15654 DAG.getConstant(1, Cond.getValueType()));
15656 // Zero extend the condition if needed.
15657 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15659 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15660 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15661 DAG.getConstant(ShAmt, MVT::i8));
15664 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15665 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15666 if (NeedsCondInvert) // Invert the condition if needed.
15667 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15668 DAG.getConstant(1, Cond.getValueType()));
15670 // Zero extend the condition if needed.
15671 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15672 FalseC->getValueType(0), Cond);
15673 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15674 SDValue(FalseC, 0));
15677 // Optimize cases that will turn into an LEA instruction. This requires
15678 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15679 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15680 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15681 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15683 bool isFastMultiplier = false;
15685 switch ((unsigned char)Diff) {
15687 case 1: // result = add base, cond
15688 case 2: // result = lea base( , cond*2)
15689 case 3: // result = lea base(cond, cond*2)
15690 case 4: // result = lea base( , cond*4)
15691 case 5: // result = lea base(cond, cond*4)
15692 case 8: // result = lea base( , cond*8)
15693 case 9: // result = lea base(cond, cond*8)
15694 isFastMultiplier = true;
15699 if (isFastMultiplier) {
15700 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15701 if (NeedsCondInvert) // Invert the condition if needed.
15702 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15703 DAG.getConstant(1, Cond.getValueType()));
15705 // Zero extend the condition if needed.
15706 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15708 // Scale the condition by the difference.
15710 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15711 DAG.getConstant(Diff, Cond.getValueType()));
15713 // Add the base if non-zero.
15714 if (FalseC->getAPIntValue() != 0)
15715 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15716 SDValue(FalseC, 0));
15723 // Canonicalize max and min:
15724 // (x > y) ? x : y -> (x >= y) ? x : y
15725 // (x < y) ? x : y -> (x <= y) ? x : y
15726 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15727 // the need for an extra compare
15728 // against zero. e.g.
15729 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15731 // testl %edi, %edi
15733 // cmovgl %edi, %eax
15737 // cmovsl %eax, %edi
15738 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15739 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15740 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15741 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15746 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15747 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
15748 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15749 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15754 // Match VSELECTs into subs with unsigned saturation.
15755 if (!DCI.isBeforeLegalize() &&
15756 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15757 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15758 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15759 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15760 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15762 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15763 // left side invert the predicate to simplify logic below.
15765 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15767 CC = ISD::getSetCCInverse(CC, true);
15768 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15772 if (Other.getNode() && Other->getNumOperands() == 2 &&
15773 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15774 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15775 SDValue CondRHS = Cond->getOperand(1);
15777 // Look for a general sub with unsigned saturation first.
15778 // x >= y ? x-y : 0 --> subus x, y
15779 // x > y ? x-y : 0 --> subus x, y
15780 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15781 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15782 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15784 // If the RHS is a constant we have to reverse the const canonicalization.
15785 // x > C-1 ? x+-C : 0 --> subus x, C
15786 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15787 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15788 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15789 if (CondRHS.getConstantOperandVal(0) == -A-1)
15790 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15791 DAG.getConstant(-A, VT));
15794 // Another special case: If C was a sign bit, the sub has been
15795 // canonicalized into a xor.
15796 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15797 // it's safe to decanonicalize the xor?
15798 // x s< 0 ? x^C : 0 --> subus x, C
15799 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15800 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15801 isSplatVector(OpRHS.getNode())) {
15802 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15804 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15809 // Try to match a min/max vector operation.
15810 if (!DCI.isBeforeLegalize() &&
15811 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15812 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15813 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15815 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15816 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15817 Cond.getOpcode() == ISD::SETCC) {
15819 assert(Cond.getValueType().isVector() &&
15820 "vector select expects a vector selector!");
15822 EVT IntVT = Cond.getValueType();
15823 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15824 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15826 if (!TValIsAllOnes && !FValIsAllZeros) {
15827 // Try invert the condition if true value is not all 1s and false value
15829 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15830 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15832 if (TValIsAllZeros || FValIsAllOnes) {
15833 SDValue CC = Cond.getOperand(2);
15834 ISD::CondCode NewCC =
15835 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15836 Cond.getOperand(0).getValueType().isInteger());
15837 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15838 std::swap(LHS, RHS);
15839 TValIsAllOnes = FValIsAllOnes;
15840 FValIsAllZeros = TValIsAllZeros;
15844 if (TValIsAllOnes || FValIsAllZeros) {
15847 if (TValIsAllOnes && FValIsAllZeros)
15849 else if (TValIsAllOnes)
15850 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15851 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15852 else if (FValIsAllZeros)
15853 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15854 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15856 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15860 // If we know that this node is legal then we know that it is going to be
15861 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15862 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15863 // to simplify previous instructions.
15864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15865 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15866 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15867 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15869 // Don't optimize vector selects that map to mask-registers.
15873 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15874 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15876 APInt KnownZero, KnownOne;
15877 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15878 DCI.isBeforeLegalizeOps());
15879 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15880 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15881 DCI.CommitTargetLoweringOpt(TLO);
15887 // Check whether a boolean test is testing a boolean value generated by
15888 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15891 // Simplify the following patterns:
15892 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15893 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15894 // to (Op EFLAGS Cond)
15896 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15897 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15898 // to (Op EFLAGS !Cond)
15900 // where Op could be BRCOND or CMOV.
15902 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15903 // Quit if not CMP and SUB with its value result used.
15904 if (Cmp.getOpcode() != X86ISD::CMP &&
15905 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15908 // Quit if not used as a boolean value.
15909 if (CC != X86::COND_E && CC != X86::COND_NE)
15912 // Check CMP operands. One of them should be 0 or 1 and the other should be
15913 // an SetCC or extended from it.
15914 SDValue Op1 = Cmp.getOperand(0);
15915 SDValue Op2 = Cmp.getOperand(1);
15918 const ConstantSDNode* C = 0;
15919 bool needOppositeCond = (CC == X86::COND_E);
15920 bool checkAgainstTrue = false; // Is it a comparison against 1?
15922 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15924 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15926 else // Quit if all operands are not constants.
15929 if (C->getZExtValue() == 1) {
15930 needOppositeCond = !needOppositeCond;
15931 checkAgainstTrue = true;
15932 } else if (C->getZExtValue() != 0)
15933 // Quit if the constant is neither 0 or 1.
15936 bool truncatedToBoolWithAnd = false;
15937 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15938 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15939 SetCC.getOpcode() == ISD::TRUNCATE ||
15940 SetCC.getOpcode() == ISD::AND) {
15941 if (SetCC.getOpcode() == ISD::AND) {
15943 ConstantSDNode *CS;
15944 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15945 CS->getZExtValue() == 1)
15947 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15948 CS->getZExtValue() == 1)
15952 SetCC = SetCC.getOperand(OpIdx);
15953 truncatedToBoolWithAnd = true;
15955 SetCC = SetCC.getOperand(0);
15958 switch (SetCC.getOpcode()) {
15959 case X86ISD::SETCC_CARRY:
15960 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15961 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15962 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15963 // truncated to i1 using 'and'.
15964 if (checkAgainstTrue && !truncatedToBoolWithAnd)
15966 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15967 "Invalid use of SETCC_CARRY!");
15969 case X86ISD::SETCC:
15970 // Set the condition code or opposite one if necessary.
15971 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15972 if (needOppositeCond)
15973 CC = X86::GetOppositeBranchCondition(CC);
15974 return SetCC.getOperand(1);
15975 case X86ISD::CMOV: {
15976 // Check whether false/true value has canonical one, i.e. 0 or 1.
15977 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15978 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15979 // Quit if true value is not a constant.
15982 // Quit if false value is not a constant.
15984 SDValue Op = SetCC.getOperand(0);
15985 // Skip 'zext' or 'trunc' node.
15986 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15987 Op.getOpcode() == ISD::TRUNCATE)
15988 Op = Op.getOperand(0);
15989 // A special case for rdrand/rdseed, where 0 is set if false cond is
15991 if ((Op.getOpcode() != X86ISD::RDRAND &&
15992 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15995 // Quit if false value is not the constant 0 or 1.
15996 bool FValIsFalse = true;
15997 if (FVal && FVal->getZExtValue() != 0) {
15998 if (FVal->getZExtValue() != 1)
16000 // If FVal is 1, opposite cond is needed.
16001 needOppositeCond = !needOppositeCond;
16002 FValIsFalse = false;
16004 // Quit if TVal is not the constant opposite of FVal.
16005 if (FValIsFalse && TVal->getZExtValue() != 1)
16007 if (!FValIsFalse && TVal->getZExtValue() != 0)
16009 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16010 if (needOppositeCond)
16011 CC = X86::GetOppositeBranchCondition(CC);
16012 return SetCC.getOperand(3);
16019 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16020 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16021 TargetLowering::DAGCombinerInfo &DCI,
16022 const X86Subtarget *Subtarget) {
16025 // If the flag operand isn't dead, don't touch this CMOV.
16026 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16029 SDValue FalseOp = N->getOperand(0);
16030 SDValue TrueOp = N->getOperand(1);
16031 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16032 SDValue Cond = N->getOperand(3);
16034 if (CC == X86::COND_E || CC == X86::COND_NE) {
16035 switch (Cond.getOpcode()) {
16039 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16040 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16041 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16047 Flags = checkBoolTestSetCCCombine(Cond, CC);
16048 if (Flags.getNode() &&
16049 // Extra check as FCMOV only supports a subset of X86 cond.
16050 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16051 SDValue Ops[] = { FalseOp, TrueOp,
16052 DAG.getConstant(CC, MVT::i8), Flags };
16053 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16054 Ops, array_lengthof(Ops));
16057 // If this is a select between two integer constants, try to do some
16058 // optimizations. Note that the operands are ordered the opposite of SELECT
16060 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16061 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16062 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16063 // larger than FalseC (the false value).
16064 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16065 CC = X86::GetOppositeBranchCondition(CC);
16066 std::swap(TrueC, FalseC);
16067 std::swap(TrueOp, FalseOp);
16070 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16071 // This is efficient for any integer data type (including i8/i16) and
16073 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16074 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16075 DAG.getConstant(CC, MVT::i8), Cond);
16077 // Zero extend the condition if needed.
16078 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16080 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16081 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16082 DAG.getConstant(ShAmt, MVT::i8));
16083 if (N->getNumValues() == 2) // Dead flag value?
16084 return DCI.CombineTo(N, Cond, SDValue());
16088 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16089 // for any integer data type, including i8/i16.
16090 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16091 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16092 DAG.getConstant(CC, MVT::i8), Cond);
16094 // Zero extend the condition if needed.
16095 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16096 FalseC->getValueType(0), Cond);
16097 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16098 SDValue(FalseC, 0));
16100 if (N->getNumValues() == 2) // Dead flag value?
16101 return DCI.CombineTo(N, Cond, SDValue());
16105 // Optimize cases that will turn into an LEA instruction. This requires
16106 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16107 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16108 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16109 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16111 bool isFastMultiplier = false;
16113 switch ((unsigned char)Diff) {
16115 case 1: // result = add base, cond
16116 case 2: // result = lea base( , cond*2)
16117 case 3: // result = lea base(cond, cond*2)
16118 case 4: // result = lea base( , cond*4)
16119 case 5: // result = lea base(cond, cond*4)
16120 case 8: // result = lea base( , cond*8)
16121 case 9: // result = lea base(cond, cond*8)
16122 isFastMultiplier = true;
16127 if (isFastMultiplier) {
16128 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16129 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16130 DAG.getConstant(CC, MVT::i8), Cond);
16131 // Zero extend the condition if needed.
16132 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16134 // Scale the condition by the difference.
16136 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16137 DAG.getConstant(Diff, Cond.getValueType()));
16139 // Add the base if non-zero.
16140 if (FalseC->getAPIntValue() != 0)
16141 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16142 SDValue(FalseC, 0));
16143 if (N->getNumValues() == 2) // Dead flag value?
16144 return DCI.CombineTo(N, Cond, SDValue());
16151 // Handle these cases:
16152 // (select (x != c), e, c) -> select (x != c), e, x),
16153 // (select (x == c), c, e) -> select (x == c), x, e)
16154 // where the c is an integer constant, and the "select" is the combination
16155 // of CMOV and CMP.
16157 // The rationale for this change is that the conditional-move from a constant
16158 // needs two instructions, however, conditional-move from a register needs
16159 // only one instruction.
16161 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16162 // some instruction-combining opportunities. This opt needs to be
16163 // postponed as late as possible.
16165 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16166 // the DCI.xxxx conditions are provided to postpone the optimization as
16167 // late as possible.
16169 ConstantSDNode *CmpAgainst = 0;
16170 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16171 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16172 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16174 if (CC == X86::COND_NE &&
16175 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16176 CC = X86::GetOppositeBranchCondition(CC);
16177 std::swap(TrueOp, FalseOp);
16180 if (CC == X86::COND_E &&
16181 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16182 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16183 DAG.getConstant(CC, MVT::i8), Cond };
16184 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16185 array_lengthof(Ops));
16193 /// PerformMulCombine - Optimize a single multiply with constant into two
16194 /// in order to implement it with two cheaper instructions, e.g.
16195 /// LEA + SHL, LEA + LEA.
16196 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16197 TargetLowering::DAGCombinerInfo &DCI) {
16198 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16201 EVT VT = N->getValueType(0);
16202 if (VT != MVT::i64)
16205 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16208 uint64_t MulAmt = C->getZExtValue();
16209 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16212 uint64_t MulAmt1 = 0;
16213 uint64_t MulAmt2 = 0;
16214 if ((MulAmt % 9) == 0) {
16216 MulAmt2 = MulAmt / 9;
16217 } else if ((MulAmt % 5) == 0) {
16219 MulAmt2 = MulAmt / 5;
16220 } else if ((MulAmt % 3) == 0) {
16222 MulAmt2 = MulAmt / 3;
16225 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16228 if (isPowerOf2_64(MulAmt2) &&
16229 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16230 // If second multiplifer is pow2, issue it first. We want the multiply by
16231 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16233 std::swap(MulAmt1, MulAmt2);
16236 if (isPowerOf2_64(MulAmt1))
16237 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16238 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16240 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16241 DAG.getConstant(MulAmt1, VT));
16243 if (isPowerOf2_64(MulAmt2))
16244 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16245 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16247 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16248 DAG.getConstant(MulAmt2, VT));
16250 // Do not add new nodes to DAG combiner worklist.
16251 DCI.CombineTo(N, NewMul, false);
16256 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16257 SDValue N0 = N->getOperand(0);
16258 SDValue N1 = N->getOperand(1);
16259 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16260 EVT VT = N0.getValueType();
16262 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16263 // since the result of setcc_c is all zero's or all ones.
16264 if (VT.isInteger() && !VT.isVector() &&
16265 N1C && N0.getOpcode() == ISD::AND &&
16266 N0.getOperand(1).getOpcode() == ISD::Constant) {
16267 SDValue N00 = N0.getOperand(0);
16268 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16269 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16270 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16271 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16272 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16273 APInt ShAmt = N1C->getAPIntValue();
16274 Mask = Mask.shl(ShAmt);
16276 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16277 N00, DAG.getConstant(Mask, VT));
16281 // Hardware support for vector shifts is sparse which makes us scalarize the
16282 // vector operations in many cases. Also, on sandybridge ADD is faster than
16284 // (shl V, 1) -> add V,V
16285 if (isSplatVector(N1.getNode())) {
16286 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16287 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16288 // We shift all of the values by one. In many cases we do not have
16289 // hardware support for this operation. This is better expressed as an ADD
16291 if (N1C && (1 == N1C->getZExtValue())) {
16292 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16299 /// PerformShiftCombine - Combine shifts.
16300 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16301 TargetLowering::DAGCombinerInfo &DCI,
16302 const X86Subtarget *Subtarget) {
16303 if (N->getOpcode() == ISD::SHL) {
16304 SDValue V = PerformSHLCombine(N, DAG);
16305 if (V.getNode()) return V;
16311 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16312 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16313 // and friends. Likewise for OR -> CMPNEQSS.
16314 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16315 TargetLowering::DAGCombinerInfo &DCI,
16316 const X86Subtarget *Subtarget) {
16319 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16320 // we're requiring SSE2 for both.
16321 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16322 SDValue N0 = N->getOperand(0);
16323 SDValue N1 = N->getOperand(1);
16324 SDValue CMP0 = N0->getOperand(1);
16325 SDValue CMP1 = N1->getOperand(1);
16328 // The SETCCs should both refer to the same CMP.
16329 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16332 SDValue CMP00 = CMP0->getOperand(0);
16333 SDValue CMP01 = CMP0->getOperand(1);
16334 EVT VT = CMP00.getValueType();
16336 if (VT == MVT::f32 || VT == MVT::f64) {
16337 bool ExpectingFlags = false;
16338 // Check for any users that want flags:
16339 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16340 !ExpectingFlags && UI != UE; ++UI)
16341 switch (UI->getOpcode()) {
16346 ExpectingFlags = true;
16348 case ISD::CopyToReg:
16349 case ISD::SIGN_EXTEND:
16350 case ISD::ZERO_EXTEND:
16351 case ISD::ANY_EXTEND:
16355 if (!ExpectingFlags) {
16356 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16357 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16359 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16360 X86::CondCode tmp = cc0;
16365 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16366 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16367 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16368 X86ISD::NodeType NTOperator = is64BitFP ?
16369 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16370 // FIXME: need symbolic constants for these magic numbers.
16371 // See X86ATTInstPrinter.cpp:printSSECC().
16372 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16373 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16374 DAG.getConstant(x86cc, MVT::i8));
16375 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16377 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16378 DAG.getConstant(1, MVT::i32));
16379 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16380 return OneBitOfTruth;
16388 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16389 /// so it can be folded inside ANDNP.
16390 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16391 EVT VT = N->getValueType(0);
16393 // Match direct AllOnes for 128 and 256-bit vectors
16394 if (ISD::isBuildVectorAllOnes(N))
16397 // Look through a bit convert.
16398 if (N->getOpcode() == ISD::BITCAST)
16399 N = N->getOperand(0).getNode();
16401 // Sometimes the operand may come from a insert_subvector building a 256-bit
16403 if (VT.is256BitVector() &&
16404 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16405 SDValue V1 = N->getOperand(0);
16406 SDValue V2 = N->getOperand(1);
16408 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16409 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16410 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16411 ISD::isBuildVectorAllOnes(V2.getNode()))
16418 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16419 // register. In most cases we actually compare or select YMM-sized registers
16420 // and mixing the two types creates horrible code. This method optimizes
16421 // some of the transition sequences.
16422 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16423 TargetLowering::DAGCombinerInfo &DCI,
16424 const X86Subtarget *Subtarget) {
16425 EVT VT = N->getValueType(0);
16426 if (!VT.is256BitVector())
16429 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16430 N->getOpcode() == ISD::ZERO_EXTEND ||
16431 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16433 SDValue Narrow = N->getOperand(0);
16434 EVT NarrowVT = Narrow->getValueType(0);
16435 if (!NarrowVT.is128BitVector())
16438 if (Narrow->getOpcode() != ISD::XOR &&
16439 Narrow->getOpcode() != ISD::AND &&
16440 Narrow->getOpcode() != ISD::OR)
16443 SDValue N0 = Narrow->getOperand(0);
16444 SDValue N1 = Narrow->getOperand(1);
16447 // The Left side has to be a trunc.
16448 if (N0.getOpcode() != ISD::TRUNCATE)
16451 // The type of the truncated inputs.
16452 EVT WideVT = N0->getOperand(0)->getValueType(0);
16456 // The right side has to be a 'trunc' or a constant vector.
16457 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16458 bool RHSConst = (isSplatVector(N1.getNode()) &&
16459 isa<ConstantSDNode>(N1->getOperand(0)));
16460 if (!RHSTrunc && !RHSConst)
16463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16465 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16468 // Set N0 and N1 to hold the inputs to the new wide operation.
16469 N0 = N0->getOperand(0);
16471 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16472 N1->getOperand(0));
16473 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16474 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16475 } else if (RHSTrunc) {
16476 N1 = N1->getOperand(0);
16479 // Generate the wide operation.
16480 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16481 unsigned Opcode = N->getOpcode();
16483 case ISD::ANY_EXTEND:
16485 case ISD::ZERO_EXTEND: {
16486 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16487 APInt Mask = APInt::getAllOnesValue(InBits);
16488 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16489 return DAG.getNode(ISD::AND, DL, VT,
16490 Op, DAG.getConstant(Mask, VT));
16492 case ISD::SIGN_EXTEND:
16493 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16494 Op, DAG.getValueType(NarrowVT));
16496 llvm_unreachable("Unexpected opcode");
16500 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16501 TargetLowering::DAGCombinerInfo &DCI,
16502 const X86Subtarget *Subtarget) {
16503 EVT VT = N->getValueType(0);
16504 if (DCI.isBeforeLegalizeOps())
16507 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16511 // Create BLSI, and BLSR instructions
16512 // BLSI is X & (-X)
16513 // BLSR is X & (X-1)
16514 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16515 SDValue N0 = N->getOperand(0);
16516 SDValue N1 = N->getOperand(1);
16519 // Check LHS for neg
16520 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16521 isZero(N0.getOperand(0)))
16522 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16524 // Check RHS for neg
16525 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16526 isZero(N1.getOperand(0)))
16527 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16529 // Check LHS for X-1
16530 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16531 isAllOnes(N0.getOperand(1)))
16532 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16534 // Check RHS for X-1
16535 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16536 isAllOnes(N1.getOperand(1)))
16537 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16542 // Want to form ANDNP nodes:
16543 // 1) In the hopes of then easily combining them with OR and AND nodes
16544 // to form PBLEND/PSIGN.
16545 // 2) To match ANDN packed intrinsics
16546 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16549 SDValue N0 = N->getOperand(0);
16550 SDValue N1 = N->getOperand(1);
16553 // Check LHS for vnot
16554 if (N0.getOpcode() == ISD::XOR &&
16555 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16556 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16557 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16559 // Check RHS for vnot
16560 if (N1.getOpcode() == ISD::XOR &&
16561 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16562 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16563 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16568 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16569 TargetLowering::DAGCombinerInfo &DCI,
16570 const X86Subtarget *Subtarget) {
16571 EVT VT = N->getValueType(0);
16572 if (DCI.isBeforeLegalizeOps())
16575 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16579 SDValue N0 = N->getOperand(0);
16580 SDValue N1 = N->getOperand(1);
16582 // look for psign/blend
16583 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16584 if (!Subtarget->hasSSSE3() ||
16585 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16588 // Canonicalize pandn to RHS
16589 if (N0.getOpcode() == X86ISD::ANDNP)
16591 // or (and (m, y), (pandn m, x))
16592 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16593 SDValue Mask = N1.getOperand(0);
16594 SDValue X = N1.getOperand(1);
16596 if (N0.getOperand(0) == Mask)
16597 Y = N0.getOperand(1);
16598 if (N0.getOperand(1) == Mask)
16599 Y = N0.getOperand(0);
16601 // Check to see if the mask appeared in both the AND and ANDNP and
16605 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16606 // Look through mask bitcast.
16607 if (Mask.getOpcode() == ISD::BITCAST)
16608 Mask = Mask.getOperand(0);
16609 if (X.getOpcode() == ISD::BITCAST)
16610 X = X.getOperand(0);
16611 if (Y.getOpcode() == ISD::BITCAST)
16612 Y = Y.getOperand(0);
16614 EVT MaskVT = Mask.getValueType();
16616 // Validate that the Mask operand is a vector sra node.
16617 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16618 // there is no psrai.b
16619 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16620 unsigned SraAmt = ~0;
16621 if (Mask.getOpcode() == ISD::SRA) {
16622 SDValue Amt = Mask.getOperand(1);
16623 if (isSplatVector(Amt.getNode())) {
16624 SDValue SclrAmt = Amt->getOperand(0);
16625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16626 SraAmt = C->getZExtValue();
16628 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16629 SDValue SraC = Mask.getOperand(1);
16630 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16632 if ((SraAmt + 1) != EltBits)
16637 // Now we know we at least have a plendvb with the mask val. See if
16638 // we can form a psignb/w/d.
16639 // psign = x.type == y.type == mask.type && y = sub(0, x);
16640 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16641 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16642 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16643 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16644 "Unsupported VT for PSIGN");
16645 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16646 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16648 // PBLENDVB only available on SSE 4.1
16649 if (!Subtarget->hasSSE41())
16652 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16654 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16655 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16656 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16657 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16658 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16662 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16665 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16666 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16668 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16670 if (!N0.hasOneUse() || !N1.hasOneUse())
16673 SDValue ShAmt0 = N0.getOperand(1);
16674 if (ShAmt0.getValueType() != MVT::i8)
16676 SDValue ShAmt1 = N1.getOperand(1);
16677 if (ShAmt1.getValueType() != MVT::i8)
16679 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16680 ShAmt0 = ShAmt0.getOperand(0);
16681 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16682 ShAmt1 = ShAmt1.getOperand(0);
16685 unsigned Opc = X86ISD::SHLD;
16686 SDValue Op0 = N0.getOperand(0);
16687 SDValue Op1 = N1.getOperand(0);
16688 if (ShAmt0.getOpcode() == ISD::SUB) {
16689 Opc = X86ISD::SHRD;
16690 std::swap(Op0, Op1);
16691 std::swap(ShAmt0, ShAmt1);
16694 unsigned Bits = VT.getSizeInBits();
16695 if (ShAmt1.getOpcode() == ISD::SUB) {
16696 SDValue Sum = ShAmt1.getOperand(0);
16697 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16698 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16699 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16700 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16701 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16702 return DAG.getNode(Opc, DL, VT,
16704 DAG.getNode(ISD::TRUNCATE, DL,
16707 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16708 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16710 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16711 return DAG.getNode(Opc, DL, VT,
16712 N0.getOperand(0), N1.getOperand(0),
16713 DAG.getNode(ISD::TRUNCATE, DL,
16720 // Generate NEG and CMOV for integer abs.
16721 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16722 EVT VT = N->getValueType(0);
16724 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16725 // 8-bit integer abs to NEG and CMOV.
16726 if (VT.isInteger() && VT.getSizeInBits() == 8)
16729 SDValue N0 = N->getOperand(0);
16730 SDValue N1 = N->getOperand(1);
16733 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16734 // and change it to SUB and CMOV.
16735 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16736 N0.getOpcode() == ISD::ADD &&
16737 N0.getOperand(1) == N1 &&
16738 N1.getOpcode() == ISD::SRA &&
16739 N1.getOperand(0) == N0.getOperand(0))
16740 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16741 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16742 // Generate SUB & CMOV.
16743 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16744 DAG.getConstant(0, VT), N0.getOperand(0));
16746 SDValue Ops[] = { N0.getOperand(0), Neg,
16747 DAG.getConstant(X86::COND_GE, MVT::i8),
16748 SDValue(Neg.getNode(), 1) };
16749 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16750 Ops, array_lengthof(Ops));
16755 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16756 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16757 TargetLowering::DAGCombinerInfo &DCI,
16758 const X86Subtarget *Subtarget) {
16759 EVT VT = N->getValueType(0);
16760 if (DCI.isBeforeLegalizeOps())
16763 if (Subtarget->hasCMov()) {
16764 SDValue RV = performIntegerAbsCombine(N, DAG);
16769 // Try forming BMI if it is available.
16770 if (!Subtarget->hasBMI())
16773 if (VT != MVT::i32 && VT != MVT::i64)
16776 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16778 // Create BLSMSK instructions by finding X ^ (X-1)
16779 SDValue N0 = N->getOperand(0);
16780 SDValue N1 = N->getOperand(1);
16783 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16784 isAllOnes(N0.getOperand(1)))
16785 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16787 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16788 isAllOnes(N1.getOperand(1)))
16789 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16794 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16795 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16796 TargetLowering::DAGCombinerInfo &DCI,
16797 const X86Subtarget *Subtarget) {
16798 LoadSDNode *Ld = cast<LoadSDNode>(N);
16799 EVT RegVT = Ld->getValueType(0);
16800 EVT MemVT = Ld->getMemoryVT();
16802 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16803 unsigned RegSz = RegVT.getSizeInBits();
16805 // On Sandybridge unaligned 256bit loads are inefficient.
16806 ISD::LoadExtType Ext = Ld->getExtensionType();
16807 unsigned Alignment = Ld->getAlignment();
16808 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16809 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16810 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16811 unsigned NumElems = RegVT.getVectorNumElements();
16815 SDValue Ptr = Ld->getBasePtr();
16816 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16818 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16820 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16821 Ld->getPointerInfo(), Ld->isVolatile(),
16822 Ld->isNonTemporal(), Ld->isInvariant(),
16824 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16825 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16826 Ld->getPointerInfo(), Ld->isVolatile(),
16827 Ld->isNonTemporal(), Ld->isInvariant(),
16828 std::min(16U, Alignment));
16829 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16831 Load2.getValue(1));
16833 SDValue NewVec = DAG.getUNDEF(RegVT);
16834 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16835 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16836 return DCI.CombineTo(N, NewVec, TF, true);
16839 // If this is a vector EXT Load then attempt to optimize it using a
16840 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16841 // expansion is still better than scalar code.
16842 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16843 // emit a shuffle and a arithmetic shift.
16844 // TODO: It is possible to support ZExt by zeroing the undef values
16845 // during the shuffle phase or after the shuffle.
16846 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16847 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16848 assert(MemVT != RegVT && "Cannot extend to the same type");
16849 assert(MemVT.isVector() && "Must load a vector from memory");
16851 unsigned NumElems = RegVT.getVectorNumElements();
16852 unsigned MemSz = MemVT.getSizeInBits();
16853 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16855 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16858 // All sizes must be a power of two.
16859 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16862 // Attempt to load the original value using scalar loads.
16863 // Find the largest scalar type that divides the total loaded size.
16864 MVT SclrLoadTy = MVT::i8;
16865 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16866 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16867 MVT Tp = (MVT::SimpleValueType)tp;
16868 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16873 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16874 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16876 SclrLoadTy = MVT::f64;
16878 // Calculate the number of scalar loads that we need to perform
16879 // in order to load our vector from memory.
16880 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16881 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16884 unsigned loadRegZize = RegSz;
16885 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16888 // Represent our vector as a sequence of elements which are the
16889 // largest scalar that we can load.
16890 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16891 loadRegZize/SclrLoadTy.getSizeInBits());
16893 // Represent the data using the same element type that is stored in
16894 // memory. In practice, we ''widen'' MemVT.
16896 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16897 loadRegZize/MemVT.getScalarType().getSizeInBits());
16899 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16900 "Invalid vector type");
16902 // We can't shuffle using an illegal type.
16903 if (!TLI.isTypeLegal(WideVecVT))
16906 SmallVector<SDValue, 8> Chains;
16907 SDValue Ptr = Ld->getBasePtr();
16908 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16909 TLI.getPointerTy());
16910 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16912 for (unsigned i = 0; i < NumLoads; ++i) {
16913 // Perform a single load.
16914 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16915 Ptr, Ld->getPointerInfo(),
16916 Ld->isVolatile(), Ld->isNonTemporal(),
16917 Ld->isInvariant(), Ld->getAlignment());
16918 Chains.push_back(ScalarLoad.getValue(1));
16919 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16920 // another round of DAGCombining.
16922 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16924 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16925 ScalarLoad, DAG.getIntPtrConstant(i));
16927 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16930 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16933 // Bitcast the loaded value to a vector of the original element type, in
16934 // the size of the target vector type.
16935 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16936 unsigned SizeRatio = RegSz/MemSz;
16938 if (Ext == ISD::SEXTLOAD) {
16939 // If we have SSE4.1 we can directly emit a VSEXT node.
16940 if (Subtarget->hasSSE41()) {
16941 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16942 return DCI.CombineTo(N, Sext, TF, true);
16945 // Otherwise we'll shuffle the small elements in the high bits of the
16946 // larger type and perform an arithmetic shift. If the shift is not legal
16947 // it's better to scalarize.
16948 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16951 // Redistribute the loaded elements into the different locations.
16952 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16953 for (unsigned i = 0; i != NumElems; ++i)
16954 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16956 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16957 DAG.getUNDEF(WideVecVT),
16960 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16962 // Build the arithmetic shift.
16963 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16964 MemVT.getVectorElementType().getSizeInBits();
16965 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16966 DAG.getConstant(Amt, RegVT));
16968 return DCI.CombineTo(N, Shuff, TF, true);
16971 // Redistribute the loaded elements into the different locations.
16972 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16973 for (unsigned i = 0; i != NumElems; ++i)
16974 ShuffleVec[i*SizeRatio] = i;
16976 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16977 DAG.getUNDEF(WideVecVT),
16980 // Bitcast to the requested type.
16981 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16982 // Replace the original load with the new sequence
16983 // and return the new chain.
16984 return DCI.CombineTo(N, Shuff, TF, true);
16990 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16991 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16992 const X86Subtarget *Subtarget) {
16993 StoreSDNode *St = cast<StoreSDNode>(N);
16994 EVT VT = St->getValue().getValueType();
16995 EVT StVT = St->getMemoryVT();
16997 SDValue StoredVal = St->getOperand(1);
16998 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17000 // If we are saving a concatenation of two XMM registers, perform two stores.
17001 // On Sandy Bridge, 256-bit memory operations are executed by two
17002 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17003 // memory operation.
17004 unsigned Alignment = St->getAlignment();
17005 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17006 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17007 StVT == VT && !IsAligned) {
17008 unsigned NumElems = VT.getVectorNumElements();
17012 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17013 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17015 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17016 SDValue Ptr0 = St->getBasePtr();
17017 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17019 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17020 St->getPointerInfo(), St->isVolatile(),
17021 St->isNonTemporal(), Alignment);
17022 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17023 St->getPointerInfo(), St->isVolatile(),
17024 St->isNonTemporal(),
17025 std::min(16U, Alignment));
17026 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17029 // Optimize trunc store (of multiple scalars) to shuffle and store.
17030 // First, pack all of the elements in one place. Next, store to memory
17031 // in fewer chunks.
17032 if (St->isTruncatingStore() && VT.isVector()) {
17033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17034 unsigned NumElems = VT.getVectorNumElements();
17035 assert(StVT != VT && "Cannot truncate to the same type");
17036 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17037 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17039 // From, To sizes and ElemCount must be pow of two
17040 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17041 // We are going to use the original vector elt for storing.
17042 // Accumulated smaller vector elements must be a multiple of the store size.
17043 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17045 unsigned SizeRatio = FromSz / ToSz;
17047 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17049 // Create a type on which we perform the shuffle
17050 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17051 StVT.getScalarType(), NumElems*SizeRatio);
17053 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17055 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17056 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17057 for (unsigned i = 0; i != NumElems; ++i)
17058 ShuffleVec[i] = i * SizeRatio;
17060 // Can't shuffle using an illegal type.
17061 if (!TLI.isTypeLegal(WideVecVT))
17064 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17065 DAG.getUNDEF(WideVecVT),
17067 // At this point all of the data is stored at the bottom of the
17068 // register. We now need to save it to mem.
17070 // Find the largest store unit
17071 MVT StoreType = MVT::i8;
17072 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17073 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17074 MVT Tp = (MVT::SimpleValueType)tp;
17075 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17079 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17080 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17081 (64 <= NumElems * ToSz))
17082 StoreType = MVT::f64;
17084 // Bitcast the original vector into a vector of store-size units
17085 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17086 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17087 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17088 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17089 SmallVector<SDValue, 8> Chains;
17090 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17091 TLI.getPointerTy());
17092 SDValue Ptr = St->getBasePtr();
17094 // Perform one or more big stores into memory.
17095 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17096 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17097 StoreType, ShuffWide,
17098 DAG.getIntPtrConstant(i));
17099 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17100 St->getPointerInfo(), St->isVolatile(),
17101 St->isNonTemporal(), St->getAlignment());
17102 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17103 Chains.push_back(Ch);
17106 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17110 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17111 // the FP state in cases where an emms may be missing.
17112 // A preferable solution to the general problem is to figure out the right
17113 // places to insert EMMS. This qualifies as a quick hack.
17115 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17116 if (VT.getSizeInBits() != 64)
17119 const Function *F = DAG.getMachineFunction().getFunction();
17120 bool NoImplicitFloatOps = F->getAttributes().
17121 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17122 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17123 && Subtarget->hasSSE2();
17124 if ((VT.isVector() ||
17125 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17126 isa<LoadSDNode>(St->getValue()) &&
17127 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17128 St->getChain().hasOneUse() && !St->isVolatile()) {
17129 SDNode* LdVal = St->getValue().getNode();
17130 LoadSDNode *Ld = 0;
17131 int TokenFactorIndex = -1;
17132 SmallVector<SDValue, 8> Ops;
17133 SDNode* ChainVal = St->getChain().getNode();
17134 // Must be a store of a load. We currently handle two cases: the load
17135 // is a direct child, and it's under an intervening TokenFactor. It is
17136 // possible to dig deeper under nested TokenFactors.
17137 if (ChainVal == LdVal)
17138 Ld = cast<LoadSDNode>(St->getChain());
17139 else if (St->getValue().hasOneUse() &&
17140 ChainVal->getOpcode() == ISD::TokenFactor) {
17141 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17142 if (ChainVal->getOperand(i).getNode() == LdVal) {
17143 TokenFactorIndex = i;
17144 Ld = cast<LoadSDNode>(St->getValue());
17146 Ops.push_back(ChainVal->getOperand(i));
17150 if (!Ld || !ISD::isNormalLoad(Ld))
17153 // If this is not the MMX case, i.e. we are just turning i64 load/store
17154 // into f64 load/store, avoid the transformation if there are multiple
17155 // uses of the loaded value.
17156 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17161 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17162 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17164 if (Subtarget->is64Bit() || F64IsLegal) {
17165 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17166 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17167 Ld->getPointerInfo(), Ld->isVolatile(),
17168 Ld->isNonTemporal(), Ld->isInvariant(),
17169 Ld->getAlignment());
17170 SDValue NewChain = NewLd.getValue(1);
17171 if (TokenFactorIndex != -1) {
17172 Ops.push_back(NewChain);
17173 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17176 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17177 St->getPointerInfo(),
17178 St->isVolatile(), St->isNonTemporal(),
17179 St->getAlignment());
17182 // Otherwise, lower to two pairs of 32-bit loads / stores.
17183 SDValue LoAddr = Ld->getBasePtr();
17184 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17185 DAG.getConstant(4, MVT::i32));
17187 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17188 Ld->getPointerInfo(),
17189 Ld->isVolatile(), Ld->isNonTemporal(),
17190 Ld->isInvariant(), Ld->getAlignment());
17191 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17192 Ld->getPointerInfo().getWithOffset(4),
17193 Ld->isVolatile(), Ld->isNonTemporal(),
17195 MinAlign(Ld->getAlignment(), 4));
17197 SDValue NewChain = LoLd.getValue(1);
17198 if (TokenFactorIndex != -1) {
17199 Ops.push_back(LoLd);
17200 Ops.push_back(HiLd);
17201 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17205 LoAddr = St->getBasePtr();
17206 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17207 DAG.getConstant(4, MVT::i32));
17209 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17210 St->getPointerInfo(),
17211 St->isVolatile(), St->isNonTemporal(),
17212 St->getAlignment());
17213 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17214 St->getPointerInfo().getWithOffset(4),
17216 St->isNonTemporal(),
17217 MinAlign(St->getAlignment(), 4));
17218 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17223 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17224 /// and return the operands for the horizontal operation in LHS and RHS. A
17225 /// horizontal operation performs the binary operation on successive elements
17226 /// of its first operand, then on successive elements of its second operand,
17227 /// returning the resulting values in a vector. For example, if
17228 /// A = < float a0, float a1, float a2, float a3 >
17230 /// B = < float b0, float b1, float b2, float b3 >
17231 /// then the result of doing a horizontal operation on A and B is
17232 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17233 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17234 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17235 /// set to A, RHS to B, and the routine returns 'true'.
17236 /// Note that the binary operation should have the property that if one of the
17237 /// operands is UNDEF then the result is UNDEF.
17238 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17239 // Look for the following pattern: if
17240 // A = < float a0, float a1, float a2, float a3 >
17241 // B = < float b0, float b1, float b2, float b3 >
17243 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17244 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17245 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17246 // which is A horizontal-op B.
17248 // At least one of the operands should be a vector shuffle.
17249 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17250 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17253 EVT VT = LHS.getValueType();
17255 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17256 "Unsupported vector type for horizontal add/sub");
17258 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17259 // operate independently on 128-bit lanes.
17260 unsigned NumElts = VT.getVectorNumElements();
17261 unsigned NumLanes = VT.getSizeInBits()/128;
17262 unsigned NumLaneElts = NumElts / NumLanes;
17263 assert((NumLaneElts % 2 == 0) &&
17264 "Vector type should have an even number of elements in each lane");
17265 unsigned HalfLaneElts = NumLaneElts/2;
17267 // View LHS in the form
17268 // LHS = VECTOR_SHUFFLE A, B, LMask
17269 // If LHS is not a shuffle then pretend it is the shuffle
17270 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17271 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17274 SmallVector<int, 16> LMask(NumElts);
17275 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17276 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17277 A = LHS.getOperand(0);
17278 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17279 B = LHS.getOperand(1);
17280 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17281 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17283 if (LHS.getOpcode() != ISD::UNDEF)
17285 for (unsigned i = 0; i != NumElts; ++i)
17289 // Likewise, view RHS in the form
17290 // RHS = VECTOR_SHUFFLE C, D, RMask
17292 SmallVector<int, 16> RMask(NumElts);
17293 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17294 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17295 C = RHS.getOperand(0);
17296 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17297 D = RHS.getOperand(1);
17298 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17299 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17301 if (RHS.getOpcode() != ISD::UNDEF)
17303 for (unsigned i = 0; i != NumElts; ++i)
17307 // Check that the shuffles are both shuffling the same vectors.
17308 if (!(A == C && B == D) && !(A == D && B == C))
17311 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17312 if (!A.getNode() && !B.getNode())
17315 // If A and B occur in reverse order in RHS, then "swap" them (which means
17316 // rewriting the mask).
17318 CommuteVectorShuffleMask(RMask, NumElts);
17320 // At this point LHS and RHS are equivalent to
17321 // LHS = VECTOR_SHUFFLE A, B, LMask
17322 // RHS = VECTOR_SHUFFLE A, B, RMask
17323 // Check that the masks correspond to performing a horizontal operation.
17324 for (unsigned i = 0; i != NumElts; ++i) {
17325 int LIdx = LMask[i], RIdx = RMask[i];
17327 // Ignore any UNDEF components.
17328 if (LIdx < 0 || RIdx < 0 ||
17329 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17330 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17333 // Check that successive elements are being operated on. If not, this is
17334 // not a horizontal operation.
17335 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17336 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17337 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17338 if (!(LIdx == Index && RIdx == Index + 1) &&
17339 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17343 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17344 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17348 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17349 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17350 const X86Subtarget *Subtarget) {
17351 EVT VT = N->getValueType(0);
17352 SDValue LHS = N->getOperand(0);
17353 SDValue RHS = N->getOperand(1);
17355 // Try to synthesize horizontal adds from adds of shuffles.
17356 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17357 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17358 isHorizontalBinOp(LHS, RHS, true))
17359 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17363 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17364 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17365 const X86Subtarget *Subtarget) {
17366 EVT VT = N->getValueType(0);
17367 SDValue LHS = N->getOperand(0);
17368 SDValue RHS = N->getOperand(1);
17370 // Try to synthesize horizontal subs from subs of shuffles.
17371 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17372 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17373 isHorizontalBinOp(LHS, RHS, false))
17374 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17378 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17379 /// X86ISD::FXOR nodes.
17380 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17381 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17382 // F[X]OR(0.0, x) -> x
17383 // F[X]OR(x, 0.0) -> x
17384 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17385 if (C->getValueAPF().isPosZero())
17386 return N->getOperand(1);
17387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17388 if (C->getValueAPF().isPosZero())
17389 return N->getOperand(0);
17393 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17394 /// X86ISD::FMAX nodes.
17395 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17396 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17398 // Only perform optimizations if UnsafeMath is used.
17399 if (!DAG.getTarget().Options.UnsafeFPMath)
17402 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17403 // into FMINC and FMAXC, which are Commutative operations.
17404 unsigned NewOp = 0;
17405 switch (N->getOpcode()) {
17406 default: llvm_unreachable("unknown opcode");
17407 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17408 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17411 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17412 N->getOperand(0), N->getOperand(1));
17415 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17416 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17417 // FAND(0.0, x) -> 0.0
17418 // FAND(x, 0.0) -> 0.0
17419 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17420 if (C->getValueAPF().isPosZero())
17421 return N->getOperand(0);
17422 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17423 if (C->getValueAPF().isPosZero())
17424 return N->getOperand(1);
17428 static SDValue PerformBTCombine(SDNode *N,
17430 TargetLowering::DAGCombinerInfo &DCI) {
17431 // BT ignores high bits in the bit index operand.
17432 SDValue Op1 = N->getOperand(1);
17433 if (Op1.hasOneUse()) {
17434 unsigned BitWidth = Op1.getValueSizeInBits();
17435 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17436 APInt KnownZero, KnownOne;
17437 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17438 !DCI.isBeforeLegalizeOps());
17439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17440 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17441 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17442 DCI.CommitTargetLoweringOpt(TLO);
17447 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17448 SDValue Op = N->getOperand(0);
17449 if (Op.getOpcode() == ISD::BITCAST)
17450 Op = Op.getOperand(0);
17451 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17452 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17453 VT.getVectorElementType().getSizeInBits() ==
17454 OpVT.getVectorElementType().getSizeInBits()) {
17455 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17460 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17461 const X86Subtarget *Subtarget) {
17462 EVT VT = N->getValueType(0);
17463 if (!VT.isVector())
17466 SDValue N0 = N->getOperand(0);
17467 SDValue N1 = N->getOperand(1);
17468 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17471 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17472 // both SSE and AVX2 since there is no sign-extended shift right
17473 // operation on a vector with 64-bit elements.
17474 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17475 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17476 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17477 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17478 SDValue N00 = N0.getOperand(0);
17480 // EXTLOAD has a better solution on AVX2,
17481 // it may be replaced with X86ISD::VSEXT node.
17482 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17483 if (!ISD::isNormalLoad(N00.getNode()))
17486 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17487 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17489 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17495 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17496 TargetLowering::DAGCombinerInfo &DCI,
17497 const X86Subtarget *Subtarget) {
17498 if (!DCI.isBeforeLegalizeOps())
17501 if (!Subtarget->hasFp256())
17504 EVT VT = N->getValueType(0);
17505 if (VT.isVector() && VT.getSizeInBits() == 256) {
17506 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17514 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17515 const X86Subtarget* Subtarget) {
17517 EVT VT = N->getValueType(0);
17519 // Let legalize expand this if it isn't a legal type yet.
17520 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17523 EVT ScalarVT = VT.getScalarType();
17524 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17525 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17528 SDValue A = N->getOperand(0);
17529 SDValue B = N->getOperand(1);
17530 SDValue C = N->getOperand(2);
17532 bool NegA = (A.getOpcode() == ISD::FNEG);
17533 bool NegB = (B.getOpcode() == ISD::FNEG);
17534 bool NegC = (C.getOpcode() == ISD::FNEG);
17536 // Negative multiplication when NegA xor NegB
17537 bool NegMul = (NegA != NegB);
17539 A = A.getOperand(0);
17541 B = B.getOperand(0);
17543 C = C.getOperand(0);
17547 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17549 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17551 return DAG.getNode(Opcode, dl, VT, A, B, C);
17554 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17555 TargetLowering::DAGCombinerInfo &DCI,
17556 const X86Subtarget *Subtarget) {
17557 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17558 // (and (i32 x86isd::setcc_carry), 1)
17559 // This eliminates the zext. This transformation is necessary because
17560 // ISD::SETCC is always legalized to i8.
17562 SDValue N0 = N->getOperand(0);
17563 EVT VT = N->getValueType(0);
17565 if (N0.getOpcode() == ISD::AND &&
17567 N0.getOperand(0).hasOneUse()) {
17568 SDValue N00 = N0.getOperand(0);
17569 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17570 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17571 if (!C || C->getZExtValue() != 1)
17573 return DAG.getNode(ISD::AND, dl, VT,
17574 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17575 N00.getOperand(0), N00.getOperand(1)),
17576 DAG.getConstant(1, VT));
17580 if (VT.is256BitVector()) {
17581 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17589 // Optimize x == -y --> x+y == 0
17590 // x != -y --> x+y != 0
17591 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17592 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17593 SDValue LHS = N->getOperand(0);
17594 SDValue RHS = N->getOperand(1);
17596 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17598 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17599 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17600 LHS.getValueType(), RHS, LHS.getOperand(1));
17601 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17602 addV, DAG.getConstant(0, addV.getValueType()), CC);
17604 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17606 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17607 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17608 RHS.getValueType(), LHS, RHS.getOperand(1));
17609 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17610 addV, DAG.getConstant(0, addV.getValueType()), CC);
17615 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17616 // as "sbb reg,reg", since it can be extended without zext and produces
17617 // an all-ones bit which is more useful than 0/1 in some cases.
17618 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17619 return DAG.getNode(ISD::AND, DL, MVT::i8,
17620 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17621 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17622 DAG.getConstant(1, MVT::i8));
17625 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17626 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17627 TargetLowering::DAGCombinerInfo &DCI,
17628 const X86Subtarget *Subtarget) {
17630 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17631 SDValue EFLAGS = N->getOperand(1);
17633 if (CC == X86::COND_A) {
17634 // Try to convert COND_A into COND_B in an attempt to facilitate
17635 // materializing "setb reg".
17637 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17638 // cannot take an immediate as its first operand.
17640 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17641 EFLAGS.getValueType().isInteger() &&
17642 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17643 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17644 EFLAGS.getNode()->getVTList(),
17645 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17646 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17647 return MaterializeSETB(DL, NewEFLAGS, DAG);
17651 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17652 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17654 if (CC == X86::COND_B)
17655 return MaterializeSETB(DL, EFLAGS, DAG);
17659 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17660 if (Flags.getNode()) {
17661 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17662 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17668 // Optimize branch condition evaluation.
17670 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17671 TargetLowering::DAGCombinerInfo &DCI,
17672 const X86Subtarget *Subtarget) {
17674 SDValue Chain = N->getOperand(0);
17675 SDValue Dest = N->getOperand(1);
17676 SDValue EFLAGS = N->getOperand(3);
17677 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17681 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17682 if (Flags.getNode()) {
17683 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17684 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17691 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17692 const X86TargetLowering *XTLI) {
17693 SDValue Op0 = N->getOperand(0);
17694 EVT InVT = Op0->getValueType(0);
17696 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17697 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17699 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17700 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17701 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17704 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17705 // a 32-bit target where SSE doesn't support i64->FP operations.
17706 if (Op0.getOpcode() == ISD::LOAD) {
17707 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17708 EVT VT = Ld->getValueType(0);
17709 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17710 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17711 !XTLI->getSubtarget()->is64Bit() &&
17712 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17713 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17714 Ld->getChain(), Op0, DAG);
17715 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17722 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17723 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17724 X86TargetLowering::DAGCombinerInfo &DCI) {
17725 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17726 // the result is either zero or one (depending on the input carry bit).
17727 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17728 if (X86::isZeroNode(N->getOperand(0)) &&
17729 X86::isZeroNode(N->getOperand(1)) &&
17730 // We don't have a good way to replace an EFLAGS use, so only do this when
17732 SDValue(N, 1).use_empty()) {
17734 EVT VT = N->getValueType(0);
17735 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17736 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17737 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17738 DAG.getConstant(X86::COND_B,MVT::i8),
17740 DAG.getConstant(1, VT));
17741 return DCI.CombineTo(N, Res1, CarryOut);
17747 // fold (add Y, (sete X, 0)) -> adc 0, Y
17748 // (add Y, (setne X, 0)) -> sbb -1, Y
17749 // (sub (sete X, 0), Y) -> sbb 0, Y
17750 // (sub (setne X, 0), Y) -> adc -1, Y
17751 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17754 // Look through ZExts.
17755 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17756 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17759 SDValue SetCC = Ext.getOperand(0);
17760 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17763 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17764 if (CC != X86::COND_E && CC != X86::COND_NE)
17767 SDValue Cmp = SetCC.getOperand(1);
17768 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17769 !X86::isZeroNode(Cmp.getOperand(1)) ||
17770 !Cmp.getOperand(0).getValueType().isInteger())
17773 SDValue CmpOp0 = Cmp.getOperand(0);
17774 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17775 DAG.getConstant(1, CmpOp0.getValueType()));
17777 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17778 if (CC == X86::COND_NE)
17779 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17780 DL, OtherVal.getValueType(), OtherVal,
17781 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17782 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17783 DL, OtherVal.getValueType(), OtherVal,
17784 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17787 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17788 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17789 const X86Subtarget *Subtarget) {
17790 EVT VT = N->getValueType(0);
17791 SDValue Op0 = N->getOperand(0);
17792 SDValue Op1 = N->getOperand(1);
17794 // Try to synthesize horizontal adds from adds of shuffles.
17795 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17796 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17797 isHorizontalBinOp(Op0, Op1, true))
17798 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
17800 return OptimizeConditionalInDecrement(N, DAG);
17803 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17804 const X86Subtarget *Subtarget) {
17805 SDValue Op0 = N->getOperand(0);
17806 SDValue Op1 = N->getOperand(1);
17808 // X86 can't encode an immediate LHS of a sub. See if we can push the
17809 // negation into a preceding instruction.
17810 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17811 // If the RHS of the sub is a XOR with one use and a constant, invert the
17812 // immediate. Then add one to the LHS of the sub so we can turn
17813 // X-Y -> X+~Y+1, saving one register.
17814 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17815 isa<ConstantSDNode>(Op1.getOperand(1))) {
17816 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17817 EVT VT = Op0.getValueType();
17818 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
17820 DAG.getConstant(~XorC, VT));
17821 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
17822 DAG.getConstant(C->getAPIntValue()+1, VT));
17826 // Try to synthesize horizontal adds from adds of shuffles.
17827 EVT VT = N->getValueType(0);
17828 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17829 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17830 isHorizontalBinOp(Op0, Op1, true))
17831 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
17833 return OptimizeConditionalInDecrement(N, DAG);
17836 /// performVZEXTCombine - Performs build vector combines
17837 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17838 TargetLowering::DAGCombinerInfo &DCI,
17839 const X86Subtarget *Subtarget) {
17840 // (vzext (bitcast (vzext (x)) -> (vzext x)
17841 SDValue In = N->getOperand(0);
17842 while (In.getOpcode() == ISD::BITCAST)
17843 In = In.getOperand(0);
17845 if (In.getOpcode() != X86ISD::VZEXT)
17848 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
17852 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17853 DAGCombinerInfo &DCI) const {
17854 SelectionDAG &DAG = DCI.DAG;
17855 switch (N->getOpcode()) {
17857 case ISD::EXTRACT_VECTOR_ELT:
17858 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17860 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17861 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17862 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17863 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17864 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17865 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17868 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17869 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17870 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17871 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17872 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17873 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17874 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17875 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17876 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17878 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17880 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17881 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17882 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17883 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17884 case ISD::ANY_EXTEND:
17885 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17886 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17887 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17888 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17889 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17890 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17891 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17892 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17893 case X86ISD::SHUFP: // Handle all target specific shuffles
17894 case X86ISD::PALIGNR:
17895 case X86ISD::UNPCKH:
17896 case X86ISD::UNPCKL:
17897 case X86ISD::MOVHLPS:
17898 case X86ISD::MOVLHPS:
17899 case X86ISD::PSHUFD:
17900 case X86ISD::PSHUFHW:
17901 case X86ISD::PSHUFLW:
17902 case X86ISD::MOVSS:
17903 case X86ISD::MOVSD:
17904 case X86ISD::VPERMILP:
17905 case X86ISD::VPERM2X128:
17906 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17907 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17913 /// isTypeDesirableForOp - Return true if the target has native support for
17914 /// the specified value type and it is 'desirable' to use the type for the
17915 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17916 /// instruction encodings are longer and some i16 instructions are slow.
17917 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17918 if (!isTypeLegal(VT))
17920 if (VT != MVT::i16)
17927 case ISD::SIGN_EXTEND:
17928 case ISD::ZERO_EXTEND:
17929 case ISD::ANY_EXTEND:
17942 /// IsDesirableToPromoteOp - This method query the target whether it is
17943 /// beneficial for dag combiner to promote the specified node. If true, it
17944 /// should return the desired promotion type by reference.
17945 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17946 EVT VT = Op.getValueType();
17947 if (VT != MVT::i16)
17950 bool Promote = false;
17951 bool Commute = false;
17952 switch (Op.getOpcode()) {
17955 LoadSDNode *LD = cast<LoadSDNode>(Op);
17956 // If the non-extending load has a single use and it's not live out, then it
17957 // might be folded.
17958 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17959 Op.hasOneUse()*/) {
17960 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17961 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17962 // The only case where we'd want to promote LOAD (rather then it being
17963 // promoted as an operand is when it's only use is liveout.
17964 if (UI->getOpcode() != ISD::CopyToReg)
17971 case ISD::SIGN_EXTEND:
17972 case ISD::ZERO_EXTEND:
17973 case ISD::ANY_EXTEND:
17978 SDValue N0 = Op.getOperand(0);
17979 // Look out for (store (shl (load), x)).
17980 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17993 SDValue N0 = Op.getOperand(0);
17994 SDValue N1 = Op.getOperand(1);
17995 if (!Commute && MayFoldLoad(N1))
17997 // Avoid disabling potential load folding opportunities.
17998 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18000 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18010 //===----------------------------------------------------------------------===//
18011 // X86 Inline Assembly Support
18012 //===----------------------------------------------------------------------===//
18015 // Helper to match a string separated by whitespace.
18016 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18017 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18019 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18020 StringRef piece(*args[i]);
18021 if (!s.startswith(piece)) // Check if the piece matches.
18024 s = s.substr(piece.size());
18025 StringRef::size_type pos = s.find_first_not_of(" \t");
18026 if (pos == 0) // We matched a prefix.
18034 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18037 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18038 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18040 std::string AsmStr = IA->getAsmString();
18042 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18043 if (!Ty || Ty->getBitWidth() % 16 != 0)
18046 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18047 SmallVector<StringRef, 4> AsmPieces;
18048 SplitString(AsmStr, AsmPieces, ";\n");
18050 switch (AsmPieces.size()) {
18051 default: return false;
18053 // FIXME: this should verify that we are targeting a 486 or better. If not,
18054 // we will turn this bswap into something that will be lowered to logical
18055 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18056 // lower so don't worry about this.
18058 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18059 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18060 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18061 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18062 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18063 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18064 // No need to check constraints, nothing other than the equivalent of
18065 // "=r,0" would be valid here.
18066 return IntrinsicLowering::LowerToByteSwap(CI);
18069 // rorw $$8, ${0:w} --> llvm.bswap.i16
18070 if (CI->getType()->isIntegerTy(16) &&
18071 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18072 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18073 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18075 const std::string &ConstraintsStr = IA->getConstraintString();
18076 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18077 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18078 if (AsmPieces.size() == 4 &&
18079 AsmPieces[0] == "~{cc}" &&
18080 AsmPieces[1] == "~{dirflag}" &&
18081 AsmPieces[2] == "~{flags}" &&
18082 AsmPieces[3] == "~{fpsr}")
18083 return IntrinsicLowering::LowerToByteSwap(CI);
18087 if (CI->getType()->isIntegerTy(32) &&
18088 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18089 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18090 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18091 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18093 const std::string &ConstraintsStr = IA->getConstraintString();
18094 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18095 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18096 if (AsmPieces.size() == 4 &&
18097 AsmPieces[0] == "~{cc}" &&
18098 AsmPieces[1] == "~{dirflag}" &&
18099 AsmPieces[2] == "~{flags}" &&
18100 AsmPieces[3] == "~{fpsr}")
18101 return IntrinsicLowering::LowerToByteSwap(CI);
18104 if (CI->getType()->isIntegerTy(64)) {
18105 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18106 if (Constraints.size() >= 2 &&
18107 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18108 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18109 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18110 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18111 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18112 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18113 return IntrinsicLowering::LowerToByteSwap(CI);
18121 /// getConstraintType - Given a constraint letter, return the type of
18122 /// constraint it is for this target.
18123 X86TargetLowering::ConstraintType
18124 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18125 if (Constraint.size() == 1) {
18126 switch (Constraint[0]) {
18137 return C_RegisterClass;
18161 return TargetLowering::getConstraintType(Constraint);
18164 /// Examine constraint type and operand type and determine a weight value.
18165 /// This object must already have been set up with the operand type
18166 /// and the current alternative constraint selected.
18167 TargetLowering::ConstraintWeight
18168 X86TargetLowering::getSingleConstraintMatchWeight(
18169 AsmOperandInfo &info, const char *constraint) const {
18170 ConstraintWeight weight = CW_Invalid;
18171 Value *CallOperandVal = info.CallOperandVal;
18172 // If we don't have a value, we can't do a match,
18173 // but allow it at the lowest weight.
18174 if (CallOperandVal == NULL)
18176 Type *type = CallOperandVal->getType();
18177 // Look at the constraint type.
18178 switch (*constraint) {
18180 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18191 if (CallOperandVal->getType()->isIntegerTy())
18192 weight = CW_SpecificReg;
18197 if (type->isFloatingPointTy())
18198 weight = CW_SpecificReg;
18201 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18202 weight = CW_SpecificReg;
18206 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18207 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18208 weight = CW_Register;
18211 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18212 if (C->getZExtValue() <= 31)
18213 weight = CW_Constant;
18217 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18218 if (C->getZExtValue() <= 63)
18219 weight = CW_Constant;
18223 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18224 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18225 weight = CW_Constant;
18229 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18230 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18231 weight = CW_Constant;
18235 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18236 if (C->getZExtValue() <= 3)
18237 weight = CW_Constant;
18241 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18242 if (C->getZExtValue() <= 0xff)
18243 weight = CW_Constant;
18248 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18249 weight = CW_Constant;
18253 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18254 if ((C->getSExtValue() >= -0x80000000LL) &&
18255 (C->getSExtValue() <= 0x7fffffffLL))
18256 weight = CW_Constant;
18260 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18261 if (C->getZExtValue() <= 0xffffffff)
18262 weight = CW_Constant;
18269 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18270 /// with another that has more specific requirements based on the type of the
18271 /// corresponding operand.
18272 const char *X86TargetLowering::
18273 LowerXConstraint(EVT ConstraintVT) const {
18274 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18275 // 'f' like normal targets.
18276 if (ConstraintVT.isFloatingPoint()) {
18277 if (Subtarget->hasSSE2())
18279 if (Subtarget->hasSSE1())
18283 return TargetLowering::LowerXConstraint(ConstraintVT);
18286 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18287 /// vector. If it is invalid, don't add anything to Ops.
18288 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18289 std::string &Constraint,
18290 std::vector<SDValue>&Ops,
18291 SelectionDAG &DAG) const {
18292 SDValue Result(0, 0);
18294 // Only support length 1 constraints for now.
18295 if (Constraint.length() > 1) return;
18297 char ConstraintLetter = Constraint[0];
18298 switch (ConstraintLetter) {
18301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18302 if (C->getZExtValue() <= 31) {
18303 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18310 if (C->getZExtValue() <= 63) {
18311 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18318 if (isInt<8>(C->getSExtValue())) {
18319 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18326 if (C->getZExtValue() <= 255) {
18327 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18333 // 32-bit signed value
18334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18335 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18336 C->getSExtValue())) {
18337 // Widen to 64 bits here to get it sign extended.
18338 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18341 // FIXME gcc accepts some relocatable values here too, but only in certain
18342 // memory models; it's complicated.
18347 // 32-bit unsigned value
18348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18349 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18350 C->getZExtValue())) {
18351 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18355 // FIXME gcc accepts some relocatable values here too, but only in certain
18356 // memory models; it's complicated.
18360 // Literal immediates are always ok.
18361 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18362 // Widen to 64 bits here to get it sign extended.
18363 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18367 // In any sort of PIC mode addresses need to be computed at runtime by
18368 // adding in a register or some sort of table lookup. These can't
18369 // be used as immediates.
18370 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18373 // If we are in non-pic codegen mode, we allow the address of a global (with
18374 // an optional displacement) to be used with 'i'.
18375 GlobalAddressSDNode *GA = 0;
18376 int64_t Offset = 0;
18378 // Match either (GA), (GA+C), (GA+C1+C2), etc.
18380 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18381 Offset += GA->getOffset();
18383 } else if (Op.getOpcode() == ISD::ADD) {
18384 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18385 Offset += C->getZExtValue();
18386 Op = Op.getOperand(0);
18389 } else if (Op.getOpcode() == ISD::SUB) {
18390 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18391 Offset += -C->getZExtValue();
18392 Op = Op.getOperand(0);
18397 // Otherwise, this isn't something we can handle, reject it.
18401 const GlobalValue *GV = GA->getGlobal();
18402 // If we require an extra load to get this address, as in PIC mode, we
18403 // can't accept it.
18404 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18405 getTargetMachine())))
18408 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18409 GA->getValueType(0), Offset);
18414 if (Result.getNode()) {
18415 Ops.push_back(Result);
18418 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18421 std::pair<unsigned, const TargetRegisterClass*>
18422 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18424 // First, see if this is a constraint that directly corresponds to an LLVM
18426 if (Constraint.size() == 1) {
18427 // GCC Constraint Letters
18428 switch (Constraint[0]) {
18430 // TODO: Slight differences here in allocation order and leaving
18431 // RIP in the class. Do they matter any more here than they do
18432 // in the normal allocation?
18433 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18434 if (Subtarget->is64Bit()) {
18435 if (VT == MVT::i32 || VT == MVT::f32)
18436 return std::make_pair(0U, &X86::GR32RegClass);
18437 if (VT == MVT::i16)
18438 return std::make_pair(0U, &X86::GR16RegClass);
18439 if (VT == MVT::i8 || VT == MVT::i1)
18440 return std::make_pair(0U, &X86::GR8RegClass);
18441 if (VT == MVT::i64 || VT == MVT::f64)
18442 return std::make_pair(0U, &X86::GR64RegClass);
18445 // 32-bit fallthrough
18446 case 'Q': // Q_REGS
18447 if (VT == MVT::i32 || VT == MVT::f32)
18448 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18449 if (VT == MVT::i16)
18450 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18451 if (VT == MVT::i8 || VT == MVT::i1)
18452 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18453 if (VT == MVT::i64)
18454 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18456 case 'r': // GENERAL_REGS
18457 case 'l': // INDEX_REGS
18458 if (VT == MVT::i8 || VT == MVT::i1)
18459 return std::make_pair(0U, &X86::GR8RegClass);
18460 if (VT == MVT::i16)
18461 return std::make_pair(0U, &X86::GR16RegClass);
18462 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18463 return std::make_pair(0U, &X86::GR32RegClass);
18464 return std::make_pair(0U, &X86::GR64RegClass);
18465 case 'R': // LEGACY_REGS
18466 if (VT == MVT::i8 || VT == MVT::i1)
18467 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18468 if (VT == MVT::i16)
18469 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18470 if (VT == MVT::i32 || !Subtarget->is64Bit())
18471 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18472 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18473 case 'f': // FP Stack registers.
18474 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18475 // value to the correct fpstack register class.
18476 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18477 return std::make_pair(0U, &X86::RFP32RegClass);
18478 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18479 return std::make_pair(0U, &X86::RFP64RegClass);
18480 return std::make_pair(0U, &X86::RFP80RegClass);
18481 case 'y': // MMX_REGS if MMX allowed.
18482 if (!Subtarget->hasMMX()) break;
18483 return std::make_pair(0U, &X86::VR64RegClass);
18484 case 'Y': // SSE_REGS if SSE2 allowed
18485 if (!Subtarget->hasSSE2()) break;
18487 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18488 if (!Subtarget->hasSSE1()) break;
18490 switch (VT.SimpleTy) {
18492 // Scalar SSE types.
18495 return std::make_pair(0U, &X86::FR32RegClass);
18498 return std::make_pair(0U, &X86::FR64RegClass);
18506 return std::make_pair(0U, &X86::VR128RegClass);
18514 return std::make_pair(0U, &X86::VR256RegClass);
18520 // Use the default implementation in TargetLowering to convert the register
18521 // constraint into a member of a register class.
18522 std::pair<unsigned, const TargetRegisterClass*> Res;
18523 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18525 // Not found as a standard register?
18526 if (Res.second == 0) {
18527 // Map st(0) -> st(7) -> ST0
18528 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18529 tolower(Constraint[1]) == 's' &&
18530 tolower(Constraint[2]) == 't' &&
18531 Constraint[3] == '(' &&
18532 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18533 Constraint[5] == ')' &&
18534 Constraint[6] == '}') {
18536 Res.first = X86::ST0+Constraint[4]-'0';
18537 Res.second = &X86::RFP80RegClass;
18541 // GCC allows "st(0)" to be called just plain "st".
18542 if (StringRef("{st}").equals_lower(Constraint)) {
18543 Res.first = X86::ST0;
18544 Res.second = &X86::RFP80RegClass;
18549 if (StringRef("{flags}").equals_lower(Constraint)) {
18550 Res.first = X86::EFLAGS;
18551 Res.second = &X86::CCRRegClass;
18555 // 'A' means EAX + EDX.
18556 if (Constraint == "A") {
18557 Res.first = X86::EAX;
18558 Res.second = &X86::GR32_ADRegClass;
18564 // Otherwise, check to see if this is a register class of the wrong value
18565 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18566 // turn into {ax},{dx}.
18567 if (Res.second->hasType(VT))
18568 return Res; // Correct type already, nothing to do.
18570 // All of the single-register GCC register classes map their values onto
18571 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18572 // really want an 8-bit or 32-bit register, map to the appropriate register
18573 // class and return the appropriate register.
18574 if (Res.second == &X86::GR16RegClass) {
18575 if (VT == MVT::i8 || VT == MVT::i1) {
18576 unsigned DestReg = 0;
18577 switch (Res.first) {
18579 case X86::AX: DestReg = X86::AL; break;
18580 case X86::DX: DestReg = X86::DL; break;
18581 case X86::CX: DestReg = X86::CL; break;
18582 case X86::BX: DestReg = X86::BL; break;
18585 Res.first = DestReg;
18586 Res.second = &X86::GR8RegClass;
18588 } else if (VT == MVT::i32 || VT == MVT::f32) {
18589 unsigned DestReg = 0;
18590 switch (Res.first) {
18592 case X86::AX: DestReg = X86::EAX; break;
18593 case X86::DX: DestReg = X86::EDX; break;
18594 case X86::CX: DestReg = X86::ECX; break;
18595 case X86::BX: DestReg = X86::EBX; break;
18596 case X86::SI: DestReg = X86::ESI; break;
18597 case X86::DI: DestReg = X86::EDI; break;
18598 case X86::BP: DestReg = X86::EBP; break;
18599 case X86::SP: DestReg = X86::ESP; break;
18602 Res.first = DestReg;
18603 Res.second = &X86::GR32RegClass;
18605 } else if (VT == MVT::i64 || VT == MVT::f64) {
18606 unsigned DestReg = 0;
18607 switch (Res.first) {
18609 case X86::AX: DestReg = X86::RAX; break;
18610 case X86::DX: DestReg = X86::RDX; break;
18611 case X86::CX: DestReg = X86::RCX; break;
18612 case X86::BX: DestReg = X86::RBX; break;
18613 case X86::SI: DestReg = X86::RSI; break;
18614 case X86::DI: DestReg = X86::RDI; break;
18615 case X86::BP: DestReg = X86::RBP; break;
18616 case X86::SP: DestReg = X86::RSP; break;
18619 Res.first = DestReg;
18620 Res.second = &X86::GR64RegClass;
18623 } else if (Res.second == &X86::FR32RegClass ||
18624 Res.second == &X86::FR64RegClass ||
18625 Res.second == &X86::VR128RegClass) {
18626 // Handle references to XMM physical registers that got mapped into the
18627 // wrong class. This can happen with constraints like {xmm0} where the
18628 // target independent register mapper will just pick the first match it can
18629 // find, ignoring the required type.
18631 if (VT == MVT::f32 || VT == MVT::i32)
18632 Res.second = &X86::FR32RegClass;
18633 else if (VT == MVT::f64 || VT == MVT::i64)
18634 Res.second = &X86::FR64RegClass;
18635 else if (X86::VR128RegClass.hasType(VT))
18636 Res.second = &X86::VR128RegClass;
18637 else if (X86::VR256RegClass.hasType(VT))
18638 Res.second = &X86::VR256RegClass;