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/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/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, DebugLoc 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, DebugLoc 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 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
874 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
875 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
876 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
877 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
878 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
879 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
880 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
886 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
905 // Do not attempt to custom lower non-128-bit vectors
906 if (!VT.is128BitVector())
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
920 if (Subtarget->is64Bit()) {
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927 MVT VT = (MVT::SimpleValueType)i;
929 // Do not attempt to promote non-128-bit vectors
930 if (!VT.is128BitVector())
933 setOperationAction(ISD::AND, VT, Promote);
934 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
935 setOperationAction(ISD::OR, VT, Promote);
936 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
937 setOperationAction(ISD::XOR, VT, Promote);
938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
939 setOperationAction(ISD::LOAD, VT, Promote);
940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
941 setOperationAction(ISD::SELECT, VT, Promote);
942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
945 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // Custom lower v2i64 and v2f64 selects.
948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
958 // As there is no 64-bit GPR available, we need build a special custom
959 // sequence to convert from v2i32 to v2f32.
960 if (!Subtarget->is64Bit())
961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
969 if (Subtarget->hasSSE41()) {
970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
973 setOperationAction(ISD::FRINT, MVT::f32, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
976 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
992 // FIXME: Do we need to handle scalar-to-vector here?
993 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1001 // i8 and i16 vectors are custom , because the source register and source
1002 // source memory operand types are not the same width. f32 vectors are
1003 // custom since the immediate controlling the insert encodes additional
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015 // FIXME: these should be Legal but thats only for the case where
1016 // the index is constant. For now custom expand to deal with that.
1017 if (Subtarget->is64Bit()) {
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1023 if (Subtarget->hasSSE2()) {
1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1033 if (Subtarget->hasInt256()) {
1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1052 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1054 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1060 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1061 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1062 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1064 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1075 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1078 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1088 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1090 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1091 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1093 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1096 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1097 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1099 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1100 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1101 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1103 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1105 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1106 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1108 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1109 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1111 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1112 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1114 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1115 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1116 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1117 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1119 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1120 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1121 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1123 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1124 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1125 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1126 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1128 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1129 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1130 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1131 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1132 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1133 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1135 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1136 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1138 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1139 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1140 setOperationAction(ISD::FMA, MVT::f32, Legal);
1141 setOperationAction(ISD::FMA, MVT::f64, Legal);
1144 if (Subtarget->hasInt256()) {
1145 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1146 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1147 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1148 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1150 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1151 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1152 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1153 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1155 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1156 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1157 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1158 // Don't lower v32i8 because there is no 128-bit byte mul
1160 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1163 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1165 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1166 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1168 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1170 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1171 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1172 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1173 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1176 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1177 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1178 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1180 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1181 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1182 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1183 // Don't lower v32i8 because there is no 128-bit byte mul
1185 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1186 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1188 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1191 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1194 // Custom lower several nodes for 256-bit types.
1195 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1196 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1197 MVT VT = (MVT::SimpleValueType)i;
1199 // Extract subvector is special because the value type
1200 // (result) is 128-bit but the source is 256-bit wide.
1201 if (VT.is128BitVector())
1202 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1204 // Do not attempt to custom lower other non-256-bit vectors
1205 if (!VT.is256BitVector())
1208 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1209 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1210 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1211 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1213 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1214 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1217 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1218 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1219 MVT VT = (MVT::SimpleValueType)i;
1221 // Do not attempt to promote non-256-bit vectors
1222 if (!VT.is256BitVector())
1225 setOperationAction(ISD::AND, VT, Promote);
1226 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1227 setOperationAction(ISD::OR, VT, Promote);
1228 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1229 setOperationAction(ISD::XOR, VT, Promote);
1230 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1231 setOperationAction(ISD::LOAD, VT, Promote);
1232 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1233 setOperationAction(ISD::SELECT, VT, Promote);
1234 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1238 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1239 // of this type with custom code.
1240 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1241 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1242 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1246 // We want to custom lower some of our intrinsics.
1247 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1248 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1250 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1251 // handle type legalization for these operations here.
1253 // FIXME: We really should do custom legalization for addition and
1254 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1255 // than generic legalization for 64-bit multiplication-with-overflow, though.
1256 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1257 // Add/Sub/Mul with overflow operations are custom lowered.
1259 setOperationAction(ISD::SADDO, VT, Custom);
1260 setOperationAction(ISD::UADDO, VT, Custom);
1261 setOperationAction(ISD::SSUBO, VT, Custom);
1262 setOperationAction(ISD::USUBO, VT, Custom);
1263 setOperationAction(ISD::SMULO, VT, Custom);
1264 setOperationAction(ISD::UMULO, VT, Custom);
1267 // There are no 8-bit 3-address imul/mul instructions
1268 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1269 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1271 if (!Subtarget->is64Bit()) {
1272 // These libcalls are not available in 32-bit.
1273 setLibcallName(RTLIB::SHL_I128, 0);
1274 setLibcallName(RTLIB::SRL_I128, 0);
1275 setLibcallName(RTLIB::SRA_I128, 0);
1278 // We have target-specific dag combine patterns for the following nodes:
1279 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1280 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1281 setTargetDAGCombine(ISD::VSELECT);
1282 setTargetDAGCombine(ISD::SELECT);
1283 setTargetDAGCombine(ISD::SHL);
1284 setTargetDAGCombine(ISD::SRA);
1285 setTargetDAGCombine(ISD::SRL);
1286 setTargetDAGCombine(ISD::OR);
1287 setTargetDAGCombine(ISD::AND);
1288 setTargetDAGCombine(ISD::ADD);
1289 setTargetDAGCombine(ISD::FADD);
1290 setTargetDAGCombine(ISD::FSUB);
1291 setTargetDAGCombine(ISD::FMA);
1292 setTargetDAGCombine(ISD::SUB);
1293 setTargetDAGCombine(ISD::LOAD);
1294 setTargetDAGCombine(ISD::STORE);
1295 setTargetDAGCombine(ISD::ZERO_EXTEND);
1296 setTargetDAGCombine(ISD::ANY_EXTEND);
1297 setTargetDAGCombine(ISD::SIGN_EXTEND);
1298 setTargetDAGCombine(ISD::TRUNCATE);
1299 setTargetDAGCombine(ISD::SINT_TO_FP);
1300 setTargetDAGCombine(ISD::SETCC);
1301 if (Subtarget->is64Bit())
1302 setTargetDAGCombine(ISD::MUL);
1303 setTargetDAGCombine(ISD::XOR);
1305 computeRegisterProperties();
1307 // On Darwin, -Os means optimize for size without hurting performance,
1308 // do not reduce the limit.
1309 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1310 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1311 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1312 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1313 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1314 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1315 setPrefLoopAlignment(4); // 2^4 bytes.
1316 benefitFromCodePlacementOpt = true;
1318 // Predictable cmov don't hurt on atom because it's in-order.
1319 predictableSelectIsExpensive = !Subtarget->isAtom();
1321 setPrefFunctionAlignment(4); // 2^4 bytes.
1324 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1325 if (!VT.isVector()) return MVT::i8;
1326 return VT.changeVectorElementTypeToInteger();
1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1330 /// the desired ByVal argument alignment.
1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1334 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1335 if (VTy->getBitWidth() == 128)
1337 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1338 unsigned EltAlign = 0;
1339 getMaxByValAlign(ATy->getElementType(), EltAlign);
1340 if (EltAlign > MaxAlign)
1341 MaxAlign = EltAlign;
1342 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1343 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1344 unsigned EltAlign = 0;
1345 getMaxByValAlign(STy->getElementType(i), EltAlign);
1346 if (EltAlign > MaxAlign)
1347 MaxAlign = EltAlign;
1354 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1355 /// function arguments in the caller parameter area. For X86, aggregates
1356 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1357 /// are at 4-byte boundaries.
1358 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1359 if (Subtarget->is64Bit()) {
1360 // Max of 8 and alignment of type.
1361 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1368 if (Subtarget->hasSSE1())
1369 getMaxByValAlign(Ty, Align);
1373 /// getOptimalMemOpType - Returns the target specific optimal type for load
1374 /// and store operations as a result of memset, memcpy, and memmove
1375 /// lowering. If DstAlign is zero that means it's safe to destination
1376 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1377 /// means there isn't a need to check it against alignment requirement,
1378 /// probably because the source does not need to be loaded. If 'IsMemset' is
1379 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1380 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1381 /// source is constant so it does not need to be loaded.
1382 /// It returns EVT::Other if the type should be determined using generic
1383 /// target-independent logic.
1385 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1386 unsigned DstAlign, unsigned SrcAlign,
1387 bool IsMemset, bool ZeroMemset,
1389 MachineFunction &MF) const {
1390 const Function *F = MF.getFunction();
1391 if ((!IsMemset || ZeroMemset) &&
1392 !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1394 (Subtarget->isUnalignedMemAccessFast() ||
1395 ((DstAlign == 0 || DstAlign >= 16) &&
1396 (SrcAlign == 0 || SrcAlign >= 16)))) {
1398 if (Subtarget->hasInt256())
1400 if (Subtarget->hasFp256())
1403 if (Subtarget->hasSSE2())
1405 if (Subtarget->hasSSE1())
1407 } else if (!MemcpyStrSrc && Size >= 8 &&
1408 !Subtarget->is64Bit() &&
1409 Subtarget->hasSSE2()) {
1410 // Do not use f64 to lower memcpy if source is string constant. It's
1411 // better to use i32 to avoid the loads.
1415 if (Subtarget->is64Bit() && Size >= 8)
1420 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1422 return X86ScalarSSEf32;
1423 else if (VT == MVT::f64)
1424 return X86ScalarSSEf64;
1429 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1431 *Fast = Subtarget->isUnalignedMemAccessFast();
1435 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1436 /// current function. The returned value is a member of the
1437 /// MachineJumpTableInfo::JTEntryKind enum.
1438 unsigned X86TargetLowering::getJumpTableEncoding() const {
1439 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1441 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1442 Subtarget->isPICStyleGOT())
1443 return MachineJumpTableInfo::EK_Custom32;
1445 // Otherwise, use the normal jump table encoding heuristics.
1446 return TargetLowering::getJumpTableEncoding();
1450 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1451 const MachineBasicBlock *MBB,
1452 unsigned uid,MCContext &Ctx) const{
1453 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1454 Subtarget->isPICStyleGOT());
1455 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1457 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1458 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1461 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1463 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1464 SelectionDAG &DAG) const {
1465 if (!Subtarget->is64Bit())
1466 // This doesn't have DebugLoc associated with it, but is not really the
1467 // same as a Register.
1468 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1472 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1473 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1475 const MCExpr *X86TargetLowering::
1476 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1477 MCContext &Ctx) const {
1478 // X86-64 uses RIP relative addressing based on the jump table label.
1479 if (Subtarget->isPICStyleRIPRel())
1480 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1482 // Otherwise, the reference is relative to the PIC base.
1483 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1486 // FIXME: Why this routine is here? Move to RegInfo!
1487 std::pair<const TargetRegisterClass*, uint8_t>
1488 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1489 const TargetRegisterClass *RRC = 0;
1491 switch (VT.SimpleTy) {
1493 return TargetLowering::findRepresentativeClass(VT);
1494 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1495 RRC = Subtarget->is64Bit() ?
1496 (const TargetRegisterClass*)&X86::GR64RegClass :
1497 (const TargetRegisterClass*)&X86::GR32RegClass;
1500 RRC = &X86::VR64RegClass;
1502 case MVT::f32: case MVT::f64:
1503 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1504 case MVT::v4f32: case MVT::v2f64:
1505 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1507 RRC = &X86::VR128RegClass;
1510 return std::make_pair(RRC, Cost);
1513 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1514 unsigned &Offset) const {
1515 if (!Subtarget->isTargetLinux())
1518 if (Subtarget->is64Bit()) {
1519 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1521 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1533 //===----------------------------------------------------------------------===//
1534 // Return Value Calling Convention Implementation
1535 //===----------------------------------------------------------------------===//
1537 #include "X86GenCallingConv.inc"
1540 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1541 MachineFunction &MF, bool isVarArg,
1542 const SmallVectorImpl<ISD::OutputArg> &Outs,
1543 LLVMContext &Context) const {
1544 SmallVector<CCValAssign, 16> RVLocs;
1545 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1547 return CCInfo.CheckReturn(Outs, RetCC_X86);
1551 X86TargetLowering::LowerReturn(SDValue Chain,
1552 CallingConv::ID CallConv, bool isVarArg,
1553 const SmallVectorImpl<ISD::OutputArg> &Outs,
1554 const SmallVectorImpl<SDValue> &OutVals,
1555 DebugLoc dl, SelectionDAG &DAG) const {
1556 MachineFunction &MF = DAG.getMachineFunction();
1557 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1559 SmallVector<CCValAssign, 16> RVLocs;
1560 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1561 RVLocs, *DAG.getContext());
1562 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1564 // Add the regs to the liveout set for the function.
1565 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1566 for (unsigned i = 0; i != RVLocs.size(); ++i)
1567 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1568 MRI.addLiveOut(RVLocs[i].getLocReg());
1572 SmallVector<SDValue, 6> RetOps;
1573 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1574 // Operand #1 = Bytes To Pop
1575 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1578 // Copy the result values into the output registers.
1579 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1580 CCValAssign &VA = RVLocs[i];
1581 assert(VA.isRegLoc() && "Can only return in registers!");
1582 SDValue ValToCopy = OutVals[i];
1583 EVT ValVT = ValToCopy.getValueType();
1585 // Promote values to the appropriate types
1586 if (VA.getLocInfo() == CCValAssign::SExt)
1587 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1588 else if (VA.getLocInfo() == CCValAssign::ZExt)
1589 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1590 else if (VA.getLocInfo() == CCValAssign::AExt)
1591 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1592 else if (VA.getLocInfo() == CCValAssign::BCvt)
1593 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1595 // If this is x86-64, and we disabled SSE, we can't return FP values,
1596 // or SSE or MMX vectors.
1597 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1598 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1599 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1600 report_fatal_error("SSE register return with SSE disabled");
1602 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1603 // llvm-gcc has never done it right and no one has noticed, so this
1604 // should be OK for now.
1605 if (ValVT == MVT::f64 &&
1606 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1607 report_fatal_error("SSE2 register return with SSE2 disabled");
1609 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1610 // the RET instruction and handled by the FP Stackifier.
1611 if (VA.getLocReg() == X86::ST0 ||
1612 VA.getLocReg() == X86::ST1) {
1613 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1614 // change the value to the FP stack register class.
1615 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1616 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1617 RetOps.push_back(ValToCopy);
1618 // Don't emit a copytoreg.
1622 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1623 // which is returned in RAX / RDX.
1624 if (Subtarget->is64Bit()) {
1625 if (ValVT == MVT::x86mmx) {
1626 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1627 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1628 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1630 // If we don't have SSE2 available, convert to v4f32 so the generated
1631 // register is legal.
1632 if (!Subtarget->hasSSE2())
1633 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1638 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1639 Flag = Chain.getValue(1);
1642 // The x86-64 ABI for returning structs by value requires that we copy
1643 // the sret argument into %rax for the return. We saved the argument into
1644 // a virtual register in the entry block, so now we copy the value out
1646 if (Subtarget->is64Bit() &&
1647 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1648 MachineFunction &MF = DAG.getMachineFunction();
1649 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1650 unsigned Reg = FuncInfo->getSRetReturnReg();
1652 "SRetReturnReg should have been set in LowerFormalArguments().");
1653 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1655 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1656 Flag = Chain.getValue(1);
1658 // RAX now acts like a return value.
1659 MRI.addLiveOut(X86::RAX);
1662 RetOps[0] = Chain; // Update chain.
1664 // Add the flag if we have it.
1666 RetOps.push_back(Flag);
1668 return DAG.getNode(X86ISD::RET_FLAG, dl,
1669 MVT::Other, &RetOps[0], RetOps.size());
1672 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1673 if (N->getNumValues() != 1)
1675 if (!N->hasNUsesOfValue(1, 0))
1678 SDValue TCChain = Chain;
1679 SDNode *Copy = *N->use_begin();
1680 if (Copy->getOpcode() == ISD::CopyToReg) {
1681 // If the copy has a glue operand, we conservatively assume it isn't safe to
1682 // perform a tail call.
1683 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1685 TCChain = Copy->getOperand(0);
1686 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1689 bool HasRet = false;
1690 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1692 if (UI->getOpcode() != X86ISD::RET_FLAG)
1705 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1706 ISD::NodeType ExtendKind) const {
1708 // TODO: Is this also valid on 32-bit?
1709 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1710 ReturnMVT = MVT::i8;
1712 ReturnMVT = MVT::i32;
1714 MVT MinVT = getRegisterType(ReturnMVT);
1715 return VT.bitsLT(MinVT) ? MinVT : VT;
1718 /// LowerCallResult - Lower the result values of a call into the
1719 /// appropriate copies out of appropriate physical registers.
1722 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1723 CallingConv::ID CallConv, bool isVarArg,
1724 const SmallVectorImpl<ISD::InputArg> &Ins,
1725 DebugLoc dl, SelectionDAG &DAG,
1726 SmallVectorImpl<SDValue> &InVals) const {
1728 // Assign locations to each value returned by this call.
1729 SmallVector<CCValAssign, 16> RVLocs;
1730 bool Is64Bit = Subtarget->is64Bit();
1731 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1732 getTargetMachine(), RVLocs, *DAG.getContext());
1733 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1735 // Copy all of the result registers out of their specified physreg.
1736 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1737 CCValAssign &VA = RVLocs[i];
1738 EVT CopyVT = VA.getValVT();
1740 // If this is x86-64, and we disabled SSE, we can't return FP values
1741 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1742 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1743 report_fatal_error("SSE register return with SSE disabled");
1748 // If this is a call to a function that returns an fp value on the floating
1749 // point stack, we must guarantee the value is popped from the stack, so
1750 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1751 // if the return value is not used. We use the FpPOP_RETVAL instruction
1753 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1754 // If we prefer to use the value in xmm registers, copy it out as f80 and
1755 // use a truncate to move it from fp stack reg to xmm reg.
1756 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1757 SDValue Ops[] = { Chain, InFlag };
1758 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1759 MVT::Other, MVT::Glue, Ops, 2), 1);
1760 Val = Chain.getValue(0);
1762 // Round the f80 to the right size, which also moves it to the appropriate
1764 if (CopyVT != VA.getValVT())
1765 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1766 // This truncation won't change the value.
1767 DAG.getIntPtrConstant(1));
1769 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1770 CopyVT, InFlag).getValue(1);
1771 Val = Chain.getValue(0);
1773 InFlag = Chain.getValue(2);
1774 InVals.push_back(Val);
1780 //===----------------------------------------------------------------------===//
1781 // C & StdCall & Fast Calling Convention implementation
1782 //===----------------------------------------------------------------------===//
1783 // StdCall calling convention seems to be standard for many Windows' API
1784 // routines and around. It differs from C calling convention just a little:
1785 // callee should clean up the stack, not caller. Symbols should be also
1786 // decorated in some fancy way :) It doesn't support any vector arguments.
1787 // For info on fast calling convention see Fast Calling Convention (tail call)
1788 // implementation LowerX86_32FastCCCallTo.
1790 /// CallIsStructReturn - Determines whether a call uses struct return
1792 enum StructReturnType {
1797 static StructReturnType
1798 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1800 return NotStructReturn;
1802 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1803 if (!Flags.isSRet())
1804 return NotStructReturn;
1805 if (Flags.isInReg())
1806 return RegStructReturn;
1807 return StackStructReturn;
1810 /// ArgsAreStructReturn - Determines whether a function uses struct
1811 /// return semantics.
1812 static StructReturnType
1813 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1815 return NotStructReturn;
1817 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1818 if (!Flags.isSRet())
1819 return NotStructReturn;
1820 if (Flags.isInReg())
1821 return RegStructReturn;
1822 return StackStructReturn;
1825 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1826 /// by "Src" to address "Dst" with size and alignment information specified by
1827 /// the specific parameter attribute. The copy will be passed as a byval
1828 /// function parameter.
1830 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1831 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1833 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1835 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1836 /*isVolatile*/false, /*AlwaysInline=*/true,
1837 MachinePointerInfo(), MachinePointerInfo());
1840 /// IsTailCallConvention - Return true if the calling convention is one that
1841 /// supports tail call optimization.
1842 static bool IsTailCallConvention(CallingConv::ID CC) {
1843 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1844 CC == CallingConv::HiPE);
1847 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1848 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1852 CallingConv::ID CalleeCC = CS.getCallingConv();
1853 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1859 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1860 /// a tailcall target by changing its ABI.
1861 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1862 bool GuaranteedTailCallOpt) {
1863 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1867 X86TargetLowering::LowerMemArgument(SDValue Chain,
1868 CallingConv::ID CallConv,
1869 const SmallVectorImpl<ISD::InputArg> &Ins,
1870 DebugLoc dl, SelectionDAG &DAG,
1871 const CCValAssign &VA,
1872 MachineFrameInfo *MFI,
1874 // Create the nodes corresponding to a load from this parameter slot.
1875 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1876 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1877 getTargetMachine().Options.GuaranteedTailCallOpt);
1878 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1881 // If value is passed by pointer we have address passed instead of the value
1883 if (VA.getLocInfo() == CCValAssign::Indirect)
1884 ValVT = VA.getLocVT();
1886 ValVT = VA.getValVT();
1888 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1889 // changed with more analysis.
1890 // In case of tail call optimization mark all arguments mutable. Since they
1891 // could be overwritten by lowering of arguments in case of a tail call.
1892 if (Flags.isByVal()) {
1893 unsigned Bytes = Flags.getByValSize();
1894 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1895 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1896 return DAG.getFrameIndex(FI, getPointerTy());
1898 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1899 VA.getLocMemOffset(), isImmutable);
1900 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1901 return DAG.getLoad(ValVT, dl, Chain, FIN,
1902 MachinePointerInfo::getFixedStack(FI),
1903 false, false, false, 0);
1908 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1909 CallingConv::ID CallConv,
1911 const SmallVectorImpl<ISD::InputArg> &Ins,
1914 SmallVectorImpl<SDValue> &InVals)
1916 MachineFunction &MF = DAG.getMachineFunction();
1917 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919 const Function* Fn = MF.getFunction();
1920 if (Fn->hasExternalLinkage() &&
1921 Subtarget->isTargetCygMing() &&
1922 Fn->getName() == "main")
1923 FuncInfo->setForceFramePointer(true);
1925 MachineFrameInfo *MFI = MF.getFrameInfo();
1926 bool Is64Bit = Subtarget->is64Bit();
1927 bool IsWindows = Subtarget->isTargetWindows();
1928 bool IsWin64 = Subtarget->isTargetWin64();
1930 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1931 "Var args not supported with calling convention fastcc, ghc or hipe");
1933 // Assign locations to all of the incoming arguments.
1934 SmallVector<CCValAssign, 16> ArgLocs;
1935 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1936 ArgLocs, *DAG.getContext());
1938 // Allocate shadow area for Win64
1940 CCInfo.AllocateStack(32, 8);
1943 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1945 unsigned LastVal = ~0U;
1947 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1948 CCValAssign &VA = ArgLocs[i];
1949 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1951 assert(VA.getValNo() != LastVal &&
1952 "Don't support value assigned to multiple locs yet");
1954 LastVal = VA.getValNo();
1956 if (VA.isRegLoc()) {
1957 EVT RegVT = VA.getLocVT();
1958 const TargetRegisterClass *RC;
1959 if (RegVT == MVT::i32)
1960 RC = &X86::GR32RegClass;
1961 else if (Is64Bit && RegVT == MVT::i64)
1962 RC = &X86::GR64RegClass;
1963 else if (RegVT == MVT::f32)
1964 RC = &X86::FR32RegClass;
1965 else if (RegVT == MVT::f64)
1966 RC = &X86::FR64RegClass;
1967 else if (RegVT.is256BitVector())
1968 RC = &X86::VR256RegClass;
1969 else if (RegVT.is128BitVector())
1970 RC = &X86::VR128RegClass;
1971 else if (RegVT == MVT::x86mmx)
1972 RC = &X86::VR64RegClass;
1974 llvm_unreachable("Unknown argument type!");
1976 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1977 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1979 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1980 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1982 if (VA.getLocInfo() == CCValAssign::SExt)
1983 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1984 DAG.getValueType(VA.getValVT()));
1985 else if (VA.getLocInfo() == CCValAssign::ZExt)
1986 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1987 DAG.getValueType(VA.getValVT()));
1988 else if (VA.getLocInfo() == CCValAssign::BCvt)
1989 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1991 if (VA.isExtInLoc()) {
1992 // Handle MMX values passed in XMM regs.
1993 if (RegVT.isVector()) {
1994 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1997 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2000 assert(VA.isMemLoc());
2001 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2004 // If value is passed via pointer - do a load.
2005 if (VA.getLocInfo() == CCValAssign::Indirect)
2006 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2007 MachinePointerInfo(), false, false, false, 0);
2009 InVals.push_back(ArgValue);
2012 // The x86-64 ABI for returning structs by value requires that we copy
2013 // the sret argument into %rax for the return. Save the argument into
2014 // a virtual register so that we can access it from the return points.
2015 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2016 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2017 unsigned Reg = FuncInfo->getSRetReturnReg();
2019 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2020 FuncInfo->setSRetReturnReg(Reg);
2022 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2023 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2026 unsigned StackSize = CCInfo.getNextStackOffset();
2027 // Align stack specially for tail calls.
2028 if (FuncIsMadeTailCallSafe(CallConv,
2029 MF.getTarget().Options.GuaranteedTailCallOpt))
2030 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2032 // If the function takes variable number of arguments, make a frame index for
2033 // the start of the first vararg value... for expansion of llvm.va_start.
2035 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2036 CallConv != CallingConv::X86_ThisCall)) {
2037 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2040 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2042 // FIXME: We should really autogenerate these arrays
2043 static const uint16_t GPR64ArgRegsWin64[] = {
2044 X86::RCX, X86::RDX, X86::R8, X86::R9
2046 static const uint16_t GPR64ArgRegs64Bit[] = {
2047 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2049 static const uint16_t XMMArgRegs64Bit[] = {
2050 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2051 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2053 const uint16_t *GPR64ArgRegs;
2054 unsigned NumXMMRegs = 0;
2057 // The XMM registers which might contain var arg parameters are shadowed
2058 // in their paired GPR. So we only need to save the GPR to their home
2060 TotalNumIntRegs = 4;
2061 GPR64ArgRegs = GPR64ArgRegsWin64;
2063 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2064 GPR64ArgRegs = GPR64ArgRegs64Bit;
2066 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2069 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2072 bool NoImplicitFloatOps = Fn->getFnAttributes().
2073 hasAttribute(Attribute::NoImplicitFloat);
2074 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2075 "SSE register cannot be used when SSE is disabled!");
2076 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2077 NoImplicitFloatOps) &&
2078 "SSE register cannot be used when SSE is disabled!");
2079 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2080 !Subtarget->hasSSE1())
2081 // Kernel mode asks for SSE to be disabled, so don't push them
2083 TotalNumXMMRegs = 0;
2086 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2087 // Get to the caller-allocated home save location. Add 8 to account
2088 // for the return address.
2089 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2090 FuncInfo->setRegSaveFrameIndex(
2091 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2092 // Fixup to set vararg frame on shadow area (4 x i64).
2094 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2096 // For X86-64, if there are vararg parameters that are passed via
2097 // registers, then we must store them to their spots on the stack so
2098 // they may be loaded by deferencing the result of va_next.
2099 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2100 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2101 FuncInfo->setRegSaveFrameIndex(
2102 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2106 // Store the integer parameter registers.
2107 SmallVector<SDValue, 8> MemOps;
2108 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2110 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2111 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2112 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2113 DAG.getIntPtrConstant(Offset));
2114 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2115 &X86::GR64RegClass);
2116 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2118 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2119 MachinePointerInfo::getFixedStack(
2120 FuncInfo->getRegSaveFrameIndex(), Offset),
2122 MemOps.push_back(Store);
2126 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2127 // Now store the XMM (fp + vector) parameter registers.
2128 SmallVector<SDValue, 11> SaveXMMOps;
2129 SaveXMMOps.push_back(Chain);
2131 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2132 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2133 SaveXMMOps.push_back(ALVal);
2135 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2136 FuncInfo->getRegSaveFrameIndex()));
2137 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2138 FuncInfo->getVarArgsFPOffset()));
2140 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2141 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2142 &X86::VR128RegClass);
2143 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2144 SaveXMMOps.push_back(Val);
2146 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2148 &SaveXMMOps[0], SaveXMMOps.size()));
2151 if (!MemOps.empty())
2152 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2153 &MemOps[0], MemOps.size());
2157 // Some CCs need callee pop.
2158 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2159 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2160 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2162 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2163 // If this is an sret function, the return should pop the hidden pointer.
2164 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2165 argsAreStructReturn(Ins) == StackStructReturn)
2166 FuncInfo->setBytesToPopOnReturn(4);
2170 // RegSaveFrameIndex is X86-64 only.
2171 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2172 if (CallConv == CallingConv::X86_FastCall ||
2173 CallConv == CallingConv::X86_ThisCall)
2174 // fastcc functions can't have varargs.
2175 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2178 FuncInfo->setArgumentStackSize(StackSize);
2184 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2185 SDValue StackPtr, SDValue Arg,
2186 DebugLoc dl, SelectionDAG &DAG,
2187 const CCValAssign &VA,
2188 ISD::ArgFlagsTy Flags) const {
2189 unsigned LocMemOffset = VA.getLocMemOffset();
2190 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2191 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2192 if (Flags.isByVal())
2193 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2195 return DAG.getStore(Chain, dl, Arg, PtrOff,
2196 MachinePointerInfo::getStack(LocMemOffset),
2200 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2201 /// optimization is performed and it is required.
2203 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2204 SDValue &OutRetAddr, SDValue Chain,
2205 bool IsTailCall, bool Is64Bit,
2206 int FPDiff, DebugLoc dl) const {
2207 // Adjust the Return address stack slot.
2208 EVT VT = getPointerTy();
2209 OutRetAddr = getReturnAddressFrameIndex(DAG);
2211 // Load the "old" Return address.
2212 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2213 false, false, false, 0);
2214 return SDValue(OutRetAddr.getNode(), 1);
2217 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2218 /// optimization is performed and it is required (FPDiff!=0).
2220 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2221 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2222 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2223 // Store the return address to the appropriate stack slot.
2224 if (!FPDiff) return Chain;
2225 // Calculate the new stack slot for the return address.
2226 int NewReturnAddrFI =
2227 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2228 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2229 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2230 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2236 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2237 SmallVectorImpl<SDValue> &InVals) const {
2238 SelectionDAG &DAG = CLI.DAG;
2239 DebugLoc &dl = CLI.DL;
2240 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2241 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2242 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2243 SDValue Chain = CLI.Chain;
2244 SDValue Callee = CLI.Callee;
2245 CallingConv::ID CallConv = CLI.CallConv;
2246 bool &isTailCall = CLI.IsTailCall;
2247 bool isVarArg = CLI.IsVarArg;
2249 MachineFunction &MF = DAG.getMachineFunction();
2250 bool Is64Bit = Subtarget->is64Bit();
2251 bool IsWin64 = Subtarget->isTargetWin64();
2252 bool IsWindows = Subtarget->isTargetWindows();
2253 StructReturnType SR = callIsStructReturn(Outs);
2254 bool IsSibcall = false;
2256 if (MF.getTarget().Options.DisableTailCalls)
2260 // Check if it's really possible to do a tail call.
2261 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2262 isVarArg, SR != NotStructReturn,
2263 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2264 Outs, OutVals, Ins, DAG);
2266 // Sibcalls are automatically detected tailcalls which do not require
2268 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2275 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2276 "Var args not supported with calling convention fastcc, ghc or hipe");
2278 // Analyze operands of the call, assigning locations to each operand.
2279 SmallVector<CCValAssign, 16> ArgLocs;
2280 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2281 ArgLocs, *DAG.getContext());
2283 // Allocate shadow area for Win64
2285 CCInfo.AllocateStack(32, 8);
2288 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2290 // Get a count of how many bytes are to be pushed on the stack.
2291 unsigned NumBytes = CCInfo.getNextStackOffset();
2293 // This is a sibcall. The memory operands are available in caller's
2294 // own caller's stack.
2296 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2297 IsTailCallConvention(CallConv))
2298 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2301 if (isTailCall && !IsSibcall) {
2302 // Lower arguments at fp - stackoffset + fpdiff.
2303 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2304 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2306 FPDiff = NumBytesCallerPushed - NumBytes;
2308 // Set the delta of movement of the returnaddr stackslot.
2309 // But only set if delta is greater than previous delta.
2310 if (FPDiff < X86Info->getTCReturnAddrDelta())
2311 X86Info->setTCReturnAddrDelta(FPDiff);
2315 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2317 SDValue RetAddrFrIdx;
2318 // Load return address for tail calls.
2319 if (isTailCall && FPDiff)
2320 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2321 Is64Bit, FPDiff, dl);
2323 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2324 SmallVector<SDValue, 8> MemOpChains;
2327 // Walk the register/memloc assignments, inserting copies/loads. In the case
2328 // of tail call optimization arguments are handle later.
2329 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330 CCValAssign &VA = ArgLocs[i];
2331 EVT RegVT = VA.getLocVT();
2332 SDValue Arg = OutVals[i];
2333 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2334 bool isByVal = Flags.isByVal();
2336 // Promote the value if needed.
2337 switch (VA.getLocInfo()) {
2338 default: llvm_unreachable("Unknown loc info!");
2339 case CCValAssign::Full: break;
2340 case CCValAssign::SExt:
2341 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2343 case CCValAssign::ZExt:
2344 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2346 case CCValAssign::AExt:
2347 if (RegVT.is128BitVector()) {
2348 // Special case: passing MMX values in XMM registers.
2349 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2350 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2351 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2353 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2355 case CCValAssign::BCvt:
2356 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2358 case CCValAssign::Indirect: {
2359 // Store the argument.
2360 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2361 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2362 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2363 MachinePointerInfo::getFixedStack(FI),
2370 if (VA.isRegLoc()) {
2371 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2372 if (isVarArg && IsWin64) {
2373 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2374 // shadow reg if callee is a varargs function.
2375 unsigned ShadowReg = 0;
2376 switch (VA.getLocReg()) {
2377 case X86::XMM0: ShadowReg = X86::RCX; break;
2378 case X86::XMM1: ShadowReg = X86::RDX; break;
2379 case X86::XMM2: ShadowReg = X86::R8; break;
2380 case X86::XMM3: ShadowReg = X86::R9; break;
2383 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2385 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2386 assert(VA.isMemLoc());
2387 if (StackPtr.getNode() == 0)
2388 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2390 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2391 dl, DAG, VA, Flags));
2395 if (!MemOpChains.empty())
2396 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2397 &MemOpChains[0], MemOpChains.size());
2399 if (Subtarget->isPICStyleGOT()) {
2400 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2403 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2404 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2406 // If we are tail calling and generating PIC/GOT style code load the
2407 // address of the callee into ECX. The value in ecx is used as target of
2408 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2409 // for tail calls on PIC/GOT architectures. Normally we would just put the
2410 // address of GOT into ebx and then call target@PLT. But for tail calls
2411 // ebx would be restored (since ebx is callee saved) before jumping to the
2414 // Note: The actual moving to ECX is done further down.
2415 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2416 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2417 !G->getGlobal()->hasProtectedVisibility())
2418 Callee = LowerGlobalAddress(Callee, DAG);
2419 else if (isa<ExternalSymbolSDNode>(Callee))
2420 Callee = LowerExternalSymbol(Callee, DAG);
2424 if (Is64Bit && isVarArg && !IsWin64) {
2425 // From AMD64 ABI document:
2426 // For calls that may call functions that use varargs or stdargs
2427 // (prototype-less calls or calls to functions containing ellipsis (...) in
2428 // the declaration) %al is used as hidden argument to specify the number
2429 // of SSE registers used. The contents of %al do not need to match exactly
2430 // the number of registers, but must be an ubound on the number of SSE
2431 // registers used and is in the range 0 - 8 inclusive.
2433 // Count the number of XMM registers allocated.
2434 static const uint16_t XMMArgRegs[] = {
2435 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2438 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2439 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2440 && "SSE registers cannot be used when SSE is disabled");
2442 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2443 DAG.getConstant(NumXMMRegs, MVT::i8)));
2446 // For tail calls lower the arguments to the 'real' stack slot.
2448 // Force all the incoming stack arguments to be loaded from the stack
2449 // before any new outgoing arguments are stored to the stack, because the
2450 // outgoing stack slots may alias the incoming argument stack slots, and
2451 // the alias isn't otherwise explicit. This is slightly more conservative
2452 // than necessary, because it means that each store effectively depends
2453 // on every argument instead of just those arguments it would clobber.
2454 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2456 SmallVector<SDValue, 8> MemOpChains2;
2459 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2460 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2461 CCValAssign &VA = ArgLocs[i];
2464 assert(VA.isMemLoc());
2465 SDValue Arg = OutVals[i];
2466 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2467 // Create frame index.
2468 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2469 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2470 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2471 FIN = DAG.getFrameIndex(FI, getPointerTy());
2473 if (Flags.isByVal()) {
2474 // Copy relative to framepointer.
2475 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2476 if (StackPtr.getNode() == 0)
2477 StackPtr = DAG.getCopyFromReg(Chain, dl,
2478 RegInfo->getStackRegister(),
2480 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2482 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2486 // Store relative to framepointer.
2487 MemOpChains2.push_back(
2488 DAG.getStore(ArgChain, dl, Arg, FIN,
2489 MachinePointerInfo::getFixedStack(FI),
2495 if (!MemOpChains2.empty())
2496 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2497 &MemOpChains2[0], MemOpChains2.size());
2499 // Store the return address to the appropriate stack slot.
2500 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2501 getPointerTy(), RegInfo->getSlotSize(),
2505 // Build a sequence of copy-to-reg nodes chained together with token chain
2506 // and flag operands which copy the outgoing args into registers.
2508 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2509 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2510 RegsToPass[i].second, InFlag);
2511 InFlag = Chain.getValue(1);
2514 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2515 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2516 // In the 64-bit large code model, we have to make all calls
2517 // through a register, since the call instruction's 32-bit
2518 // pc-relative offset may not be large enough to hold the whole
2520 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2521 // If the callee is a GlobalAddress node (quite common, every direct call
2522 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2525 // We should use extra load for direct calls to dllimported functions in
2527 const GlobalValue *GV = G->getGlobal();
2528 if (!GV->hasDLLImportLinkage()) {
2529 unsigned char OpFlags = 0;
2530 bool ExtraLoad = false;
2531 unsigned WrapperKind = ISD::DELETED_NODE;
2533 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2534 // external symbols most go through the PLT in PIC mode. If the symbol
2535 // has hidden or protected visibility, or if it is static or local, then
2536 // we don't need to use the PLT - we can directly call it.
2537 if (Subtarget->isTargetELF() &&
2538 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2539 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2540 OpFlags = X86II::MO_PLT;
2541 } else if (Subtarget->isPICStyleStubAny() &&
2542 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2543 (!Subtarget->getTargetTriple().isMacOSX() ||
2544 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2545 // PC-relative references to external symbols should go through $stub,
2546 // unless we're building with the leopard linker or later, which
2547 // automatically synthesizes these stubs.
2548 OpFlags = X86II::MO_DARWIN_STUB;
2549 } else if (Subtarget->isPICStyleRIPRel() &&
2550 isa<Function>(GV) &&
2551 cast<Function>(GV)->getFnAttributes().
2552 hasAttribute(Attribute::NonLazyBind)) {
2553 // If the function is marked as non-lazy, generate an indirect call
2554 // which loads from the GOT directly. This avoids runtime overhead
2555 // at the cost of eager binding (and one extra byte of encoding).
2556 OpFlags = X86II::MO_GOTPCREL;
2557 WrapperKind = X86ISD::WrapperRIP;
2561 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2562 G->getOffset(), OpFlags);
2564 // Add a wrapper if needed.
2565 if (WrapperKind != ISD::DELETED_NODE)
2566 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2567 // Add extra indirection if needed.
2569 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2570 MachinePointerInfo::getGOT(),
2571 false, false, false, 0);
2573 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2574 unsigned char OpFlags = 0;
2576 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2577 // external symbols should go through the PLT.
2578 if (Subtarget->isTargetELF() &&
2579 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2580 OpFlags = X86II::MO_PLT;
2581 } else if (Subtarget->isPICStyleStubAny() &&
2582 (!Subtarget->getTargetTriple().isMacOSX() ||
2583 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2584 // PC-relative references to external symbols should go through $stub,
2585 // unless we're building with the leopard linker or later, which
2586 // automatically synthesizes these stubs.
2587 OpFlags = X86II::MO_DARWIN_STUB;
2590 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2594 // Returns a chain & a flag for retval copy to use.
2595 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2596 SmallVector<SDValue, 8> Ops;
2598 if (!IsSibcall && isTailCall) {
2599 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2600 DAG.getIntPtrConstant(0, true), InFlag);
2601 InFlag = Chain.getValue(1);
2604 Ops.push_back(Chain);
2605 Ops.push_back(Callee);
2608 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2610 // Add argument registers to the end of the list so that they are known live
2612 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2613 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2614 RegsToPass[i].second.getValueType()));
2616 // Add a register mask operand representing the call-preserved registers.
2617 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2618 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2619 assert(Mask && "Missing call preserved mask for calling convention");
2620 Ops.push_back(DAG.getRegisterMask(Mask));
2622 if (InFlag.getNode())
2623 Ops.push_back(InFlag);
2627 //// If this is the first return lowered for this function, add the regs
2628 //// to the liveout set for the function.
2629 // This isn't right, although it's probably harmless on x86; liveouts
2630 // should be computed from returns not tail calls. Consider a void
2631 // function making a tail call to a function returning int.
2632 return DAG.getNode(X86ISD::TC_RETURN, dl,
2633 NodeTys, &Ops[0], Ops.size());
2636 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2637 InFlag = Chain.getValue(1);
2639 // Create the CALLSEQ_END node.
2640 unsigned NumBytesForCalleeToPush;
2641 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642 getTargetMachine().Options.GuaranteedTailCallOpt))
2643 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2644 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2645 SR == StackStructReturn)
2646 // If this is a call to a struct-return function, the callee
2647 // pops the hidden struct pointer, so we have to push it back.
2648 // This is common for Darwin/X86, Linux & Mingw32 targets.
2649 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2650 NumBytesForCalleeToPush = 4;
2652 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2654 // Returns a flag for retval copy to use.
2656 Chain = DAG.getCALLSEQ_END(Chain,
2657 DAG.getIntPtrConstant(NumBytes, true),
2658 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2661 InFlag = Chain.getValue(1);
2664 // Handle result values, copying them out of physregs into vregs that we
2666 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2667 Ins, dl, DAG, InVals);
2670 //===----------------------------------------------------------------------===//
2671 // Fast Calling Convention (tail call) implementation
2672 //===----------------------------------------------------------------------===//
2674 // Like std call, callee cleans arguments, convention except that ECX is
2675 // reserved for storing the tail called function address. Only 2 registers are
2676 // free for argument passing (inreg). Tail call optimization is performed
2678 // * tailcallopt is enabled
2679 // * caller/callee are fastcc
2680 // On X86_64 architecture with GOT-style position independent code only local
2681 // (within module) calls are supported at the moment.
2682 // To keep the stack aligned according to platform abi the function
2683 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2684 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2685 // If a tail called function callee has more arguments than the caller the
2686 // caller needs to make sure that there is room to move the RETADDR to. This is
2687 // achieved by reserving an area the size of the argument delta right after the
2688 // original REtADDR, but before the saved framepointer or the spilled registers
2689 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2701 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2702 /// for a 16 byte align requirement.
2704 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2705 SelectionDAG& DAG) const {
2706 MachineFunction &MF = DAG.getMachineFunction();
2707 const TargetMachine &TM = MF.getTarget();
2708 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2709 unsigned StackAlignment = TFI.getStackAlignment();
2710 uint64_t AlignMask = StackAlignment - 1;
2711 int64_t Offset = StackSize;
2712 unsigned SlotSize = RegInfo->getSlotSize();
2713 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2714 // Number smaller than 12 so just add the difference.
2715 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2717 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2718 Offset = ((~AlignMask) & Offset) + StackAlignment +
2719 (StackAlignment-SlotSize);
2724 /// MatchingStackOffset - Return true if the given stack call argument is
2725 /// already available in the same position (relatively) of the caller's
2726 /// incoming argument stack.
2728 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2729 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2730 const X86InstrInfo *TII) {
2731 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2733 if (Arg.getOpcode() == ISD::CopyFromReg) {
2734 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2735 if (!TargetRegisterInfo::isVirtualRegister(VR))
2737 MachineInstr *Def = MRI->getVRegDef(VR);
2740 if (!Flags.isByVal()) {
2741 if (!TII->isLoadFromStackSlot(Def, FI))
2744 unsigned Opcode = Def->getOpcode();
2745 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2746 Def->getOperand(1).isFI()) {
2747 FI = Def->getOperand(1).getIndex();
2748 Bytes = Flags.getByValSize();
2752 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2753 if (Flags.isByVal())
2754 // ByVal argument is passed in as a pointer but it's now being
2755 // dereferenced. e.g.
2756 // define @foo(%struct.X* %A) {
2757 // tail call @bar(%struct.X* byval %A)
2760 SDValue Ptr = Ld->getBasePtr();
2761 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2764 FI = FINode->getIndex();
2765 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2766 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2767 FI = FINode->getIndex();
2768 Bytes = Flags.getByValSize();
2772 assert(FI != INT_MAX);
2773 if (!MFI->isFixedObjectIndex(FI))
2775 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2778 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2779 /// for tail call optimization. Targets which want to do tail call
2780 /// optimization should implement this function.
2782 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2783 CallingConv::ID CalleeCC,
2785 bool isCalleeStructRet,
2786 bool isCallerStructRet,
2788 const SmallVectorImpl<ISD::OutputArg> &Outs,
2789 const SmallVectorImpl<SDValue> &OutVals,
2790 const SmallVectorImpl<ISD::InputArg> &Ins,
2791 SelectionDAG& DAG) const {
2792 if (!IsTailCallConvention(CalleeCC) &&
2793 CalleeCC != CallingConv::C)
2796 // If -tailcallopt is specified, make fastcc functions tail-callable.
2797 const MachineFunction &MF = DAG.getMachineFunction();
2798 const Function *CallerF = DAG.getMachineFunction().getFunction();
2800 // If the function return type is x86_fp80 and the callee return type is not,
2801 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2802 // perform a tailcall optimization here.
2803 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2806 CallingConv::ID CallerCC = CallerF->getCallingConv();
2807 bool CCMatch = CallerCC == CalleeCC;
2809 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2810 if (IsTailCallConvention(CalleeCC) && CCMatch)
2815 // Look for obvious safe cases to perform tail call optimization that do not
2816 // require ABI changes. This is what gcc calls sibcall.
2818 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2819 // emit a special epilogue.
2820 if (RegInfo->needsStackRealignment(MF))
2823 // Also avoid sibcall optimization if either caller or callee uses struct
2824 // return semantics.
2825 if (isCalleeStructRet || isCallerStructRet)
2828 // An stdcall caller is expected to clean up its arguments; the callee
2829 // isn't going to do that.
2830 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2833 // Do not sibcall optimize vararg calls unless all arguments are passed via
2835 if (isVarArg && !Outs.empty()) {
2837 // Optimizing for varargs on Win64 is unlikely to be safe without
2838 // additional testing.
2839 if (Subtarget->isTargetWin64())
2842 SmallVector<CCValAssign, 16> ArgLocs;
2843 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2844 getTargetMachine(), ArgLocs, *DAG.getContext());
2846 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2847 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2848 if (!ArgLocs[i].isRegLoc())
2852 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2853 // stack. Therefore, if it's not used by the call it is not safe to optimize
2854 // this into a sibcall.
2855 bool Unused = false;
2856 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2863 SmallVector<CCValAssign, 16> RVLocs;
2864 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2865 getTargetMachine(), RVLocs, *DAG.getContext());
2866 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2867 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2868 CCValAssign &VA = RVLocs[i];
2869 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2874 // If the calling conventions do not match, then we'd better make sure the
2875 // results are returned in the same way as what the caller expects.
2877 SmallVector<CCValAssign, 16> RVLocs1;
2878 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2879 getTargetMachine(), RVLocs1, *DAG.getContext());
2880 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2882 SmallVector<CCValAssign, 16> RVLocs2;
2883 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2884 getTargetMachine(), RVLocs2, *DAG.getContext());
2885 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2887 if (RVLocs1.size() != RVLocs2.size())
2889 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2890 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2892 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2894 if (RVLocs1[i].isRegLoc()) {
2895 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2898 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2904 // If the callee takes no arguments then go on to check the results of the
2906 if (!Outs.empty()) {
2907 // Check if stack adjustment is needed. For now, do not do this if any
2908 // argument is passed on the stack.
2909 SmallVector<CCValAssign, 16> ArgLocs;
2910 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2911 getTargetMachine(), ArgLocs, *DAG.getContext());
2913 // Allocate shadow area for Win64
2914 if (Subtarget->isTargetWin64()) {
2915 CCInfo.AllocateStack(32, 8);
2918 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2919 if (CCInfo.getNextStackOffset()) {
2920 MachineFunction &MF = DAG.getMachineFunction();
2921 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2924 // Check if the arguments are already laid out in the right way as
2925 // the caller's fixed stack objects.
2926 MachineFrameInfo *MFI = MF.getFrameInfo();
2927 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2928 const X86InstrInfo *TII =
2929 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2930 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2931 CCValAssign &VA = ArgLocs[i];
2932 SDValue Arg = OutVals[i];
2933 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2934 if (VA.getLocInfo() == CCValAssign::Indirect)
2936 if (!VA.isRegLoc()) {
2937 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2944 // If the tailcall address may be in a register, then make sure it's
2945 // possible to register allocate for it. In 32-bit, the call address can
2946 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2947 // callee-saved registers are restored. These happen to be the same
2948 // registers used to pass 'inreg' arguments so watch out for those.
2949 if (!Subtarget->is64Bit() &&
2950 !isa<GlobalAddressSDNode>(Callee) &&
2951 !isa<ExternalSymbolSDNode>(Callee)) {
2952 unsigned NumInRegs = 0;
2953 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2954 CCValAssign &VA = ArgLocs[i];
2957 unsigned Reg = VA.getLocReg();
2960 case X86::EAX: case X86::EDX: case X86::ECX:
2961 if (++NumInRegs == 3)
2973 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2974 const TargetLibraryInfo *libInfo) const {
2975 return X86::createFastISel(funcInfo, libInfo);
2978 //===----------------------------------------------------------------------===//
2979 // Other Lowering Hooks
2980 //===----------------------------------------------------------------------===//
2982 static bool MayFoldLoad(SDValue Op) {
2983 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2986 static bool MayFoldIntoStore(SDValue Op) {
2987 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2990 static bool isTargetShuffle(unsigned Opcode) {
2992 default: return false;
2993 case X86ISD::PSHUFD:
2994 case X86ISD::PSHUFHW:
2995 case X86ISD::PSHUFLW:
2997 case X86ISD::PALIGN:
2998 case X86ISD::MOVLHPS:
2999 case X86ISD::MOVLHPD:
3000 case X86ISD::MOVHLPS:
3001 case X86ISD::MOVLPS:
3002 case X86ISD::MOVLPD:
3003 case X86ISD::MOVSHDUP:
3004 case X86ISD::MOVSLDUP:
3005 case X86ISD::MOVDDUP:
3008 case X86ISD::UNPCKL:
3009 case X86ISD::UNPCKH:
3010 case X86ISD::VPERMILP:
3011 case X86ISD::VPERM2X128:
3012 case X86ISD::VPERMI:
3017 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3018 SDValue V1, SelectionDAG &DAG) {
3020 default: llvm_unreachable("Unknown x86 shuffle node");
3021 case X86ISD::MOVSHDUP:
3022 case X86ISD::MOVSLDUP:
3023 case X86ISD::MOVDDUP:
3024 return DAG.getNode(Opc, dl, VT, V1);
3028 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3029 SDValue V1, unsigned TargetMask,
3030 SelectionDAG &DAG) {
3032 default: llvm_unreachable("Unknown x86 shuffle node");
3033 case X86ISD::PSHUFD:
3034 case X86ISD::PSHUFHW:
3035 case X86ISD::PSHUFLW:
3036 case X86ISD::VPERMILP:
3037 case X86ISD::VPERMI:
3038 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3042 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3043 SDValue V1, SDValue V2, unsigned TargetMask,
3044 SelectionDAG &DAG) {
3046 default: llvm_unreachable("Unknown x86 shuffle node");
3047 case X86ISD::PALIGN:
3049 case X86ISD::VPERM2X128:
3050 return DAG.getNode(Opc, dl, VT, V1, V2,
3051 DAG.getConstant(TargetMask, MVT::i8));
3055 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3056 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3058 default: llvm_unreachable("Unknown x86 shuffle node");
3059 case X86ISD::MOVLHPS:
3060 case X86ISD::MOVLHPD:
3061 case X86ISD::MOVHLPS:
3062 case X86ISD::MOVLPS:
3063 case X86ISD::MOVLPD:
3066 case X86ISD::UNPCKL:
3067 case X86ISD::UNPCKH:
3068 return DAG.getNode(Opc, dl, VT, V1, V2);
3072 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3073 MachineFunction &MF = DAG.getMachineFunction();
3074 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3075 int ReturnAddrIndex = FuncInfo->getRAIndex();
3077 if (ReturnAddrIndex == 0) {
3078 // Set up a frame object for the return address.
3079 unsigned SlotSize = RegInfo->getSlotSize();
3080 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3082 FuncInfo->setRAIndex(ReturnAddrIndex);
3085 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3088 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3089 bool hasSymbolicDisplacement) {
3090 // Offset should fit into 32 bit immediate field.
3091 if (!isInt<32>(Offset))
3094 // If we don't have a symbolic displacement - we don't have any extra
3096 if (!hasSymbolicDisplacement)
3099 // FIXME: Some tweaks might be needed for medium code model.
3100 if (M != CodeModel::Small && M != CodeModel::Kernel)
3103 // For small code model we assume that latest object is 16MB before end of 31
3104 // bits boundary. We may also accept pretty large negative constants knowing
3105 // that all objects are in the positive half of address space.
3106 if (M == CodeModel::Small && Offset < 16*1024*1024)
3109 // For kernel code model we know that all object resist in the negative half
3110 // of 32bits address space. We may not accept negative offsets, since they may
3111 // be just off and we may accept pretty large positive ones.
3112 if (M == CodeModel::Kernel && Offset > 0)
3118 /// isCalleePop - Determines whether the callee is required to pop its
3119 /// own arguments. Callee pop is necessary to support tail calls.
3120 bool X86::isCalleePop(CallingConv::ID CallingConv,
3121 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3125 switch (CallingConv) {
3128 case CallingConv::X86_StdCall:
3130 case CallingConv::X86_FastCall:
3132 case CallingConv::X86_ThisCall:
3134 case CallingConv::Fast:
3136 case CallingConv::GHC:
3138 case CallingConv::HiPE:
3143 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3144 /// specific condition code, returning the condition code and the LHS/RHS of the
3145 /// comparison to make.
3146 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3147 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3149 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3150 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3151 // X > -1 -> X == 0, jump !sign.
3152 RHS = DAG.getConstant(0, RHS.getValueType());
3153 return X86::COND_NS;
3155 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3156 // X < 0 -> X == 0, jump on sign.
3159 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3161 RHS = DAG.getConstant(0, RHS.getValueType());
3162 return X86::COND_LE;
3166 switch (SetCCOpcode) {
3167 default: llvm_unreachable("Invalid integer condition!");
3168 case ISD::SETEQ: return X86::COND_E;
3169 case ISD::SETGT: return X86::COND_G;
3170 case ISD::SETGE: return X86::COND_GE;
3171 case ISD::SETLT: return X86::COND_L;
3172 case ISD::SETLE: return X86::COND_LE;
3173 case ISD::SETNE: return X86::COND_NE;
3174 case ISD::SETULT: return X86::COND_B;
3175 case ISD::SETUGT: return X86::COND_A;
3176 case ISD::SETULE: return X86::COND_BE;
3177 case ISD::SETUGE: return X86::COND_AE;
3181 // First determine if it is required or is profitable to flip the operands.
3183 // If LHS is a foldable load, but RHS is not, flip the condition.
3184 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3185 !ISD::isNON_EXTLoad(RHS.getNode())) {
3186 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3187 std::swap(LHS, RHS);
3190 switch (SetCCOpcode) {
3196 std::swap(LHS, RHS);
3200 // On a floating point condition, the flags are set as follows:
3202 // 0 | 0 | 0 | X > Y
3203 // 0 | 0 | 1 | X < Y
3204 // 1 | 0 | 0 | X == Y
3205 // 1 | 1 | 1 | unordered
3206 switch (SetCCOpcode) {
3207 default: llvm_unreachable("Condcode should be pre-legalized away");
3209 case ISD::SETEQ: return X86::COND_E;
3210 case ISD::SETOLT: // flipped
3212 case ISD::SETGT: return X86::COND_A;
3213 case ISD::SETOLE: // flipped
3215 case ISD::SETGE: return X86::COND_AE;
3216 case ISD::SETUGT: // flipped
3218 case ISD::SETLT: return X86::COND_B;
3219 case ISD::SETUGE: // flipped
3221 case ISD::SETLE: return X86::COND_BE;
3223 case ISD::SETNE: return X86::COND_NE;
3224 case ISD::SETUO: return X86::COND_P;
3225 case ISD::SETO: return X86::COND_NP;
3227 case ISD::SETUNE: return X86::COND_INVALID;
3231 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3232 /// code. Current x86 isa includes the following FP cmov instructions:
3233 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3234 static bool hasFPCMov(unsigned X86CC) {
3250 /// isFPImmLegal - Returns true if the target can instruction select the
3251 /// specified FP immediate natively. If false, the legalizer will
3252 /// materialize the FP immediate as a load from a constant pool.
3253 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3254 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3255 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3261 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3262 /// the specified range (L, H].
3263 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3264 return (Val < 0) || (Val >= Low && Val < Hi);
3267 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3268 /// specified value.
3269 static bool isUndefOrEqual(int Val, int CmpVal) {
3270 return (Val < 0 || Val == CmpVal);
3273 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3274 /// from position Pos and ending in Pos+Size, falls within the specified
3275 /// sequential range (L, L+Pos]. or is undef.
3276 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3277 unsigned Pos, unsigned Size, int Low) {
3278 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3279 if (!isUndefOrEqual(Mask[i], Low))
3284 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3285 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3286 /// the second operand.
3287 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3288 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3289 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3290 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3291 return (Mask[0] < 2 && Mask[1] < 2);
3295 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3296 /// is suitable for input to PSHUFHW.
3297 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3298 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3301 // Lower quadword copied in order or undef.
3302 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3305 // Upper quadword shuffled.
3306 for (unsigned i = 4; i != 8; ++i)
3307 if (!isUndefOrInRange(Mask[i], 4, 8))
3310 if (VT == MVT::v16i16) {
3311 // Lower quadword copied in order or undef.
3312 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3315 // Upper quadword shuffled.
3316 for (unsigned i = 12; i != 16; ++i)
3317 if (!isUndefOrInRange(Mask[i], 12, 16))
3324 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3325 /// is suitable for input to PSHUFLW.
3326 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3327 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3330 // Upper quadword copied in order.
3331 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3334 // Lower quadword shuffled.
3335 for (unsigned i = 0; i != 4; ++i)
3336 if (!isUndefOrInRange(Mask[i], 0, 4))
3339 if (VT == MVT::v16i16) {
3340 // Upper quadword copied in order.
3341 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3344 // Lower quadword shuffled.
3345 for (unsigned i = 8; i != 12; ++i)
3346 if (!isUndefOrInRange(Mask[i], 8, 12))
3353 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3354 /// is suitable for input to PALIGNR.
3355 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3356 const X86Subtarget *Subtarget) {
3357 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3358 (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3361 unsigned NumElts = VT.getVectorNumElements();
3362 unsigned NumLanes = VT.getSizeInBits()/128;
3363 unsigned NumLaneElts = NumElts/NumLanes;
3365 // Do not handle 64-bit element shuffles with palignr.
3366 if (NumLaneElts == 2)
3369 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3371 for (i = 0; i != NumLaneElts; ++i) {
3376 // Lane is all undef, go to next lane
3377 if (i == NumLaneElts)
3380 int Start = Mask[i+l];
3382 // Make sure its in this lane in one of the sources
3383 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3384 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3387 // If not lane 0, then we must match lane 0
3388 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3391 // Correct second source to be contiguous with first source
3392 if (Start >= (int)NumElts)
3393 Start -= NumElts - NumLaneElts;
3395 // Make sure we're shifting in the right direction.
3396 if (Start <= (int)(i+l))
3401 // Check the rest of the elements to see if they are consecutive.
3402 for (++i; i != NumLaneElts; ++i) {
3403 int Idx = Mask[i+l];
3405 // Make sure its in this lane
3406 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3407 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3410 // If not lane 0, then we must match lane 0
3411 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3414 if (Idx >= (int)NumElts)
3415 Idx -= NumElts - NumLaneElts;
3417 if (!isUndefOrEqual(Idx, Start+i))
3426 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3427 /// the two vector operands have swapped position.
3428 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3429 unsigned NumElems) {
3430 for (unsigned i = 0; i != NumElems; ++i) {
3434 else if (idx < (int)NumElems)
3435 Mask[i] = idx + NumElems;
3437 Mask[i] = idx - NumElems;
3441 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3442 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3443 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3444 /// reverse of what x86 shuffles want.
3445 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3446 bool Commuted = false) {
3447 if (!HasFp256 && VT.getSizeInBits() == 256)
3450 unsigned NumElems = VT.getVectorNumElements();
3451 unsigned NumLanes = VT.getSizeInBits()/128;
3452 unsigned NumLaneElems = NumElems/NumLanes;
3454 if (NumLaneElems != 2 && NumLaneElems != 4)
3457 // VSHUFPSY divides the resulting vector into 4 chunks.
3458 // The sources are also splitted into 4 chunks, and each destination
3459 // chunk must come from a different source chunk.
3461 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3462 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3464 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3465 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3467 // VSHUFPDY divides the resulting vector into 4 chunks.
3468 // The sources are also splitted into 4 chunks, and each destination
3469 // chunk must come from a different source chunk.
3471 // SRC1 => X3 X2 X1 X0
3472 // SRC2 => Y3 Y2 Y1 Y0
3474 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3476 unsigned HalfLaneElems = NumLaneElems/2;
3477 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3478 for (unsigned i = 0; i != NumLaneElems; ++i) {
3479 int Idx = Mask[i+l];
3480 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3481 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3483 // For VSHUFPSY, the mask of the second half must be the same as the
3484 // first but with the appropriate offsets. This works in the same way as
3485 // VPERMILPS works with masks.
3486 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3488 if (!isUndefOrEqual(Idx, Mask[i]+l))
3496 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3498 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3499 if (!VT.is128BitVector())
3502 unsigned NumElems = VT.getVectorNumElements();
3507 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3508 return isUndefOrEqual(Mask[0], 6) &&
3509 isUndefOrEqual(Mask[1], 7) &&
3510 isUndefOrEqual(Mask[2], 2) &&
3511 isUndefOrEqual(Mask[3], 3);
3514 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3515 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3517 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3518 if (!VT.is128BitVector())
3521 unsigned NumElems = VT.getVectorNumElements();
3526 return isUndefOrEqual(Mask[0], 2) &&
3527 isUndefOrEqual(Mask[1], 3) &&
3528 isUndefOrEqual(Mask[2], 2) &&
3529 isUndefOrEqual(Mask[3], 3);
3532 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3533 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3534 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3535 if (!VT.is128BitVector())
3538 unsigned NumElems = VT.getVectorNumElements();
3540 if (NumElems != 2 && NumElems != 4)
3543 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3544 if (!isUndefOrEqual(Mask[i], i + NumElems))
3547 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3548 if (!isUndefOrEqual(Mask[i], i))
3554 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3555 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3556 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3557 if (!VT.is128BitVector())
3560 unsigned NumElems = VT.getVectorNumElements();
3562 if (NumElems != 2 && NumElems != 4)
3565 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3566 if (!isUndefOrEqual(Mask[i], i))
3569 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3570 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3577 // Some special combinations that can be optimized.
3580 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3581 SelectionDAG &DAG) {
3582 EVT VT = SVOp->getValueType(0);
3583 DebugLoc dl = SVOp->getDebugLoc();
3585 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3588 ArrayRef<int> Mask = SVOp->getMask();
3590 // These are the special masks that may be optimized.
3591 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3592 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3593 bool MatchEvenMask = true;
3594 bool MatchOddMask = true;
3595 for (int i=0; i<8; ++i) {
3596 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3597 MatchEvenMask = false;
3598 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3599 MatchOddMask = false;
3602 if (!MatchEvenMask && !MatchOddMask)
3605 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3607 SDValue Op0 = SVOp->getOperand(0);
3608 SDValue Op1 = SVOp->getOperand(1);
3610 if (MatchEvenMask) {
3611 // Shift the second operand right to 32 bits.
3612 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3613 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3615 // Shift the first operand left to 32 bits.
3616 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3617 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3619 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3620 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3623 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3624 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3625 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3626 bool HasInt256, bool V2IsSplat = false) {
3627 unsigned NumElts = VT.getVectorNumElements();
3629 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3630 "Unsupported vector type for unpckh");
3632 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3633 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3636 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3637 // independently on 128-bit lanes.
3638 unsigned NumLanes = VT.getSizeInBits()/128;
3639 unsigned NumLaneElts = NumElts/NumLanes;
3641 for (unsigned l = 0; l != NumLanes; ++l) {
3642 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3643 i != (l+1)*NumLaneElts;
3646 int BitI1 = Mask[i+1];
3647 if (!isUndefOrEqual(BitI, j))
3650 if (!isUndefOrEqual(BitI1, NumElts))
3653 if (!isUndefOrEqual(BitI1, j + NumElts))
3662 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3663 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3664 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3665 bool HasInt256, bool V2IsSplat = false) {
3666 unsigned NumElts = VT.getVectorNumElements();
3668 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3669 "Unsupported vector type for unpckh");
3671 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3672 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3675 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3676 // independently on 128-bit lanes.
3677 unsigned NumLanes = VT.getSizeInBits()/128;
3678 unsigned NumLaneElts = NumElts/NumLanes;
3680 for (unsigned l = 0; l != NumLanes; ++l) {
3681 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3682 i != (l+1)*NumLaneElts; i += 2, ++j) {
3684 int BitI1 = Mask[i+1];
3685 if (!isUndefOrEqual(BitI, j))
3688 if (isUndefOrEqual(BitI1, NumElts))
3691 if (!isUndefOrEqual(BitI1, j+NumElts))
3699 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3700 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3702 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3704 unsigned NumElts = VT.getVectorNumElements();
3706 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3707 "Unsupported vector type for unpckh");
3709 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3710 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3713 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3714 // FIXME: Need a better way to get rid of this, there's no latency difference
3715 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3716 // the former later. We should also remove the "_undef" special mask.
3717 if (NumElts == 4 && VT.getSizeInBits() == 256)
3720 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3721 // independently on 128-bit lanes.
3722 unsigned NumLanes = VT.getSizeInBits()/128;
3723 unsigned NumLaneElts = NumElts/NumLanes;
3725 for (unsigned l = 0; l != NumLanes; ++l) {
3726 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3727 i != (l+1)*NumLaneElts;
3730 int BitI1 = Mask[i+1];
3732 if (!isUndefOrEqual(BitI, j))
3734 if (!isUndefOrEqual(BitI1, j))
3742 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3743 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3745 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3746 unsigned NumElts = VT.getVectorNumElements();
3748 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3749 "Unsupported vector type for unpckh");
3751 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3752 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3755 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3756 // independently on 128-bit lanes.
3757 unsigned NumLanes = VT.getSizeInBits()/128;
3758 unsigned NumLaneElts = NumElts/NumLanes;
3760 for (unsigned l = 0; l != NumLanes; ++l) {
3761 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3762 i != (l+1)*NumLaneElts; i += 2, ++j) {
3764 int BitI1 = Mask[i+1];
3765 if (!isUndefOrEqual(BitI, j))
3767 if (!isUndefOrEqual(BitI1, j))
3774 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3775 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3776 /// MOVSD, and MOVD, i.e. setting the lowest element.
3777 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3778 if (VT.getVectorElementType().getSizeInBits() < 32)
3780 if (!VT.is128BitVector())
3783 unsigned NumElts = VT.getVectorNumElements();
3785 if (!isUndefOrEqual(Mask[0], NumElts))
3788 for (unsigned i = 1; i != NumElts; ++i)
3789 if (!isUndefOrEqual(Mask[i], i))
3795 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3796 /// as permutations between 128-bit chunks or halves. As an example: this
3798 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3799 /// The first half comes from the second half of V1 and the second half from the
3800 /// the second half of V2.
3801 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3802 if (!HasFp256 || !VT.is256BitVector())
3805 // The shuffle result is divided into half A and half B. In total the two
3806 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3807 // B must come from C, D, E or F.
3808 unsigned HalfSize = VT.getVectorNumElements()/2;
3809 bool MatchA = false, MatchB = false;
3811 // Check if A comes from one of C, D, E, F.
3812 for (unsigned Half = 0; Half != 4; ++Half) {
3813 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3819 // Check if B comes from one of C, D, E, F.
3820 for (unsigned Half = 0; Half != 4; ++Half) {
3821 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3827 return MatchA && MatchB;
3830 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3831 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3832 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3833 EVT VT = SVOp->getValueType(0);
3835 unsigned HalfSize = VT.getVectorNumElements()/2;
3837 unsigned FstHalf = 0, SndHalf = 0;
3838 for (unsigned i = 0; i < HalfSize; ++i) {
3839 if (SVOp->getMaskElt(i) > 0) {
3840 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3844 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3845 if (SVOp->getMaskElt(i) > 0) {
3846 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3851 return (FstHalf | (SndHalf << 4));
3854 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3856 /// Note that VPERMIL mask matching is different depending whether theunderlying
3857 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3858 /// to the same elements of the low, but to the higher half of the source.
3859 /// In VPERMILPD the two lanes could be shuffled independently of each other
3860 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3861 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3865 unsigned NumElts = VT.getVectorNumElements();
3866 // Only match 256-bit with 32/64-bit types
3867 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3870 unsigned NumLanes = VT.getSizeInBits()/128;
3871 unsigned LaneSize = NumElts/NumLanes;
3872 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3873 for (unsigned i = 0; i != LaneSize; ++i) {
3874 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3876 if (NumElts != 8 || l == 0)
3878 // VPERMILPS handling
3881 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3889 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3890 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3891 /// element of vector 2 and the other elements to come from vector 1 in order.
3892 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3893 bool V2IsSplat = false, bool V2IsUndef = false) {
3894 if (!VT.is128BitVector())
3897 unsigned NumOps = VT.getVectorNumElements();
3898 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3901 if (!isUndefOrEqual(Mask[0], 0))
3904 for (unsigned i = 1; i != NumOps; ++i)
3905 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3906 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3907 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3913 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3915 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3916 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3917 const X86Subtarget *Subtarget) {
3918 if (!Subtarget->hasSSE3())
3921 unsigned NumElems = VT.getVectorNumElements();
3923 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3924 (VT.getSizeInBits() == 256 && NumElems != 8))
3927 // "i+1" is the value the indexed mask element must have
3928 for (unsigned i = 0; i != NumElems; i += 2)
3929 if (!isUndefOrEqual(Mask[i], i+1) ||
3930 !isUndefOrEqual(Mask[i+1], i+1))
3936 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3938 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3939 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3940 const X86Subtarget *Subtarget) {
3941 if (!Subtarget->hasSSE3())
3944 unsigned NumElems = VT.getVectorNumElements();
3946 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3947 (VT.getSizeInBits() == 256 && NumElems != 8))
3950 // "i" is the value the indexed mask element must have
3951 for (unsigned i = 0; i != NumElems; i += 2)
3952 if (!isUndefOrEqual(Mask[i], i) ||
3953 !isUndefOrEqual(Mask[i+1], i))
3959 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to 256-bit
3961 /// version of MOVDDUP.
3962 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3963 if (!HasFp256 || !VT.is256BitVector())
3966 unsigned NumElts = VT.getVectorNumElements();
3970 for (unsigned i = 0; i != NumElts/2; ++i)
3971 if (!isUndefOrEqual(Mask[i], 0))
3973 for (unsigned i = NumElts/2; i != NumElts; ++i)
3974 if (!isUndefOrEqual(Mask[i], NumElts/2))
3979 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3980 /// specifies a shuffle of elements that is suitable for input to 128-bit
3981 /// version of MOVDDUP.
3982 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3983 if (!VT.is128BitVector())
3986 unsigned e = VT.getVectorNumElements() / 2;
3987 for (unsigned i = 0; i != e; ++i)
3988 if (!isUndefOrEqual(Mask[i], i))
3990 for (unsigned i = 0; i != e; ++i)
3991 if (!isUndefOrEqual(Mask[e+i], i))
3996 /// isVEXTRACTF128Index - Return true if the specified
3997 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3998 /// suitable for input to VEXTRACTF128.
3999 bool X86::isVEXTRACTF128Index(SDNode *N) {
4000 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4003 // The index should be aligned on a 128-bit boundary.
4005 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4007 unsigned VL = N->getValueType(0).getVectorNumElements();
4008 unsigned VBits = N->getValueType(0).getSizeInBits();
4009 unsigned ElSize = VBits / VL;
4010 bool Result = (Index * ElSize) % 128 == 0;
4015 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4016 /// operand specifies a subvector insert that is suitable for input to
4018 bool X86::isVINSERTF128Index(SDNode *N) {
4019 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4022 // The index should be aligned on a 128-bit boundary.
4024 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4026 unsigned VL = N->getValueType(0).getVectorNumElements();
4027 unsigned VBits = N->getValueType(0).getSizeInBits();
4028 unsigned ElSize = VBits / VL;
4029 bool Result = (Index * ElSize) % 128 == 0;
4034 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4035 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4036 /// Handles 128-bit and 256-bit.
4037 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4038 EVT VT = N->getValueType(0);
4040 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4041 "Unsupported vector type for PSHUF/SHUFP");
4043 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4044 // independently on 128-bit lanes.
4045 unsigned NumElts = VT.getVectorNumElements();
4046 unsigned NumLanes = VT.getSizeInBits()/128;
4047 unsigned NumLaneElts = NumElts/NumLanes;
4049 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4050 "Only supports 2 or 4 elements per lane");
4052 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4054 for (unsigned i = 0; i != NumElts; ++i) {
4055 int Elt = N->getMaskElt(i);
4056 if (Elt < 0) continue;
4057 Elt &= NumLaneElts - 1;
4058 unsigned ShAmt = (i << Shift) % 8;
4059 Mask |= Elt << ShAmt;
4065 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4067 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4068 EVT VT = N->getValueType(0);
4070 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4071 "Unsupported vector type for PSHUFHW");
4073 unsigned NumElts = VT.getVectorNumElements();
4076 for (unsigned l = 0; l != NumElts; l += 8) {
4077 // 8 nodes per lane, but we only care about the last 4.
4078 for (unsigned i = 0; i < 4; ++i) {
4079 int Elt = N->getMaskElt(l+i+4);
4080 if (Elt < 0) continue;
4081 Elt &= 0x3; // only 2-bits.
4082 Mask |= Elt << (i * 2);
4089 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4091 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4092 EVT VT = N->getValueType(0);
4094 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4095 "Unsupported vector type for PSHUFHW");
4097 unsigned NumElts = VT.getVectorNumElements();
4100 for (unsigned l = 0; l != NumElts; l += 8) {
4101 // 8 nodes per lane, but we only care about the first 4.
4102 for (unsigned i = 0; i < 4; ++i) {
4103 int Elt = N->getMaskElt(l+i);
4104 if (Elt < 0) continue;
4105 Elt &= 0x3; // only 2-bits
4106 Mask |= Elt << (i * 2);
4113 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4115 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4116 EVT VT = SVOp->getValueType(0);
4117 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4119 unsigned NumElts = VT.getVectorNumElements();
4120 unsigned NumLanes = VT.getSizeInBits()/128;
4121 unsigned NumLaneElts = NumElts/NumLanes;
4125 for (i = 0; i != NumElts; ++i) {
4126 Val = SVOp->getMaskElt(i);
4130 if (Val >= (int)NumElts)
4131 Val -= NumElts - NumLaneElts;
4133 assert(Val - i > 0 && "PALIGNR imm should be positive");
4134 return (Val - i) * EltSize;
4137 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4140 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4141 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4142 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4145 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4147 EVT VecVT = N->getOperand(0).getValueType();
4148 EVT ElVT = VecVT.getVectorElementType();
4150 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4151 return Index / NumElemsPerChunk;
4154 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4155 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4157 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4158 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4159 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4162 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4164 EVT VecVT = N->getValueType(0);
4165 EVT ElVT = VecVT.getVectorElementType();
4167 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4168 return Index / NumElemsPerChunk;
4171 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4172 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4173 /// Handles 256-bit.
4174 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4175 EVT VT = N->getValueType(0);
4177 unsigned NumElts = VT.getVectorNumElements();
4179 assert((VT.is256BitVector() && NumElts == 4) &&
4180 "Unsupported vector type for VPERMQ/VPERMPD");
4183 for (unsigned i = 0; i != NumElts; ++i) {
4184 int Elt = N->getMaskElt(i);
4187 Mask |= Elt << (i*2);
4192 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4194 bool X86::isZeroNode(SDValue Elt) {
4195 return ((isa<ConstantSDNode>(Elt) &&
4196 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4197 (isa<ConstantFPSDNode>(Elt) &&
4198 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4201 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4202 /// their permute mask.
4203 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4204 SelectionDAG &DAG) {
4205 EVT VT = SVOp->getValueType(0);
4206 unsigned NumElems = VT.getVectorNumElements();
4207 SmallVector<int, 8> MaskVec;
4209 for (unsigned i = 0; i != NumElems; ++i) {
4210 int Idx = SVOp->getMaskElt(i);
4212 if (Idx < (int)NumElems)
4217 MaskVec.push_back(Idx);
4219 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4220 SVOp->getOperand(0), &MaskVec[0]);
4223 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4224 /// match movhlps. The lower half elements should come from upper half of
4225 /// V1 (and in order), and the upper half elements should come from the upper
4226 /// half of V2 (and in order).
4227 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4228 if (!VT.is128BitVector())
4230 if (VT.getVectorNumElements() != 4)
4232 for (unsigned i = 0, e = 2; i != e; ++i)
4233 if (!isUndefOrEqual(Mask[i], i+2))
4235 for (unsigned i = 2; i != 4; ++i)
4236 if (!isUndefOrEqual(Mask[i], i+4))
4241 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4242 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4244 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4245 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4247 N = N->getOperand(0).getNode();
4248 if (!ISD::isNON_EXTLoad(N))
4251 *LD = cast<LoadSDNode>(N);
4255 // Test whether the given value is a vector value which will be legalized
4257 static bool WillBeConstantPoolLoad(SDNode *N) {
4258 if (N->getOpcode() != ISD::BUILD_VECTOR)
4261 // Check for any non-constant elements.
4262 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4263 switch (N->getOperand(i).getNode()->getOpcode()) {
4265 case ISD::ConstantFP:
4272 // Vectors of all-zeros and all-ones are materialized with special
4273 // instructions rather than being loaded.
4274 return !ISD::isBuildVectorAllZeros(N) &&
4275 !ISD::isBuildVectorAllOnes(N);
4278 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4279 /// match movlp{s|d}. The lower half elements should come from lower half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order). And since V1 will become the source of the
4282 /// MOVLP, it must be either a vector load or a scalar load to vector.
4283 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4284 ArrayRef<int> Mask, EVT VT) {
4285 if (!VT.is128BitVector())
4288 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4290 // Is V2 is a vector load, don't do this transformation. We will try to use
4291 // load folding shufps op.
4292 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4295 unsigned NumElems = VT.getVectorNumElements();
4297 if (NumElems != 2 && NumElems != 4)
4299 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4300 if (!isUndefOrEqual(Mask[i], i))
4302 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4303 if (!isUndefOrEqual(Mask[i], i+NumElems))
4308 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4310 static bool isSplatVector(SDNode *N) {
4311 if (N->getOpcode() != ISD::BUILD_VECTOR)
4314 SDValue SplatValue = N->getOperand(0);
4315 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4316 if (N->getOperand(i) != SplatValue)
4321 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4322 /// to an zero vector.
4323 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4324 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4325 SDValue V1 = N->getOperand(0);
4326 SDValue V2 = N->getOperand(1);
4327 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4328 for (unsigned i = 0; i != NumElems; ++i) {
4329 int Idx = N->getMaskElt(i);
4330 if (Idx >= (int)NumElems) {
4331 unsigned Opc = V2.getOpcode();
4332 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4334 if (Opc != ISD::BUILD_VECTOR ||
4335 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4337 } else if (Idx >= 0) {
4338 unsigned Opc = V1.getOpcode();
4339 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4341 if (Opc != ISD::BUILD_VECTOR ||
4342 !X86::isZeroNode(V1.getOperand(Idx)))
4349 /// getZeroVector - Returns a vector of specified type with all zero elements.
4351 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4352 SelectionDAG &DAG, DebugLoc dl) {
4353 assert(VT.isVector() && "Expected a vector type");
4354 unsigned Size = VT.getSizeInBits();
4356 // Always build SSE zero vectors as <4 x i32> bitcasted
4357 // to their dest type. This ensures they get CSE'd.
4359 if (Size == 128) { // SSE
4360 if (Subtarget->hasSSE2()) { // SSE2
4361 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4364 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4365 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4367 } else if (Size == 256) { // AVX
4368 if (Subtarget->hasInt256()) { // AVX2
4369 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4370 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4371 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4373 // 256-bit logic and arithmetic instructions in AVX are all
4374 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4375 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4376 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4377 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4380 llvm_unreachable("Unexpected vector type");
4382 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4385 /// getOnesVector - Returns a vector of specified type with all bits set.
4386 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4387 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4388 /// Then bitcast to their original type, ensuring they get CSE'd.
4389 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4391 assert(VT.isVector() && "Expected a vector type");
4392 unsigned Size = VT.getSizeInBits();
4394 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4397 if (HasInt256) { // AVX2
4398 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4401 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4404 } else if (Size == 128) {
4405 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4407 llvm_unreachable("Unexpected vector type");
4409 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4413 /// that point to V2 points to its first element.
4414 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4415 for (unsigned i = 0; i != NumElems; ++i) {
4416 if (Mask[i] > (int)NumElems) {
4422 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4423 /// operation of specified width.
4424 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4426 unsigned NumElems = VT.getVectorNumElements();
4427 SmallVector<int, 8> Mask;
4428 Mask.push_back(NumElems);
4429 for (unsigned i = 1; i != NumElems; ++i)
4431 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4434 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4435 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4437 unsigned NumElems = VT.getVectorNumElements();
4438 SmallVector<int, 8> Mask;
4439 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4441 Mask.push_back(i + NumElems);
4443 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4446 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4447 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4449 unsigned NumElems = VT.getVectorNumElements();
4450 SmallVector<int, 8> Mask;
4451 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4452 Mask.push_back(i + Half);
4453 Mask.push_back(i + NumElems + Half);
4455 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4458 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4459 // a generic shuffle instruction because the target has no such instructions.
4460 // Generate shuffles which repeat i16 and i8 several times until they can be
4461 // represented by v4f32 and then be manipulated by target suported shuffles.
4462 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4463 EVT VT = V.getValueType();
4464 int NumElems = VT.getVectorNumElements();
4465 DebugLoc dl = V.getDebugLoc();
4467 while (NumElems > 4) {
4468 if (EltNo < NumElems/2) {
4469 V = getUnpackl(DAG, dl, VT, V, V);
4471 V = getUnpackh(DAG, dl, VT, V, V);
4472 EltNo -= NumElems/2;
4479 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4480 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4481 EVT VT = V.getValueType();
4482 DebugLoc dl = V.getDebugLoc();
4483 unsigned Size = VT.getSizeInBits();
4486 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4487 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4488 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4490 } else if (Size == 256) {
4491 // To use VPERMILPS to splat scalars, the second half of indicies must
4492 // refer to the higher part, which is a duplication of the lower one,
4493 // because VPERMILPS can only handle in-lane permutations.
4494 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4495 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4497 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4498 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4501 llvm_unreachable("Vector size not supported");
4503 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4506 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4507 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4508 EVT SrcVT = SV->getValueType(0);
4509 SDValue V1 = SV->getOperand(0);
4510 DebugLoc dl = SV->getDebugLoc();
4512 int EltNo = SV->getSplatIndex();
4513 int NumElems = SrcVT.getVectorNumElements();
4514 unsigned Size = SrcVT.getSizeInBits();
4516 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4517 "Unknown how to promote splat for type");
4519 // Extract the 128-bit part containing the splat element and update
4520 // the splat element index when it refers to the higher register.
4522 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4523 if (EltNo >= NumElems/2)
4524 EltNo -= NumElems/2;
4527 // All i16 and i8 vector types can't be used directly by a generic shuffle
4528 // instruction because the target has no such instruction. Generate shuffles
4529 // which repeat i16 and i8 several times until they fit in i32, and then can
4530 // be manipulated by target suported shuffles.
4531 EVT EltVT = SrcVT.getVectorElementType();
4532 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4533 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4535 // Recreate the 256-bit vector and place the same 128-bit vector
4536 // into the low and high part. This is necessary because we want
4537 // to use VPERM* to shuffle the vectors
4539 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4542 return getLegalSplat(DAG, V1, EltNo);
4545 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4546 /// vector of zero or undef vector. This produces a shuffle where the low
4547 /// element of V2 is swizzled into the zero/undef vector, landing at element
4548 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4549 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4551 const X86Subtarget *Subtarget,
4552 SelectionDAG &DAG) {
4553 EVT VT = V2.getValueType();
4555 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4556 unsigned NumElems = VT.getVectorNumElements();
4557 SmallVector<int, 16> MaskVec;
4558 for (unsigned i = 0; i != NumElems; ++i)
4559 // If this is the insertion idx, put the low elt of V2 here.
4560 MaskVec.push_back(i == Idx ? NumElems : i);
4561 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4564 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4565 /// target specific opcode. Returns true if the Mask could be calculated.
4566 /// Sets IsUnary to true if only uses one source.
4567 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4568 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4569 unsigned NumElems = VT.getVectorNumElements();
4573 switch(N->getOpcode()) {
4575 ImmN = N->getOperand(N->getNumOperands()-1);
4576 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4578 case X86ISD::UNPCKH:
4579 DecodeUNPCKHMask(VT, Mask);
4581 case X86ISD::UNPCKL:
4582 DecodeUNPCKLMask(VT, Mask);
4584 case X86ISD::MOVHLPS:
4585 DecodeMOVHLPSMask(NumElems, Mask);
4587 case X86ISD::MOVLHPS:
4588 DecodeMOVLHPSMask(NumElems, Mask);
4590 case X86ISD::PSHUFD:
4591 case X86ISD::VPERMILP:
4592 ImmN = N->getOperand(N->getNumOperands()-1);
4593 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596 case X86ISD::PSHUFHW:
4597 ImmN = N->getOperand(N->getNumOperands()-1);
4598 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601 case X86ISD::PSHUFLW:
4602 ImmN = N->getOperand(N->getNumOperands()-1);
4603 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606 case X86ISD::VPERMI:
4607 ImmN = N->getOperand(N->getNumOperands()-1);
4608 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4612 case X86ISD::MOVSD: {
4613 // The index 0 always comes from the first element of the second source,
4614 // this is why MOVSS and MOVSD are used in the first place. The other
4615 // elements come from the other positions of the first source vector
4616 Mask.push_back(NumElems);
4617 for (unsigned i = 1; i != NumElems; ++i) {
4622 case X86ISD::VPERM2X128:
4623 ImmN = N->getOperand(N->getNumOperands()-1);
4624 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4625 if (Mask.empty()) return false;
4627 case X86ISD::MOVDDUP:
4628 case X86ISD::MOVLHPD:
4629 case X86ISD::MOVLPD:
4630 case X86ISD::MOVLPS:
4631 case X86ISD::MOVSHDUP:
4632 case X86ISD::MOVSLDUP:
4633 case X86ISD::PALIGN:
4634 // Not yet implemented
4636 default: llvm_unreachable("unknown target shuffle node");
4642 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4643 /// element of the result of the vector shuffle.
4644 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4647 return SDValue(); // Limit search depth.
4649 SDValue V = SDValue(N, 0);
4650 EVT VT = V.getValueType();
4651 unsigned Opcode = V.getOpcode();
4653 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4654 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4655 int Elt = SV->getMaskElt(Index);
4658 return DAG.getUNDEF(VT.getVectorElementType());
4660 unsigned NumElems = VT.getVectorNumElements();
4661 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4662 : SV->getOperand(1);
4663 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4666 // Recurse into target specific vector shuffles to find scalars.
4667 if (isTargetShuffle(Opcode)) {
4668 MVT ShufVT = V.getValueType().getSimpleVT();
4669 unsigned NumElems = ShufVT.getVectorNumElements();
4670 SmallVector<int, 16> ShuffleMask;
4673 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4676 int Elt = ShuffleMask[Index];
4678 return DAG.getUNDEF(ShufVT.getVectorElementType());
4680 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4682 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4686 // Actual nodes that may contain scalar elements
4687 if (Opcode == ISD::BITCAST) {
4688 V = V.getOperand(0);
4689 EVT SrcVT = V.getValueType();
4690 unsigned NumElems = VT.getVectorNumElements();
4692 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4696 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4697 return (Index == 0) ? V.getOperand(0)
4698 : DAG.getUNDEF(VT.getVectorElementType());
4700 if (V.getOpcode() == ISD::BUILD_VECTOR)
4701 return V.getOperand(Index);
4706 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4707 /// shuffle operation which come from a consecutively from a zero. The
4708 /// search can start in two different directions, from left or right.
4710 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4711 bool ZerosFromLeft, SelectionDAG &DAG) {
4713 for (i = 0; i != NumElems; ++i) {
4714 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4715 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4716 if (!(Elt.getNode() &&
4717 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4724 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4725 /// correspond consecutively to elements from one of the vector operands,
4726 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4728 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4729 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4730 unsigned NumElems, unsigned &OpNum) {
4731 bool SeenV1 = false;
4732 bool SeenV2 = false;
4734 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4735 int Idx = SVOp->getMaskElt(i);
4736 // Ignore undef indicies
4740 if (Idx < (int)NumElems)
4745 // Only accept consecutive elements from the same vector
4746 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4750 OpNum = SeenV1 ? 0 : 1;
4754 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4755 /// logical left shift of a vector.
4756 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4757 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4758 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4759 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4760 false /* check zeros from right */, DAG);
4766 // Considering the elements in the mask that are not consecutive zeros,
4767 // check if they consecutively come from only one of the source vectors.
4769 // V1 = {X, A, B, C} 0
4771 // vector_shuffle V1, V2 <1, 2, 3, X>
4773 if (!isShuffleMaskConsecutive(SVOp,
4774 0, // Mask Start Index
4775 NumElems-NumZeros, // Mask End Index(exclusive)
4776 NumZeros, // Where to start looking in the src vector
4777 NumElems, // Number of elements in vector
4778 OpSrc)) // Which source operand ?
4783 ShVal = SVOp->getOperand(OpSrc);
4787 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4788 /// logical left shift of a vector.
4789 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4790 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4791 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4792 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4793 true /* check zeros from left */, DAG);
4799 // Considering the elements in the mask that are not consecutive zeros,
4800 // check if they consecutively come from only one of the source vectors.
4802 // 0 { A, B, X, X } = V2
4804 // vector_shuffle V1, V2 <X, X, 4, 5>
4806 if (!isShuffleMaskConsecutive(SVOp,
4807 NumZeros, // Mask Start Index
4808 NumElems, // Mask End Index(exclusive)
4809 0, // Where to start looking in the src vector
4810 NumElems, // Number of elements in vector
4811 OpSrc)) // Which source operand ?
4816 ShVal = SVOp->getOperand(OpSrc);
4820 /// isVectorShift - Returns true if the shuffle can be implemented as a
4821 /// logical left or right shift of a vector.
4822 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4823 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4824 // Although the logic below support any bitwidth size, there are no
4825 // shift instructions which handle more than 128-bit vectors.
4826 if (!SVOp->getValueType(0).is128BitVector())
4829 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4830 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4836 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4838 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4839 unsigned NumNonZero, unsigned NumZero,
4841 const X86Subtarget* Subtarget,
4842 const TargetLowering &TLI) {
4846 DebugLoc dl = Op.getDebugLoc();
4849 for (unsigned i = 0; i < 16; ++i) {
4850 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4851 if (ThisIsNonZero && First) {
4853 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4855 V = DAG.getUNDEF(MVT::v8i16);
4860 SDValue ThisElt(0, 0), LastElt(0, 0);
4861 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4862 if (LastIsNonZero) {
4863 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4864 MVT::i16, Op.getOperand(i-1));
4866 if (ThisIsNonZero) {
4867 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4868 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4869 ThisElt, DAG.getConstant(8, MVT::i8));
4871 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4875 if (ThisElt.getNode())
4876 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4877 DAG.getIntPtrConstant(i/2));
4881 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4884 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4886 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4887 unsigned NumNonZero, unsigned NumZero,
4889 const X86Subtarget* Subtarget,
4890 const TargetLowering &TLI) {
4894 DebugLoc dl = Op.getDebugLoc();
4897 for (unsigned i = 0; i < 8; ++i) {
4898 bool isNonZero = (NonZeros & (1 << i)) != 0;
4902 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4904 V = DAG.getUNDEF(MVT::v8i16);
4907 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4908 MVT::v8i16, V, Op.getOperand(i),
4909 DAG.getIntPtrConstant(i));
4916 /// getVShift - Return a vector logical shift node.
4918 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4919 unsigned NumBits, SelectionDAG &DAG,
4920 const TargetLowering &TLI, DebugLoc dl) {
4921 assert(VT.is128BitVector() && "Unknown type for VShift");
4922 EVT ShVT = MVT::v2i64;
4923 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4924 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4925 return DAG.getNode(ISD::BITCAST, dl, VT,
4926 DAG.getNode(Opc, dl, ShVT, SrcOp,
4927 DAG.getConstant(NumBits,
4928 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4932 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4933 SelectionDAG &DAG) const {
4935 // Check if the scalar load can be widened into a vector load. And if
4936 // the address is "base + cst" see if the cst can be "absorbed" into
4937 // the shuffle mask.
4938 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4939 SDValue Ptr = LD->getBasePtr();
4940 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4942 EVT PVT = LD->getValueType(0);
4943 if (PVT != MVT::i32 && PVT != MVT::f32)
4948 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4949 FI = FINode->getIndex();
4951 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4952 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4953 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4954 Offset = Ptr.getConstantOperandVal(1);
4955 Ptr = Ptr.getOperand(0);
4960 // FIXME: 256-bit vector instructions don't require a strict alignment,
4961 // improve this code to support it better.
4962 unsigned RequiredAlign = VT.getSizeInBits()/8;
4963 SDValue Chain = LD->getChain();
4964 // Make sure the stack object alignment is at least 16 or 32.
4965 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4966 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4967 if (MFI->isFixedObjectIndex(FI)) {
4968 // Can't change the alignment. FIXME: It's possible to compute
4969 // the exact stack offset and reference FI + adjust offset instead.
4970 // If someone *really* cares about this. That's the way to implement it.
4973 MFI->setObjectAlignment(FI, RequiredAlign);
4977 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4978 // Ptr + (Offset & ~15).
4981 if ((Offset % RequiredAlign) & 3)
4983 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4985 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4986 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4988 int EltNo = (Offset - StartOffset) >> 2;
4989 unsigned NumElems = VT.getVectorNumElements();
4991 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4992 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4993 LD->getPointerInfo().getWithOffset(StartOffset),
4994 false, false, false, 0);
4996 SmallVector<int, 8> Mask;
4997 for (unsigned i = 0; i != NumElems; ++i)
4998 Mask.push_back(EltNo);
5000 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5006 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5007 /// vector of type 'VT', see if the elements can be replaced by a single large
5008 /// load which has the same value as a build_vector whose operands are 'elts'.
5010 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5012 /// FIXME: we'd also like to handle the case where the last elements are zero
5013 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5014 /// There's even a handy isZeroNode for that purpose.
5015 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5016 DebugLoc &DL, SelectionDAG &DAG) {
5017 EVT EltVT = VT.getVectorElementType();
5018 unsigned NumElems = Elts.size();
5020 LoadSDNode *LDBase = NULL;
5021 unsigned LastLoadedElt = -1U;
5023 // For each element in the initializer, see if we've found a load or an undef.
5024 // If we don't find an initial load element, or later load elements are
5025 // non-consecutive, bail out.
5026 for (unsigned i = 0; i < NumElems; ++i) {
5027 SDValue Elt = Elts[i];
5029 if (!Elt.getNode() ||
5030 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5033 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5035 LDBase = cast<LoadSDNode>(Elt.getNode());
5039 if (Elt.getOpcode() == ISD::UNDEF)
5042 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5043 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5048 // If we have found an entire vector of loads and undefs, then return a large
5049 // load of the entire vector width starting at the base pointer. If we found
5050 // consecutive loads for the low half, generate a vzext_load node.
5051 if (LastLoadedElt == NumElems - 1) {
5052 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5053 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5054 LDBase->getPointerInfo(),
5055 LDBase->isVolatile(), LDBase->isNonTemporal(),
5056 LDBase->isInvariant(), 0);
5057 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5058 LDBase->getPointerInfo(),
5059 LDBase->isVolatile(), LDBase->isNonTemporal(),
5060 LDBase->isInvariant(), LDBase->getAlignment());
5062 if (NumElems == 4 && LastLoadedElt == 1 &&
5063 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5064 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5065 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5067 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5068 LDBase->getPointerInfo(),
5069 LDBase->getAlignment(),
5070 false/*isVolatile*/, true/*ReadMem*/,
5073 // Make sure the newly-created LOAD is in the same position as LDBase in
5074 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5075 // update uses of LDBase's output chain to use the TokenFactor.
5076 if (LDBase->hasAnyUseOfValue(1)) {
5077 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5078 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5079 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5080 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5081 SDValue(ResNode.getNode(), 1));
5084 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5089 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5090 /// to generate a splat value for the following cases:
5091 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5092 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5093 /// a scalar load, or a constant.
5094 /// The VBROADCAST node is returned when a pattern is found,
5095 /// or SDValue() otherwise.
5097 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5098 if (!Subtarget->hasFp256())
5101 EVT VT = Op.getValueType();
5102 DebugLoc dl = Op.getDebugLoc();
5104 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5105 "Unsupported vector type for broadcast.");
5110 switch (Op.getOpcode()) {
5112 // Unknown pattern found.
5115 case ISD::BUILD_VECTOR: {
5116 // The BUILD_VECTOR node must be a splat.
5117 if (!isSplatVector(Op.getNode()))
5120 Ld = Op.getOperand(0);
5121 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5122 Ld.getOpcode() == ISD::ConstantFP);
5124 // The suspected load node has several users. Make sure that all
5125 // of its users are from the BUILD_VECTOR node.
5126 // Constants may have multiple users.
5127 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5132 case ISD::VECTOR_SHUFFLE: {
5133 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5135 // Shuffles must have a splat mask where the first element is
5137 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5140 SDValue Sc = Op.getOperand(0);
5141 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5142 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5144 if (!Subtarget->hasInt256())
5147 // Use the register form of the broadcast instruction available on AVX2.
5148 if (VT.is256BitVector())
5149 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5150 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5153 Ld = Sc.getOperand(0);
5154 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5155 Ld.getOpcode() == ISD::ConstantFP);
5157 // The scalar_to_vector node and the suspected
5158 // load node must have exactly one user.
5159 // Constants may have multiple users.
5160 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5166 bool Is256 = VT.is256BitVector();
5168 // Handle the broadcasting a single constant scalar from the constant pool
5169 // into a vector. On Sandybridge it is still better to load a constant vector
5170 // from the constant pool and not to broadcast it from a scalar.
5171 if (ConstSplatVal && Subtarget->hasInt256()) {
5172 EVT CVT = Ld.getValueType();
5173 assert(!CVT.isVector() && "Must not broadcast a vector type");
5174 unsigned ScalarSize = CVT.getSizeInBits();
5176 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5177 const Constant *C = 0;
5178 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5179 C = CI->getConstantIntValue();
5180 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5181 C = CF->getConstantFPValue();
5183 assert(C && "Invalid constant type");
5185 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5186 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5187 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5188 MachinePointerInfo::getConstantPool(),
5189 false, false, false, Alignment);
5191 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5195 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5196 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5198 // Handle AVX2 in-register broadcasts.
5199 if (!IsLoad && Subtarget->hasInt256() &&
5200 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5201 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5203 // The scalar source must be a normal load.
5207 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5208 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5210 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5211 // double since there is no vbroadcastsd xmm
5212 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5213 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5214 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5217 // Unsupported broadcast.
5222 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5223 EVT VT = Op.getValueType();
5225 // Skip if insert_vec_elt is not supported.
5226 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5229 DebugLoc DL = Op.getDebugLoc();
5230 unsigned NumElems = Op.getNumOperands();
5234 SmallVector<unsigned, 4> InsertIndices;
5235 SmallVector<int, 8> Mask(NumElems, -1);
5237 for (unsigned i = 0; i != NumElems; ++i) {
5238 unsigned Opc = Op.getOperand(i).getOpcode();
5240 if (Opc == ISD::UNDEF)
5243 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5244 // Quit if more than 1 elements need inserting.
5245 if (InsertIndices.size() > 1)
5248 InsertIndices.push_back(i);
5252 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5253 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5255 // Quit if extracted from vector of different type.
5256 if (ExtractedFromVec.getValueType() != VT)
5259 // Quit if non-constant index.
5260 if (!isa<ConstantSDNode>(ExtIdx))
5263 if (VecIn1.getNode() == 0)
5264 VecIn1 = ExtractedFromVec;
5265 else if (VecIn1 != ExtractedFromVec) {
5266 if (VecIn2.getNode() == 0)
5267 VecIn2 = ExtractedFromVec;
5268 else if (VecIn2 != ExtractedFromVec)
5269 // Quit if more than 2 vectors to shuffle
5273 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5275 if (ExtractedFromVec == VecIn1)
5277 else if (ExtractedFromVec == VecIn2)
5278 Mask[i] = Idx + NumElems;
5281 if (VecIn1.getNode() == 0)
5284 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5285 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5286 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5287 unsigned Idx = InsertIndices[i];
5288 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5289 DAG.getIntPtrConstant(Idx));
5296 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5297 DebugLoc dl = Op.getDebugLoc();
5299 EVT VT = Op.getValueType();
5300 EVT ExtVT = VT.getVectorElementType();
5301 unsigned NumElems = Op.getNumOperands();
5303 // Vectors containing all zeros can be matched by pxor and xorps later
5304 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5305 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5306 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5307 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5310 return getZeroVector(VT, Subtarget, DAG, dl);
5313 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5314 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5315 // vpcmpeqd on 256-bit vectors.
5316 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5317 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5320 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5323 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5324 if (Broadcast.getNode())
5327 unsigned EVTBits = ExtVT.getSizeInBits();
5329 unsigned NumZero = 0;
5330 unsigned NumNonZero = 0;
5331 unsigned NonZeros = 0;
5332 bool IsAllConstants = true;
5333 SmallSet<SDValue, 8> Values;
5334 for (unsigned i = 0; i < NumElems; ++i) {
5335 SDValue Elt = Op.getOperand(i);
5336 if (Elt.getOpcode() == ISD::UNDEF)
5339 if (Elt.getOpcode() != ISD::Constant &&
5340 Elt.getOpcode() != ISD::ConstantFP)
5341 IsAllConstants = false;
5342 if (X86::isZeroNode(Elt))
5345 NonZeros |= (1 << i);
5350 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5351 if (NumNonZero == 0)
5352 return DAG.getUNDEF(VT);
5354 // Special case for single non-zero, non-undef, element.
5355 if (NumNonZero == 1) {
5356 unsigned Idx = CountTrailingZeros_32(NonZeros);
5357 SDValue Item = Op.getOperand(Idx);
5359 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5360 // the value are obviously zero, truncate the value to i32 and do the
5361 // insertion that way. Only do this if the value is non-constant or if the
5362 // value is a constant being inserted into element 0. It is cheaper to do
5363 // a constant pool load than it is to do a movd + shuffle.
5364 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5365 (!IsAllConstants || Idx == 0)) {
5366 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5368 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5369 EVT VecVT = MVT::v4i32;
5370 unsigned VecElts = 4;
5372 // Truncate the value (which may itself be a constant) to i32, and
5373 // convert it to a vector with movd (S2V+shuffle to zero extend).
5374 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5375 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5376 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5378 // Now we have our 32-bit value zero extended in the low element of
5379 // a vector. If Idx != 0, swizzle it into place.
5381 SmallVector<int, 4> Mask;
5382 Mask.push_back(Idx);
5383 for (unsigned i = 1; i != VecElts; ++i)
5385 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5388 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5392 // If we have a constant or non-constant insertion into the low element of
5393 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5394 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5395 // depending on what the source datatype is.
5398 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5400 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5401 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5402 if (VT.is256BitVector()) {
5403 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5404 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5405 Item, DAG.getIntPtrConstant(0));
5407 assert(VT.is128BitVector() && "Expected an SSE value type!");
5408 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5409 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5410 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5413 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5414 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5415 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5416 if (VT.is256BitVector()) {
5417 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5418 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5420 assert(VT.is128BitVector() && "Expected an SSE value type!");
5421 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5423 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5427 // Is it a vector logical left shift?
5428 if (NumElems == 2 && Idx == 1 &&
5429 X86::isZeroNode(Op.getOperand(0)) &&
5430 !X86::isZeroNode(Op.getOperand(1))) {
5431 unsigned NumBits = VT.getSizeInBits();
5432 return getVShift(true, VT,
5433 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5434 VT, Op.getOperand(1)),
5435 NumBits/2, DAG, *this, dl);
5438 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5441 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5442 // is a non-constant being inserted into an element other than the low one,
5443 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5444 // movd/movss) to move this into the low element, then shuffle it into
5446 if (EVTBits == 32) {
5447 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5449 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5450 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5451 SmallVector<int, 8> MaskVec;
5452 for (unsigned i = 0; i != NumElems; ++i)
5453 MaskVec.push_back(i == Idx ? 0 : 1);
5454 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5458 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5459 if (Values.size() == 1) {
5460 if (EVTBits == 32) {
5461 // Instead of a shuffle like this:
5462 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5463 // Check if it's possible to issue this instead.
5464 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5465 unsigned Idx = CountTrailingZeros_32(NonZeros);
5466 SDValue Item = Op.getOperand(Idx);
5467 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5468 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5473 // A vector full of immediates; various special cases are already
5474 // handled, so this is best done with a single constant-pool load.
5478 // For AVX-length vectors, build the individual 128-bit pieces and use
5479 // shuffles to put them in place.
5480 if (VT.is256BitVector()) {
5481 SmallVector<SDValue, 32> V;
5482 for (unsigned i = 0; i != NumElems; ++i)
5483 V.push_back(Op.getOperand(i));
5485 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5487 // Build both the lower and upper subvector.
5488 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5489 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5492 // Recreate the wider vector with the lower and upper part.
5493 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5496 // Let legalizer expand 2-wide build_vectors.
5497 if (EVTBits == 64) {
5498 if (NumNonZero == 1) {
5499 // One half is zero or undef.
5500 unsigned Idx = CountTrailingZeros_32(NonZeros);
5501 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5502 Op.getOperand(Idx));
5503 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5508 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5509 if (EVTBits == 8 && NumElems == 16) {
5510 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5512 if (V.getNode()) return V;
5515 if (EVTBits == 16 && NumElems == 8) {
5516 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5518 if (V.getNode()) return V;
5521 // If element VT is == 32 bits, turn it into a number of shuffles.
5522 SmallVector<SDValue, 8> V(NumElems);
5523 if (NumElems == 4 && NumZero > 0) {
5524 for (unsigned i = 0; i < 4; ++i) {
5525 bool isZero = !(NonZeros & (1 << i));
5527 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5529 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5532 for (unsigned i = 0; i < 2; ++i) {
5533 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5536 V[i] = V[i*2]; // Must be a zero vector.
5539 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5542 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5545 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5550 bool Reverse1 = (NonZeros & 0x3) == 2;
5551 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5555 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5556 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5558 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5561 if (Values.size() > 1 && VT.is128BitVector()) {
5562 // Check for a build vector of consecutive loads.
5563 for (unsigned i = 0; i < NumElems; ++i)
5564 V[i] = Op.getOperand(i);
5566 // Check for elements which are consecutive loads.
5567 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5571 // Check for a build vector from mostly shuffle plus few inserting.
5572 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5576 // For SSE 4.1, use insertps to put the high elements into the low element.
5577 if (getSubtarget()->hasSSE41()) {
5579 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5580 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5582 Result = DAG.getUNDEF(VT);
5584 for (unsigned i = 1; i < NumElems; ++i) {
5585 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5586 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5587 Op.getOperand(i), DAG.getIntPtrConstant(i));
5592 // Otherwise, expand into a number of unpckl*, start by extending each of
5593 // our (non-undef) elements to the full vector width with the element in the
5594 // bottom slot of the vector (which generates no code for SSE).
5595 for (unsigned i = 0; i < NumElems; ++i) {
5596 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5597 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5599 V[i] = DAG.getUNDEF(VT);
5602 // Next, we iteratively mix elements, e.g. for v4f32:
5603 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5604 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5605 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5606 unsigned EltStride = NumElems >> 1;
5607 while (EltStride != 0) {
5608 for (unsigned i = 0; i < EltStride; ++i) {
5609 // If V[i+EltStride] is undef and this is the first round of mixing,
5610 // then it is safe to just drop this shuffle: V[i] is already in the
5611 // right place, the one element (since it's the first round) being
5612 // inserted as undef can be dropped. This isn't safe for successive
5613 // rounds because they will permute elements within both vectors.
5614 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5615 EltStride == NumElems/2)
5618 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5627 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5628 // to create 256-bit vectors from two other 128-bit ones.
5629 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5630 DebugLoc dl = Op.getDebugLoc();
5631 EVT ResVT = Op.getValueType();
5633 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5635 SDValue V1 = Op.getOperand(0);
5636 SDValue V2 = Op.getOperand(1);
5637 unsigned NumElems = ResVT.getVectorNumElements();
5639 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5642 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5643 assert(Op.getNumOperands() == 2);
5645 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5646 // from two other 128-bit ones.
5647 return LowerAVXCONCAT_VECTORS(Op, DAG);
5650 // Try to lower a shuffle node into a simple blend instruction.
5652 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5653 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5654 SDValue V1 = SVOp->getOperand(0);
5655 SDValue V2 = SVOp->getOperand(1);
5656 DebugLoc dl = SVOp->getDebugLoc();
5657 EVT VT = SVOp->getValueType(0);
5658 EVT EltVT = VT.getVectorElementType();
5659 unsigned NumElems = VT.getVectorNumElements();
5661 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5663 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5666 // Check the mask for BLEND and build the value.
5667 unsigned MaskValue = 0;
5668 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5669 unsigned NumLanes = (NumElems-1)/8 + 1;
5670 unsigned NumElemsInLane = NumElems / NumLanes;
5672 // Blend for v16i16 should be symetric for the both lanes.
5673 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5675 int SndLaneEltIdx = (NumLanes == 2) ?
5676 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5677 int EltIdx = SVOp->getMaskElt(i);
5679 if ((EltIdx == -1 || EltIdx == (int)i) &&
5680 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5683 if (((unsigned)EltIdx == (i + NumElems)) &&
5684 (SndLaneEltIdx == -1 ||
5685 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5686 MaskValue |= (1<<i);
5691 // Convert i32 vectors to floating point if it is not AVX2.
5692 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5694 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5695 BlendVT = EVT::getVectorVT(*DAG.getContext(),
5696 EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5698 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5699 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5702 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5703 DAG.getConstant(MaskValue, MVT::i32));
5704 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5707 // v8i16 shuffles - Prefer shuffles in the following order:
5708 // 1. [all] pshuflw, pshufhw, optional move
5709 // 2. [ssse3] 1 x pshufb
5710 // 3. [ssse3] 2 x pshufb + 1 x por
5711 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5713 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5714 SelectionDAG &DAG) {
5715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5716 SDValue V1 = SVOp->getOperand(0);
5717 SDValue V2 = SVOp->getOperand(1);
5718 DebugLoc dl = SVOp->getDebugLoc();
5719 SmallVector<int, 8> MaskVals;
5721 // Determine if more than 1 of the words in each of the low and high quadwords
5722 // of the result come from the same quadword of one of the two inputs. Undef
5723 // mask values count as coming from any quadword, for better codegen.
5724 unsigned LoQuad[] = { 0, 0, 0, 0 };
5725 unsigned HiQuad[] = { 0, 0, 0, 0 };
5726 std::bitset<4> InputQuads;
5727 for (unsigned i = 0; i < 8; ++i) {
5728 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5729 int EltIdx = SVOp->getMaskElt(i);
5730 MaskVals.push_back(EltIdx);
5739 InputQuads.set(EltIdx / 4);
5742 int BestLoQuad = -1;
5743 unsigned MaxQuad = 1;
5744 for (unsigned i = 0; i < 4; ++i) {
5745 if (LoQuad[i] > MaxQuad) {
5747 MaxQuad = LoQuad[i];
5751 int BestHiQuad = -1;
5753 for (unsigned i = 0; i < 4; ++i) {
5754 if (HiQuad[i] > MaxQuad) {
5756 MaxQuad = HiQuad[i];
5760 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5761 // of the two input vectors, shuffle them into one input vector so only a
5762 // single pshufb instruction is necessary. If There are more than 2 input
5763 // quads, disable the next transformation since it does not help SSSE3.
5764 bool V1Used = InputQuads[0] || InputQuads[1];
5765 bool V2Used = InputQuads[2] || InputQuads[3];
5766 if (Subtarget->hasSSSE3()) {
5767 if (InputQuads.count() == 2 && V1Used && V2Used) {
5768 BestLoQuad = InputQuads[0] ? 0 : 1;
5769 BestHiQuad = InputQuads[2] ? 2 : 3;
5771 if (InputQuads.count() > 2) {
5777 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5778 // the shuffle mask. If a quad is scored as -1, that means that it contains
5779 // words from all 4 input quadwords.
5781 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5783 BestLoQuad < 0 ? 0 : BestLoQuad,
5784 BestHiQuad < 0 ? 1 : BestHiQuad
5786 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5787 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5788 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5789 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5791 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5792 // source words for the shuffle, to aid later transformations.
5793 bool AllWordsInNewV = true;
5794 bool InOrder[2] = { true, true };
5795 for (unsigned i = 0; i != 8; ++i) {
5796 int idx = MaskVals[i];
5798 InOrder[i/4] = false;
5799 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5801 AllWordsInNewV = false;
5805 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5806 if (AllWordsInNewV) {
5807 for (int i = 0; i != 8; ++i) {
5808 int idx = MaskVals[i];
5811 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5812 if ((idx != i) && idx < 4)
5814 if ((idx != i) && idx > 3)
5823 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5824 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5825 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5826 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5827 unsigned TargetMask = 0;
5828 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5829 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5830 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5831 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5832 getShufflePSHUFLWImmediate(SVOp);
5833 V1 = NewV.getOperand(0);
5834 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5838 // If we have SSSE3, and all words of the result are from 1 input vector,
5839 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5840 // is present, fall back to case 4.
5841 if (Subtarget->hasSSSE3()) {
5842 SmallVector<SDValue,16> pshufbMask;
5844 // If we have elements from both input vectors, set the high bit of the
5845 // shuffle mask element to zero out elements that come from V2 in the V1
5846 // mask, and elements that come from V1 in the V2 mask, so that the two
5847 // results can be OR'd together.
5848 bool TwoInputs = V1Used && V2Used;
5849 for (unsigned i = 0; i != 8; ++i) {
5850 int EltIdx = MaskVals[i] * 2;
5851 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5852 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5853 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5854 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5856 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5857 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5858 DAG.getNode(ISD::BUILD_VECTOR, dl,
5859 MVT::v16i8, &pshufbMask[0], 16));
5861 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5863 // Calculate the shuffle mask for the second input, shuffle it, and
5864 // OR it with the first shuffled input.
5866 for (unsigned i = 0; i != 8; ++i) {
5867 int EltIdx = MaskVals[i] * 2;
5868 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5869 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5870 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5871 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5873 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5874 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5875 DAG.getNode(ISD::BUILD_VECTOR, dl,
5876 MVT::v16i8, &pshufbMask[0], 16));
5877 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5878 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5881 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5882 // and update MaskVals with new element order.
5883 std::bitset<8> InOrder;
5884 if (BestLoQuad >= 0) {
5885 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5886 for (int i = 0; i != 4; ++i) {
5887 int idx = MaskVals[i];
5890 } else if ((idx / 4) == BestLoQuad) {
5895 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5898 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5899 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5900 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5902 getShufflePSHUFLWImmediate(SVOp), DAG);
5906 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5907 // and update MaskVals with the new element order.
5908 if (BestHiQuad >= 0) {
5909 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5910 for (unsigned i = 4; i != 8; ++i) {
5911 int idx = MaskVals[i];
5914 } else if ((idx / 4) == BestHiQuad) {
5915 MaskV[i] = (idx & 3) + 4;
5919 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5922 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5923 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5924 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5926 getShufflePSHUFHWImmediate(SVOp), DAG);
5930 // In case BestHi & BestLo were both -1, which means each quadword has a word
5931 // from each of the four input quadwords, calculate the InOrder bitvector now
5932 // before falling through to the insert/extract cleanup.
5933 if (BestLoQuad == -1 && BestHiQuad == -1) {
5935 for (int i = 0; i != 8; ++i)
5936 if (MaskVals[i] < 0 || MaskVals[i] == i)
5940 // The other elements are put in the right place using pextrw and pinsrw.
5941 for (unsigned i = 0; i != 8; ++i) {
5944 int EltIdx = MaskVals[i];
5947 SDValue ExtOp = (EltIdx < 8) ?
5948 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5949 DAG.getIntPtrConstant(EltIdx)) :
5950 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5951 DAG.getIntPtrConstant(EltIdx - 8));
5952 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5953 DAG.getIntPtrConstant(i));
5958 // v16i8 shuffles - Prefer shuffles in the following order:
5959 // 1. [ssse3] 1 x pshufb
5960 // 2. [ssse3] 2 x pshufb + 1 x por
5961 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5963 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5965 const X86TargetLowering &TLI) {
5966 SDValue V1 = SVOp->getOperand(0);
5967 SDValue V2 = SVOp->getOperand(1);
5968 DebugLoc dl = SVOp->getDebugLoc();
5969 ArrayRef<int> MaskVals = SVOp->getMask();
5971 // If we have SSSE3, case 1 is generated when all result bytes come from
5972 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5973 // present, fall back to case 3.
5975 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5976 if (TLI.getSubtarget()->hasSSSE3()) {
5977 SmallVector<SDValue,16> pshufbMask;
5979 // If all result elements are from one input vector, then only translate
5980 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5982 // Otherwise, we have elements from both input vectors, and must zero out
5983 // elements that come from V2 in the first mask, and V1 in the second mask
5984 // so that we can OR them together.
5985 for (unsigned i = 0; i != 16; ++i) {
5986 int EltIdx = MaskVals[i];
5987 if (EltIdx < 0 || EltIdx >= 16)
5989 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5991 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5992 DAG.getNode(ISD::BUILD_VECTOR, dl,
5993 MVT::v16i8, &pshufbMask[0], 16));
5995 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5996 // the 2nd operand if it's undefined or zero.
5997 if (V2.getOpcode() == ISD::UNDEF ||
5998 ISD::isBuildVectorAllZeros(V2.getNode()))
6001 // Calculate the shuffle mask for the second input, shuffle it, and
6002 // OR it with the first shuffled input.
6004 for (unsigned i = 0; i != 16; ++i) {
6005 int EltIdx = MaskVals[i];
6006 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6007 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6009 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6010 DAG.getNode(ISD::BUILD_VECTOR, dl,
6011 MVT::v16i8, &pshufbMask[0], 16));
6012 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6015 // No SSSE3 - Calculate in place words and then fix all out of place words
6016 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6017 // the 16 different words that comprise the two doublequadword input vectors.
6018 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6019 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6021 for (int i = 0; i != 8; ++i) {
6022 int Elt0 = MaskVals[i*2];
6023 int Elt1 = MaskVals[i*2+1];
6025 // This word of the result is all undef, skip it.
6026 if (Elt0 < 0 && Elt1 < 0)
6029 // This word of the result is already in the correct place, skip it.
6030 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6033 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6034 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6037 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6038 // using a single extract together, load it and store it.
6039 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6040 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6041 DAG.getIntPtrConstant(Elt1 / 2));
6042 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6043 DAG.getIntPtrConstant(i));
6047 // If Elt1 is defined, extract it from the appropriate source. If the
6048 // source byte is not also odd, shift the extracted word left 8 bits
6049 // otherwise clear the bottom 8 bits if we need to do an or.
6051 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6052 DAG.getIntPtrConstant(Elt1 / 2));
6053 if ((Elt1 & 1) == 0)
6054 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6056 TLI.getShiftAmountTy(InsElt.getValueType())));
6058 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6059 DAG.getConstant(0xFF00, MVT::i16));
6061 // If Elt0 is defined, extract it from the appropriate source. If the
6062 // source byte is not also even, shift the extracted word right 8 bits. If
6063 // Elt1 was also defined, OR the extracted values together before
6064 // inserting them in the result.
6066 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6067 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6068 if ((Elt0 & 1) != 0)
6069 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6071 TLI.getShiftAmountTy(InsElt0.getValueType())));
6073 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6074 DAG.getConstant(0x00FF, MVT::i16));
6075 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6078 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6079 DAG.getIntPtrConstant(i));
6081 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6084 // v32i8 shuffles - Translate to VPSHUFB if possible.
6086 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6087 const X86Subtarget *Subtarget,
6088 SelectionDAG &DAG) {
6089 EVT VT = SVOp->getValueType(0);
6090 SDValue V1 = SVOp->getOperand(0);
6091 SDValue V2 = SVOp->getOperand(1);
6092 DebugLoc dl = SVOp->getDebugLoc();
6093 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6095 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6096 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6097 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6099 // VPSHUFB may be generated if
6100 // (1) one of input vector is undefined or zeroinitializer.
6101 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6102 // And (2) the mask indexes don't cross the 128-bit lane.
6103 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6104 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6107 if (V1IsAllZero && !V2IsAllZero) {
6108 CommuteVectorShuffleMask(MaskVals, 32);
6111 SmallVector<SDValue, 32> pshufbMask;
6112 for (unsigned i = 0; i != 32; i++) {
6113 int EltIdx = MaskVals[i];
6114 if (EltIdx < 0 || EltIdx >= 32)
6117 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6118 // Cross lane is not allowed.
6122 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6124 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6125 DAG.getNode(ISD::BUILD_VECTOR, dl,
6126 MVT::v32i8, &pshufbMask[0], 32));
6129 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6130 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6131 /// done when every pair / quad of shuffle mask elements point to elements in
6132 /// the right sequence. e.g.
6133 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6135 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6136 SelectionDAG &DAG, DebugLoc dl) {
6137 MVT VT = SVOp->getValueType(0).getSimpleVT();
6138 unsigned NumElems = VT.getVectorNumElements();
6141 switch (VT.SimpleTy) {
6142 default: llvm_unreachable("Unexpected!");
6143 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6144 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6145 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6146 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6147 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6148 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6151 SmallVector<int, 8> MaskVec;
6152 for (unsigned i = 0; i != NumElems; i += Scale) {
6154 for (unsigned j = 0; j != Scale; ++j) {
6155 int EltIdx = SVOp->getMaskElt(i+j);
6159 StartIdx = (EltIdx / Scale);
6160 if (EltIdx != (int)(StartIdx*Scale + j))
6163 MaskVec.push_back(StartIdx);
6166 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6167 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6168 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6171 /// getVZextMovL - Return a zero-extending vector move low node.
6173 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6174 SDValue SrcOp, SelectionDAG &DAG,
6175 const X86Subtarget *Subtarget, DebugLoc dl) {
6176 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6177 LoadSDNode *LD = NULL;
6178 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6179 LD = dyn_cast<LoadSDNode>(SrcOp);
6181 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6183 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6184 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6185 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6186 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6187 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6189 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6190 return DAG.getNode(ISD::BITCAST, dl, VT,
6191 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6192 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6200 return DAG.getNode(ISD::BITCAST, dl, VT,
6201 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6202 DAG.getNode(ISD::BITCAST, dl,
6206 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6207 /// which could not be matched by any known target speficic shuffle
6209 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6211 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6212 if (NewOp.getNode())
6215 EVT VT = SVOp->getValueType(0);
6217 unsigned NumElems = VT.getVectorNumElements();
6218 unsigned NumLaneElems = NumElems / 2;
6220 DebugLoc dl = SVOp->getDebugLoc();
6221 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6222 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6225 SmallVector<int, 16> Mask;
6226 for (unsigned l = 0; l < 2; ++l) {
6227 // Build a shuffle mask for the output, discovering on the fly which
6228 // input vectors to use as shuffle operands (recorded in InputUsed).
6229 // If building a suitable shuffle vector proves too hard, then bail
6230 // out with UseBuildVector set.
6231 bool UseBuildVector = false;
6232 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6233 unsigned LaneStart = l * NumLaneElems;
6234 for (unsigned i = 0; i != NumLaneElems; ++i) {
6235 // The mask element. This indexes into the input.
6236 int Idx = SVOp->getMaskElt(i+LaneStart);
6238 // the mask element does not index into any input vector.
6243 // The input vector this mask element indexes into.
6244 int Input = Idx / NumLaneElems;
6246 // Turn the index into an offset from the start of the input vector.
6247 Idx -= Input * NumLaneElems;
6249 // Find or create a shuffle vector operand to hold this input.
6251 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6252 if (InputUsed[OpNo] == Input)
6253 // This input vector is already an operand.
6255 if (InputUsed[OpNo] < 0) {
6256 // Create a new operand for this input vector.
6257 InputUsed[OpNo] = Input;
6262 if (OpNo >= array_lengthof(InputUsed)) {
6263 // More than two input vectors used! Give up on trying to create a
6264 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6265 UseBuildVector = true;
6269 // Add the mask index for the new shuffle vector.
6270 Mask.push_back(Idx + OpNo * NumLaneElems);
6273 if (UseBuildVector) {
6274 SmallVector<SDValue, 16> SVOps;
6275 for (unsigned i = 0; i != NumLaneElems; ++i) {
6276 // The mask element. This indexes into the input.
6277 int Idx = SVOp->getMaskElt(i+LaneStart);
6279 SVOps.push_back(DAG.getUNDEF(EltVT));
6283 // The input vector this mask element indexes into.
6284 int Input = Idx / NumElems;
6286 // Turn the index into an offset from the start of the input vector.
6287 Idx -= Input * NumElems;
6289 // Extract the vector element by hand.
6290 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6291 SVOp->getOperand(Input),
6292 DAG.getIntPtrConstant(Idx)));
6295 // Construct the output using a BUILD_VECTOR.
6296 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6298 } else if (InputUsed[0] < 0) {
6299 // No input vectors were used! The result is undefined.
6300 Output[l] = DAG.getUNDEF(NVT);
6302 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6303 (InputUsed[0] % 2) * NumLaneElems,
6305 // If only one input was used, use an undefined vector for the other.
6306 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6307 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6308 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6309 // At least one input vector was used. Create a new shuffle vector.
6310 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6316 // Concatenate the result back
6317 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6320 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6321 /// 4 elements, and match them with several different shuffle types.
6323 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6324 SDValue V1 = SVOp->getOperand(0);
6325 SDValue V2 = SVOp->getOperand(1);
6326 DebugLoc dl = SVOp->getDebugLoc();
6327 EVT VT = SVOp->getValueType(0);
6329 assert(VT.is128BitVector() && "Unsupported vector size");
6331 std::pair<int, int> Locs[4];
6332 int Mask1[] = { -1, -1, -1, -1 };
6333 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6337 for (unsigned i = 0; i != 4; ++i) {
6338 int Idx = PermMask[i];
6340 Locs[i] = std::make_pair(-1, -1);
6342 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6344 Locs[i] = std::make_pair(0, NumLo);
6348 Locs[i] = std::make_pair(1, NumHi);
6350 Mask1[2+NumHi] = Idx;
6356 if (NumLo <= 2 && NumHi <= 2) {
6357 // If no more than two elements come from either vector. This can be
6358 // implemented with two shuffles. First shuffle gather the elements.
6359 // The second shuffle, which takes the first shuffle as both of its
6360 // vector operands, put the elements into the right order.
6361 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6363 int Mask2[] = { -1, -1, -1, -1 };
6365 for (unsigned i = 0; i != 4; ++i)
6366 if (Locs[i].first != -1) {
6367 unsigned Idx = (i < 2) ? 0 : 4;
6368 Idx += Locs[i].first * 2 + Locs[i].second;
6372 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6375 if (NumLo == 3 || NumHi == 3) {
6376 // Otherwise, we must have three elements from one vector, call it X, and
6377 // one element from the other, call it Y. First, use a shufps to build an
6378 // intermediate vector with the one element from Y and the element from X
6379 // that will be in the same half in the final destination (the indexes don't
6380 // matter). Then, use a shufps to build the final vector, taking the half
6381 // containing the element from Y from the intermediate, and the other half
6384 // Normalize it so the 3 elements come from V1.
6385 CommuteVectorShuffleMask(PermMask, 4);
6389 // Find the element from V2.
6391 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6392 int Val = PermMask[HiIndex];
6399 Mask1[0] = PermMask[HiIndex];
6401 Mask1[2] = PermMask[HiIndex^1];
6403 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6406 Mask1[0] = PermMask[0];
6407 Mask1[1] = PermMask[1];
6408 Mask1[2] = HiIndex & 1 ? 6 : 4;
6409 Mask1[3] = HiIndex & 1 ? 4 : 6;
6410 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6413 Mask1[0] = HiIndex & 1 ? 2 : 0;
6414 Mask1[1] = HiIndex & 1 ? 0 : 2;
6415 Mask1[2] = PermMask[2];
6416 Mask1[3] = PermMask[3];
6421 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6424 // Break it into (shuffle shuffle_hi, shuffle_lo).
6425 int LoMask[] = { -1, -1, -1, -1 };
6426 int HiMask[] = { -1, -1, -1, -1 };
6428 int *MaskPtr = LoMask;
6429 unsigned MaskIdx = 0;
6432 for (unsigned i = 0; i != 4; ++i) {
6439 int Idx = PermMask[i];
6441 Locs[i] = std::make_pair(-1, -1);
6442 } else if (Idx < 4) {
6443 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6444 MaskPtr[LoIdx] = Idx;
6447 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6448 MaskPtr[HiIdx] = Idx;
6453 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6454 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6455 int MaskOps[] = { -1, -1, -1, -1 };
6456 for (unsigned i = 0; i != 4; ++i)
6457 if (Locs[i].first != -1)
6458 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6459 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6462 static bool MayFoldVectorLoad(SDValue V) {
6463 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6464 V = V.getOperand(0);
6466 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6467 V = V.getOperand(0);
6468 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6469 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6470 // BUILD_VECTOR (load), undef
6471 V = V.getOperand(0);
6473 return MayFoldLoad(V);
6477 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6478 EVT VT = Op.getValueType();
6480 // Canonizalize to v2f64.
6481 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6482 return DAG.getNode(ISD::BITCAST, dl, VT,
6483 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6488 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6490 SDValue V1 = Op.getOperand(0);
6491 SDValue V2 = Op.getOperand(1);
6492 EVT VT = Op.getValueType();
6494 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6496 if (HasSSE2 && VT == MVT::v2f64)
6497 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6499 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6500 return DAG.getNode(ISD::BITCAST, dl, VT,
6501 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6502 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6503 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6507 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6508 SDValue V1 = Op.getOperand(0);
6509 SDValue V2 = Op.getOperand(1);
6510 EVT VT = Op.getValueType();
6512 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6513 "unsupported shuffle type");
6515 if (V2.getOpcode() == ISD::UNDEF)
6519 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6523 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6524 SDValue V1 = Op.getOperand(0);
6525 SDValue V2 = Op.getOperand(1);
6526 EVT VT = Op.getValueType();
6527 unsigned NumElems = VT.getVectorNumElements();
6529 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6530 // operand of these instructions is only memory, so check if there's a
6531 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6533 bool CanFoldLoad = false;
6535 // Trivial case, when V2 comes from a load.
6536 if (MayFoldVectorLoad(V2))
6539 // When V1 is a load, it can be folded later into a store in isel, example:
6540 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6542 // (MOVLPSmr addr:$src1, VR128:$src2)
6543 // So, recognize this potential and also use MOVLPS or MOVLPD
6544 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6547 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6549 if (HasSSE2 && NumElems == 2)
6550 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6553 // If we don't care about the second element, proceed to use movss.
6554 if (SVOp->getMaskElt(1) != -1)
6555 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6558 // movl and movlp will both match v2i64, but v2i64 is never matched by
6559 // movl earlier because we make it strict to avoid messing with the movlp load
6560 // folding logic (see the code above getMOVLP call). Match it here then,
6561 // this is horrible, but will stay like this until we move all shuffle
6562 // matching to x86 specific nodes. Note that for the 1st condition all
6563 // types are matched with movsd.
6565 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6566 // as to remove this logic from here, as much as possible
6567 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6568 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6569 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6572 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6574 // Invert the operand order and use SHUFPS to match it.
6575 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6576 getShuffleSHUFImmediate(SVOp), DAG);
6579 // Reduce a vector shuffle to zext.
6581 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6582 // PMOVZX is only available from SSE41.
6583 if (!Subtarget->hasSSE41())
6586 EVT VT = Op.getValueType();
6588 // Only AVX2 support 256-bit vector integer extending.
6589 if (!Subtarget->hasInt256() && VT.is256BitVector())
6592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6593 DebugLoc DL = Op.getDebugLoc();
6594 SDValue V1 = Op.getOperand(0);
6595 SDValue V2 = Op.getOperand(1);
6596 unsigned NumElems = VT.getVectorNumElements();
6598 // Extending is an unary operation and the element type of the source vector
6599 // won't be equal to or larger than i64.
6600 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6601 VT.getVectorElementType() == MVT::i64)
6604 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6605 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6606 while ((1U << Shift) < NumElems) {
6607 if (SVOp->getMaskElt(1U << Shift) == 1)
6610 // The maximal ratio is 8, i.e. from i8 to i64.
6615 // Check the shuffle mask.
6616 unsigned Mask = (1U << Shift) - 1;
6617 for (unsigned i = 0; i != NumElems; ++i) {
6618 int EltIdx = SVOp->getMaskElt(i);
6619 if ((i & Mask) != 0 && EltIdx != -1)
6621 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6625 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6626 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6627 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6629 if (!isTypeLegal(NVT))
6632 // Simplify the operand as it's prepared to be fed into shuffle.
6633 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6634 if (V1.getOpcode() == ISD::BITCAST &&
6635 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6636 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6638 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6639 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6640 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6641 ConstantSDNode *CIdx =
6642 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6643 // If it's foldable, i.e. normal load with single use, we will let code
6644 // selection to fold it. Otherwise, we will short the conversion sequence.
6645 if (CIdx && CIdx->getZExtValue() == 0 &&
6646 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6647 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6650 return DAG.getNode(ISD::BITCAST, DL, VT,
6651 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6655 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6656 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6657 EVT VT = Op.getValueType();
6658 DebugLoc dl = Op.getDebugLoc();
6659 SDValue V1 = Op.getOperand(0);
6660 SDValue V2 = Op.getOperand(1);
6662 if (isZeroShuffle(SVOp))
6663 return getZeroVector(VT, Subtarget, DAG, dl);
6665 // Handle splat operations
6666 if (SVOp->isSplat()) {
6667 unsigned NumElem = VT.getVectorNumElements();
6668 int Size = VT.getSizeInBits();
6670 // Use vbroadcast whenever the splat comes from a foldable load
6671 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6672 if (Broadcast.getNode())
6675 // Handle splats by matching through known shuffle masks
6676 if ((Size == 128 && NumElem <= 4) ||
6677 (Size == 256 && NumElem <= 8))
6680 // All remaning splats are promoted to target supported vector shuffles.
6681 return PromoteSplat(SVOp, DAG);
6684 // Check integer expanding shuffles.
6685 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6686 if (NewOp.getNode())
6689 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6691 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6692 VT == MVT::v16i16 || VT == MVT::v32i8) {
6693 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694 if (NewOp.getNode())
6695 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6696 } else if ((VT == MVT::v4i32 ||
6697 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6698 // FIXME: Figure out a cleaner way to do this.
6699 // Try to make use of movq to zero out the top part.
6700 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6701 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6702 if (NewOp.getNode()) {
6703 EVT NewVT = NewOp.getValueType();
6704 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6705 NewVT, true, false))
6706 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6707 DAG, Subtarget, dl);
6709 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6710 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6711 if (NewOp.getNode()) {
6712 EVT NewVT = NewOp.getValueType();
6713 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6714 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6715 DAG, Subtarget, dl);
6723 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6724 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6725 SDValue V1 = Op.getOperand(0);
6726 SDValue V2 = Op.getOperand(1);
6727 EVT VT = Op.getValueType();
6728 DebugLoc dl = Op.getDebugLoc();
6729 unsigned NumElems = VT.getVectorNumElements();
6730 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6731 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6732 bool V1IsSplat = false;
6733 bool V2IsSplat = false;
6734 bool HasSSE2 = Subtarget->hasSSE2();
6735 bool HasFp256 = Subtarget->hasFp256();
6736 bool HasInt256 = Subtarget->hasInt256();
6737 MachineFunction &MF = DAG.getMachineFunction();
6738 bool OptForSize = MF.getFunction()->getFnAttributes().
6739 hasAttribute(Attribute::OptimizeForSize);
6741 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6743 if (V1IsUndef && V2IsUndef)
6744 return DAG.getUNDEF(VT);
6746 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6748 // Vector shuffle lowering takes 3 steps:
6750 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6751 // narrowing and commutation of operands should be handled.
6752 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6754 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6755 // so the shuffle can be broken into other shuffles and the legalizer can
6756 // try the lowering again.
6758 // The general idea is that no vector_shuffle operation should be left to
6759 // be matched during isel, all of them must be converted to a target specific
6762 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6763 // narrowing and commutation of operands should be handled. The actual code
6764 // doesn't include all of those, work in progress...
6765 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6766 if (NewOp.getNode())
6769 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6771 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6772 // unpckh_undef). Only use pshufd if speed is more important than size.
6773 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6774 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6775 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6776 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6778 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6779 V2IsUndef && MayFoldVectorLoad(V1))
6780 return getMOVDDup(Op, dl, V1, DAG);
6782 if (isMOVHLPS_v_undef_Mask(M, VT))
6783 return getMOVHighToLow(Op, dl, DAG);
6785 // Use to match splats
6786 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6787 (VT == MVT::v2f64 || VT == MVT::v2i64))
6788 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6790 if (isPSHUFDMask(M, VT)) {
6791 // The actual implementation will match the mask in the if above and then
6792 // during isel it can match several different instructions, not only pshufd
6793 // as its name says, sad but true, emulate the behavior for now...
6794 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6795 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6797 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6799 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6800 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6802 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6803 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6806 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6810 // Check if this can be converted into a logical shift.
6811 bool isLeft = false;
6814 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6815 if (isShift && ShVal.hasOneUse()) {
6816 // If the shifted value has multiple uses, it may be cheaper to use
6817 // v_set0 + movlhps or movhlps, etc.
6818 EVT EltVT = VT.getVectorElementType();
6819 ShAmt *= EltVT.getSizeInBits();
6820 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6823 if (isMOVLMask(M, VT)) {
6824 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6825 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6826 if (!isMOVLPMask(M, VT)) {
6827 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6828 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6830 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6831 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6835 // FIXME: fold these into legal mask.
6836 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6837 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6839 if (isMOVHLPSMask(M, VT))
6840 return getMOVHighToLow(Op, dl, DAG);
6842 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6843 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6845 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6846 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6848 if (isMOVLPMask(M, VT))
6849 return getMOVLP(Op, dl, DAG, HasSSE2);
6851 if (ShouldXformToMOVHLPS(M, VT) ||
6852 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6853 return CommuteVectorShuffle(SVOp, DAG);
6856 // No better options. Use a vshldq / vsrldq.
6857 EVT EltVT = VT.getVectorElementType();
6858 ShAmt *= EltVT.getSizeInBits();
6859 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6862 bool Commuted = false;
6863 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6864 // 1,1,1,1 -> v8i16 though.
6865 V1IsSplat = isSplatVector(V1.getNode());
6866 V2IsSplat = isSplatVector(V2.getNode());
6868 // Canonicalize the splat or undef, if present, to be on the RHS.
6869 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6870 CommuteVectorShuffleMask(M, NumElems);
6872 std::swap(V1IsSplat, V2IsSplat);
6876 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6877 // Shuffling low element of v1 into undef, just return v1.
6880 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6881 // the instruction selector will not match, so get a canonical MOVL with
6882 // swapped operands to undo the commute.
6883 return getMOVL(DAG, dl, VT, V2, V1);
6886 if (isUNPCKLMask(M, VT, HasInt256))
6887 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6889 if (isUNPCKHMask(M, VT, HasInt256))
6890 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6893 // Normalize mask so all entries that point to V2 points to its first
6894 // element then try to match unpck{h|l} again. If match, return a
6895 // new vector_shuffle with the corrected mask.p
6896 SmallVector<int, 8> NewMask(M.begin(), M.end());
6897 NormalizeMask(NewMask, NumElems);
6898 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6899 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6900 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6901 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6905 // Commute is back and try unpck* again.
6906 // FIXME: this seems wrong.
6907 CommuteVectorShuffleMask(M, NumElems);
6909 std::swap(V1IsSplat, V2IsSplat);
6912 if (isUNPCKLMask(M, VT, HasInt256))
6913 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6915 if (isUNPCKHMask(M, VT, HasInt256))
6916 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6919 // Normalize the node to match x86 shuffle ops if needed
6920 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6921 return CommuteVectorShuffle(SVOp, DAG);
6923 // The checks below are all present in isShuffleMaskLegal, but they are
6924 // inlined here right now to enable us to directly emit target specific
6925 // nodes, and remove one by one until they don't return Op anymore.
6927 if (isPALIGNRMask(M, VT, Subtarget))
6928 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6929 getShufflePALIGNRImmediate(SVOp),
6932 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6933 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6934 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6935 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6938 if (isPSHUFHWMask(M, VT, HasInt256))
6939 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6940 getShufflePSHUFHWImmediate(SVOp),
6943 if (isPSHUFLWMask(M, VT, HasInt256))
6944 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6945 getShufflePSHUFLWImmediate(SVOp),
6948 if (isSHUFPMask(M, VT, HasFp256))
6949 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6950 getShuffleSHUFImmediate(SVOp), DAG);
6952 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6953 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6954 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6955 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6957 //===--------------------------------------------------------------------===//
6958 // Generate target specific nodes for 128 or 256-bit shuffles only
6959 // supported in the AVX instruction set.
6962 // Handle VMOVDDUPY permutations
6963 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6964 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6966 // Handle VPERMILPS/D* permutations
6967 if (isVPERMILPMask(M, VT, HasFp256)) {
6968 if (HasInt256 && VT == MVT::v8i32)
6969 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6970 getShuffleSHUFImmediate(SVOp), DAG);
6971 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6972 getShuffleSHUFImmediate(SVOp), DAG);
6975 // Handle VPERM2F128/VPERM2I128 permutations
6976 if (isVPERM2X128Mask(M, VT, HasFp256))
6977 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6978 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6980 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6981 if (BlendOp.getNode())
6984 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6985 SmallVector<SDValue, 8> permclMask;
6986 for (unsigned i = 0; i != 8; ++i) {
6987 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6989 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6991 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6992 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6993 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6996 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6997 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6998 getShuffleCLImmediate(SVOp), DAG);
7000 //===--------------------------------------------------------------------===//
7001 // Since no target specific shuffle was selected for this generic one,
7002 // lower it into other known shuffles. FIXME: this isn't true yet, but
7003 // this is the plan.
7006 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7007 if (VT == MVT::v8i16) {
7008 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7009 if (NewOp.getNode())
7013 if (VT == MVT::v16i8) {
7014 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7015 if (NewOp.getNode())
7019 if (VT == MVT::v32i8) {
7020 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7021 if (NewOp.getNode())
7025 // Handle all 128-bit wide vectors with 4 elements, and match them with
7026 // several different shuffle types.
7027 if (NumElems == 4 && VT.is128BitVector())
7028 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7030 // Handle general 256-bit shuffles
7031 if (VT.is256BitVector())
7032 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7038 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7039 SelectionDAG &DAG) const {
7040 EVT VT = Op.getValueType();
7041 DebugLoc dl = Op.getDebugLoc();
7043 if (!Op.getOperand(0).getValueType().is128BitVector())
7046 if (VT.getSizeInBits() == 8) {
7047 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7048 Op.getOperand(0), Op.getOperand(1));
7049 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7050 DAG.getValueType(VT));
7051 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7054 if (VT.getSizeInBits() == 16) {
7055 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7056 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7058 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7059 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7060 DAG.getNode(ISD::BITCAST, dl,
7064 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7065 Op.getOperand(0), Op.getOperand(1));
7066 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7067 DAG.getValueType(VT));
7068 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7071 if (VT == MVT::f32) {
7072 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7073 // the result back to FR32 register. It's only worth matching if the
7074 // result has a single use which is a store or a bitcast to i32. And in
7075 // the case of a store, it's not worth it if the index is a constant 0,
7076 // because a MOVSSmr can be used instead, which is smaller and faster.
7077 if (!Op.hasOneUse())
7079 SDNode *User = *Op.getNode()->use_begin();
7080 if ((User->getOpcode() != ISD::STORE ||
7081 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7082 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7083 (User->getOpcode() != ISD::BITCAST ||
7084 User->getValueType(0) != MVT::i32))
7086 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7087 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7090 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7093 if (VT == MVT::i32 || VT == MVT::i64) {
7094 // ExtractPS/pextrq works with constant index.
7095 if (isa<ConstantSDNode>(Op.getOperand(1)))
7102 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7103 SelectionDAG &DAG) const {
7104 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7107 SDValue Vec = Op.getOperand(0);
7108 EVT VecVT = Vec.getValueType();
7110 // If this is a 256-bit vector result, first extract the 128-bit vector and
7111 // then extract the element from the 128-bit vector.
7112 if (VecVT.is256BitVector()) {
7113 DebugLoc dl = Op.getNode()->getDebugLoc();
7114 unsigned NumElems = VecVT.getVectorNumElements();
7115 SDValue Idx = Op.getOperand(1);
7116 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7118 // Get the 128-bit vector.
7119 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7121 if (IdxVal >= NumElems/2)
7122 IdxVal -= NumElems/2;
7123 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7124 DAG.getConstant(IdxVal, MVT::i32));
7127 assert(VecVT.is128BitVector() && "Unexpected vector length");
7129 if (Subtarget->hasSSE41()) {
7130 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7135 EVT VT = Op.getValueType();
7136 DebugLoc dl = Op.getDebugLoc();
7137 // TODO: handle v16i8.
7138 if (VT.getSizeInBits() == 16) {
7139 SDValue Vec = Op.getOperand(0);
7140 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7142 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7143 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7144 DAG.getNode(ISD::BITCAST, dl,
7147 // Transform it so it match pextrw which produces a 32-bit result.
7148 EVT EltVT = MVT::i32;
7149 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7150 Op.getOperand(0), Op.getOperand(1));
7151 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7152 DAG.getValueType(VT));
7153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7156 if (VT.getSizeInBits() == 32) {
7157 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7161 // SHUFPS the element to the lowest double word, then movss.
7162 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7163 EVT VVT = Op.getOperand(0).getValueType();
7164 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7165 DAG.getUNDEF(VVT), Mask);
7166 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7167 DAG.getIntPtrConstant(0));
7170 if (VT.getSizeInBits() == 64) {
7171 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7172 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7173 // to match extract_elt for f64.
7174 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7178 // UNPCKHPD the element to the lowest double word, then movsd.
7179 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7180 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7181 int Mask[2] = { 1, -1 };
7182 EVT VVT = Op.getOperand(0).getValueType();
7183 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7184 DAG.getUNDEF(VVT), Mask);
7185 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7186 DAG.getIntPtrConstant(0));
7193 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7194 SelectionDAG &DAG) const {
7195 EVT VT = Op.getValueType();
7196 EVT EltVT = VT.getVectorElementType();
7197 DebugLoc dl = Op.getDebugLoc();
7199 SDValue N0 = Op.getOperand(0);
7200 SDValue N1 = Op.getOperand(1);
7201 SDValue N2 = Op.getOperand(2);
7203 if (!VT.is128BitVector())
7206 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7207 isa<ConstantSDNode>(N2)) {
7209 if (VT == MVT::v8i16)
7210 Opc = X86ISD::PINSRW;
7211 else if (VT == MVT::v16i8)
7212 Opc = X86ISD::PINSRB;
7214 Opc = X86ISD::PINSRB;
7216 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7218 if (N1.getValueType() != MVT::i32)
7219 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7220 if (N2.getValueType() != MVT::i32)
7221 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7222 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7225 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7226 // Bits [7:6] of the constant are the source select. This will always be
7227 // zero here. The DAG Combiner may combine an extract_elt index into these
7228 // bits. For example (insert (extract, 3), 2) could be matched by putting
7229 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7230 // Bits [5:4] of the constant are the destination select. This is the
7231 // value of the incoming immediate.
7232 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7233 // combine either bitwise AND or insert of float 0.0 to set these bits.
7234 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7235 // Create this as a scalar to vector..
7236 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7237 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7240 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7241 // PINSR* works with constant index.
7248 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7249 EVT VT = Op.getValueType();
7250 EVT EltVT = VT.getVectorElementType();
7252 DebugLoc dl = Op.getDebugLoc();
7253 SDValue N0 = Op.getOperand(0);
7254 SDValue N1 = Op.getOperand(1);
7255 SDValue N2 = Op.getOperand(2);
7257 // If this is a 256-bit vector result, first extract the 128-bit vector,
7258 // insert the element into the extracted half and then place it back.
7259 if (VT.is256BitVector()) {
7260 if (!isa<ConstantSDNode>(N2))
7263 // Get the desired 128-bit vector half.
7264 unsigned NumElems = VT.getVectorNumElements();
7265 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7266 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7268 // Insert the element into the desired half.
7269 bool Upper = IdxVal >= NumElems/2;
7270 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7271 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7273 // Insert the changed part back to the 256-bit vector
7274 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7277 if (Subtarget->hasSSE41())
7278 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7280 if (EltVT == MVT::i8)
7283 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7284 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7285 // as its second argument.
7286 if (N1.getValueType() != MVT::i32)
7287 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7288 if (N2.getValueType() != MVT::i32)
7289 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7290 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7295 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7296 LLVMContext *Context = DAG.getContext();
7297 DebugLoc dl = Op.getDebugLoc();
7298 EVT OpVT = Op.getValueType();
7300 // If this is a 256-bit vector result, first insert into a 128-bit
7301 // vector and then insert into the 256-bit vector.
7302 if (!OpVT.is128BitVector()) {
7303 // Insert into a 128-bit vector.
7304 EVT VT128 = EVT::getVectorVT(*Context,
7305 OpVT.getVectorElementType(),
7306 OpVT.getVectorNumElements() / 2);
7308 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7310 // Insert the 128-bit vector.
7311 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7314 if (OpVT == MVT::v1i64 &&
7315 Op.getOperand(0).getValueType() == MVT::i64)
7316 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7318 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7319 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7320 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7321 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7324 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7325 // a simple subregister reference or explicit instructions to grab
7326 // upper bits of a vector.
7327 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7328 SelectionDAG &DAG) {
7329 if (Subtarget->hasFp256()) {
7330 DebugLoc dl = Op.getNode()->getDebugLoc();
7331 SDValue Vec = Op.getNode()->getOperand(0);
7332 SDValue Idx = Op.getNode()->getOperand(1);
7334 if (Op.getNode()->getValueType(0).is128BitVector() &&
7335 Vec.getNode()->getValueType(0).is256BitVector() &&
7336 isa<ConstantSDNode>(Idx)) {
7337 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7338 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7344 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7345 // simple superregister reference or explicit instructions to insert
7346 // the upper bits of a vector.
7347 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7348 SelectionDAG &DAG) {
7349 if (Subtarget->hasFp256()) {
7350 DebugLoc dl = Op.getNode()->getDebugLoc();
7351 SDValue Vec = Op.getNode()->getOperand(0);
7352 SDValue SubVec = Op.getNode()->getOperand(1);
7353 SDValue Idx = Op.getNode()->getOperand(2);
7355 if (Op.getNode()->getValueType(0).is256BitVector() &&
7356 SubVec.getNode()->getValueType(0).is128BitVector() &&
7357 isa<ConstantSDNode>(Idx)) {
7358 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7359 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7365 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7366 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7367 // one of the above mentioned nodes. It has to be wrapped because otherwise
7368 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7369 // be used to form addressing mode. These wrapped nodes will be selected
7372 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7373 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7375 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7377 unsigned char OpFlag = 0;
7378 unsigned WrapperKind = X86ISD::Wrapper;
7379 CodeModel::Model M = getTargetMachine().getCodeModel();
7381 if (Subtarget->isPICStyleRIPRel() &&
7382 (M == CodeModel::Small || M == CodeModel::Kernel))
7383 WrapperKind = X86ISD::WrapperRIP;
7384 else if (Subtarget->isPICStyleGOT())
7385 OpFlag = X86II::MO_GOTOFF;
7386 else if (Subtarget->isPICStyleStubPIC())
7387 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7389 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7391 CP->getOffset(), OpFlag);
7392 DebugLoc DL = CP->getDebugLoc();
7393 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7394 // With PIC, the address is actually $g + Offset.
7396 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7397 DAG.getNode(X86ISD::GlobalBaseReg,
7398 DebugLoc(), getPointerTy()),
7405 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7406 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7408 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7410 unsigned char OpFlag = 0;
7411 unsigned WrapperKind = X86ISD::Wrapper;
7412 CodeModel::Model M = getTargetMachine().getCodeModel();
7414 if (Subtarget->isPICStyleRIPRel() &&
7415 (M == CodeModel::Small || M == CodeModel::Kernel))
7416 WrapperKind = X86ISD::WrapperRIP;
7417 else if (Subtarget->isPICStyleGOT())
7418 OpFlag = X86II::MO_GOTOFF;
7419 else if (Subtarget->isPICStyleStubPIC())
7420 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7422 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7424 DebugLoc DL = JT->getDebugLoc();
7425 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7427 // With PIC, the address is actually $g + Offset.
7429 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7430 DAG.getNode(X86ISD::GlobalBaseReg,
7431 DebugLoc(), getPointerTy()),
7438 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7439 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7441 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7443 unsigned char OpFlag = 0;
7444 unsigned WrapperKind = X86ISD::Wrapper;
7445 CodeModel::Model M = getTargetMachine().getCodeModel();
7447 if (Subtarget->isPICStyleRIPRel() &&
7448 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7449 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7450 OpFlag = X86II::MO_GOTPCREL;
7451 WrapperKind = X86ISD::WrapperRIP;
7452 } else if (Subtarget->isPICStyleGOT()) {
7453 OpFlag = X86II::MO_GOT;
7454 } else if (Subtarget->isPICStyleStubPIC()) {
7455 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7456 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7457 OpFlag = X86II::MO_DARWIN_NONLAZY;
7460 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7462 DebugLoc DL = Op.getDebugLoc();
7463 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7465 // With PIC, the address is actually $g + Offset.
7466 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7467 !Subtarget->is64Bit()) {
7468 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7469 DAG.getNode(X86ISD::GlobalBaseReg,
7470 DebugLoc(), getPointerTy()),
7474 // For symbols that require a load from a stub to get the address, emit the
7476 if (isGlobalStubReference(OpFlag))
7477 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7478 MachinePointerInfo::getGOT(), false, false, false, 0);
7484 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7485 // Create the TargetBlockAddressAddress node.
7486 unsigned char OpFlags =
7487 Subtarget->ClassifyBlockAddressReference();
7488 CodeModel::Model M = getTargetMachine().getCodeModel();
7489 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7490 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7491 DebugLoc dl = Op.getDebugLoc();
7492 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7495 if (Subtarget->isPICStyleRIPRel() &&
7496 (M == CodeModel::Small || M == CodeModel::Kernel))
7497 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7499 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7501 // With PIC, the address is actually $g + Offset.
7502 if (isGlobalRelativeToPICBase(OpFlags)) {
7503 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7504 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7512 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7514 SelectionDAG &DAG) const {
7515 // Create the TargetGlobalAddress node, folding in the constant
7516 // offset if it is legal.
7517 unsigned char OpFlags =
7518 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7519 CodeModel::Model M = getTargetMachine().getCodeModel();
7521 if (OpFlags == X86II::MO_NO_FLAG &&
7522 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7523 // A direct static reference to a global.
7524 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7527 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7530 if (Subtarget->isPICStyleRIPRel() &&
7531 (M == CodeModel::Small || M == CodeModel::Kernel))
7532 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7534 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7536 // With PIC, the address is actually $g + Offset.
7537 if (isGlobalRelativeToPICBase(OpFlags)) {
7538 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7539 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7543 // For globals that require a load from a stub to get the address, emit the
7545 if (isGlobalStubReference(OpFlags))
7546 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7547 MachinePointerInfo::getGOT(), false, false, false, 0);
7549 // If there was a non-zero offset that we didn't fold, create an explicit
7552 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7553 DAG.getConstant(Offset, getPointerTy()));
7559 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7560 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7561 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7562 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7566 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7567 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7568 unsigned char OperandFlags, bool LocalDynamic = false) {
7569 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7570 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7571 DebugLoc dl = GA->getDebugLoc();
7572 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7573 GA->getValueType(0),
7577 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7581 SDValue Ops[] = { Chain, TGA, *InFlag };
7582 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7584 SDValue Ops[] = { Chain, TGA };
7585 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7588 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7589 MFI->setAdjustsStack(true);
7591 SDValue Flag = Chain.getValue(1);
7592 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7595 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7597 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7600 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7601 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7602 DAG.getNode(X86ISD::GlobalBaseReg,
7603 DebugLoc(), PtrVT), InFlag);
7604 InFlag = Chain.getValue(1);
7606 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7609 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7611 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7613 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7614 X86::RAX, X86II::MO_TLSGD);
7617 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7621 DebugLoc dl = GA->getDebugLoc();
7623 // Get the start address of the TLS block for this module.
7624 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7625 .getInfo<X86MachineFunctionInfo>();
7626 MFI->incNumLocalDynamicTLSAccesses();
7630 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7631 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7634 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7635 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7636 InFlag = Chain.getValue(1);
7637 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7638 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7641 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7645 unsigned char OperandFlags = X86II::MO_DTPOFF;
7646 unsigned WrapperKind = X86ISD::Wrapper;
7647 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7648 GA->getValueType(0),
7649 GA->getOffset(), OperandFlags);
7650 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7652 // Add x@dtpoff with the base.
7653 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7656 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7657 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7658 const EVT PtrVT, TLSModel::Model model,
7659 bool is64Bit, bool isPIC) {
7660 DebugLoc dl = GA->getDebugLoc();
7662 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7663 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7664 is64Bit ? 257 : 256));
7666 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7667 DAG.getIntPtrConstant(0),
7668 MachinePointerInfo(Ptr),
7669 false, false, false, 0);
7671 unsigned char OperandFlags = 0;
7672 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7674 unsigned WrapperKind = X86ISD::Wrapper;
7675 if (model == TLSModel::LocalExec) {
7676 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7677 } else if (model == TLSModel::InitialExec) {
7679 OperandFlags = X86II::MO_GOTTPOFF;
7680 WrapperKind = X86ISD::WrapperRIP;
7682 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7685 llvm_unreachable("Unexpected model");
7688 // emit "addl x@ntpoff,%eax" (local exec)
7689 // or "addl x@indntpoff,%eax" (initial exec)
7690 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7691 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7692 GA->getValueType(0),
7693 GA->getOffset(), OperandFlags);
7694 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7696 if (model == TLSModel::InitialExec) {
7697 if (isPIC && !is64Bit) {
7698 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7699 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7703 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7704 MachinePointerInfo::getGOT(), false, false, false,
7708 // The address of the thread local variable is the add of the thread
7709 // pointer with the offset of the variable.
7710 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7714 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7716 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7717 const GlobalValue *GV = GA->getGlobal();
7719 if (Subtarget->isTargetELF()) {
7720 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7723 case TLSModel::GeneralDynamic:
7724 if (Subtarget->is64Bit())
7725 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7726 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7727 case TLSModel::LocalDynamic:
7728 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7729 Subtarget->is64Bit());
7730 case TLSModel::InitialExec:
7731 case TLSModel::LocalExec:
7732 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7733 Subtarget->is64Bit(),
7734 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7736 llvm_unreachable("Unknown TLS model.");
7739 if (Subtarget->isTargetDarwin()) {
7740 // Darwin only has one model of TLS. Lower to that.
7741 unsigned char OpFlag = 0;
7742 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7743 X86ISD::WrapperRIP : X86ISD::Wrapper;
7745 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7747 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7748 !Subtarget->is64Bit();
7750 OpFlag = X86II::MO_TLVP_PIC_BASE;
7752 OpFlag = X86II::MO_TLVP;
7753 DebugLoc DL = Op.getDebugLoc();
7754 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7755 GA->getValueType(0),
7756 GA->getOffset(), OpFlag);
7757 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7759 // With PIC32, the address is actually $g + Offset.
7761 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7762 DAG.getNode(X86ISD::GlobalBaseReg,
7763 DebugLoc(), getPointerTy()),
7766 // Lowering the machine isd will make sure everything is in the right
7768 SDValue Chain = DAG.getEntryNode();
7769 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7770 SDValue Args[] = { Chain, Offset };
7771 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7773 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7774 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7775 MFI->setAdjustsStack(true);
7777 // And our return value (tls address) is in the standard call return value
7779 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7780 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7784 if (Subtarget->isTargetWindows()) {
7785 // Just use the implicit TLS architecture
7786 // Need to generate someting similar to:
7787 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7789 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7790 // mov rcx, qword [rdx+rcx*8]
7791 // mov eax, .tls$:tlsvar
7792 // [rax+rcx] contains the address
7793 // Windows 64bit: gs:0x58
7794 // Windows 32bit: fs:__tls_array
7796 // If GV is an alias then use the aliasee for determining
7797 // thread-localness.
7798 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7799 GV = GA->resolveAliasedGlobal(false);
7800 DebugLoc dl = GA->getDebugLoc();
7801 SDValue Chain = DAG.getEntryNode();
7803 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7804 // %gs:0x58 (64-bit).
7805 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7806 ? Type::getInt8PtrTy(*DAG.getContext(),
7808 : Type::getInt32PtrTy(*DAG.getContext(),
7811 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7812 Subtarget->is64Bit()
7813 ? DAG.getIntPtrConstant(0x58)
7814 : DAG.getExternalSymbol("_tls_array",
7816 MachinePointerInfo(Ptr),
7817 false, false, false, 0);
7819 // Load the _tls_index variable
7820 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7821 if (Subtarget->is64Bit())
7822 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7823 IDX, MachinePointerInfo(), MVT::i32,
7826 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7827 false, false, false, 0);
7829 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7831 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7833 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7834 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7835 false, false, false, 0);
7837 // Get the offset of start of .tls section
7838 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7839 GA->getValueType(0),
7840 GA->getOffset(), X86II::MO_SECREL);
7841 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7843 // The address of the thread local variable is the add of the thread
7844 // pointer with the offset of the variable.
7845 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7848 llvm_unreachable("TLS not implemented for this target.");
7851 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7852 /// and take a 2 x i32 value to shift plus a shift amount.
7853 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7854 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7855 EVT VT = Op.getValueType();
7856 unsigned VTBits = VT.getSizeInBits();
7857 DebugLoc dl = Op.getDebugLoc();
7858 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7859 SDValue ShOpLo = Op.getOperand(0);
7860 SDValue ShOpHi = Op.getOperand(1);
7861 SDValue ShAmt = Op.getOperand(2);
7862 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7863 DAG.getConstant(VTBits - 1, MVT::i8))
7864 : DAG.getConstant(0, VT);
7867 if (Op.getOpcode() == ISD::SHL_PARTS) {
7868 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7869 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7871 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7872 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7875 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7876 DAG.getConstant(VTBits, MVT::i8));
7877 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7878 AndNode, DAG.getConstant(0, MVT::i8));
7881 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7882 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7883 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7885 if (Op.getOpcode() == ISD::SHL_PARTS) {
7886 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7887 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7889 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7890 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7893 SDValue Ops[2] = { Lo, Hi };
7894 return DAG.getMergeValues(Ops, 2, dl);
7897 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7898 SelectionDAG &DAG) const {
7899 EVT SrcVT = Op.getOperand(0).getValueType();
7901 if (SrcVT.isVector())
7904 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7905 "Unknown SINT_TO_FP to lower!");
7907 // These are really Legal; return the operand so the caller accepts it as
7909 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7911 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7912 Subtarget->is64Bit()) {
7916 DebugLoc dl = Op.getDebugLoc();
7917 unsigned Size = SrcVT.getSizeInBits()/8;
7918 MachineFunction &MF = DAG.getMachineFunction();
7919 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7920 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7921 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7923 MachinePointerInfo::getFixedStack(SSFI),
7925 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7928 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7930 SelectionDAG &DAG) const {
7932 DebugLoc DL = Op.getDebugLoc();
7934 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7936 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7938 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7940 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7942 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7943 MachineMemOperand *MMO;
7945 int SSFI = FI->getIndex();
7947 DAG.getMachineFunction()
7948 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7949 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7951 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7952 StackSlot = StackSlot.getOperand(1);
7954 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7955 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7957 Tys, Ops, array_lengthof(Ops),
7961 Chain = Result.getValue(1);
7962 SDValue InFlag = Result.getValue(2);
7964 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7965 // shouldn't be necessary except that RFP cannot be live across
7966 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7967 MachineFunction &MF = DAG.getMachineFunction();
7968 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7969 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7970 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7971 Tys = DAG.getVTList(MVT::Other);
7973 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7975 MachineMemOperand *MMO =
7976 DAG.getMachineFunction()
7977 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7978 MachineMemOperand::MOStore, SSFISize, SSFISize);
7980 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7981 Ops, array_lengthof(Ops),
7982 Op.getValueType(), MMO);
7983 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7984 MachinePointerInfo::getFixedStack(SSFI),
7985 false, false, false, 0);
7991 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7992 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7993 SelectionDAG &DAG) const {
7994 // This algorithm is not obvious. Here it is what we're trying to output:
7997 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7998 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8002 pshufd $0x4e, %xmm0, %xmm1
8007 DebugLoc dl = Op.getDebugLoc();
8008 LLVMContext *Context = DAG.getContext();
8010 // Build some magic constants.
8011 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8012 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8013 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8015 SmallVector<Constant*,2> CV1;
8017 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8019 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8020 Constant *C1 = ConstantVector::get(CV1);
8021 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8023 // Load the 64-bit value into an XMM register.
8024 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8026 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8027 MachinePointerInfo::getConstantPool(),
8028 false, false, false, 16);
8029 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8030 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8033 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8034 MachinePointerInfo::getConstantPool(),
8035 false, false, false, 16);
8036 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8037 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8040 if (Subtarget->hasSSE3()) {
8041 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8042 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8044 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8045 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8047 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8048 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8053 DAG.getIntPtrConstant(0));
8056 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8057 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8058 SelectionDAG &DAG) const {
8059 DebugLoc dl = Op.getDebugLoc();
8060 // FP constant to bias correct the final result.
8061 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8064 // Load the 32-bit value into an XMM register.
8065 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8068 // Zero out the upper parts of the register.
8069 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8071 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8072 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8073 DAG.getIntPtrConstant(0));
8075 // Or the load with the bias.
8076 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8077 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8078 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8080 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8081 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8082 MVT::v2f64, Bias)));
8083 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8084 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8085 DAG.getIntPtrConstant(0));
8087 // Subtract the bias.
8088 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8090 // Handle final rounding.
8091 EVT DestVT = Op.getValueType();
8093 if (DestVT.bitsLT(MVT::f64))
8094 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8095 DAG.getIntPtrConstant(0));
8096 if (DestVT.bitsGT(MVT::f64))
8097 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8099 // Handle final rounding.
8103 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8104 SelectionDAG &DAG) const {
8105 SDValue N0 = Op.getOperand(0);
8106 EVT SVT = N0.getValueType();
8107 DebugLoc dl = Op.getDebugLoc();
8109 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8110 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8111 "Custom UINT_TO_FP is not supported!");
8113 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8114 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8115 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8118 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8119 SelectionDAG &DAG) const {
8120 SDValue N0 = Op.getOperand(0);
8121 DebugLoc dl = Op.getDebugLoc();
8123 if (Op.getValueType().isVector())
8124 return lowerUINT_TO_FP_vec(Op, DAG);
8126 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8127 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8128 // the optimization here.
8129 if (DAG.SignBitIsZero(N0))
8130 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8132 EVT SrcVT = N0.getValueType();
8133 EVT DstVT = Op.getValueType();
8134 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8135 return LowerUINT_TO_FP_i64(Op, DAG);
8136 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8137 return LowerUINT_TO_FP_i32(Op, DAG);
8138 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8141 // Make a 64-bit buffer, and use it to build an FILD.
8142 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8143 if (SrcVT == MVT::i32) {
8144 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8145 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8146 getPointerTy(), StackSlot, WordOff);
8147 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8148 StackSlot, MachinePointerInfo(),
8150 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8151 OffsetSlot, MachinePointerInfo(),
8153 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8157 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8158 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8159 StackSlot, MachinePointerInfo(),
8161 // For i64 source, we need to add the appropriate power of 2 if the input
8162 // was negative. This is the same as the optimization in
8163 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8164 // we must be careful to do the computation in x87 extended precision, not
8165 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8166 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8167 MachineMemOperand *MMO =
8168 DAG.getMachineFunction()
8169 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8170 MachineMemOperand::MOLoad, 8, 8);
8172 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8173 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8174 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8177 APInt FF(32, 0x5F800000ULL);
8179 // Check whether the sign bit is set.
8180 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8181 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8184 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8185 SDValue FudgePtr = DAG.getConstantPool(
8186 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8189 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8190 SDValue Zero = DAG.getIntPtrConstant(0);
8191 SDValue Four = DAG.getIntPtrConstant(4);
8192 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8194 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8196 // Load the value out, extending it from f32 to f80.
8197 // FIXME: Avoid the extend by constructing the right constant pool?
8198 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8199 FudgePtr, MachinePointerInfo::getConstantPool(),
8200 MVT::f32, false, false, 4);
8201 // Extend everything to 80 bits to force it to be done on x87.
8202 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8203 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8206 std::pair<SDValue,SDValue> X86TargetLowering::
8207 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8208 DebugLoc DL = Op.getDebugLoc();
8210 EVT DstTy = Op.getValueType();
8212 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8213 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8217 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8218 DstTy.getSimpleVT() >= MVT::i16 &&
8219 "Unknown FP_TO_INT to lower!");
8221 // These are really Legal.
8222 if (DstTy == MVT::i32 &&
8223 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8224 return std::make_pair(SDValue(), SDValue());
8225 if (Subtarget->is64Bit() &&
8226 DstTy == MVT::i64 &&
8227 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8228 return std::make_pair(SDValue(), SDValue());
8230 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8231 // stack slot, or into the FTOL runtime function.
8232 MachineFunction &MF = DAG.getMachineFunction();
8233 unsigned MemSize = DstTy.getSizeInBits()/8;
8234 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8235 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8238 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8239 Opc = X86ISD::WIN_FTOL;
8241 switch (DstTy.getSimpleVT().SimpleTy) {
8242 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8243 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8244 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8245 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8248 SDValue Chain = DAG.getEntryNode();
8249 SDValue Value = Op.getOperand(0);
8250 EVT TheVT = Op.getOperand(0).getValueType();
8251 // FIXME This causes a redundant load/store if the SSE-class value is already
8252 // in memory, such as if it is on the callstack.
8253 if (isScalarFPTypeInSSEReg(TheVT)) {
8254 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8255 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8256 MachinePointerInfo::getFixedStack(SSFI),
8258 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8260 Chain, StackSlot, DAG.getValueType(TheVT)
8263 MachineMemOperand *MMO =
8264 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8265 MachineMemOperand::MOLoad, MemSize, MemSize);
8266 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8268 Chain = Value.getValue(1);
8269 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8270 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8273 MachineMemOperand *MMO =
8274 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8275 MachineMemOperand::MOStore, MemSize, MemSize);
8277 if (Opc != X86ISD::WIN_FTOL) {
8278 // Build the FP_TO_INT*_IN_MEM
8279 SDValue Ops[] = { Chain, Value, StackSlot };
8280 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8281 Ops, 3, DstTy, MMO);
8282 return std::make_pair(FIST, StackSlot);
8284 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8285 DAG.getVTList(MVT::Other, MVT::Glue),
8287 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8288 MVT::i32, ftol.getValue(1));
8289 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8290 MVT::i32, eax.getValue(2));
8291 SDValue Ops[] = { eax, edx };
8292 SDValue pair = IsReplace
8293 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8294 : DAG.getMergeValues(Ops, 2, DL);
8295 return std::make_pair(pair, SDValue());
8299 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8300 const X86Subtarget *Subtarget) {
8301 EVT VT = Op->getValueType(0);
8302 SDValue In = Op->getOperand(0);
8303 EVT InVT = In.getValueType();
8304 DebugLoc dl = Op->getDebugLoc();
8306 // Optimize vectors in AVX mode:
8309 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8310 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8311 // Concat upper and lower parts.
8314 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8315 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8316 // Concat upper and lower parts.
8319 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8320 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8323 if (Subtarget->hasInt256())
8324 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8326 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8327 SDValue Undef = DAG.getUNDEF(InVT);
8328 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8329 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8330 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8332 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8333 VT.getVectorNumElements()/2);
8335 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8336 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8338 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8341 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8342 SelectionDAG &DAG) const {
8343 if (Subtarget->hasFp256()) {
8344 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8351 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8352 SelectionDAG &DAG) const {
8353 DebugLoc DL = Op.getDebugLoc();
8354 EVT VT = Op.getValueType();
8355 SDValue In = Op.getOperand(0);
8356 EVT SVT = In.getValueType();
8358 if (Subtarget->hasFp256()) {
8359 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8364 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8365 VT.getVectorNumElements() != SVT.getVectorNumElements())
8368 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8370 // AVX2 has better support of integer extending.
8371 if (Subtarget->hasInt256())
8372 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8374 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8375 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8376 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8377 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8378 DAG.getUNDEF(MVT::v8i16),
8381 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8384 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8385 DebugLoc DL = Op.getDebugLoc();
8386 EVT VT = Op.getValueType();
8387 SDValue In = Op.getOperand(0);
8388 EVT SVT = In.getValueType();
8390 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8391 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8392 if (Subtarget->hasInt256()) {
8393 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8394 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8395 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8397 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8398 DAG.getIntPtrConstant(0));
8401 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8402 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8403 DAG.getIntPtrConstant(0));
8404 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8405 DAG.getIntPtrConstant(2));
8407 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8408 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8411 static const int ShufMask1[] = {0, 2, 0, 0};
8412 SDValue Undef = DAG.getUNDEF(VT);
8413 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8414 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8416 // The MOVLHPS mask:
8417 static const int ShufMask2[] = {0, 1, 4, 5};
8418 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8421 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8422 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8423 if (Subtarget->hasInt256()) {
8424 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8426 SmallVector<SDValue,32> pshufbMask;
8427 for (unsigned i = 0; i < 2; ++i) {
8428 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8429 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8430 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8431 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8432 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8433 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8434 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8435 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8436 for (unsigned j = 0; j < 8; ++j)
8437 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8439 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8440 &pshufbMask[0], 32);
8441 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8442 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8444 static const int ShufMask[] = {0, 2, -1, -1};
8445 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8447 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8448 DAG.getIntPtrConstant(0));
8449 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8452 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8453 DAG.getIntPtrConstant(0));
8455 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8456 DAG.getIntPtrConstant(4));
8458 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8459 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8462 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8463 -1, -1, -1, -1, -1, -1, -1, -1};
8465 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8466 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8467 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8469 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8470 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8472 // The MOVLHPS Mask:
8473 static const int ShufMask2[] = {0, 1, 4, 5};
8474 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8475 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8478 // Handle truncation of V256 to V128 using shuffles.
8479 if (!VT.is128BitVector() || !SVT.is256BitVector())
8482 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8484 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8486 unsigned NumElems = VT.getVectorNumElements();
8487 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8490 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8491 // Prepare truncation shuffle mask
8492 for (unsigned i = 0; i != NumElems; ++i)
8494 SDValue V = DAG.getVectorShuffle(NVT, DL,
8495 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8496 DAG.getUNDEF(NVT), &MaskVec[0]);
8497 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8498 DAG.getIntPtrConstant(0));
8501 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8502 SelectionDAG &DAG) const {
8503 if (Op.getValueType().isVector()) {
8504 if (Op.getValueType() == MVT::v8i16)
8505 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8506 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8507 MVT::v8i32, Op.getOperand(0)));
8511 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8512 /*IsSigned=*/ true, /*IsReplace=*/ false);
8513 SDValue FIST = Vals.first, StackSlot = Vals.second;
8514 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8515 if (FIST.getNode() == 0) return Op;
8517 if (StackSlot.getNode())
8519 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8520 FIST, StackSlot, MachinePointerInfo(),
8521 false, false, false, 0);
8523 // The node is the result.
8527 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8528 SelectionDAG &DAG) const {
8529 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8530 /*IsSigned=*/ false, /*IsReplace=*/ false);
8531 SDValue FIST = Vals.first, StackSlot = Vals.second;
8532 assert(FIST.getNode() && "Unexpected failure");
8534 if (StackSlot.getNode())
8536 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8537 FIST, StackSlot, MachinePointerInfo(),
8538 false, false, false, 0);
8540 // The node is the result.
8544 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8545 SelectionDAG &DAG) const {
8546 DebugLoc DL = Op.getDebugLoc();
8547 EVT VT = Op.getValueType();
8548 SDValue In = Op.getOperand(0);
8549 EVT SVT = In.getValueType();
8551 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8553 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8554 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8555 In, DAG.getUNDEF(SVT)));
8558 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8559 LLVMContext *Context = DAG.getContext();
8560 DebugLoc dl = Op.getDebugLoc();
8561 EVT VT = Op.getValueType();
8563 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8564 if (VT.isVector()) {
8565 EltVT = VT.getVectorElementType();
8566 NumElts = VT.getVectorNumElements();
8569 if (EltVT == MVT::f64)
8570 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8572 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8573 C = ConstantVector::getSplat(NumElts, C);
8574 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8575 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8576 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8577 MachinePointerInfo::getConstantPool(),
8578 false, false, false, Alignment);
8579 if (VT.isVector()) {
8580 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8581 return DAG.getNode(ISD::BITCAST, dl, VT,
8582 DAG.getNode(ISD::AND, dl, ANDVT,
8583 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8585 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8587 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8590 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8591 LLVMContext *Context = DAG.getContext();
8592 DebugLoc dl = Op.getDebugLoc();
8593 EVT VT = Op.getValueType();
8595 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8596 if (VT.isVector()) {
8597 EltVT = VT.getVectorElementType();
8598 NumElts = VT.getVectorNumElements();
8601 if (EltVT == MVT::f64)
8602 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8604 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8605 C = ConstantVector::getSplat(NumElts, C);
8606 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8607 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8608 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8609 MachinePointerInfo::getConstantPool(),
8610 false, false, false, Alignment);
8611 if (VT.isVector()) {
8612 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8613 return DAG.getNode(ISD::BITCAST, dl, VT,
8614 DAG.getNode(ISD::XOR, dl, XORVT,
8615 DAG.getNode(ISD::BITCAST, dl, XORVT,
8617 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8620 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8623 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8624 LLVMContext *Context = DAG.getContext();
8625 SDValue Op0 = Op.getOperand(0);
8626 SDValue Op1 = Op.getOperand(1);
8627 DebugLoc dl = Op.getDebugLoc();
8628 EVT VT = Op.getValueType();
8629 EVT SrcVT = Op1.getValueType();
8631 // If second operand is smaller, extend it first.
8632 if (SrcVT.bitsLT(VT)) {
8633 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8636 // And if it is bigger, shrink it first.
8637 if (SrcVT.bitsGT(VT)) {
8638 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8642 // At this point the operands and the result should have the same
8643 // type, and that won't be f80 since that is not custom lowered.
8645 // First get the sign bit of second operand.
8646 SmallVector<Constant*,4> CV;
8647 if (SrcVT == MVT::f64) {
8648 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8649 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8651 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8652 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8653 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8654 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8656 Constant *C = ConstantVector::get(CV);
8657 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8658 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8659 MachinePointerInfo::getConstantPool(),
8660 false, false, false, 16);
8661 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8663 // Shift sign bit right or left if the two operands have different types.
8664 if (SrcVT.bitsGT(VT)) {
8665 // Op0 is MVT::f32, Op1 is MVT::f64.
8666 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8667 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8668 DAG.getConstant(32, MVT::i32));
8669 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8670 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8671 DAG.getIntPtrConstant(0));
8674 // Clear first operand sign bit.
8676 if (VT == MVT::f64) {
8677 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8678 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8680 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8681 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8682 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8683 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8685 C = ConstantVector::get(CV);
8686 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8687 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8688 MachinePointerInfo::getConstantPool(),
8689 false, false, false, 16);
8690 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8692 // Or the value with the sign bit.
8693 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8696 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8697 SDValue N0 = Op.getOperand(0);
8698 DebugLoc dl = Op.getDebugLoc();
8699 EVT VT = Op.getValueType();
8701 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8702 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8703 DAG.getConstant(1, VT));
8704 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8707 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8709 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8710 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8712 if (!Subtarget->hasSSE41())
8715 if (!Op->hasOneUse())
8718 SDNode *N = Op.getNode();
8719 DebugLoc DL = N->getDebugLoc();
8721 SmallVector<SDValue, 8> Opnds;
8722 DenseMap<SDValue, unsigned> VecInMap;
8723 EVT VT = MVT::Other;
8725 // Recognize a special case where a vector is casted into wide integer to
8727 Opnds.push_back(N->getOperand(0));
8728 Opnds.push_back(N->getOperand(1));
8730 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8731 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8732 // BFS traverse all OR'd operands.
8733 if (I->getOpcode() == ISD::OR) {
8734 Opnds.push_back(I->getOperand(0));
8735 Opnds.push_back(I->getOperand(1));
8736 // Re-evaluate the number of nodes to be traversed.
8737 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8741 // Quit if a non-EXTRACT_VECTOR_ELT
8742 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8745 // Quit if without a constant index.
8746 SDValue Idx = I->getOperand(1);
8747 if (!isa<ConstantSDNode>(Idx))
8750 SDValue ExtractedFromVec = I->getOperand(0);
8751 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8752 if (M == VecInMap.end()) {
8753 VT = ExtractedFromVec.getValueType();
8754 // Quit if not 128/256-bit vector.
8755 if (!VT.is128BitVector() && !VT.is256BitVector())
8757 // Quit if not the same type.
8758 if (VecInMap.begin() != VecInMap.end() &&
8759 VT != VecInMap.begin()->first.getValueType())
8761 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8763 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8766 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8767 "Not extracted from 128-/256-bit vector.");
8769 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8770 SmallVector<SDValue, 8> VecIns;
8772 for (DenseMap<SDValue, unsigned>::const_iterator
8773 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8774 // Quit if not all elements are used.
8775 if (I->second != FullMask)
8777 VecIns.push_back(I->first);
8780 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8782 // Cast all vectors into TestVT for PTEST.
8783 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8784 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8786 // If more than one full vectors are evaluated, OR them first before PTEST.
8787 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8788 // Each iteration will OR 2 nodes and append the result until there is only
8789 // 1 node left, i.e. the final OR'd value of all vectors.
8790 SDValue LHS = VecIns[Slot];
8791 SDValue RHS = VecIns[Slot + 1];
8792 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8795 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8796 VecIns.back(), VecIns.back());
8799 /// Emit nodes that will be selected as "test Op0,Op0", or something
8801 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8802 SelectionDAG &DAG) const {
8803 DebugLoc dl = Op.getDebugLoc();
8805 // CF and OF aren't always set the way we want. Determine which
8806 // of these we need.
8807 bool NeedCF = false;
8808 bool NeedOF = false;
8811 case X86::COND_A: case X86::COND_AE:
8812 case X86::COND_B: case X86::COND_BE:
8815 case X86::COND_G: case X86::COND_GE:
8816 case X86::COND_L: case X86::COND_LE:
8817 case X86::COND_O: case X86::COND_NO:
8822 // See if we can use the EFLAGS value from the operand instead of
8823 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8824 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8825 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8826 // Emit a CMP with 0, which is the TEST pattern.
8827 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8828 DAG.getConstant(0, Op.getValueType()));
8830 unsigned Opcode = 0;
8831 unsigned NumOperands = 0;
8833 // Truncate operations may prevent the merge of the SETCC instruction
8834 // and the arithmetic intruction before it. Attempt to truncate the operands
8835 // of the arithmetic instruction and use a reduced bit-width instruction.
8836 bool NeedTruncation = false;
8837 SDValue ArithOp = Op;
8838 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8839 SDValue Arith = Op->getOperand(0);
8840 // Both the trunc and the arithmetic op need to have one user each.
8841 if (Arith->hasOneUse())
8842 switch (Arith.getOpcode()) {
8849 NeedTruncation = true;
8855 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8856 // which may be the result of a CAST. We use the variable 'Op', which is the
8857 // non-casted variable when we check for possible users.
8858 switch (ArithOp.getOpcode()) {
8860 // Due to an isel shortcoming, be conservative if this add is likely to be
8861 // selected as part of a load-modify-store instruction. When the root node
8862 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8863 // uses of other nodes in the match, such as the ADD in this case. This
8864 // leads to the ADD being left around and reselected, with the result being
8865 // two adds in the output. Alas, even if none our users are stores, that
8866 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8867 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8868 // climbing the DAG back to the root, and it doesn't seem to be worth the
8870 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8871 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8872 if (UI->getOpcode() != ISD::CopyToReg &&
8873 UI->getOpcode() != ISD::SETCC &&
8874 UI->getOpcode() != ISD::STORE)
8877 if (ConstantSDNode *C =
8878 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8879 // An add of one will be selected as an INC.
8880 if (C->getAPIntValue() == 1) {
8881 Opcode = X86ISD::INC;
8886 // An add of negative one (subtract of one) will be selected as a DEC.
8887 if (C->getAPIntValue().isAllOnesValue()) {
8888 Opcode = X86ISD::DEC;
8894 // Otherwise use a regular EFLAGS-setting add.
8895 Opcode = X86ISD::ADD;
8899 // If the primary and result isn't used, don't bother using X86ISD::AND,
8900 // because a TEST instruction will be better.
8901 bool NonFlagUse = false;
8902 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8903 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8905 unsigned UOpNo = UI.getOperandNo();
8906 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8907 // Look pass truncate.
8908 UOpNo = User->use_begin().getOperandNo();
8909 User = *User->use_begin();
8912 if (User->getOpcode() != ISD::BRCOND &&
8913 User->getOpcode() != ISD::SETCC &&
8914 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8927 // Due to the ISEL shortcoming noted above, be conservative if this op is
8928 // likely to be selected as part of a load-modify-store instruction.
8929 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8930 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8931 if (UI->getOpcode() == ISD::STORE)
8934 // Otherwise use a regular EFLAGS-setting instruction.
8935 switch (ArithOp.getOpcode()) {
8936 default: llvm_unreachable("unexpected operator!");
8937 case ISD::SUB: Opcode = X86ISD::SUB; break;
8938 case ISD::XOR: Opcode = X86ISD::XOR; break;
8939 case ISD::AND: Opcode = X86ISD::AND; break;
8941 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8942 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8943 if (EFLAGS.getNode())
8946 Opcode = X86ISD::OR;
8960 return SDValue(Op.getNode(), 1);
8966 // If we found that truncation is beneficial, perform the truncation and
8968 if (NeedTruncation) {
8969 EVT VT = Op.getValueType();
8970 SDValue WideVal = Op->getOperand(0);
8971 EVT WideVT = WideVal.getValueType();
8972 unsigned ConvertedOp = 0;
8973 // Use a target machine opcode to prevent further DAGCombine
8974 // optimizations that may separate the arithmetic operations
8975 // from the setcc node.
8976 switch (WideVal.getOpcode()) {
8978 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8979 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8980 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8981 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8982 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8987 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8988 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8989 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8990 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8996 // Emit a CMP with 0, which is the TEST pattern.
8997 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8998 DAG.getConstant(0, Op.getValueType()));
9000 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9001 SmallVector<SDValue, 4> Ops;
9002 for (unsigned i = 0; i != NumOperands; ++i)
9003 Ops.push_back(Op.getOperand(i));
9005 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9006 DAG.ReplaceAllUsesWith(Op, New);
9007 return SDValue(New.getNode(), 1);
9010 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9012 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9013 SelectionDAG &DAG) const {
9014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9015 if (C->getAPIntValue() == 0)
9016 return EmitTest(Op0, X86CC, DAG);
9018 DebugLoc dl = Op0.getDebugLoc();
9019 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9020 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9021 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9022 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9023 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9025 return SDValue(Sub.getNode(), 1);
9027 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9030 /// Convert a comparison if required by the subtarget.
9031 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9032 SelectionDAG &DAG) const {
9033 // If the subtarget does not support the FUCOMI instruction, floating-point
9034 // comparisons have to be converted.
9035 if (Subtarget->hasCMov() ||
9036 Cmp.getOpcode() != X86ISD::CMP ||
9037 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9038 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9041 // The instruction selector will select an FUCOM instruction instead of
9042 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9043 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9044 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9045 DebugLoc dl = Cmp.getDebugLoc();
9046 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9047 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9048 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9049 DAG.getConstant(8, MVT::i8));
9050 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9051 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9054 static bool isAllOnes(SDValue V) {
9055 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9056 return C && C->isAllOnesValue();
9059 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9060 /// if it's possible.
9061 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9062 DebugLoc dl, SelectionDAG &DAG) const {
9063 SDValue Op0 = And.getOperand(0);
9064 SDValue Op1 = And.getOperand(1);
9065 if (Op0.getOpcode() == ISD::TRUNCATE)
9066 Op0 = Op0.getOperand(0);
9067 if (Op1.getOpcode() == ISD::TRUNCATE)
9068 Op1 = Op1.getOperand(0);
9071 if (Op1.getOpcode() == ISD::SHL)
9072 std::swap(Op0, Op1);
9073 if (Op0.getOpcode() == ISD::SHL) {
9074 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9075 if (And00C->getZExtValue() == 1) {
9076 // If we looked past a truncate, check that it's only truncating away
9078 unsigned BitWidth = Op0.getValueSizeInBits();
9079 unsigned AndBitWidth = And.getValueSizeInBits();
9080 if (BitWidth > AndBitWidth) {
9082 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9083 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9087 RHS = Op0.getOperand(1);
9089 } else if (Op1.getOpcode() == ISD::Constant) {
9090 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9091 uint64_t AndRHSVal = AndRHS->getZExtValue();
9092 SDValue AndLHS = Op0;
9094 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9095 LHS = AndLHS.getOperand(0);
9096 RHS = AndLHS.getOperand(1);
9099 // Use BT if the immediate can't be encoded in a TEST instruction.
9100 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9102 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9106 if (LHS.getNode()) {
9107 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9108 // the condition code later.
9109 bool Invert = false;
9110 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9112 LHS = LHS.getOperand(0);
9115 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9116 // instruction. Since the shift amount is in-range-or-undefined, we know
9117 // that doing a bittest on the i32 value is ok. We extend to i32 because
9118 // the encoding for the i16 version is larger than the i32 version.
9119 // Also promote i16 to i32 for performance / code size reason.
9120 if (LHS.getValueType() == MVT::i8 ||
9121 LHS.getValueType() == MVT::i16)
9122 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9124 // If the operand types disagree, extend the shift amount to match. Since
9125 // BT ignores high bits (like shifts) we can use anyextend.
9126 if (LHS.getValueType() != RHS.getValueType())
9127 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9129 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9130 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9131 // Flip the condition if the LHS was a not instruction
9133 Cond = X86::GetOppositeBranchCondition(Cond);
9134 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9135 DAG.getConstant(Cond, MVT::i8), BT);
9141 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9143 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
9145 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
9146 SDValue Op0 = Op.getOperand(0);
9147 SDValue Op1 = Op.getOperand(1);
9148 DebugLoc dl = Op.getDebugLoc();
9149 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9151 // Optimize to BT if possible.
9152 // Lower (X & (1 << N)) == 0 to BT(X, N).
9153 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9154 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9155 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9156 Op1.getOpcode() == ISD::Constant &&
9157 cast<ConstantSDNode>(Op1)->isNullValue() &&
9158 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9159 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9160 if (NewSetCC.getNode())
9164 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9166 if (Op1.getOpcode() == ISD::Constant &&
9167 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9168 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9169 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9171 // If the input is a setcc, then reuse the input setcc or use a new one with
9172 // the inverted condition.
9173 if (Op0.getOpcode() == X86ISD::SETCC) {
9174 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9175 bool Invert = (CC == ISD::SETNE) ^
9176 cast<ConstantSDNode>(Op1)->isNullValue();
9177 if (!Invert) return Op0;
9179 CCode = X86::GetOppositeBranchCondition(CCode);
9180 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9181 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9185 bool isFP = Op1.getValueType().isFloatingPoint();
9186 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9187 if (X86CC == X86::COND_INVALID)
9190 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9191 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9192 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9193 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9196 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9197 // ones, and then concatenate the result back.
9198 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9199 EVT VT = Op.getValueType();
9201 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9202 "Unsupported value type for operation");
9204 unsigned NumElems = VT.getVectorNumElements();
9205 DebugLoc dl = Op.getDebugLoc();
9206 SDValue CC = Op.getOperand(2);
9208 // Extract the LHS vectors
9209 SDValue LHS = Op.getOperand(0);
9210 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9211 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9213 // Extract the RHS vectors
9214 SDValue RHS = Op.getOperand(1);
9215 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9216 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9218 // Issue the operation on the smaller types and concatenate the result back
9219 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9220 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9221 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9222 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9223 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9226 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9228 SDValue Op0 = Op.getOperand(0);
9229 SDValue Op1 = Op.getOperand(1);
9230 SDValue CC = Op.getOperand(2);
9231 EVT VT = Op.getValueType();
9232 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9233 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9234 DebugLoc dl = Op.getDebugLoc();
9238 EVT EltVT = Op0.getValueType().getVectorElementType();
9239 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9245 // SSE Condition code mapping:
9254 switch (SetCCOpcode) {
9255 default: llvm_unreachable("Unexpected SETCC condition");
9257 case ISD::SETEQ: SSECC = 0; break;
9259 case ISD::SETGT: Swap = true; // Fallthrough
9261 case ISD::SETOLT: SSECC = 1; break;
9263 case ISD::SETGE: Swap = true; // Fallthrough
9265 case ISD::SETOLE: SSECC = 2; break;
9266 case ISD::SETUO: SSECC = 3; break;
9268 case ISD::SETNE: SSECC = 4; break;
9269 case ISD::SETULE: Swap = true; // Fallthrough
9270 case ISD::SETUGE: SSECC = 5; break;
9271 case ISD::SETULT: Swap = true; // Fallthrough
9272 case ISD::SETUGT: SSECC = 6; break;
9273 case ISD::SETO: SSECC = 7; break;
9275 case ISD::SETONE: SSECC = 8; break;
9278 std::swap(Op0, Op1);
9280 // In the two special cases we can't handle, emit two comparisons.
9283 unsigned CombineOpc;
9284 if (SetCCOpcode == ISD::SETUEQ) {
9285 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9287 assert(SetCCOpcode == ISD::SETONE);
9288 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9291 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9292 DAG.getConstant(CC0, MVT::i8));
9293 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9294 DAG.getConstant(CC1, MVT::i8));
9295 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9297 // Handle all other FP comparisons here.
9298 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9299 DAG.getConstant(SSECC, MVT::i8));
9302 // Break 256-bit integer vector compare into smaller ones.
9303 if (VT.is256BitVector() && !Subtarget->hasInt256())
9304 return Lower256IntVSETCC(Op, DAG);
9306 // We are handling one of the integer comparisons here. Since SSE only has
9307 // GT and EQ comparisons for integer, swapping operands and multiple
9308 // operations may be required for some comparisons.
9310 bool Swap = false, Invert = false, FlipSigns = false;
9312 switch (SetCCOpcode) {
9313 default: llvm_unreachable("Unexpected SETCC condition");
9314 case ISD::SETNE: Invert = true;
9315 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9316 case ISD::SETLT: Swap = true;
9317 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9318 case ISD::SETGE: Swap = true;
9319 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9320 case ISD::SETULT: Swap = true;
9321 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9322 case ISD::SETUGE: Swap = true;
9323 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9326 std::swap(Op0, Op1);
9328 // Check that the operation in question is available (most are plain SSE2,
9329 // but PCMPGTQ and PCMPEQQ have different requirements).
9330 if (VT == MVT::v2i64) {
9331 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9333 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9334 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9335 // pcmpeqd + pshufd + pand.
9336 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9338 // First cast everything to the right type,
9339 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9340 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9343 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9345 // Make sure the lower and upper halves are both all-ones.
9346 const int Mask[] = { 1, 0, 3, 2 };
9347 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9348 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9351 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9353 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9357 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9358 // bits of the inputs before performing those operations.
9360 EVT EltVT = VT.getVectorElementType();
9361 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9363 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9364 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9366 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9367 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9370 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9372 // If the logical-not of the result is required, perform that now.
9374 Result = DAG.getNOT(dl, Result, VT);
9379 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9380 static bool isX86LogicalCmp(SDValue Op) {
9381 unsigned Opc = Op.getNode()->getOpcode();
9382 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9383 Opc == X86ISD::SAHF)
9385 if (Op.getResNo() == 1 &&
9386 (Opc == X86ISD::ADD ||
9387 Opc == X86ISD::SUB ||
9388 Opc == X86ISD::ADC ||
9389 Opc == X86ISD::SBB ||
9390 Opc == X86ISD::SMUL ||
9391 Opc == X86ISD::UMUL ||
9392 Opc == X86ISD::INC ||
9393 Opc == X86ISD::DEC ||
9394 Opc == X86ISD::OR ||
9395 Opc == X86ISD::XOR ||
9396 Opc == X86ISD::AND))
9399 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9405 static bool isZero(SDValue V) {
9406 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9407 return C && C->isNullValue();
9410 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9411 if (V.getOpcode() != ISD::TRUNCATE)
9414 SDValue VOp0 = V.getOperand(0);
9415 unsigned InBits = VOp0.getValueSizeInBits();
9416 unsigned Bits = V.getValueSizeInBits();
9417 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9420 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9421 bool addTest = true;
9422 SDValue Cond = Op.getOperand(0);
9423 SDValue Op1 = Op.getOperand(1);
9424 SDValue Op2 = Op.getOperand(2);
9425 DebugLoc DL = Op.getDebugLoc();
9428 if (Cond.getOpcode() == ISD::SETCC) {
9429 SDValue NewCond = LowerSETCC(Cond, DAG);
9430 if (NewCond.getNode())
9434 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9435 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9436 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9437 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9438 if (Cond.getOpcode() == X86ISD::SETCC &&
9439 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9440 isZero(Cond.getOperand(1).getOperand(1))) {
9441 SDValue Cmp = Cond.getOperand(1);
9443 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9445 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9446 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9447 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9449 SDValue CmpOp0 = Cmp.getOperand(0);
9450 // Apply further optimizations for special cases
9451 // (select (x != 0), -1, 0) -> neg & sbb
9452 // (select (x == 0), 0, -1) -> neg & sbb
9453 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9454 if (YC->isNullValue() &&
9455 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9456 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9457 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9458 DAG.getConstant(0, CmpOp0.getValueType()),
9460 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9461 DAG.getConstant(X86::COND_B, MVT::i8),
9462 SDValue(Neg.getNode(), 1));
9466 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9467 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9468 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9470 SDValue Res = // Res = 0 or -1.
9471 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9472 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9474 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9475 Res = DAG.getNOT(DL, Res, Res.getValueType());
9477 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9478 if (N2C == 0 || !N2C->isNullValue())
9479 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9484 // Look past (and (setcc_carry (cmp ...)), 1).
9485 if (Cond.getOpcode() == ISD::AND &&
9486 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9487 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9488 if (C && C->getAPIntValue() == 1)
9489 Cond = Cond.getOperand(0);
9492 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9493 // setting operand in place of the X86ISD::SETCC.
9494 unsigned CondOpcode = Cond.getOpcode();
9495 if (CondOpcode == X86ISD::SETCC ||
9496 CondOpcode == X86ISD::SETCC_CARRY) {
9497 CC = Cond.getOperand(0);
9499 SDValue Cmp = Cond.getOperand(1);
9500 unsigned Opc = Cmp.getOpcode();
9501 EVT VT = Op.getValueType();
9503 bool IllegalFPCMov = false;
9504 if (VT.isFloatingPoint() && !VT.isVector() &&
9505 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9506 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9508 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9509 Opc == X86ISD::BT) { // FIXME
9513 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9514 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9515 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9516 Cond.getOperand(0).getValueType() != MVT::i8)) {
9517 SDValue LHS = Cond.getOperand(0);
9518 SDValue RHS = Cond.getOperand(1);
9522 switch (CondOpcode) {
9523 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9524 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9525 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9526 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9527 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9528 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9529 default: llvm_unreachable("unexpected overflowing operator");
9531 if (CondOpcode == ISD::UMULO)
9532 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9535 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9537 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9539 if (CondOpcode == ISD::UMULO)
9540 Cond = X86Op.getValue(2);
9542 Cond = X86Op.getValue(1);
9544 CC = DAG.getConstant(X86Cond, MVT::i8);
9549 // Look pass the truncate if the high bits are known zero.
9550 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9551 Cond = Cond.getOperand(0);
9553 // We know the result of AND is compared against zero. Try to match
9555 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9556 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9557 if (NewSetCC.getNode()) {
9558 CC = NewSetCC.getOperand(0);
9559 Cond = NewSetCC.getOperand(1);
9566 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9567 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9570 // a < b ? -1 : 0 -> RES = ~setcc_carry
9571 // a < b ? 0 : -1 -> RES = setcc_carry
9572 // a >= b ? -1 : 0 -> RES = setcc_carry
9573 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9574 if (Cond.getOpcode() == X86ISD::SUB) {
9575 Cond = ConvertCmpIfNecessary(Cond, DAG);
9576 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9578 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9579 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9580 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9581 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9582 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9583 return DAG.getNOT(DL, Res, Res.getValueType());
9588 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9589 // widen the cmov and push the truncate through. This avoids introducing a new
9590 // branch during isel and doesn't add any extensions.
9591 if (Op.getValueType() == MVT::i8 &&
9592 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9593 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9594 if (T1.getValueType() == T2.getValueType() &&
9595 // Blacklist CopyFromReg to avoid partial register stalls.
9596 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9597 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9598 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9599 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9603 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9604 // condition is true.
9605 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9606 SDValue Ops[] = { Op2, Op1, CC, Cond };
9607 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9610 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9611 SelectionDAG &DAG) const {
9612 EVT VT = Op->getValueType(0);
9613 SDValue In = Op->getOperand(0);
9614 EVT InVT = In.getValueType();
9615 DebugLoc dl = Op->getDebugLoc();
9617 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9618 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9621 if (Subtarget->hasInt256())
9622 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9624 // Optimize vectors in AVX mode
9625 // Sign extend v8i16 to v8i32 and
9628 // Divide input vector into two parts
9629 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9630 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9631 // concat the vectors to original VT
9633 unsigned NumElems = InVT.getVectorNumElements();
9634 SDValue Undef = DAG.getUNDEF(InVT);
9636 SmallVector<int,8> ShufMask1(NumElems, -1);
9637 for (unsigned i = 0; i != NumElems/2; ++i)
9640 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9642 SmallVector<int,8> ShufMask2(NumElems, -1);
9643 for (unsigned i = 0; i != NumElems/2; ++i)
9644 ShufMask2[i] = i + NumElems/2;
9646 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9648 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
9649 VT.getVectorNumElements()/2);
9651 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9652 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9654 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9657 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9658 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9659 // from the AND / OR.
9660 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9661 Opc = Op.getOpcode();
9662 if (Opc != ISD::OR && Opc != ISD::AND)
9664 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9665 Op.getOperand(0).hasOneUse() &&
9666 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9667 Op.getOperand(1).hasOneUse());
9670 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9671 // 1 and that the SETCC node has a single use.
9672 static bool isXor1OfSetCC(SDValue Op) {
9673 if (Op.getOpcode() != ISD::XOR)
9675 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9676 if (N1C && N1C->getAPIntValue() == 1) {
9677 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9678 Op.getOperand(0).hasOneUse();
9683 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9684 bool addTest = true;
9685 SDValue Chain = Op.getOperand(0);
9686 SDValue Cond = Op.getOperand(1);
9687 SDValue Dest = Op.getOperand(2);
9688 DebugLoc dl = Op.getDebugLoc();
9690 bool Inverted = false;
9692 if (Cond.getOpcode() == ISD::SETCC) {
9693 // Check for setcc([su]{add,sub,mul}o == 0).
9694 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9695 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9696 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9697 Cond.getOperand(0).getResNo() == 1 &&
9698 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9699 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9700 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9701 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9702 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9703 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9705 Cond = Cond.getOperand(0);
9707 SDValue NewCond = LowerSETCC(Cond, DAG);
9708 if (NewCond.getNode())
9713 // FIXME: LowerXALUO doesn't handle these!!
9714 else if (Cond.getOpcode() == X86ISD::ADD ||
9715 Cond.getOpcode() == X86ISD::SUB ||
9716 Cond.getOpcode() == X86ISD::SMUL ||
9717 Cond.getOpcode() == X86ISD::UMUL)
9718 Cond = LowerXALUO(Cond, DAG);
9721 // Look pass (and (setcc_carry (cmp ...)), 1).
9722 if (Cond.getOpcode() == ISD::AND &&
9723 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9725 if (C && C->getAPIntValue() == 1)
9726 Cond = Cond.getOperand(0);
9729 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9730 // setting operand in place of the X86ISD::SETCC.
9731 unsigned CondOpcode = Cond.getOpcode();
9732 if (CondOpcode == X86ISD::SETCC ||
9733 CondOpcode == X86ISD::SETCC_CARRY) {
9734 CC = Cond.getOperand(0);
9736 SDValue Cmp = Cond.getOperand(1);
9737 unsigned Opc = Cmp.getOpcode();
9738 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9739 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9743 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9747 // These can only come from an arithmetic instruction with overflow,
9748 // e.g. SADDO, UADDO.
9749 Cond = Cond.getNode()->getOperand(1);
9755 CondOpcode = Cond.getOpcode();
9756 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9757 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9758 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9759 Cond.getOperand(0).getValueType() != MVT::i8)) {
9760 SDValue LHS = Cond.getOperand(0);
9761 SDValue RHS = Cond.getOperand(1);
9765 switch (CondOpcode) {
9766 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9767 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9768 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9769 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9770 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9771 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9772 default: llvm_unreachable("unexpected overflowing operator");
9775 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9776 if (CondOpcode == ISD::UMULO)
9777 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9780 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9782 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9784 if (CondOpcode == ISD::UMULO)
9785 Cond = X86Op.getValue(2);
9787 Cond = X86Op.getValue(1);
9789 CC = DAG.getConstant(X86Cond, MVT::i8);
9793 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9794 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9795 if (CondOpc == ISD::OR) {
9796 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9797 // two branches instead of an explicit OR instruction with a
9799 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9800 isX86LogicalCmp(Cmp)) {
9801 CC = Cond.getOperand(0).getOperand(0);
9802 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9803 Chain, Dest, CC, Cmp);
9804 CC = Cond.getOperand(1).getOperand(0);
9808 } else { // ISD::AND
9809 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9810 // two branches instead of an explicit AND instruction with a
9811 // separate test. However, we only do this if this block doesn't
9812 // have a fall-through edge, because this requires an explicit
9813 // jmp when the condition is false.
9814 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9815 isX86LogicalCmp(Cmp) &&
9816 Op.getNode()->hasOneUse()) {
9817 X86::CondCode CCode =
9818 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9819 CCode = X86::GetOppositeBranchCondition(CCode);
9820 CC = DAG.getConstant(CCode, MVT::i8);
9821 SDNode *User = *Op.getNode()->use_begin();
9822 // Look for an unconditional branch following this conditional branch.
9823 // We need this because we need to reverse the successors in order
9824 // to implement FCMP_OEQ.
9825 if (User->getOpcode() == ISD::BR) {
9826 SDValue FalseBB = User->getOperand(1);
9828 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9829 assert(NewBR == User);
9833 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9834 Chain, Dest, CC, Cmp);
9835 X86::CondCode CCode =
9836 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9837 CCode = X86::GetOppositeBranchCondition(CCode);
9838 CC = DAG.getConstant(CCode, MVT::i8);
9844 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9845 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9846 // It should be transformed during dag combiner except when the condition
9847 // is set by a arithmetics with overflow node.
9848 X86::CondCode CCode =
9849 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9850 CCode = X86::GetOppositeBranchCondition(CCode);
9851 CC = DAG.getConstant(CCode, MVT::i8);
9852 Cond = Cond.getOperand(0).getOperand(1);
9854 } else if (Cond.getOpcode() == ISD::SETCC &&
9855 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9856 // For FCMP_OEQ, we can emit
9857 // two branches instead of an explicit AND instruction with a
9858 // separate test. However, we only do this if this block doesn't
9859 // have a fall-through edge, because this requires an explicit
9860 // jmp when the condition is false.
9861 if (Op.getNode()->hasOneUse()) {
9862 SDNode *User = *Op.getNode()->use_begin();
9863 // Look for an unconditional branch following this conditional branch.
9864 // We need this because we need to reverse the successors in order
9865 // to implement FCMP_OEQ.
9866 if (User->getOpcode() == ISD::BR) {
9867 SDValue FalseBB = User->getOperand(1);
9869 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9870 assert(NewBR == User);
9874 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9875 Cond.getOperand(0), Cond.getOperand(1));
9876 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9877 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9878 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9879 Chain, Dest, CC, Cmp);
9880 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9885 } else if (Cond.getOpcode() == ISD::SETCC &&
9886 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9887 // For FCMP_UNE, we can emit
9888 // two branches instead of an explicit AND instruction with a
9889 // separate test. However, we only do this if this block doesn't
9890 // have a fall-through edge, because this requires an explicit
9891 // jmp when the condition is false.
9892 if (Op.getNode()->hasOneUse()) {
9893 SDNode *User = *Op.getNode()->use_begin();
9894 // Look for an unconditional branch following this conditional branch.
9895 // We need this because we need to reverse the successors in order
9896 // to implement FCMP_UNE.
9897 if (User->getOpcode() == ISD::BR) {
9898 SDValue FalseBB = User->getOperand(1);
9900 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9901 assert(NewBR == User);
9904 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9905 Cond.getOperand(0), Cond.getOperand(1));
9906 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9907 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9908 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9909 Chain, Dest, CC, Cmp);
9910 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9920 // Look pass the truncate if the high bits are known zero.
9921 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9922 Cond = Cond.getOperand(0);
9924 // We know the result of AND is compared against zero. Try to match
9926 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9927 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9928 if (NewSetCC.getNode()) {
9929 CC = NewSetCC.getOperand(0);
9930 Cond = NewSetCC.getOperand(1);
9937 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9938 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9940 Cond = ConvertCmpIfNecessary(Cond, DAG);
9941 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9942 Chain, Dest, CC, Cond);
9945 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9946 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9947 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9948 // that the guard pages used by the OS virtual memory manager are allocated in
9949 // correct sequence.
9951 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9952 SelectionDAG &DAG) const {
9953 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9954 getTargetMachine().Options.EnableSegmentedStacks) &&
9955 "This should be used only on Windows targets or when segmented stacks "
9957 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9958 DebugLoc dl = Op.getDebugLoc();
9961 SDValue Chain = Op.getOperand(0);
9962 SDValue Size = Op.getOperand(1);
9963 // FIXME: Ensure alignment here
9965 bool Is64Bit = Subtarget->is64Bit();
9966 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9968 if (getTargetMachine().Options.EnableSegmentedStacks) {
9969 MachineFunction &MF = DAG.getMachineFunction();
9970 MachineRegisterInfo &MRI = MF.getRegInfo();
9973 // The 64 bit implementation of segmented stacks needs to clobber both r10
9974 // r11. This makes it impossible to use it along with nested parameters.
9975 const Function *F = MF.getFunction();
9977 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9979 if (I->hasNestAttr())
9980 report_fatal_error("Cannot use segmented stacks with functions that "
9981 "have nested arguments.");
9984 const TargetRegisterClass *AddrRegClass =
9985 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9986 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9987 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9988 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9989 DAG.getRegister(Vreg, SPTy));
9990 SDValue Ops1[2] = { Value, Chain };
9991 return DAG.getMergeValues(Ops1, 2, dl);
9994 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9996 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9997 Flag = Chain.getValue(1);
9998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10000 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10001 Flag = Chain.getValue(1);
10003 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10006 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10007 return DAG.getMergeValues(Ops1, 2, dl);
10011 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10012 MachineFunction &MF = DAG.getMachineFunction();
10013 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10015 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10016 DebugLoc DL = Op.getDebugLoc();
10018 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10019 // vastart just stores the address of the VarArgsFrameIndex slot into the
10020 // memory location argument.
10021 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10023 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10024 MachinePointerInfo(SV), false, false, 0);
10028 // gp_offset (0 - 6 * 8)
10029 // fp_offset (48 - 48 + 8 * 16)
10030 // overflow_arg_area (point to parameters coming in memory).
10032 SmallVector<SDValue, 8> MemOps;
10033 SDValue FIN = Op.getOperand(1);
10035 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10036 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10038 FIN, MachinePointerInfo(SV), false, false, 0);
10039 MemOps.push_back(Store);
10042 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10043 FIN, DAG.getIntPtrConstant(4));
10044 Store = DAG.getStore(Op.getOperand(0), DL,
10045 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10047 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10048 MemOps.push_back(Store);
10050 // Store ptr to overflow_arg_area
10051 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10052 FIN, DAG.getIntPtrConstant(4));
10053 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10055 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10056 MachinePointerInfo(SV, 8),
10058 MemOps.push_back(Store);
10060 // Store ptr to reg_save_area.
10061 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10062 FIN, DAG.getIntPtrConstant(8));
10063 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10065 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10066 MachinePointerInfo(SV, 16), false, false, 0);
10067 MemOps.push_back(Store);
10068 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10069 &MemOps[0], MemOps.size());
10072 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10073 assert(Subtarget->is64Bit() &&
10074 "LowerVAARG only handles 64-bit va_arg!");
10075 assert((Subtarget->isTargetLinux() ||
10076 Subtarget->isTargetDarwin()) &&
10077 "Unhandled target in LowerVAARG");
10078 assert(Op.getNode()->getNumOperands() == 4);
10079 SDValue Chain = Op.getOperand(0);
10080 SDValue SrcPtr = Op.getOperand(1);
10081 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10082 unsigned Align = Op.getConstantOperandVal(3);
10083 DebugLoc dl = Op.getDebugLoc();
10085 EVT ArgVT = Op.getNode()->getValueType(0);
10086 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10087 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10090 // Decide which area this value should be read from.
10091 // TODO: Implement the AMD64 ABI in its entirety. This simple
10092 // selection mechanism works only for the basic types.
10093 if (ArgVT == MVT::f80) {
10094 llvm_unreachable("va_arg for f80 not yet implemented");
10095 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10096 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10097 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10098 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10100 llvm_unreachable("Unhandled argument type in LowerVAARG");
10103 if (ArgMode == 2) {
10104 // Sanity Check: Make sure using fp_offset makes sense.
10105 assert(!getTargetMachine().Options.UseSoftFloat &&
10106 !(DAG.getMachineFunction()
10107 .getFunction()->getFnAttributes()
10108 .hasAttribute(Attribute::NoImplicitFloat)) &&
10109 Subtarget->hasSSE1());
10112 // Insert VAARG_64 node into the DAG
10113 // VAARG_64 returns two values: Variable Argument Address, Chain
10114 SmallVector<SDValue, 11> InstOps;
10115 InstOps.push_back(Chain);
10116 InstOps.push_back(SrcPtr);
10117 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10118 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10119 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10120 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10121 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10122 VTs, &InstOps[0], InstOps.size(),
10124 MachinePointerInfo(SV),
10126 /*Volatile=*/false,
10128 /*WriteMem=*/true);
10129 Chain = VAARG.getValue(1);
10131 // Load the next argument and return it
10132 return DAG.getLoad(ArgVT, dl,
10135 MachinePointerInfo(),
10136 false, false, false, 0);
10139 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10140 SelectionDAG &DAG) {
10141 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10142 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10143 SDValue Chain = Op.getOperand(0);
10144 SDValue DstPtr = Op.getOperand(1);
10145 SDValue SrcPtr = Op.getOperand(2);
10146 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10147 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10148 DebugLoc DL = Op.getDebugLoc();
10150 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10151 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10153 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10156 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10157 // may or may not be a constant. Takes immediate version of shift as input.
10158 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10159 SDValue SrcOp, SDValue ShAmt,
10160 SelectionDAG &DAG) {
10161 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10163 if (isa<ConstantSDNode>(ShAmt)) {
10164 // Constant may be a TargetConstant. Use a regular constant.
10165 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10167 default: llvm_unreachable("Unknown target vector shift node");
10168 case X86ISD::VSHLI:
10169 case X86ISD::VSRLI:
10170 case X86ISD::VSRAI:
10171 return DAG.getNode(Opc, dl, VT, SrcOp,
10172 DAG.getConstant(ShiftAmt, MVT::i32));
10176 // Change opcode to non-immediate version
10178 default: llvm_unreachable("Unknown target vector shift node");
10179 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10180 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10181 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10184 // Need to build a vector containing shift amount
10185 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10188 ShOps[1] = DAG.getConstant(0, MVT::i32);
10189 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10190 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10192 // The return type has to be a 128-bit type with the same element
10193 // type as the input type.
10194 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10195 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10197 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10198 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10201 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10202 DebugLoc dl = Op.getDebugLoc();
10203 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10205 default: return SDValue(); // Don't custom lower most intrinsics.
10206 // Comparison intrinsics.
10207 case Intrinsic::x86_sse_comieq_ss:
10208 case Intrinsic::x86_sse_comilt_ss:
10209 case Intrinsic::x86_sse_comile_ss:
10210 case Intrinsic::x86_sse_comigt_ss:
10211 case Intrinsic::x86_sse_comige_ss:
10212 case Intrinsic::x86_sse_comineq_ss:
10213 case Intrinsic::x86_sse_ucomieq_ss:
10214 case Intrinsic::x86_sse_ucomilt_ss:
10215 case Intrinsic::x86_sse_ucomile_ss:
10216 case Intrinsic::x86_sse_ucomigt_ss:
10217 case Intrinsic::x86_sse_ucomige_ss:
10218 case Intrinsic::x86_sse_ucomineq_ss:
10219 case Intrinsic::x86_sse2_comieq_sd:
10220 case Intrinsic::x86_sse2_comilt_sd:
10221 case Intrinsic::x86_sse2_comile_sd:
10222 case Intrinsic::x86_sse2_comigt_sd:
10223 case Intrinsic::x86_sse2_comige_sd:
10224 case Intrinsic::x86_sse2_comineq_sd:
10225 case Intrinsic::x86_sse2_ucomieq_sd:
10226 case Intrinsic::x86_sse2_ucomilt_sd:
10227 case Intrinsic::x86_sse2_ucomile_sd:
10228 case Intrinsic::x86_sse2_ucomigt_sd:
10229 case Intrinsic::x86_sse2_ucomige_sd:
10230 case Intrinsic::x86_sse2_ucomineq_sd: {
10234 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10235 case Intrinsic::x86_sse_comieq_ss:
10236 case Intrinsic::x86_sse2_comieq_sd:
10237 Opc = X86ISD::COMI;
10240 case Intrinsic::x86_sse_comilt_ss:
10241 case Intrinsic::x86_sse2_comilt_sd:
10242 Opc = X86ISD::COMI;
10245 case Intrinsic::x86_sse_comile_ss:
10246 case Intrinsic::x86_sse2_comile_sd:
10247 Opc = X86ISD::COMI;
10250 case Intrinsic::x86_sse_comigt_ss:
10251 case Intrinsic::x86_sse2_comigt_sd:
10252 Opc = X86ISD::COMI;
10255 case Intrinsic::x86_sse_comige_ss:
10256 case Intrinsic::x86_sse2_comige_sd:
10257 Opc = X86ISD::COMI;
10260 case Intrinsic::x86_sse_comineq_ss:
10261 case Intrinsic::x86_sse2_comineq_sd:
10262 Opc = X86ISD::COMI;
10265 case Intrinsic::x86_sse_ucomieq_ss:
10266 case Intrinsic::x86_sse2_ucomieq_sd:
10267 Opc = X86ISD::UCOMI;
10270 case Intrinsic::x86_sse_ucomilt_ss:
10271 case Intrinsic::x86_sse2_ucomilt_sd:
10272 Opc = X86ISD::UCOMI;
10275 case Intrinsic::x86_sse_ucomile_ss:
10276 case Intrinsic::x86_sse2_ucomile_sd:
10277 Opc = X86ISD::UCOMI;
10280 case Intrinsic::x86_sse_ucomigt_ss:
10281 case Intrinsic::x86_sse2_ucomigt_sd:
10282 Opc = X86ISD::UCOMI;
10285 case Intrinsic::x86_sse_ucomige_ss:
10286 case Intrinsic::x86_sse2_ucomige_sd:
10287 Opc = X86ISD::UCOMI;
10290 case Intrinsic::x86_sse_ucomineq_ss:
10291 case Intrinsic::x86_sse2_ucomineq_sd:
10292 Opc = X86ISD::UCOMI;
10297 SDValue LHS = Op.getOperand(1);
10298 SDValue RHS = Op.getOperand(2);
10299 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10300 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10301 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10302 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10303 DAG.getConstant(X86CC, MVT::i8), Cond);
10304 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10307 // Arithmetic intrinsics.
10308 case Intrinsic::x86_sse2_pmulu_dq:
10309 case Intrinsic::x86_avx2_pmulu_dq:
10310 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10311 Op.getOperand(1), Op.getOperand(2));
10313 // SSE2/AVX2 sub with unsigned saturation intrinsics
10314 case Intrinsic::x86_sse2_psubus_b:
10315 case Intrinsic::x86_sse2_psubus_w:
10316 case Intrinsic::x86_avx2_psubus_b:
10317 case Intrinsic::x86_avx2_psubus_w:
10318 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10319 Op.getOperand(1), Op.getOperand(2));
10321 // SSE3/AVX horizontal add/sub intrinsics
10322 case Intrinsic::x86_sse3_hadd_ps:
10323 case Intrinsic::x86_sse3_hadd_pd:
10324 case Intrinsic::x86_avx_hadd_ps_256:
10325 case Intrinsic::x86_avx_hadd_pd_256:
10326 case Intrinsic::x86_sse3_hsub_ps:
10327 case Intrinsic::x86_sse3_hsub_pd:
10328 case Intrinsic::x86_avx_hsub_ps_256:
10329 case Intrinsic::x86_avx_hsub_pd_256:
10330 case Intrinsic::x86_ssse3_phadd_w_128:
10331 case Intrinsic::x86_ssse3_phadd_d_128:
10332 case Intrinsic::x86_avx2_phadd_w:
10333 case Intrinsic::x86_avx2_phadd_d:
10334 case Intrinsic::x86_ssse3_phsub_w_128:
10335 case Intrinsic::x86_ssse3_phsub_d_128:
10336 case Intrinsic::x86_avx2_phsub_w:
10337 case Intrinsic::x86_avx2_phsub_d: {
10340 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10341 case Intrinsic::x86_sse3_hadd_ps:
10342 case Intrinsic::x86_sse3_hadd_pd:
10343 case Intrinsic::x86_avx_hadd_ps_256:
10344 case Intrinsic::x86_avx_hadd_pd_256:
10345 Opcode = X86ISD::FHADD;
10347 case Intrinsic::x86_sse3_hsub_ps:
10348 case Intrinsic::x86_sse3_hsub_pd:
10349 case Intrinsic::x86_avx_hsub_ps_256:
10350 case Intrinsic::x86_avx_hsub_pd_256:
10351 Opcode = X86ISD::FHSUB;
10353 case Intrinsic::x86_ssse3_phadd_w_128:
10354 case Intrinsic::x86_ssse3_phadd_d_128:
10355 case Intrinsic::x86_avx2_phadd_w:
10356 case Intrinsic::x86_avx2_phadd_d:
10357 Opcode = X86ISD::HADD;
10359 case Intrinsic::x86_ssse3_phsub_w_128:
10360 case Intrinsic::x86_ssse3_phsub_d_128:
10361 case Intrinsic::x86_avx2_phsub_w:
10362 case Intrinsic::x86_avx2_phsub_d:
10363 Opcode = X86ISD::HSUB;
10366 return DAG.getNode(Opcode, dl, Op.getValueType(),
10367 Op.getOperand(1), Op.getOperand(2));
10370 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10371 case Intrinsic::x86_sse2_pmaxu_b:
10372 case Intrinsic::x86_sse41_pmaxuw:
10373 case Intrinsic::x86_sse41_pmaxud:
10374 case Intrinsic::x86_avx2_pmaxu_b:
10375 case Intrinsic::x86_avx2_pmaxu_w:
10376 case Intrinsic::x86_avx2_pmaxu_d:
10377 return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10378 Op.getOperand(1), Op.getOperand(2));
10379 case Intrinsic::x86_sse2_pminu_b:
10380 case Intrinsic::x86_sse41_pminuw:
10381 case Intrinsic::x86_sse41_pminud:
10382 case Intrinsic::x86_avx2_pminu_b:
10383 case Intrinsic::x86_avx2_pminu_w:
10384 case Intrinsic::x86_avx2_pminu_d:
10385 return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10386 Op.getOperand(1), Op.getOperand(2));
10387 case Intrinsic::x86_sse41_pmaxsb:
10388 case Intrinsic::x86_sse2_pmaxs_w:
10389 case Intrinsic::x86_sse41_pmaxsd:
10390 case Intrinsic::x86_avx2_pmaxs_b:
10391 case Intrinsic::x86_avx2_pmaxs_w:
10392 case Intrinsic::x86_avx2_pmaxs_d:
10393 return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10394 Op.getOperand(1), Op.getOperand(2));
10395 case Intrinsic::x86_sse41_pminsb:
10396 case Intrinsic::x86_sse2_pmins_w:
10397 case Intrinsic::x86_sse41_pminsd:
10398 case Intrinsic::x86_avx2_pmins_b:
10399 case Intrinsic::x86_avx2_pmins_w:
10400 case Intrinsic::x86_avx2_pmins_d:
10401 return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10402 Op.getOperand(1), Op.getOperand(2));
10404 // AVX2 variable shift intrinsics
10405 case Intrinsic::x86_avx2_psllv_d:
10406 case Intrinsic::x86_avx2_psllv_q:
10407 case Intrinsic::x86_avx2_psllv_d_256:
10408 case Intrinsic::x86_avx2_psllv_q_256:
10409 case Intrinsic::x86_avx2_psrlv_d:
10410 case Intrinsic::x86_avx2_psrlv_q:
10411 case Intrinsic::x86_avx2_psrlv_d_256:
10412 case Intrinsic::x86_avx2_psrlv_q_256:
10413 case Intrinsic::x86_avx2_psrav_d:
10414 case Intrinsic::x86_avx2_psrav_d_256: {
10417 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10418 case Intrinsic::x86_avx2_psllv_d:
10419 case Intrinsic::x86_avx2_psllv_q:
10420 case Intrinsic::x86_avx2_psllv_d_256:
10421 case Intrinsic::x86_avx2_psllv_q_256:
10424 case Intrinsic::x86_avx2_psrlv_d:
10425 case Intrinsic::x86_avx2_psrlv_q:
10426 case Intrinsic::x86_avx2_psrlv_d_256:
10427 case Intrinsic::x86_avx2_psrlv_q_256:
10430 case Intrinsic::x86_avx2_psrav_d:
10431 case Intrinsic::x86_avx2_psrav_d_256:
10435 return DAG.getNode(Opcode, dl, Op.getValueType(),
10436 Op.getOperand(1), Op.getOperand(2));
10439 case Intrinsic::x86_ssse3_pshuf_b_128:
10440 case Intrinsic::x86_avx2_pshuf_b:
10441 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10442 Op.getOperand(1), Op.getOperand(2));
10444 case Intrinsic::x86_ssse3_psign_b_128:
10445 case Intrinsic::x86_ssse3_psign_w_128:
10446 case Intrinsic::x86_ssse3_psign_d_128:
10447 case Intrinsic::x86_avx2_psign_b:
10448 case Intrinsic::x86_avx2_psign_w:
10449 case Intrinsic::x86_avx2_psign_d:
10450 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10451 Op.getOperand(1), Op.getOperand(2));
10453 case Intrinsic::x86_sse41_insertps:
10454 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10455 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10457 case Intrinsic::x86_avx_vperm2f128_ps_256:
10458 case Intrinsic::x86_avx_vperm2f128_pd_256:
10459 case Intrinsic::x86_avx_vperm2f128_si_256:
10460 case Intrinsic::x86_avx2_vperm2i128:
10461 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10462 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10464 case Intrinsic::x86_avx2_permd:
10465 case Intrinsic::x86_avx2_permps:
10466 // Operands intentionally swapped. Mask is last operand to intrinsic,
10467 // but second operand for node/intruction.
10468 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10469 Op.getOperand(2), Op.getOperand(1));
10471 // ptest and testp intrinsics. The intrinsic these come from are designed to
10472 // return an integer value, not just an instruction so lower it to the ptest
10473 // or testp pattern and a setcc for the result.
10474 case Intrinsic::x86_sse41_ptestz:
10475 case Intrinsic::x86_sse41_ptestc:
10476 case Intrinsic::x86_sse41_ptestnzc:
10477 case Intrinsic::x86_avx_ptestz_256:
10478 case Intrinsic::x86_avx_ptestc_256:
10479 case Intrinsic::x86_avx_ptestnzc_256:
10480 case Intrinsic::x86_avx_vtestz_ps:
10481 case Intrinsic::x86_avx_vtestc_ps:
10482 case Intrinsic::x86_avx_vtestnzc_ps:
10483 case Intrinsic::x86_avx_vtestz_pd:
10484 case Intrinsic::x86_avx_vtestc_pd:
10485 case Intrinsic::x86_avx_vtestnzc_pd:
10486 case Intrinsic::x86_avx_vtestz_ps_256:
10487 case Intrinsic::x86_avx_vtestc_ps_256:
10488 case Intrinsic::x86_avx_vtestnzc_ps_256:
10489 case Intrinsic::x86_avx_vtestz_pd_256:
10490 case Intrinsic::x86_avx_vtestc_pd_256:
10491 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10492 bool IsTestPacked = false;
10495 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10496 case Intrinsic::x86_avx_vtestz_ps:
10497 case Intrinsic::x86_avx_vtestz_pd:
10498 case Intrinsic::x86_avx_vtestz_ps_256:
10499 case Intrinsic::x86_avx_vtestz_pd_256:
10500 IsTestPacked = true; // Fallthrough
10501 case Intrinsic::x86_sse41_ptestz:
10502 case Intrinsic::x86_avx_ptestz_256:
10504 X86CC = X86::COND_E;
10506 case Intrinsic::x86_avx_vtestc_ps:
10507 case Intrinsic::x86_avx_vtestc_pd:
10508 case Intrinsic::x86_avx_vtestc_ps_256:
10509 case Intrinsic::x86_avx_vtestc_pd_256:
10510 IsTestPacked = true; // Fallthrough
10511 case Intrinsic::x86_sse41_ptestc:
10512 case Intrinsic::x86_avx_ptestc_256:
10514 X86CC = X86::COND_B;
10516 case Intrinsic::x86_avx_vtestnzc_ps:
10517 case Intrinsic::x86_avx_vtestnzc_pd:
10518 case Intrinsic::x86_avx_vtestnzc_ps_256:
10519 case Intrinsic::x86_avx_vtestnzc_pd_256:
10520 IsTestPacked = true; // Fallthrough
10521 case Intrinsic::x86_sse41_ptestnzc:
10522 case Intrinsic::x86_avx_ptestnzc_256:
10524 X86CC = X86::COND_A;
10528 SDValue LHS = Op.getOperand(1);
10529 SDValue RHS = Op.getOperand(2);
10530 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10531 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10532 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10533 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10534 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10537 // SSE/AVX shift intrinsics
10538 case Intrinsic::x86_sse2_psll_w:
10539 case Intrinsic::x86_sse2_psll_d:
10540 case Intrinsic::x86_sse2_psll_q:
10541 case Intrinsic::x86_avx2_psll_w:
10542 case Intrinsic::x86_avx2_psll_d:
10543 case Intrinsic::x86_avx2_psll_q:
10544 case Intrinsic::x86_sse2_psrl_w:
10545 case Intrinsic::x86_sse2_psrl_d:
10546 case Intrinsic::x86_sse2_psrl_q:
10547 case Intrinsic::x86_avx2_psrl_w:
10548 case Intrinsic::x86_avx2_psrl_d:
10549 case Intrinsic::x86_avx2_psrl_q:
10550 case Intrinsic::x86_sse2_psra_w:
10551 case Intrinsic::x86_sse2_psra_d:
10552 case Intrinsic::x86_avx2_psra_w:
10553 case Intrinsic::x86_avx2_psra_d: {
10556 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10557 case Intrinsic::x86_sse2_psll_w:
10558 case Intrinsic::x86_sse2_psll_d:
10559 case Intrinsic::x86_sse2_psll_q:
10560 case Intrinsic::x86_avx2_psll_w:
10561 case Intrinsic::x86_avx2_psll_d:
10562 case Intrinsic::x86_avx2_psll_q:
10563 Opcode = X86ISD::VSHL;
10565 case Intrinsic::x86_sse2_psrl_w:
10566 case Intrinsic::x86_sse2_psrl_d:
10567 case Intrinsic::x86_sse2_psrl_q:
10568 case Intrinsic::x86_avx2_psrl_w:
10569 case Intrinsic::x86_avx2_psrl_d:
10570 case Intrinsic::x86_avx2_psrl_q:
10571 Opcode = X86ISD::VSRL;
10573 case Intrinsic::x86_sse2_psra_w:
10574 case Intrinsic::x86_sse2_psra_d:
10575 case Intrinsic::x86_avx2_psra_w:
10576 case Intrinsic::x86_avx2_psra_d:
10577 Opcode = X86ISD::VSRA;
10580 return DAG.getNode(Opcode, dl, Op.getValueType(),
10581 Op.getOperand(1), Op.getOperand(2));
10584 // SSE/AVX immediate shift intrinsics
10585 case Intrinsic::x86_sse2_pslli_w:
10586 case Intrinsic::x86_sse2_pslli_d:
10587 case Intrinsic::x86_sse2_pslli_q:
10588 case Intrinsic::x86_avx2_pslli_w:
10589 case Intrinsic::x86_avx2_pslli_d:
10590 case Intrinsic::x86_avx2_pslli_q:
10591 case Intrinsic::x86_sse2_psrli_w:
10592 case Intrinsic::x86_sse2_psrli_d:
10593 case Intrinsic::x86_sse2_psrli_q:
10594 case Intrinsic::x86_avx2_psrli_w:
10595 case Intrinsic::x86_avx2_psrli_d:
10596 case Intrinsic::x86_avx2_psrli_q:
10597 case Intrinsic::x86_sse2_psrai_w:
10598 case Intrinsic::x86_sse2_psrai_d:
10599 case Intrinsic::x86_avx2_psrai_w:
10600 case Intrinsic::x86_avx2_psrai_d: {
10603 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10604 case Intrinsic::x86_sse2_pslli_w:
10605 case Intrinsic::x86_sse2_pslli_d:
10606 case Intrinsic::x86_sse2_pslli_q:
10607 case Intrinsic::x86_avx2_pslli_w:
10608 case Intrinsic::x86_avx2_pslli_d:
10609 case Intrinsic::x86_avx2_pslli_q:
10610 Opcode = X86ISD::VSHLI;
10612 case Intrinsic::x86_sse2_psrli_w:
10613 case Intrinsic::x86_sse2_psrli_d:
10614 case Intrinsic::x86_sse2_psrli_q:
10615 case Intrinsic::x86_avx2_psrli_w:
10616 case Intrinsic::x86_avx2_psrli_d:
10617 case Intrinsic::x86_avx2_psrli_q:
10618 Opcode = X86ISD::VSRLI;
10620 case Intrinsic::x86_sse2_psrai_w:
10621 case Intrinsic::x86_sse2_psrai_d:
10622 case Intrinsic::x86_avx2_psrai_w:
10623 case Intrinsic::x86_avx2_psrai_d:
10624 Opcode = X86ISD::VSRAI;
10627 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10628 Op.getOperand(1), Op.getOperand(2), DAG);
10631 case Intrinsic::x86_sse42_pcmpistria128:
10632 case Intrinsic::x86_sse42_pcmpestria128:
10633 case Intrinsic::x86_sse42_pcmpistric128:
10634 case Intrinsic::x86_sse42_pcmpestric128:
10635 case Intrinsic::x86_sse42_pcmpistrio128:
10636 case Intrinsic::x86_sse42_pcmpestrio128:
10637 case Intrinsic::x86_sse42_pcmpistris128:
10638 case Intrinsic::x86_sse42_pcmpestris128:
10639 case Intrinsic::x86_sse42_pcmpistriz128:
10640 case Intrinsic::x86_sse42_pcmpestriz128: {
10644 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10645 case Intrinsic::x86_sse42_pcmpistria128:
10646 Opcode = X86ISD::PCMPISTRI;
10647 X86CC = X86::COND_A;
10649 case Intrinsic::x86_sse42_pcmpestria128:
10650 Opcode = X86ISD::PCMPESTRI;
10651 X86CC = X86::COND_A;
10653 case Intrinsic::x86_sse42_pcmpistric128:
10654 Opcode = X86ISD::PCMPISTRI;
10655 X86CC = X86::COND_B;
10657 case Intrinsic::x86_sse42_pcmpestric128:
10658 Opcode = X86ISD::PCMPESTRI;
10659 X86CC = X86::COND_B;
10661 case Intrinsic::x86_sse42_pcmpistrio128:
10662 Opcode = X86ISD::PCMPISTRI;
10663 X86CC = X86::COND_O;
10665 case Intrinsic::x86_sse42_pcmpestrio128:
10666 Opcode = X86ISD::PCMPESTRI;
10667 X86CC = X86::COND_O;
10669 case Intrinsic::x86_sse42_pcmpistris128:
10670 Opcode = X86ISD::PCMPISTRI;
10671 X86CC = X86::COND_S;
10673 case Intrinsic::x86_sse42_pcmpestris128:
10674 Opcode = X86ISD::PCMPESTRI;
10675 X86CC = X86::COND_S;
10677 case Intrinsic::x86_sse42_pcmpistriz128:
10678 Opcode = X86ISD::PCMPISTRI;
10679 X86CC = X86::COND_E;
10681 case Intrinsic::x86_sse42_pcmpestriz128:
10682 Opcode = X86ISD::PCMPESTRI;
10683 X86CC = X86::COND_E;
10686 SmallVector<SDValue, 5> NewOps;
10687 NewOps.append(Op->op_begin()+1, Op->op_end());
10688 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10689 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10690 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10691 DAG.getConstant(X86CC, MVT::i8),
10692 SDValue(PCMP.getNode(), 1));
10693 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10696 case Intrinsic::x86_sse42_pcmpistri128:
10697 case Intrinsic::x86_sse42_pcmpestri128: {
10699 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10700 Opcode = X86ISD::PCMPISTRI;
10702 Opcode = X86ISD::PCMPESTRI;
10704 SmallVector<SDValue, 5> NewOps;
10705 NewOps.append(Op->op_begin()+1, Op->op_end());
10706 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10707 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10709 case Intrinsic::x86_fma_vfmadd_ps:
10710 case Intrinsic::x86_fma_vfmadd_pd:
10711 case Intrinsic::x86_fma_vfmsub_ps:
10712 case Intrinsic::x86_fma_vfmsub_pd:
10713 case Intrinsic::x86_fma_vfnmadd_ps:
10714 case Intrinsic::x86_fma_vfnmadd_pd:
10715 case Intrinsic::x86_fma_vfnmsub_ps:
10716 case Intrinsic::x86_fma_vfnmsub_pd:
10717 case Intrinsic::x86_fma_vfmaddsub_ps:
10718 case Intrinsic::x86_fma_vfmaddsub_pd:
10719 case Intrinsic::x86_fma_vfmsubadd_ps:
10720 case Intrinsic::x86_fma_vfmsubadd_pd:
10721 case Intrinsic::x86_fma_vfmadd_ps_256:
10722 case Intrinsic::x86_fma_vfmadd_pd_256:
10723 case Intrinsic::x86_fma_vfmsub_ps_256:
10724 case Intrinsic::x86_fma_vfmsub_pd_256:
10725 case Intrinsic::x86_fma_vfnmadd_ps_256:
10726 case Intrinsic::x86_fma_vfnmadd_pd_256:
10727 case Intrinsic::x86_fma_vfnmsub_ps_256:
10728 case Intrinsic::x86_fma_vfnmsub_pd_256:
10729 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10730 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10731 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10732 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10735 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10736 case Intrinsic::x86_fma_vfmadd_ps:
10737 case Intrinsic::x86_fma_vfmadd_pd:
10738 case Intrinsic::x86_fma_vfmadd_ps_256:
10739 case Intrinsic::x86_fma_vfmadd_pd_256:
10740 Opc = X86ISD::FMADD;
10742 case Intrinsic::x86_fma_vfmsub_ps:
10743 case Intrinsic::x86_fma_vfmsub_pd:
10744 case Intrinsic::x86_fma_vfmsub_ps_256:
10745 case Intrinsic::x86_fma_vfmsub_pd_256:
10746 Opc = X86ISD::FMSUB;
10748 case Intrinsic::x86_fma_vfnmadd_ps:
10749 case Intrinsic::x86_fma_vfnmadd_pd:
10750 case Intrinsic::x86_fma_vfnmadd_ps_256:
10751 case Intrinsic::x86_fma_vfnmadd_pd_256:
10752 Opc = X86ISD::FNMADD;
10754 case Intrinsic::x86_fma_vfnmsub_ps:
10755 case Intrinsic::x86_fma_vfnmsub_pd:
10756 case Intrinsic::x86_fma_vfnmsub_ps_256:
10757 case Intrinsic::x86_fma_vfnmsub_pd_256:
10758 Opc = X86ISD::FNMSUB;
10760 case Intrinsic::x86_fma_vfmaddsub_ps:
10761 case Intrinsic::x86_fma_vfmaddsub_pd:
10762 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10763 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10764 Opc = X86ISD::FMADDSUB;
10766 case Intrinsic::x86_fma_vfmsubadd_ps:
10767 case Intrinsic::x86_fma_vfmsubadd_pd:
10768 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10769 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10770 Opc = X86ISD::FMSUBADD;
10774 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10775 Op.getOperand(2), Op.getOperand(3));
10780 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10781 DebugLoc dl = Op.getDebugLoc();
10782 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10784 default: return SDValue(); // Don't custom lower most intrinsics.
10786 // RDRAND intrinsics.
10787 case Intrinsic::x86_rdrand_16:
10788 case Intrinsic::x86_rdrand_32:
10789 case Intrinsic::x86_rdrand_64: {
10790 // Emit the node with the right value type.
10791 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10792 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10794 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10795 // return the value from Rand, which is always 0, casted to i32.
10796 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10797 DAG.getConstant(1, Op->getValueType(1)),
10798 DAG.getConstant(X86::COND_B, MVT::i32),
10799 SDValue(Result.getNode(), 1) };
10800 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10801 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10804 // Return { result, isValid, chain }.
10805 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10806 SDValue(Result.getNode(), 2));
10811 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10812 SelectionDAG &DAG) const {
10813 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10814 MFI->setReturnAddressIsTaken(true);
10816 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10817 DebugLoc dl = Op.getDebugLoc();
10818 EVT PtrVT = getPointerTy();
10821 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10823 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10824 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10825 DAG.getNode(ISD::ADD, dl, PtrVT,
10826 FrameAddr, Offset),
10827 MachinePointerInfo(), false, false, false, 0);
10830 // Just load the return address.
10831 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10832 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10833 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10836 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10837 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10838 MFI->setFrameAddressIsTaken(true);
10840 EVT VT = Op.getValueType();
10841 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10842 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10843 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10844 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10846 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10847 MachinePointerInfo(),
10848 false, false, false, 0);
10852 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10853 SelectionDAG &DAG) const {
10854 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10857 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10858 SDValue Chain = Op.getOperand(0);
10859 SDValue Offset = Op.getOperand(1);
10860 SDValue Handler = Op.getOperand(2);
10861 DebugLoc dl = Op.getDebugLoc();
10863 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10864 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10866 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10868 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10869 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10870 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10871 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10873 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10875 return DAG.getNode(X86ISD::EH_RETURN, dl,
10877 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10880 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10881 SelectionDAG &DAG) const {
10882 DebugLoc DL = Op.getDebugLoc();
10883 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10884 DAG.getVTList(MVT::i32, MVT::Other),
10885 Op.getOperand(0), Op.getOperand(1));
10888 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10889 SelectionDAG &DAG) const {
10890 DebugLoc DL = Op.getDebugLoc();
10891 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10892 Op.getOperand(0), Op.getOperand(1));
10895 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10896 return Op.getOperand(0);
10899 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10900 SelectionDAG &DAG) const {
10901 SDValue Root = Op.getOperand(0);
10902 SDValue Trmp = Op.getOperand(1); // trampoline
10903 SDValue FPtr = Op.getOperand(2); // nested function
10904 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10905 DebugLoc dl = Op.getDebugLoc();
10907 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10908 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10910 if (Subtarget->is64Bit()) {
10911 SDValue OutChains[6];
10913 // Large code-model.
10914 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10915 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10917 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10918 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10920 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10922 // Load the pointer to the nested function into R11.
10923 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10924 SDValue Addr = Trmp;
10925 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10926 Addr, MachinePointerInfo(TrmpAddr),
10929 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10930 DAG.getConstant(2, MVT::i64));
10931 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10932 MachinePointerInfo(TrmpAddr, 2),
10935 // Load the 'nest' parameter value into R10.
10936 // R10 is specified in X86CallingConv.td
10937 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10938 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10939 DAG.getConstant(10, MVT::i64));
10940 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10941 Addr, MachinePointerInfo(TrmpAddr, 10),
10944 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10945 DAG.getConstant(12, MVT::i64));
10946 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10947 MachinePointerInfo(TrmpAddr, 12),
10950 // Jump to the nested function.
10951 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10952 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10953 DAG.getConstant(20, MVT::i64));
10954 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10955 Addr, MachinePointerInfo(TrmpAddr, 20),
10958 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10959 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10960 DAG.getConstant(22, MVT::i64));
10961 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10962 MachinePointerInfo(TrmpAddr, 22),
10965 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10967 const Function *Func =
10968 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10969 CallingConv::ID CC = Func->getCallingConv();
10974 llvm_unreachable("Unsupported calling convention");
10975 case CallingConv::C:
10976 case CallingConv::X86_StdCall: {
10977 // Pass 'nest' parameter in ECX.
10978 // Must be kept in sync with X86CallingConv.td
10979 NestReg = X86::ECX;
10981 // Check that ECX wasn't needed by an 'inreg' parameter.
10982 FunctionType *FTy = Func->getFunctionType();
10983 const AttributeSet &Attrs = Func->getAttributes();
10985 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10986 unsigned InRegCount = 0;
10989 for (FunctionType::param_iterator I = FTy->param_begin(),
10990 E = FTy->param_end(); I != E; ++I, ++Idx)
10991 if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10992 // FIXME: should only count parameters that are lowered to integers.
10993 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10995 if (InRegCount > 2) {
10996 report_fatal_error("Nest register in use - reduce number of inreg"
11002 case CallingConv::X86_FastCall:
11003 case CallingConv::X86_ThisCall:
11004 case CallingConv::Fast:
11005 // Pass 'nest' parameter in EAX.
11006 // Must be kept in sync with X86CallingConv.td
11007 NestReg = X86::EAX;
11011 SDValue OutChains[4];
11012 SDValue Addr, Disp;
11014 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11015 DAG.getConstant(10, MVT::i32));
11016 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11018 // This is storing the opcode for MOV32ri.
11019 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11020 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11021 OutChains[0] = DAG.getStore(Root, dl,
11022 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11023 Trmp, MachinePointerInfo(TrmpAddr),
11026 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11027 DAG.getConstant(1, MVT::i32));
11028 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11029 MachinePointerInfo(TrmpAddr, 1),
11032 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11033 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11034 DAG.getConstant(5, MVT::i32));
11035 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11036 MachinePointerInfo(TrmpAddr, 5),
11039 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11040 DAG.getConstant(6, MVT::i32));
11041 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11042 MachinePointerInfo(TrmpAddr, 6),
11045 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11049 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11050 SelectionDAG &DAG) const {
11052 The rounding mode is in bits 11:10 of FPSR, and has the following
11054 00 Round to nearest
11059 FLT_ROUNDS, on the other hand, expects the following:
11066 To perform the conversion, we do:
11067 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11070 MachineFunction &MF = DAG.getMachineFunction();
11071 const TargetMachine &TM = MF.getTarget();
11072 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11073 unsigned StackAlignment = TFI.getStackAlignment();
11074 EVT VT = Op.getValueType();
11075 DebugLoc DL = Op.getDebugLoc();
11077 // Save FP Control Word to stack slot
11078 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11079 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11081 MachineMemOperand *MMO =
11082 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11083 MachineMemOperand::MOStore, 2, 2);
11085 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11086 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11087 DAG.getVTList(MVT::Other),
11088 Ops, 2, MVT::i16, MMO);
11090 // Load FP Control Word from stack slot
11091 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11092 MachinePointerInfo(), false, false, false, 0);
11094 // Transform as necessary
11096 DAG.getNode(ISD::SRL, DL, MVT::i16,
11097 DAG.getNode(ISD::AND, DL, MVT::i16,
11098 CWD, DAG.getConstant(0x800, MVT::i16)),
11099 DAG.getConstant(11, MVT::i8));
11101 DAG.getNode(ISD::SRL, DL, MVT::i16,
11102 DAG.getNode(ISD::AND, DL, MVT::i16,
11103 CWD, DAG.getConstant(0x400, MVT::i16)),
11104 DAG.getConstant(9, MVT::i8));
11107 DAG.getNode(ISD::AND, DL, MVT::i16,
11108 DAG.getNode(ISD::ADD, DL, MVT::i16,
11109 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11110 DAG.getConstant(1, MVT::i16)),
11111 DAG.getConstant(3, MVT::i16));
11113 return DAG.getNode((VT.getSizeInBits() < 16 ?
11114 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11117 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11118 EVT VT = Op.getValueType();
11120 unsigned NumBits = VT.getSizeInBits();
11121 DebugLoc dl = Op.getDebugLoc();
11123 Op = Op.getOperand(0);
11124 if (VT == MVT::i8) {
11125 // Zero extend to i32 since there is not an i8 bsr.
11127 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11130 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11131 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11132 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11134 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11137 DAG.getConstant(NumBits+NumBits-1, OpVT),
11138 DAG.getConstant(X86::COND_E, MVT::i8),
11141 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11143 // Finally xor with NumBits-1.
11144 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11147 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11151 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11152 EVT VT = Op.getValueType();
11154 unsigned NumBits = VT.getSizeInBits();
11155 DebugLoc dl = Op.getDebugLoc();
11157 Op = Op.getOperand(0);
11158 if (VT == MVT::i8) {
11159 // Zero extend to i32 since there is not an i8 bsr.
11161 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11164 // Issue a bsr (scan bits in reverse).
11165 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11166 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11168 // And xor with NumBits-1.
11169 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11172 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11176 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11177 EVT VT = Op.getValueType();
11178 unsigned NumBits = VT.getSizeInBits();
11179 DebugLoc dl = Op.getDebugLoc();
11180 Op = Op.getOperand(0);
11182 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11183 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11184 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11186 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11189 DAG.getConstant(NumBits, VT),
11190 DAG.getConstant(X86::COND_E, MVT::i8),
11193 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11196 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11197 // ones, and then concatenate the result back.
11198 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11199 EVT VT = Op.getValueType();
11201 assert(VT.is256BitVector() && VT.isInteger() &&
11202 "Unsupported value type for operation");
11204 unsigned NumElems = VT.getVectorNumElements();
11205 DebugLoc dl = Op.getDebugLoc();
11207 // Extract the LHS vectors
11208 SDValue LHS = Op.getOperand(0);
11209 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11210 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11212 // Extract the RHS vectors
11213 SDValue RHS = Op.getOperand(1);
11214 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11215 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11217 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11218 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11220 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11221 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11222 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11225 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11226 assert(Op.getValueType().is256BitVector() &&
11227 Op.getValueType().isInteger() &&
11228 "Only handle AVX 256-bit vector integer operation");
11229 return Lower256IntArith(Op, DAG);
11232 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11233 assert(Op.getValueType().is256BitVector() &&
11234 Op.getValueType().isInteger() &&
11235 "Only handle AVX 256-bit vector integer operation");
11236 return Lower256IntArith(Op, DAG);
11239 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11240 SelectionDAG &DAG) {
11241 DebugLoc dl = Op.getDebugLoc();
11242 EVT VT = Op.getValueType();
11244 // Decompose 256-bit ops into smaller 128-bit ops.
11245 if (VT.is256BitVector() && !Subtarget->hasInt256())
11246 return Lower256IntArith(Op, DAG);
11248 SDValue A = Op.getOperand(0);
11249 SDValue B = Op.getOperand(1);
11251 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11252 if (VT == MVT::v4i32) {
11253 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11254 "Should not custom lower when pmuldq is available!");
11256 // Extract the odd parts.
11257 const int UnpackMask[] = { 1, -1, 3, -1 };
11258 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11259 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11261 // Multiply the even parts.
11262 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11263 // Now multiply odd parts.
11264 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11266 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11267 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11269 // Merge the two vectors back together with a shuffle. This expands into 2
11271 const int ShufMask[] = { 0, 4, 2, 6 };
11272 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11275 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11276 "Only know how to lower V2I64/V4I64 multiply");
11278 // Ahi = psrlqi(a, 32);
11279 // Bhi = psrlqi(b, 32);
11281 // AloBlo = pmuludq(a, b);
11282 // AloBhi = pmuludq(a, Bhi);
11283 // AhiBlo = pmuludq(Ahi, b);
11285 // AloBhi = psllqi(AloBhi, 32);
11286 // AhiBlo = psllqi(AhiBlo, 32);
11287 // return AloBlo + AloBhi + AhiBlo;
11289 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11291 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11292 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11294 // Bit cast to 32-bit vectors for MULUDQ
11295 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11296 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11297 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11298 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11299 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11301 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11302 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11303 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11305 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11306 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11308 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11309 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11312 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11314 EVT VT = Op.getValueType();
11315 DebugLoc dl = Op.getDebugLoc();
11316 SDValue R = Op.getOperand(0);
11317 SDValue Amt = Op.getOperand(1);
11318 LLVMContext *Context = DAG.getContext();
11320 if (!Subtarget->hasSSE2())
11323 // Optimize shl/srl/sra with constant shift amount.
11324 if (isSplatVector(Amt.getNode())) {
11325 SDValue SclrAmt = Amt->getOperand(0);
11326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11327 uint64_t ShiftAmt = C->getZExtValue();
11329 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11330 (Subtarget->hasInt256() &&
11331 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11332 if (Op.getOpcode() == ISD::SHL)
11333 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11334 DAG.getConstant(ShiftAmt, MVT::i32));
11335 if (Op.getOpcode() == ISD::SRL)
11336 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11337 DAG.getConstant(ShiftAmt, MVT::i32));
11338 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11339 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11340 DAG.getConstant(ShiftAmt, MVT::i32));
11343 if (VT == MVT::v16i8) {
11344 if (Op.getOpcode() == ISD::SHL) {
11345 // Make a large shift.
11346 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11347 DAG.getConstant(ShiftAmt, MVT::i32));
11348 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11349 // Zero out the rightmost bits.
11350 SmallVector<SDValue, 16> V(16,
11351 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11353 return DAG.getNode(ISD::AND, dl, VT, SHL,
11354 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11356 if (Op.getOpcode() == ISD::SRL) {
11357 // Make a large shift.
11358 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11359 DAG.getConstant(ShiftAmt, MVT::i32));
11360 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11361 // Zero out the leftmost bits.
11362 SmallVector<SDValue, 16> V(16,
11363 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11365 return DAG.getNode(ISD::AND, dl, VT, SRL,
11366 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11368 if (Op.getOpcode() == ISD::SRA) {
11369 if (ShiftAmt == 7) {
11370 // R s>> 7 === R s< 0
11371 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11372 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11375 // R s>> a === ((R u>> a) ^ m) - m
11376 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11377 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11379 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11380 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11381 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11384 llvm_unreachable("Unknown shift opcode.");
11387 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11388 if (Op.getOpcode() == ISD::SHL) {
11389 // Make a large shift.
11390 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11391 DAG.getConstant(ShiftAmt, MVT::i32));
11392 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11393 // Zero out the rightmost bits.
11394 SmallVector<SDValue, 32> V(32,
11395 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11397 return DAG.getNode(ISD::AND, dl, VT, SHL,
11398 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11400 if (Op.getOpcode() == ISD::SRL) {
11401 // Make a large shift.
11402 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11403 DAG.getConstant(ShiftAmt, MVT::i32));
11404 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11405 // Zero out the leftmost bits.
11406 SmallVector<SDValue, 32> V(32,
11407 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11409 return DAG.getNode(ISD::AND, dl, VT, SRL,
11410 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11412 if (Op.getOpcode() == ISD::SRA) {
11413 if (ShiftAmt == 7) {
11414 // R s>> 7 === R s< 0
11415 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11416 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11419 // R s>> a === ((R u>> a) ^ m) - m
11420 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11421 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11423 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11424 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11425 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11428 llvm_unreachable("Unknown shift opcode.");
11433 // Lower SHL with variable shift amount.
11434 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11435 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11436 DAG.getConstant(23, MVT::i32));
11438 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11439 Constant *C = ConstantDataVector::get(*Context, CV);
11440 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11441 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11442 MachinePointerInfo::getConstantPool(),
11443 false, false, false, 16);
11445 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11446 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11447 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11448 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11450 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11451 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11454 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11455 DAG.getConstant(5, MVT::i32));
11456 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11458 // Turn 'a' into a mask suitable for VSELECT
11459 SDValue VSelM = DAG.getConstant(0x80, VT);
11460 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11461 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11463 SDValue CM1 = DAG.getConstant(0x0f, VT);
11464 SDValue CM2 = DAG.getConstant(0x3f, VT);
11466 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11467 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11468 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11469 DAG.getConstant(4, MVT::i32), DAG);
11470 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11471 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11474 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11475 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11476 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11478 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11479 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11480 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11481 DAG.getConstant(2, MVT::i32), DAG);
11482 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11483 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11486 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11487 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11488 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11490 // return VSELECT(r, r+r, a);
11491 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11492 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11496 // Decompose 256-bit shifts into smaller 128-bit shifts.
11497 if (VT.is256BitVector()) {
11498 unsigned NumElems = VT.getVectorNumElements();
11499 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11500 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11502 // Extract the two vectors
11503 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11504 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11506 // Recreate the shift amount vectors
11507 SDValue Amt1, Amt2;
11508 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11509 // Constant shift amount
11510 SmallVector<SDValue, 4> Amt1Csts;
11511 SmallVector<SDValue, 4> Amt2Csts;
11512 for (unsigned i = 0; i != NumElems/2; ++i)
11513 Amt1Csts.push_back(Amt->getOperand(i));
11514 for (unsigned i = NumElems/2; i != NumElems; ++i)
11515 Amt2Csts.push_back(Amt->getOperand(i));
11517 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11518 &Amt1Csts[0], NumElems/2);
11519 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11520 &Amt2Csts[0], NumElems/2);
11522 // Variable shift amount
11523 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11524 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11527 // Issue new vector shifts for the smaller types
11528 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11529 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11531 // Concatenate the result back
11532 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11538 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11539 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11540 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11541 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11542 // has only one use.
11543 SDNode *N = Op.getNode();
11544 SDValue LHS = N->getOperand(0);
11545 SDValue RHS = N->getOperand(1);
11546 unsigned BaseOp = 0;
11548 DebugLoc DL = Op.getDebugLoc();
11549 switch (Op.getOpcode()) {
11550 default: llvm_unreachable("Unknown ovf instruction!");
11552 // A subtract of one will be selected as a INC. Note that INC doesn't
11553 // set CF, so we can't do this for UADDO.
11554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11556 BaseOp = X86ISD::INC;
11557 Cond = X86::COND_O;
11560 BaseOp = X86ISD::ADD;
11561 Cond = X86::COND_O;
11564 BaseOp = X86ISD::ADD;
11565 Cond = X86::COND_B;
11568 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11569 // set CF, so we can't do this for USUBO.
11570 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11572 BaseOp = X86ISD::DEC;
11573 Cond = X86::COND_O;
11576 BaseOp = X86ISD::SUB;
11577 Cond = X86::COND_O;
11580 BaseOp = X86ISD::SUB;
11581 Cond = X86::COND_B;
11584 BaseOp = X86ISD::SMUL;
11585 Cond = X86::COND_O;
11587 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11588 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11590 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11593 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11594 DAG.getConstant(X86::COND_O, MVT::i32),
11595 SDValue(Sum.getNode(), 2));
11597 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11601 // Also sets EFLAGS.
11602 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11603 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11606 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11607 DAG.getConstant(Cond, MVT::i32),
11608 SDValue(Sum.getNode(), 1));
11610 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11613 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11614 SelectionDAG &DAG) const {
11615 DebugLoc dl = Op.getDebugLoc();
11616 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11617 EVT VT = Op.getValueType();
11619 if (!Subtarget->hasSSE2() || !VT.isVector())
11622 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11623 ExtraVT.getScalarType().getSizeInBits();
11624 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11626 switch (VT.getSimpleVT().SimpleTy) {
11627 default: return SDValue();
11630 if (!Subtarget->hasFp256())
11632 if (!Subtarget->hasInt256()) {
11633 // needs to be split
11634 unsigned NumElems = VT.getVectorNumElements();
11636 // Extract the LHS vectors
11637 SDValue LHS = Op.getOperand(0);
11638 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11639 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11641 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11642 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11644 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11645 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11646 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11648 SDValue Extra = DAG.getValueType(ExtraVT);
11650 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11651 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11653 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11658 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11659 Op.getOperand(0), ShAmt, DAG);
11660 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11665 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11666 SelectionDAG &DAG) {
11667 DebugLoc dl = Op.getDebugLoc();
11669 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11670 // There isn't any reason to disable it if the target processor supports it.
11671 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11672 SDValue Chain = Op.getOperand(0);
11673 SDValue Zero = DAG.getConstant(0, MVT::i32);
11675 DAG.getRegister(X86::ESP, MVT::i32), // Base
11676 DAG.getTargetConstant(1, MVT::i8), // Scale
11677 DAG.getRegister(0, MVT::i32), // Index
11678 DAG.getTargetConstant(0, MVT::i32), // Disp
11679 DAG.getRegister(0, MVT::i32), // Segment.
11684 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11685 array_lengthof(Ops));
11686 return SDValue(Res, 0);
11689 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11691 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11693 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11694 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11695 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11696 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11698 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11699 if (!Op1 && !Op2 && !Op3 && Op4)
11700 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11702 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11703 if (Op1 && !Op2 && !Op3 && !Op4)
11704 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11706 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11708 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11711 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11712 SelectionDAG &DAG) {
11713 DebugLoc dl = Op.getDebugLoc();
11714 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11715 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11716 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11717 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11719 // The only fence that needs an instruction is a sequentially-consistent
11720 // cross-thread fence.
11721 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11722 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11723 // no-sse2). There isn't any reason to disable it if the target processor
11725 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11726 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11728 SDValue Chain = Op.getOperand(0);
11729 SDValue Zero = DAG.getConstant(0, MVT::i32);
11731 DAG.getRegister(X86::ESP, MVT::i32), // Base
11732 DAG.getTargetConstant(1, MVT::i8), // Scale
11733 DAG.getRegister(0, MVT::i32), // Index
11734 DAG.getTargetConstant(0, MVT::i32), // Disp
11735 DAG.getRegister(0, MVT::i32), // Segment.
11740 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11741 array_lengthof(Ops));
11742 return SDValue(Res, 0);
11745 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11746 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11749 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11750 SelectionDAG &DAG) {
11751 EVT T = Op.getValueType();
11752 DebugLoc DL = Op.getDebugLoc();
11755 switch(T.getSimpleVT().SimpleTy) {
11756 default: llvm_unreachable("Invalid value type!");
11757 case MVT::i8: Reg = X86::AL; size = 1; break;
11758 case MVT::i16: Reg = X86::AX; size = 2; break;
11759 case MVT::i32: Reg = X86::EAX; size = 4; break;
11761 assert(Subtarget->is64Bit() && "Node not type legal!");
11762 Reg = X86::RAX; size = 8;
11765 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11766 Op.getOperand(2), SDValue());
11767 SDValue Ops[] = { cpIn.getValue(0),
11770 DAG.getTargetConstant(size, MVT::i8),
11771 cpIn.getValue(1) };
11772 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11773 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11774 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11777 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11781 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11782 SelectionDAG &DAG) {
11783 assert(Subtarget->is64Bit() && "Result not type legalized?");
11784 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11785 SDValue TheChain = Op.getOperand(0);
11786 DebugLoc dl = Op.getDebugLoc();
11787 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11788 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11789 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11791 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11792 DAG.getConstant(32, MVT::i8));
11794 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11797 return DAG.getMergeValues(Ops, 2, dl);
11800 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11801 EVT SrcVT = Op.getOperand(0).getValueType();
11802 EVT DstVT = Op.getValueType();
11803 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11804 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11805 assert((DstVT == MVT::i64 ||
11806 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11807 "Unexpected custom BITCAST");
11808 // i64 <=> MMX conversions are Legal.
11809 if (SrcVT==MVT::i64 && DstVT.isVector())
11811 if (DstVT==MVT::i64 && SrcVT.isVector())
11813 // MMX <=> MMX conversions are Legal.
11814 if (SrcVT.isVector() && DstVT.isVector())
11816 // All other conversions need to be expanded.
11820 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11821 SDNode *Node = Op.getNode();
11822 DebugLoc dl = Node->getDebugLoc();
11823 EVT T = Node->getValueType(0);
11824 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11825 DAG.getConstant(0, T), Node->getOperand(2));
11826 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11827 cast<AtomicSDNode>(Node)->getMemoryVT(),
11828 Node->getOperand(0),
11829 Node->getOperand(1), negOp,
11830 cast<AtomicSDNode>(Node)->getSrcValue(),
11831 cast<AtomicSDNode>(Node)->getAlignment(),
11832 cast<AtomicSDNode>(Node)->getOrdering(),
11833 cast<AtomicSDNode>(Node)->getSynchScope());
11836 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11837 SDNode *Node = Op.getNode();
11838 DebugLoc dl = Node->getDebugLoc();
11839 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11841 // Convert seq_cst store -> xchg
11842 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11843 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11844 // (The only way to get a 16-byte store is cmpxchg16b)
11845 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11846 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11847 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11848 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11849 cast<AtomicSDNode>(Node)->getMemoryVT(),
11850 Node->getOperand(0),
11851 Node->getOperand(1), Node->getOperand(2),
11852 cast<AtomicSDNode>(Node)->getMemOperand(),
11853 cast<AtomicSDNode>(Node)->getOrdering(),
11854 cast<AtomicSDNode>(Node)->getSynchScope());
11855 return Swap.getValue(1);
11857 // Other atomic stores have a simple pattern.
11861 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11862 EVT VT = Op.getNode()->getValueType(0);
11864 // Let legalize expand this if it isn't a legal type yet.
11865 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11868 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11871 bool ExtraOp = false;
11872 switch (Op.getOpcode()) {
11873 default: llvm_unreachable("Invalid code");
11874 case ISD::ADDC: Opc = X86ISD::ADD; break;
11875 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11876 case ISD::SUBC: Opc = X86ISD::SUB; break;
11877 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11881 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11883 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11884 Op.getOperand(1), Op.getOperand(2));
11887 /// LowerOperation - Provide custom lowering hooks for some operations.
11889 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11890 switch (Op.getOpcode()) {
11891 default: llvm_unreachable("Should not custom lower this!");
11892 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11893 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11894 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11895 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11896 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11897 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11898 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11899 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11900 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11901 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11902 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11903 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11904 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11905 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11906 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11907 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11908 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11909 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11910 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11911 case ISD::SHL_PARTS:
11912 case ISD::SRA_PARTS:
11913 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11914 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11915 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11916 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11917 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
11918 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
11919 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
11920 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11921 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11922 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11923 case ISD::FABS: return LowerFABS(Op, DAG);
11924 case ISD::FNEG: return LowerFNEG(Op, DAG);
11925 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11926 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11927 case ISD::SETCC: return LowerSETCC(Op, DAG);
11928 case ISD::SELECT: return LowerSELECT(Op, DAG);
11929 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11930 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11931 case ISD::VASTART: return LowerVASTART(Op, DAG);
11932 case ISD::VAARG: return LowerVAARG(Op, DAG);
11933 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11934 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11935 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11936 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11937 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11938 case ISD::FRAME_TO_ARGS_OFFSET:
11939 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11940 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11941 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11942 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11943 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11944 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11945 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11946 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11947 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11948 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11949 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11950 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11953 case ISD::SHL: return LowerShift(Op, DAG);
11959 case ISD::UMULO: return LowerXALUO(Op, DAG);
11960 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11961 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11965 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11966 case ISD::ADD: return LowerADD(Op, DAG);
11967 case ISD::SUB: return LowerSUB(Op, DAG);
11971 static void ReplaceATOMIC_LOAD(SDNode *Node,
11972 SmallVectorImpl<SDValue> &Results,
11973 SelectionDAG &DAG) {
11974 DebugLoc dl = Node->getDebugLoc();
11975 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11977 // Convert wide load -> cmpxchg8b/cmpxchg16b
11978 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11979 // (The only way to get a 16-byte load is cmpxchg16b)
11980 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11981 SDValue Zero = DAG.getConstant(0, VT);
11982 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11983 Node->getOperand(0),
11984 Node->getOperand(1), Zero, Zero,
11985 cast<AtomicSDNode>(Node)->getMemOperand(),
11986 cast<AtomicSDNode>(Node)->getOrdering(),
11987 cast<AtomicSDNode>(Node)->getSynchScope());
11988 Results.push_back(Swap.getValue(0));
11989 Results.push_back(Swap.getValue(1));
11993 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11994 SelectionDAG &DAG, unsigned NewOp) {
11995 DebugLoc dl = Node->getDebugLoc();
11996 assert (Node->getValueType(0) == MVT::i64 &&
11997 "Only know how to expand i64 atomics");
11999 SDValue Chain = Node->getOperand(0);
12000 SDValue In1 = Node->getOperand(1);
12001 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12002 Node->getOperand(2), DAG.getIntPtrConstant(0));
12003 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12004 Node->getOperand(2), DAG.getIntPtrConstant(1));
12005 SDValue Ops[] = { Chain, In1, In2L, In2H };
12006 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12008 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12009 cast<MemSDNode>(Node)->getMemOperand());
12010 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12011 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12012 Results.push_back(Result.getValue(2));
12015 /// ReplaceNodeResults - Replace a node with an illegal result type
12016 /// with a new node built out of custom code.
12017 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12018 SmallVectorImpl<SDValue>&Results,
12019 SelectionDAG &DAG) const {
12020 DebugLoc dl = N->getDebugLoc();
12021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12022 switch (N->getOpcode()) {
12024 llvm_unreachable("Do not know how to custom type legalize this operation!");
12025 case ISD::SIGN_EXTEND_INREG:
12030 // We don't want to expand or promote these.
12032 case ISD::FP_TO_SINT:
12033 case ISD::FP_TO_UINT: {
12034 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12036 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12039 std::pair<SDValue,SDValue> Vals =
12040 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12041 SDValue FIST = Vals.first, StackSlot = Vals.second;
12042 if (FIST.getNode() != 0) {
12043 EVT VT = N->getValueType(0);
12044 // Return a load from the stack slot.
12045 if (StackSlot.getNode() != 0)
12046 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12047 MachinePointerInfo(),
12048 false, false, false, 0));
12050 Results.push_back(FIST);
12054 case ISD::UINT_TO_FP: {
12055 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12056 N->getValueType(0) != MVT::v2f32)
12058 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12060 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12062 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12063 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12064 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12065 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12066 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12067 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12070 case ISD::FP_ROUND: {
12071 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12073 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12074 Results.push_back(V);
12077 case ISD::READCYCLECOUNTER: {
12078 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12079 SDValue TheChain = N->getOperand(0);
12080 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12081 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12083 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12085 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12086 SDValue Ops[] = { eax, edx };
12087 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12088 Results.push_back(edx.getValue(1));
12091 case ISD::ATOMIC_CMP_SWAP: {
12092 EVT T = N->getValueType(0);
12093 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12094 bool Regs64bit = T == MVT::i128;
12095 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12096 SDValue cpInL, cpInH;
12097 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12098 DAG.getConstant(0, HalfT));
12099 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12100 DAG.getConstant(1, HalfT));
12101 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12102 Regs64bit ? X86::RAX : X86::EAX,
12104 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12105 Regs64bit ? X86::RDX : X86::EDX,
12106 cpInH, cpInL.getValue(1));
12107 SDValue swapInL, swapInH;
12108 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12109 DAG.getConstant(0, HalfT));
12110 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12111 DAG.getConstant(1, HalfT));
12112 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12113 Regs64bit ? X86::RBX : X86::EBX,
12114 swapInL, cpInH.getValue(1));
12115 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12116 Regs64bit ? X86::RCX : X86::ECX,
12117 swapInH, swapInL.getValue(1));
12118 SDValue Ops[] = { swapInH.getValue(0),
12120 swapInH.getValue(1) };
12121 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12122 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12123 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12124 X86ISD::LCMPXCHG8_DAG;
12125 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12127 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12128 Regs64bit ? X86::RAX : X86::EAX,
12129 HalfT, Result.getValue(1));
12130 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12131 Regs64bit ? X86::RDX : X86::EDX,
12132 HalfT, cpOutL.getValue(2));
12133 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12134 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12135 Results.push_back(cpOutH.getValue(1));
12138 case ISD::ATOMIC_LOAD_ADD:
12139 case ISD::ATOMIC_LOAD_AND:
12140 case ISD::ATOMIC_LOAD_NAND:
12141 case ISD::ATOMIC_LOAD_OR:
12142 case ISD::ATOMIC_LOAD_SUB:
12143 case ISD::ATOMIC_LOAD_XOR:
12144 case ISD::ATOMIC_LOAD_MAX:
12145 case ISD::ATOMIC_LOAD_MIN:
12146 case ISD::ATOMIC_LOAD_UMAX:
12147 case ISD::ATOMIC_LOAD_UMIN:
12148 case ISD::ATOMIC_SWAP: {
12150 switch (N->getOpcode()) {
12151 default: llvm_unreachable("Unexpected opcode");
12152 case ISD::ATOMIC_LOAD_ADD:
12153 Opc = X86ISD::ATOMADD64_DAG;
12155 case ISD::ATOMIC_LOAD_AND:
12156 Opc = X86ISD::ATOMAND64_DAG;
12158 case ISD::ATOMIC_LOAD_NAND:
12159 Opc = X86ISD::ATOMNAND64_DAG;
12161 case ISD::ATOMIC_LOAD_OR:
12162 Opc = X86ISD::ATOMOR64_DAG;
12164 case ISD::ATOMIC_LOAD_SUB:
12165 Opc = X86ISD::ATOMSUB64_DAG;
12167 case ISD::ATOMIC_LOAD_XOR:
12168 Opc = X86ISD::ATOMXOR64_DAG;
12170 case ISD::ATOMIC_LOAD_MAX:
12171 Opc = X86ISD::ATOMMAX64_DAG;
12173 case ISD::ATOMIC_LOAD_MIN:
12174 Opc = X86ISD::ATOMMIN64_DAG;
12176 case ISD::ATOMIC_LOAD_UMAX:
12177 Opc = X86ISD::ATOMUMAX64_DAG;
12179 case ISD::ATOMIC_LOAD_UMIN:
12180 Opc = X86ISD::ATOMUMIN64_DAG;
12182 case ISD::ATOMIC_SWAP:
12183 Opc = X86ISD::ATOMSWAP64_DAG;
12186 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12189 case ISD::ATOMIC_LOAD:
12190 ReplaceATOMIC_LOAD(N, Results, DAG);
12194 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12196 default: return NULL;
12197 case X86ISD::BSF: return "X86ISD::BSF";
12198 case X86ISD::BSR: return "X86ISD::BSR";
12199 case X86ISD::SHLD: return "X86ISD::SHLD";
12200 case X86ISD::SHRD: return "X86ISD::SHRD";
12201 case X86ISD::FAND: return "X86ISD::FAND";
12202 case X86ISD::FOR: return "X86ISD::FOR";
12203 case X86ISD::FXOR: return "X86ISD::FXOR";
12204 case X86ISD::FSRL: return "X86ISD::FSRL";
12205 case X86ISD::FILD: return "X86ISD::FILD";
12206 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12207 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12208 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12209 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12210 case X86ISD::FLD: return "X86ISD::FLD";
12211 case X86ISD::FST: return "X86ISD::FST";
12212 case X86ISD::CALL: return "X86ISD::CALL";
12213 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12214 case X86ISD::BT: return "X86ISD::BT";
12215 case X86ISD::CMP: return "X86ISD::CMP";
12216 case X86ISD::COMI: return "X86ISD::COMI";
12217 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12218 case X86ISD::SETCC: return "X86ISD::SETCC";
12219 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12220 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12221 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12222 case X86ISD::CMOV: return "X86ISD::CMOV";
12223 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12224 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12225 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12226 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12227 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12228 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12229 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12230 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12231 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12232 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12233 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12234 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12235 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12236 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12237 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12238 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12239 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12240 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12241 case X86ISD::HADD: return "X86ISD::HADD";
12242 case X86ISD::HSUB: return "X86ISD::HSUB";
12243 case X86ISD::FHADD: return "X86ISD::FHADD";
12244 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12245 case X86ISD::UMAX: return "X86ISD::UMAX";
12246 case X86ISD::UMIN: return "X86ISD::UMIN";
12247 case X86ISD::SMAX: return "X86ISD::SMAX";
12248 case X86ISD::SMIN: return "X86ISD::SMIN";
12249 case X86ISD::FMAX: return "X86ISD::FMAX";
12250 case X86ISD::FMIN: return "X86ISD::FMIN";
12251 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12252 case X86ISD::FMINC: return "X86ISD::FMINC";
12253 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12254 case X86ISD::FRCP: return "X86ISD::FRCP";
12255 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12256 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12257 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12258 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12259 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12260 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12261 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12262 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12263 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12264 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12265 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12266 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12267 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12268 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12269 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12270 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12271 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12272 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12273 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12274 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12275 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12276 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12277 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12278 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12279 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12280 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12281 case X86ISD::VSHL: return "X86ISD::VSHL";
12282 case X86ISD::VSRL: return "X86ISD::VSRL";
12283 case X86ISD::VSRA: return "X86ISD::VSRA";
12284 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12285 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12286 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12287 case X86ISD::CMPP: return "X86ISD::CMPP";
12288 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12289 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12290 case X86ISD::ADD: return "X86ISD::ADD";
12291 case X86ISD::SUB: return "X86ISD::SUB";
12292 case X86ISD::ADC: return "X86ISD::ADC";
12293 case X86ISD::SBB: return "X86ISD::SBB";
12294 case X86ISD::SMUL: return "X86ISD::SMUL";
12295 case X86ISD::UMUL: return "X86ISD::UMUL";
12296 case X86ISD::INC: return "X86ISD::INC";
12297 case X86ISD::DEC: return "X86ISD::DEC";
12298 case X86ISD::OR: return "X86ISD::OR";
12299 case X86ISD::XOR: return "X86ISD::XOR";
12300 case X86ISD::AND: return "X86ISD::AND";
12301 case X86ISD::BLSI: return "X86ISD::BLSI";
12302 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12303 case X86ISD::BLSR: return "X86ISD::BLSR";
12304 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12305 case X86ISD::PTEST: return "X86ISD::PTEST";
12306 case X86ISD::TESTP: return "X86ISD::TESTP";
12307 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12308 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12309 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12310 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12311 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12312 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12313 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12314 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12315 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12316 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12317 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12318 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12319 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12320 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12321 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12322 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12323 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12324 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12325 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12326 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12327 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12328 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12329 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12330 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12331 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12332 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12333 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12334 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12335 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12336 case X86ISD::SAHF: return "X86ISD::SAHF";
12337 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12338 case X86ISD::FMADD: return "X86ISD::FMADD";
12339 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12340 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12341 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12342 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12343 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12344 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12345 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12349 // isLegalAddressingMode - Return true if the addressing mode represented
12350 // by AM is legal for this target, for a load/store of the specified type.
12351 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12353 // X86 supports extremely general addressing modes.
12354 CodeModel::Model M = getTargetMachine().getCodeModel();
12355 Reloc::Model R = getTargetMachine().getRelocationModel();
12357 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12358 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12363 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12365 // If a reference to this global requires an extra load, we can't fold it.
12366 if (isGlobalStubReference(GVFlags))
12369 // If BaseGV requires a register for the PIC base, we cannot also have a
12370 // BaseReg specified.
12371 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12374 // If lower 4G is not available, then we must use rip-relative addressing.
12375 if ((M != CodeModel::Small || R != Reloc::Static) &&
12376 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12380 switch (AM.Scale) {
12386 // These scales always work.
12391 // These scales are formed with basereg+scalereg. Only accept if there is
12396 default: // Other stuff never works.
12403 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12404 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12406 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12407 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12408 if (NumBits1 <= NumBits2)
12413 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12414 return Imm == (int32_t)Imm;
12417 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12418 // Can also use sub to handle negated immediates.
12419 return Imm == (int32_t)Imm;
12422 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12423 if (!VT1.isInteger() || !VT2.isInteger())
12425 unsigned NumBits1 = VT1.getSizeInBits();
12426 unsigned NumBits2 = VT2.getSizeInBits();
12427 if (NumBits1 <= NumBits2)
12432 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12433 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12434 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12437 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12438 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12439 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12442 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12443 EVT VT1 = Val.getValueType();
12444 if (isZExtFree(VT1, VT2))
12447 if (Val.getOpcode() != ISD::LOAD)
12450 if (!VT1.isSimple() || !VT1.isInteger() ||
12451 !VT2.isSimple() || !VT2.isInteger())
12454 switch (VT1.getSimpleVT().SimpleTy) {
12459 // X86 has 8, 16, and 32-bit zero-extending loads.
12466 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12467 // i16 instructions are longer (0x66 prefix) and potentially slower.
12468 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12471 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12472 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12473 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12474 /// are assumed to be legal.
12476 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12478 // Very little shuffling can be done for 64-bit vectors right now.
12479 if (VT.getSizeInBits() == 64)
12482 // FIXME: pshufb, blends, shifts.
12483 return (VT.getVectorNumElements() == 2 ||
12484 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12485 isMOVLMask(M, VT) ||
12486 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12487 isPSHUFDMask(M, VT) ||
12488 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12489 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12490 isPALIGNRMask(M, VT, Subtarget) ||
12491 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12492 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12493 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12494 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12498 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12500 unsigned NumElts = VT.getVectorNumElements();
12501 // FIXME: This collection of masks seems suspect.
12504 if (NumElts == 4 && VT.is128BitVector()) {
12505 return (isMOVLMask(Mask, VT) ||
12506 isCommutedMOVLMask(Mask, VT, true) ||
12507 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12508 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12513 //===----------------------------------------------------------------------===//
12514 // X86 Scheduler Hooks
12515 //===----------------------------------------------------------------------===//
12517 /// Utility function to emit xbegin specifying the start of an RTM region.
12518 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12519 const TargetInstrInfo *TII) {
12520 DebugLoc DL = MI->getDebugLoc();
12522 const BasicBlock *BB = MBB->getBasicBlock();
12523 MachineFunction::iterator I = MBB;
12526 // For the v = xbegin(), we generate
12537 MachineBasicBlock *thisMBB = MBB;
12538 MachineFunction *MF = MBB->getParent();
12539 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12540 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12541 MF->insert(I, mainMBB);
12542 MF->insert(I, sinkMBB);
12544 // Transfer the remainder of BB and its successor edges to sinkMBB.
12545 sinkMBB->splice(sinkMBB->begin(), MBB,
12546 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12547 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12551 // # fallthrough to mainMBB
12552 // # abortion to sinkMBB
12553 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12554 thisMBB->addSuccessor(mainMBB);
12555 thisMBB->addSuccessor(sinkMBB);
12559 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12560 mainMBB->addSuccessor(sinkMBB);
12563 // EAX is live into the sinkMBB
12564 sinkMBB->addLiveIn(X86::EAX);
12565 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12566 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12569 MI->eraseFromParent();
12573 // Get CMPXCHG opcode for the specified data type.
12574 static unsigned getCmpXChgOpcode(EVT VT) {
12575 switch (VT.getSimpleVT().SimpleTy) {
12576 case MVT::i8: return X86::LCMPXCHG8;
12577 case MVT::i16: return X86::LCMPXCHG16;
12578 case MVT::i32: return X86::LCMPXCHG32;
12579 case MVT::i64: return X86::LCMPXCHG64;
12583 llvm_unreachable("Invalid operand size!");
12586 // Get LOAD opcode for the specified data type.
12587 static unsigned getLoadOpcode(EVT VT) {
12588 switch (VT.getSimpleVT().SimpleTy) {
12589 case MVT::i8: return X86::MOV8rm;
12590 case MVT::i16: return X86::MOV16rm;
12591 case MVT::i32: return X86::MOV32rm;
12592 case MVT::i64: return X86::MOV64rm;
12596 llvm_unreachable("Invalid operand size!");
12599 // Get opcode of the non-atomic one from the specified atomic instruction.
12600 static unsigned getNonAtomicOpcode(unsigned Opc) {
12602 case X86::ATOMAND8: return X86::AND8rr;
12603 case X86::ATOMAND16: return X86::AND16rr;
12604 case X86::ATOMAND32: return X86::AND32rr;
12605 case X86::ATOMAND64: return X86::AND64rr;
12606 case X86::ATOMOR8: return X86::OR8rr;
12607 case X86::ATOMOR16: return X86::OR16rr;
12608 case X86::ATOMOR32: return X86::OR32rr;
12609 case X86::ATOMOR64: return X86::OR64rr;
12610 case X86::ATOMXOR8: return X86::XOR8rr;
12611 case X86::ATOMXOR16: return X86::XOR16rr;
12612 case X86::ATOMXOR32: return X86::XOR32rr;
12613 case X86::ATOMXOR64: return X86::XOR64rr;
12615 llvm_unreachable("Unhandled atomic-load-op opcode!");
12618 // Get opcode of the non-atomic one from the specified atomic instruction with
12620 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12621 unsigned &ExtraOpc) {
12623 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12624 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12625 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12626 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12627 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12628 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12629 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12630 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12631 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12632 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12633 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12634 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12635 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12636 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12637 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12638 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12639 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12640 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12641 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12642 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12644 llvm_unreachable("Unhandled atomic-load-op opcode!");
12647 // Get opcode of the non-atomic one from the specified atomic instruction for
12648 // 64-bit data type on 32-bit target.
12649 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12651 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12652 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12653 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12654 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12655 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12656 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12657 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12658 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12659 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12660 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12662 llvm_unreachable("Unhandled atomic-load-op opcode!");
12665 // Get opcode of the non-atomic one from the specified atomic instruction for
12666 // 64-bit data type on 32-bit target with extra opcode.
12667 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12669 unsigned &ExtraOpc) {
12671 case X86::ATOMNAND6432:
12672 ExtraOpc = X86::NOT32r;
12673 HiOpc = X86::AND32rr;
12674 return X86::AND32rr;
12676 llvm_unreachable("Unhandled atomic-load-op opcode!");
12679 // Get pseudo CMOV opcode from the specified data type.
12680 static unsigned getPseudoCMOVOpc(EVT VT) {
12681 switch (VT.getSimpleVT().SimpleTy) {
12682 case MVT::i8: return X86::CMOV_GR8;
12683 case MVT::i16: return X86::CMOV_GR16;
12684 case MVT::i32: return X86::CMOV_GR32;
12688 llvm_unreachable("Unknown CMOV opcode!");
12691 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12692 // They will be translated into a spin-loop or compare-exchange loop from
12695 // dst = atomic-fetch-op MI.addr, MI.val
12701 // EAX = LOAD MI.addr
12703 // t1 = OP MI.val, EAX
12704 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12709 MachineBasicBlock *
12710 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12711 MachineBasicBlock *MBB) const {
12712 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12713 DebugLoc DL = MI->getDebugLoc();
12715 MachineFunction *MF = MBB->getParent();
12716 MachineRegisterInfo &MRI = MF->getRegInfo();
12718 const BasicBlock *BB = MBB->getBasicBlock();
12719 MachineFunction::iterator I = MBB;
12722 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12723 "Unexpected number of operands");
12725 assert(MI->hasOneMemOperand() &&
12726 "Expected atomic-load-op to have one memoperand");
12728 // Memory Reference
12729 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12730 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12732 unsigned DstReg, SrcReg;
12733 unsigned MemOpndSlot;
12735 unsigned CurOp = 0;
12737 DstReg = MI->getOperand(CurOp++).getReg();
12738 MemOpndSlot = CurOp;
12739 CurOp += X86::AddrNumOperands;
12740 SrcReg = MI->getOperand(CurOp++).getReg();
12742 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12743 MVT::SimpleValueType VT = *RC->vt_begin();
12744 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12746 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12747 unsigned LOADOpc = getLoadOpcode(VT);
12749 // For the atomic load-arith operator, we generate
12752 // EAX = LOAD [MI.addr]
12754 // t1 = OP MI.val, EAX
12755 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12759 MachineBasicBlock *thisMBB = MBB;
12760 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12761 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12762 MF->insert(I, mainMBB);
12763 MF->insert(I, sinkMBB);
12765 MachineInstrBuilder MIB;
12767 // Transfer the remainder of BB and its successor edges to sinkMBB.
12768 sinkMBB->splice(sinkMBB->begin(), MBB,
12769 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12770 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12773 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12774 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12775 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12776 MIB.setMemRefs(MMOBegin, MMOEnd);
12778 thisMBB->addSuccessor(mainMBB);
12781 MachineBasicBlock *origMainMBB = mainMBB;
12782 mainMBB->addLiveIn(AccPhyReg);
12784 // Copy AccPhyReg as it is used more than once.
12785 unsigned AccReg = MRI.createVirtualRegister(RC);
12786 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12787 .addReg(AccPhyReg);
12789 unsigned t1 = MRI.createVirtualRegister(RC);
12790 unsigned Opc = MI->getOpcode();
12793 llvm_unreachable("Unhandled atomic-load-op opcode!");
12794 case X86::ATOMAND8:
12795 case X86::ATOMAND16:
12796 case X86::ATOMAND32:
12797 case X86::ATOMAND64:
12799 case X86::ATOMOR16:
12800 case X86::ATOMOR32:
12801 case X86::ATOMOR64:
12802 case X86::ATOMXOR8:
12803 case X86::ATOMXOR16:
12804 case X86::ATOMXOR32:
12805 case X86::ATOMXOR64: {
12806 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12807 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12811 case X86::ATOMNAND8:
12812 case X86::ATOMNAND16:
12813 case X86::ATOMNAND32:
12814 case X86::ATOMNAND64: {
12815 unsigned t2 = MRI.createVirtualRegister(RC);
12817 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12818 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12820 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12823 case X86::ATOMMAX8:
12824 case X86::ATOMMAX16:
12825 case X86::ATOMMAX32:
12826 case X86::ATOMMAX64:
12827 case X86::ATOMMIN8:
12828 case X86::ATOMMIN16:
12829 case X86::ATOMMIN32:
12830 case X86::ATOMMIN64:
12831 case X86::ATOMUMAX8:
12832 case X86::ATOMUMAX16:
12833 case X86::ATOMUMAX32:
12834 case X86::ATOMUMAX64:
12835 case X86::ATOMUMIN8:
12836 case X86::ATOMUMIN16:
12837 case X86::ATOMUMIN32:
12838 case X86::ATOMUMIN64: {
12840 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12842 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12846 if (Subtarget->hasCMov()) {
12847 if (VT != MVT::i8) {
12849 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12853 // Promote i8 to i32 to use CMOV32
12854 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12855 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12856 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12857 unsigned t2 = MRI.createVirtualRegister(RC32);
12859 unsigned Undef = MRI.createVirtualRegister(RC32);
12860 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12862 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12865 .addImm(X86::sub_8bit);
12866 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12869 .addImm(X86::sub_8bit);
12871 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12875 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12876 .addReg(t2, 0, X86::sub_8bit);
12879 // Use pseudo select and lower them.
12880 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12881 "Invalid atomic-load-op transformation!");
12882 unsigned SelOpc = getPseudoCMOVOpc(VT);
12883 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12884 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12885 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12886 .addReg(SrcReg).addReg(AccReg)
12888 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12894 // Copy AccPhyReg back from virtual register.
12895 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12898 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12899 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12900 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12902 MIB.setMemRefs(MMOBegin, MMOEnd);
12904 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12906 mainMBB->addSuccessor(origMainMBB);
12907 mainMBB->addSuccessor(sinkMBB);
12910 sinkMBB->addLiveIn(AccPhyReg);
12912 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12913 TII->get(TargetOpcode::COPY), DstReg)
12914 .addReg(AccPhyReg);
12916 MI->eraseFromParent();
12920 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12921 // instructions. They will be translated into a spin-loop or compare-exchange
12925 // dst = atomic-fetch-op MI.addr, MI.val
12931 // EAX = LOAD [MI.addr + 0]
12932 // EDX = LOAD [MI.addr + 4]
12934 // EBX = OP MI.val.lo, EAX
12935 // ECX = OP MI.val.hi, EDX
12936 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12941 MachineBasicBlock *
12942 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12943 MachineBasicBlock *MBB) const {
12944 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12945 DebugLoc DL = MI->getDebugLoc();
12947 MachineFunction *MF = MBB->getParent();
12948 MachineRegisterInfo &MRI = MF->getRegInfo();
12950 const BasicBlock *BB = MBB->getBasicBlock();
12951 MachineFunction::iterator I = MBB;
12954 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12955 "Unexpected number of operands");
12957 assert(MI->hasOneMemOperand() &&
12958 "Expected atomic-load-op32 to have one memoperand");
12960 // Memory Reference
12961 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12962 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12964 unsigned DstLoReg, DstHiReg;
12965 unsigned SrcLoReg, SrcHiReg;
12966 unsigned MemOpndSlot;
12968 unsigned CurOp = 0;
12970 DstLoReg = MI->getOperand(CurOp++).getReg();
12971 DstHiReg = MI->getOperand(CurOp++).getReg();
12972 MemOpndSlot = CurOp;
12973 CurOp += X86::AddrNumOperands;
12974 SrcLoReg = MI->getOperand(CurOp++).getReg();
12975 SrcHiReg = MI->getOperand(CurOp++).getReg();
12977 const TargetRegisterClass *RC = &X86::GR32RegClass;
12978 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12980 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12981 unsigned LOADOpc = X86::MOV32rm;
12983 // For the atomic load-arith operator, we generate
12986 // EAX = LOAD [MI.addr + 0]
12987 // EDX = LOAD [MI.addr + 4]
12989 // EBX = OP MI.vallo, EAX
12990 // ECX = OP MI.valhi, EDX
12991 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12995 MachineBasicBlock *thisMBB = MBB;
12996 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12997 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12998 MF->insert(I, mainMBB);
12999 MF->insert(I, sinkMBB);
13001 MachineInstrBuilder MIB;
13003 // Transfer the remainder of BB and its successor edges to sinkMBB.
13004 sinkMBB->splice(sinkMBB->begin(), MBB,
13005 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13006 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13010 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13011 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13012 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13013 MIB.setMemRefs(MMOBegin, MMOEnd);
13015 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13016 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13017 if (i == X86::AddrDisp)
13018 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13020 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13022 MIB.setMemRefs(MMOBegin, MMOEnd);
13024 thisMBB->addSuccessor(mainMBB);
13027 MachineBasicBlock *origMainMBB = mainMBB;
13028 mainMBB->addLiveIn(X86::EAX);
13029 mainMBB->addLiveIn(X86::EDX);
13031 // Copy EDX:EAX as they are used more than once.
13032 unsigned LoReg = MRI.createVirtualRegister(RC);
13033 unsigned HiReg = MRI.createVirtualRegister(RC);
13034 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13035 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13037 unsigned t1L = MRI.createVirtualRegister(RC);
13038 unsigned t1H = MRI.createVirtualRegister(RC);
13040 unsigned Opc = MI->getOpcode();
13043 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13044 case X86::ATOMAND6432:
13045 case X86::ATOMOR6432:
13046 case X86::ATOMXOR6432:
13047 case X86::ATOMADD6432:
13048 case X86::ATOMSUB6432: {
13050 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13051 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13052 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13055 case X86::ATOMNAND6432: {
13056 unsigned HiOpc, NOTOpc;
13057 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13058 unsigned t2L = MRI.createVirtualRegister(RC);
13059 unsigned t2H = MRI.createVirtualRegister(RC);
13060 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13061 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13062 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13063 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13066 case X86::ATOMMAX6432:
13067 case X86::ATOMMIN6432:
13068 case X86::ATOMUMAX6432:
13069 case X86::ATOMUMIN6432: {
13071 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13072 unsigned cL = MRI.createVirtualRegister(RC8);
13073 unsigned cH = MRI.createVirtualRegister(RC8);
13074 unsigned cL32 = MRI.createVirtualRegister(RC);
13075 unsigned cH32 = MRI.createVirtualRegister(RC);
13076 unsigned cc = MRI.createVirtualRegister(RC);
13077 // cl := cmp src_lo, lo
13078 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13079 .addReg(SrcLoReg).addReg(LoReg);
13080 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13081 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13082 // ch := cmp src_hi, hi
13083 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13084 .addReg(SrcHiReg).addReg(HiReg);
13085 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13086 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13087 // cc := if (src_hi == hi) ? cl : ch;
13088 if (Subtarget->hasCMov()) {
13089 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13090 .addReg(cH32).addReg(cL32);
13092 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13093 .addReg(cH32).addReg(cL32)
13094 .addImm(X86::COND_E);
13095 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13097 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13098 if (Subtarget->hasCMov()) {
13099 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13100 .addReg(SrcLoReg).addReg(LoReg);
13101 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13102 .addReg(SrcHiReg).addReg(HiReg);
13104 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13105 .addReg(SrcLoReg).addReg(LoReg)
13106 .addImm(X86::COND_NE);
13107 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13108 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13109 .addReg(SrcHiReg).addReg(HiReg)
13110 .addImm(X86::COND_NE);
13111 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13115 case X86::ATOMSWAP6432: {
13117 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13118 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13119 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13124 // Copy EDX:EAX back from HiReg:LoReg
13125 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13126 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13127 // Copy ECX:EBX from t1H:t1L
13128 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13129 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13131 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13132 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13133 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13134 MIB.setMemRefs(MMOBegin, MMOEnd);
13136 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13138 mainMBB->addSuccessor(origMainMBB);
13139 mainMBB->addSuccessor(sinkMBB);
13142 sinkMBB->addLiveIn(X86::EAX);
13143 sinkMBB->addLiveIn(X86::EDX);
13145 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13146 TII->get(TargetOpcode::COPY), DstLoReg)
13148 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13149 TII->get(TargetOpcode::COPY), DstHiReg)
13152 MI->eraseFromParent();
13156 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13157 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13158 // in the .td file.
13159 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13160 const TargetInstrInfo *TII) {
13162 switch (MI->getOpcode()) {
13163 default: llvm_unreachable("illegal opcode!");
13164 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13165 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13166 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13167 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13168 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13169 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13170 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13171 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13174 DebugLoc dl = MI->getDebugLoc();
13175 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13177 unsigned NumArgs = MI->getNumOperands();
13178 for (unsigned i = 1; i < NumArgs; ++i) {
13179 MachineOperand &Op = MI->getOperand(i);
13180 if (!(Op.isReg() && Op.isImplicit()))
13181 MIB.addOperand(Op);
13183 if (MI->hasOneMemOperand())
13184 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13186 BuildMI(*BB, MI, dl,
13187 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13188 .addReg(X86::XMM0);
13190 MI->eraseFromParent();
13194 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13195 // defs in an instruction pattern
13196 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13197 const TargetInstrInfo *TII) {
13199 switch (MI->getOpcode()) {
13200 default: llvm_unreachable("illegal opcode!");
13201 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13202 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13203 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13204 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13205 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13206 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13207 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13208 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13211 DebugLoc dl = MI->getDebugLoc();
13212 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13214 unsigned NumArgs = MI->getNumOperands(); // remove the results
13215 for (unsigned i = 1; i < NumArgs; ++i) {
13216 MachineOperand &Op = MI->getOperand(i);
13217 if (!(Op.isReg() && Op.isImplicit()))
13218 MIB.addOperand(Op);
13220 if (MI->hasOneMemOperand())
13221 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13223 BuildMI(*BB, MI, dl,
13224 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13227 MI->eraseFromParent();
13231 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13232 const TargetInstrInfo *TII,
13233 const X86Subtarget* Subtarget) {
13234 DebugLoc dl = MI->getDebugLoc();
13236 // Address into RAX/EAX, other two args into ECX, EDX.
13237 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13238 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13239 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13240 for (int i = 0; i < X86::AddrNumOperands; ++i)
13241 MIB.addOperand(MI->getOperand(i));
13243 unsigned ValOps = X86::AddrNumOperands;
13244 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13245 .addReg(MI->getOperand(ValOps).getReg());
13246 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13247 .addReg(MI->getOperand(ValOps+1).getReg());
13249 // The instruction doesn't actually take any operands though.
13250 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13252 MI->eraseFromParent(); // The pseudo is gone now.
13256 MachineBasicBlock *
13257 X86TargetLowering::EmitVAARG64WithCustomInserter(
13259 MachineBasicBlock *MBB) const {
13260 // Emit va_arg instruction on X86-64.
13262 // Operands to this pseudo-instruction:
13263 // 0 ) Output : destination address (reg)
13264 // 1-5) Input : va_list address (addr, i64mem)
13265 // 6 ) ArgSize : Size (in bytes) of vararg type
13266 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13267 // 8 ) Align : Alignment of type
13268 // 9 ) EFLAGS (implicit-def)
13270 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13271 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13273 unsigned DestReg = MI->getOperand(0).getReg();
13274 MachineOperand &Base = MI->getOperand(1);
13275 MachineOperand &Scale = MI->getOperand(2);
13276 MachineOperand &Index = MI->getOperand(3);
13277 MachineOperand &Disp = MI->getOperand(4);
13278 MachineOperand &Segment = MI->getOperand(5);
13279 unsigned ArgSize = MI->getOperand(6).getImm();
13280 unsigned ArgMode = MI->getOperand(7).getImm();
13281 unsigned Align = MI->getOperand(8).getImm();
13283 // Memory Reference
13284 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13285 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13286 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13288 // Machine Information
13289 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13290 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13291 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13292 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13293 DebugLoc DL = MI->getDebugLoc();
13295 // struct va_list {
13298 // i64 overflow_area (address)
13299 // i64 reg_save_area (address)
13301 // sizeof(va_list) = 24
13302 // alignment(va_list) = 8
13304 unsigned TotalNumIntRegs = 6;
13305 unsigned TotalNumXMMRegs = 8;
13306 bool UseGPOffset = (ArgMode == 1);
13307 bool UseFPOffset = (ArgMode == 2);
13308 unsigned MaxOffset = TotalNumIntRegs * 8 +
13309 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13311 /* Align ArgSize to a multiple of 8 */
13312 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13313 bool NeedsAlign = (Align > 8);
13315 MachineBasicBlock *thisMBB = MBB;
13316 MachineBasicBlock *overflowMBB;
13317 MachineBasicBlock *offsetMBB;
13318 MachineBasicBlock *endMBB;
13320 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13321 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13322 unsigned OffsetReg = 0;
13324 if (!UseGPOffset && !UseFPOffset) {
13325 // If we only pull from the overflow region, we don't create a branch.
13326 // We don't need to alter control flow.
13327 OffsetDestReg = 0; // unused
13328 OverflowDestReg = DestReg;
13331 overflowMBB = thisMBB;
13334 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13335 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13336 // If not, pull from overflow_area. (branch to overflowMBB)
13341 // offsetMBB overflowMBB
13346 // Registers for the PHI in endMBB
13347 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13348 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13350 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13351 MachineFunction *MF = MBB->getParent();
13352 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13353 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13354 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13356 MachineFunction::iterator MBBIter = MBB;
13359 // Insert the new basic blocks
13360 MF->insert(MBBIter, offsetMBB);
13361 MF->insert(MBBIter, overflowMBB);
13362 MF->insert(MBBIter, endMBB);
13364 // Transfer the remainder of MBB and its successor edges to endMBB.
13365 endMBB->splice(endMBB->begin(), thisMBB,
13366 llvm::next(MachineBasicBlock::iterator(MI)),
13368 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13370 // Make offsetMBB and overflowMBB successors of thisMBB
13371 thisMBB->addSuccessor(offsetMBB);
13372 thisMBB->addSuccessor(overflowMBB);
13374 // endMBB is a successor of both offsetMBB and overflowMBB
13375 offsetMBB->addSuccessor(endMBB);
13376 overflowMBB->addSuccessor(endMBB);
13378 // Load the offset value into a register
13379 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13380 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13384 .addDisp(Disp, UseFPOffset ? 4 : 0)
13385 .addOperand(Segment)
13386 .setMemRefs(MMOBegin, MMOEnd);
13388 // Check if there is enough room left to pull this argument.
13389 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13391 .addImm(MaxOffset + 8 - ArgSizeA8);
13393 // Branch to "overflowMBB" if offset >= max
13394 // Fall through to "offsetMBB" otherwise
13395 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13396 .addMBB(overflowMBB);
13399 // In offsetMBB, emit code to use the reg_save_area.
13401 assert(OffsetReg != 0);
13403 // Read the reg_save_area address.
13404 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13405 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13410 .addOperand(Segment)
13411 .setMemRefs(MMOBegin, MMOEnd);
13413 // Zero-extend the offset
13414 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13415 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13418 .addImm(X86::sub_32bit);
13420 // Add the offset to the reg_save_area to get the final address.
13421 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13422 .addReg(OffsetReg64)
13423 .addReg(RegSaveReg);
13425 // Compute the offset for the next argument
13426 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13427 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13429 .addImm(UseFPOffset ? 16 : 8);
13431 // Store it back into the va_list.
13432 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13436 .addDisp(Disp, UseFPOffset ? 4 : 0)
13437 .addOperand(Segment)
13438 .addReg(NextOffsetReg)
13439 .setMemRefs(MMOBegin, MMOEnd);
13442 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13447 // Emit code to use overflow area
13450 // Load the overflow_area address into a register.
13451 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13452 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13457 .addOperand(Segment)
13458 .setMemRefs(MMOBegin, MMOEnd);
13460 // If we need to align it, do so. Otherwise, just copy the address
13461 // to OverflowDestReg.
13463 // Align the overflow address
13464 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13465 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13467 // aligned_addr = (addr + (align-1)) & ~(align-1)
13468 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13469 .addReg(OverflowAddrReg)
13472 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13474 .addImm(~(uint64_t)(Align-1));
13476 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13477 .addReg(OverflowAddrReg);
13480 // Compute the next overflow address after this argument.
13481 // (the overflow address should be kept 8-byte aligned)
13482 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13483 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13484 .addReg(OverflowDestReg)
13485 .addImm(ArgSizeA8);
13487 // Store the new overflow address.
13488 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13493 .addOperand(Segment)
13494 .addReg(NextAddrReg)
13495 .setMemRefs(MMOBegin, MMOEnd);
13497 // If we branched, emit the PHI to the front of endMBB.
13499 BuildMI(*endMBB, endMBB->begin(), DL,
13500 TII->get(X86::PHI), DestReg)
13501 .addReg(OffsetDestReg).addMBB(offsetMBB)
13502 .addReg(OverflowDestReg).addMBB(overflowMBB);
13505 // Erase the pseudo instruction
13506 MI->eraseFromParent();
13511 MachineBasicBlock *
13512 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13514 MachineBasicBlock *MBB) const {
13515 // Emit code to save XMM registers to the stack. The ABI says that the
13516 // number of registers to save is given in %al, so it's theoretically
13517 // possible to do an indirect jump trick to avoid saving all of them,
13518 // however this code takes a simpler approach and just executes all
13519 // of the stores if %al is non-zero. It's less code, and it's probably
13520 // easier on the hardware branch predictor, and stores aren't all that
13521 // expensive anyway.
13523 // Create the new basic blocks. One block contains all the XMM stores,
13524 // and one block is the final destination regardless of whether any
13525 // stores were performed.
13526 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13527 MachineFunction *F = MBB->getParent();
13528 MachineFunction::iterator MBBIter = MBB;
13530 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13531 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13532 F->insert(MBBIter, XMMSaveMBB);
13533 F->insert(MBBIter, EndMBB);
13535 // Transfer the remainder of MBB and its successor edges to EndMBB.
13536 EndMBB->splice(EndMBB->begin(), MBB,
13537 llvm::next(MachineBasicBlock::iterator(MI)),
13539 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13541 // The original block will now fall through to the XMM save block.
13542 MBB->addSuccessor(XMMSaveMBB);
13543 // The XMMSaveMBB will fall through to the end block.
13544 XMMSaveMBB->addSuccessor(EndMBB);
13546 // Now add the instructions.
13547 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13548 DebugLoc DL = MI->getDebugLoc();
13550 unsigned CountReg = MI->getOperand(0).getReg();
13551 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13552 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13554 if (!Subtarget->isTargetWin64()) {
13555 // If %al is 0, branch around the XMM save block.
13556 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13557 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13558 MBB->addSuccessor(EndMBB);
13561 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13562 // In the XMM save block, save all the XMM argument registers.
13563 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13564 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13565 MachineMemOperand *MMO =
13566 F->getMachineMemOperand(
13567 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13568 MachineMemOperand::MOStore,
13569 /*Size=*/16, /*Align=*/16);
13570 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13571 .addFrameIndex(RegSaveFrameIndex)
13572 .addImm(/*Scale=*/1)
13573 .addReg(/*IndexReg=*/0)
13574 .addImm(/*Disp=*/Offset)
13575 .addReg(/*Segment=*/0)
13576 .addReg(MI->getOperand(i).getReg())
13577 .addMemOperand(MMO);
13580 MI->eraseFromParent(); // The pseudo instruction is gone now.
13585 // The EFLAGS operand of SelectItr might be missing a kill marker
13586 // because there were multiple uses of EFLAGS, and ISel didn't know
13587 // which to mark. Figure out whether SelectItr should have had a
13588 // kill marker, and set it if it should. Returns the correct kill
13590 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13591 MachineBasicBlock* BB,
13592 const TargetRegisterInfo* TRI) {
13593 // Scan forward through BB for a use/def of EFLAGS.
13594 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13595 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13596 const MachineInstr& mi = *miI;
13597 if (mi.readsRegister(X86::EFLAGS))
13599 if (mi.definesRegister(X86::EFLAGS))
13600 break; // Should have kill-flag - update below.
13603 // If we hit the end of the block, check whether EFLAGS is live into a
13605 if (miI == BB->end()) {
13606 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13607 sEnd = BB->succ_end();
13608 sItr != sEnd; ++sItr) {
13609 MachineBasicBlock* succ = *sItr;
13610 if (succ->isLiveIn(X86::EFLAGS))
13615 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13616 // out. SelectMI should have a kill flag on EFLAGS.
13617 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13621 MachineBasicBlock *
13622 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13623 MachineBasicBlock *BB) const {
13624 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13625 DebugLoc DL = MI->getDebugLoc();
13627 // To "insert" a SELECT_CC instruction, we actually have to insert the
13628 // diamond control-flow pattern. The incoming instruction knows the
13629 // destination vreg to set, the condition code register to branch on, the
13630 // true/false values to select between, and a branch opcode to use.
13631 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13632 MachineFunction::iterator It = BB;
13638 // cmpTY ccX, r1, r2
13640 // fallthrough --> copy0MBB
13641 MachineBasicBlock *thisMBB = BB;
13642 MachineFunction *F = BB->getParent();
13643 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13644 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13645 F->insert(It, copy0MBB);
13646 F->insert(It, sinkMBB);
13648 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13649 // live into the sink and copy blocks.
13650 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13651 if (!MI->killsRegister(X86::EFLAGS) &&
13652 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13653 copy0MBB->addLiveIn(X86::EFLAGS);
13654 sinkMBB->addLiveIn(X86::EFLAGS);
13657 // Transfer the remainder of BB and its successor edges to sinkMBB.
13658 sinkMBB->splice(sinkMBB->begin(), BB,
13659 llvm::next(MachineBasicBlock::iterator(MI)),
13661 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13663 // Add the true and fallthrough blocks as its successors.
13664 BB->addSuccessor(copy0MBB);
13665 BB->addSuccessor(sinkMBB);
13667 // Create the conditional branch instruction.
13669 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13670 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13673 // %FalseValue = ...
13674 // # fallthrough to sinkMBB
13675 copy0MBB->addSuccessor(sinkMBB);
13678 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13680 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13681 TII->get(X86::PHI), MI->getOperand(0).getReg())
13682 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13683 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13685 MI->eraseFromParent(); // The pseudo instruction is gone now.
13689 MachineBasicBlock *
13690 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13691 bool Is64Bit) const {
13692 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13693 DebugLoc DL = MI->getDebugLoc();
13694 MachineFunction *MF = BB->getParent();
13695 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13697 assert(getTargetMachine().Options.EnableSegmentedStacks);
13699 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13700 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13703 // ... [Till the alloca]
13704 // If stacklet is not large enough, jump to mallocMBB
13707 // Allocate by subtracting from RSP
13708 // Jump to continueMBB
13711 // Allocate by call to runtime
13715 // [rest of original BB]
13718 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13719 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13720 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13722 MachineRegisterInfo &MRI = MF->getRegInfo();
13723 const TargetRegisterClass *AddrRegClass =
13724 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13726 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13727 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13728 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13729 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13730 sizeVReg = MI->getOperand(1).getReg(),
13731 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13733 MachineFunction::iterator MBBIter = BB;
13736 MF->insert(MBBIter, bumpMBB);
13737 MF->insert(MBBIter, mallocMBB);
13738 MF->insert(MBBIter, continueMBB);
13740 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13741 (MachineBasicBlock::iterator(MI)), BB->end());
13742 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13744 // Add code to the main basic block to check if the stack limit has been hit,
13745 // and if so, jump to mallocMBB otherwise to bumpMBB.
13746 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13747 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13748 .addReg(tmpSPVReg).addReg(sizeVReg);
13749 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13750 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13751 .addReg(SPLimitVReg);
13752 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13754 // bumpMBB simply decreases the stack pointer, since we know the current
13755 // stacklet has enough space.
13756 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13757 .addReg(SPLimitVReg);
13758 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13759 .addReg(SPLimitVReg);
13760 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13762 // Calls into a routine in libgcc to allocate more space from the heap.
13763 const uint32_t *RegMask =
13764 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13766 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13768 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13769 .addExternalSymbol("__morestack_allocate_stack_space")
13770 .addRegMask(RegMask)
13771 .addReg(X86::RDI, RegState::Implicit)
13772 .addReg(X86::RAX, RegState::ImplicitDefine);
13774 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13776 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13777 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13778 .addExternalSymbol("__morestack_allocate_stack_space")
13779 .addRegMask(RegMask)
13780 .addReg(X86::EAX, RegState::ImplicitDefine);
13784 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13787 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13788 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13789 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13791 // Set up the CFG correctly.
13792 BB->addSuccessor(bumpMBB);
13793 BB->addSuccessor(mallocMBB);
13794 mallocMBB->addSuccessor(continueMBB);
13795 bumpMBB->addSuccessor(continueMBB);
13797 // Take care of the PHI nodes.
13798 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13799 MI->getOperand(0).getReg())
13800 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13801 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13803 // Delete the original pseudo instruction.
13804 MI->eraseFromParent();
13807 return continueMBB;
13810 MachineBasicBlock *
13811 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13812 MachineBasicBlock *BB) const {
13813 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13814 DebugLoc DL = MI->getDebugLoc();
13816 assert(!Subtarget->isTargetEnvMacho());
13818 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13819 // non-trivial part is impdef of ESP.
13821 if (Subtarget->isTargetWin64()) {
13822 if (Subtarget->isTargetCygMing()) {
13823 // ___chkstk(Mingw64):
13824 // Clobbers R10, R11, RAX and EFLAGS.
13826 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13827 .addExternalSymbol("___chkstk")
13828 .addReg(X86::RAX, RegState::Implicit)
13829 .addReg(X86::RSP, RegState::Implicit)
13830 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13831 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13832 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13834 // __chkstk(MSVCRT): does not update stack pointer.
13835 // Clobbers R10, R11 and EFLAGS.
13836 // FIXME: RAX(allocated size) might be reused and not killed.
13837 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13838 .addExternalSymbol("__chkstk")
13839 .addReg(X86::RAX, RegState::Implicit)
13840 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13841 // RAX has the offset to subtracted from RSP.
13842 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13847 const char *StackProbeSymbol =
13848 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13850 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13851 .addExternalSymbol(StackProbeSymbol)
13852 .addReg(X86::EAX, RegState::Implicit)
13853 .addReg(X86::ESP, RegState::Implicit)
13854 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13855 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13856 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13859 MI->eraseFromParent(); // The pseudo instruction is gone now.
13863 MachineBasicBlock *
13864 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13865 MachineBasicBlock *BB) const {
13866 // This is pretty easy. We're taking the value that we received from
13867 // our load from the relocation, sticking it in either RDI (x86-64)
13868 // or EAX and doing an indirect call. The return value will then
13869 // be in the normal return register.
13870 const X86InstrInfo *TII
13871 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13872 DebugLoc DL = MI->getDebugLoc();
13873 MachineFunction *F = BB->getParent();
13875 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13876 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13878 // Get a register mask for the lowered call.
13879 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13880 // proper register mask.
13881 const uint32_t *RegMask =
13882 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13883 if (Subtarget->is64Bit()) {
13884 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13885 TII->get(X86::MOV64rm), X86::RDI)
13887 .addImm(0).addReg(0)
13888 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13889 MI->getOperand(3).getTargetFlags())
13891 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13892 addDirectMem(MIB, X86::RDI);
13893 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13894 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13895 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13896 TII->get(X86::MOV32rm), X86::EAX)
13898 .addImm(0).addReg(0)
13899 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13900 MI->getOperand(3).getTargetFlags())
13902 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13903 addDirectMem(MIB, X86::EAX);
13904 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13906 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13907 TII->get(X86::MOV32rm), X86::EAX)
13908 .addReg(TII->getGlobalBaseReg(F))
13909 .addImm(0).addReg(0)
13910 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13911 MI->getOperand(3).getTargetFlags())
13913 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13914 addDirectMem(MIB, X86::EAX);
13915 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13918 MI->eraseFromParent(); // The pseudo instruction is gone now.
13922 MachineBasicBlock *
13923 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13924 MachineBasicBlock *MBB) const {
13925 DebugLoc DL = MI->getDebugLoc();
13926 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13928 MachineFunction *MF = MBB->getParent();
13929 MachineRegisterInfo &MRI = MF->getRegInfo();
13931 const BasicBlock *BB = MBB->getBasicBlock();
13932 MachineFunction::iterator I = MBB;
13935 // Memory Reference
13936 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13937 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13940 unsigned MemOpndSlot = 0;
13942 unsigned CurOp = 0;
13944 DstReg = MI->getOperand(CurOp++).getReg();
13945 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13946 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13947 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13948 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13950 MemOpndSlot = CurOp;
13952 MVT PVT = getPointerTy();
13953 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13954 "Invalid Pointer Size!");
13956 // For v = setjmp(buf), we generate
13959 // buf[LabelOffset] = restoreMBB
13960 // SjLjSetup restoreMBB
13966 // v = phi(main, restore)
13971 MachineBasicBlock *thisMBB = MBB;
13972 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13973 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13974 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13975 MF->insert(I, mainMBB);
13976 MF->insert(I, sinkMBB);
13977 MF->push_back(restoreMBB);
13979 MachineInstrBuilder MIB;
13981 // Transfer the remainder of BB and its successor edges to sinkMBB.
13982 sinkMBB->splice(sinkMBB->begin(), MBB,
13983 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13984 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13987 unsigned PtrStoreOpc = 0;
13988 unsigned LabelReg = 0;
13989 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13990 Reloc::Model RM = getTargetMachine().getRelocationModel();
13991 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13992 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13994 // Prepare IP either in reg or imm.
13995 if (!UseImmLabel) {
13996 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13997 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13998 LabelReg = MRI.createVirtualRegister(PtrRC);
13999 if (Subtarget->is64Bit()) {
14000 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14004 .addMBB(restoreMBB)
14007 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14008 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14009 .addReg(XII->getGlobalBaseReg(MF))
14012 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14016 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14018 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14019 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14020 if (i == X86::AddrDisp)
14021 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14023 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14026 MIB.addReg(LabelReg);
14028 MIB.addMBB(restoreMBB);
14029 MIB.setMemRefs(MMOBegin, MMOEnd);
14031 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14032 .addMBB(restoreMBB);
14033 MIB.addRegMask(RegInfo->getNoPreservedMask());
14034 thisMBB->addSuccessor(mainMBB);
14035 thisMBB->addSuccessor(restoreMBB);
14039 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14040 mainMBB->addSuccessor(sinkMBB);
14043 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14044 TII->get(X86::PHI), DstReg)
14045 .addReg(mainDstReg).addMBB(mainMBB)
14046 .addReg(restoreDstReg).addMBB(restoreMBB);
14049 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14050 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14051 restoreMBB->addSuccessor(sinkMBB);
14053 MI->eraseFromParent();
14057 MachineBasicBlock *
14058 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14059 MachineBasicBlock *MBB) const {
14060 DebugLoc DL = MI->getDebugLoc();
14061 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14063 MachineFunction *MF = MBB->getParent();
14064 MachineRegisterInfo &MRI = MF->getRegInfo();
14066 // Memory Reference
14067 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14068 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14070 MVT PVT = getPointerTy();
14071 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14072 "Invalid Pointer Size!");
14074 const TargetRegisterClass *RC =
14075 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14076 unsigned Tmp = MRI.createVirtualRegister(RC);
14077 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14078 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14079 unsigned SP = RegInfo->getStackRegister();
14081 MachineInstrBuilder MIB;
14083 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14084 const int64_t SPOffset = 2 * PVT.getStoreSize();
14086 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14087 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14090 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14091 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14092 MIB.addOperand(MI->getOperand(i));
14093 MIB.setMemRefs(MMOBegin, MMOEnd);
14095 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14096 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14097 if (i == X86::AddrDisp)
14098 MIB.addDisp(MI->getOperand(i), LabelOffset);
14100 MIB.addOperand(MI->getOperand(i));
14102 MIB.setMemRefs(MMOBegin, MMOEnd);
14104 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14105 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14106 if (i == X86::AddrDisp)
14107 MIB.addDisp(MI->getOperand(i), SPOffset);
14109 MIB.addOperand(MI->getOperand(i));
14111 MIB.setMemRefs(MMOBegin, MMOEnd);
14113 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14115 MI->eraseFromParent();
14119 MachineBasicBlock *
14120 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14121 MachineBasicBlock *BB) const {
14122 switch (MI->getOpcode()) {
14123 default: llvm_unreachable("Unexpected instr type to insert");
14124 case X86::TAILJMPd64:
14125 case X86::TAILJMPr64:
14126 case X86::TAILJMPm64:
14127 llvm_unreachable("TAILJMP64 would not be touched here.");
14128 case X86::TCRETURNdi64:
14129 case X86::TCRETURNri64:
14130 case X86::TCRETURNmi64:
14132 case X86::WIN_ALLOCA:
14133 return EmitLoweredWinAlloca(MI, BB);
14134 case X86::SEG_ALLOCA_32:
14135 return EmitLoweredSegAlloca(MI, BB, false);
14136 case X86::SEG_ALLOCA_64:
14137 return EmitLoweredSegAlloca(MI, BB, true);
14138 case X86::TLSCall_32:
14139 case X86::TLSCall_64:
14140 return EmitLoweredTLSCall(MI, BB);
14141 case X86::CMOV_GR8:
14142 case X86::CMOV_FR32:
14143 case X86::CMOV_FR64:
14144 case X86::CMOV_V4F32:
14145 case X86::CMOV_V2F64:
14146 case X86::CMOV_V2I64:
14147 case X86::CMOV_V8F32:
14148 case X86::CMOV_V4F64:
14149 case X86::CMOV_V4I64:
14150 case X86::CMOV_GR16:
14151 case X86::CMOV_GR32:
14152 case X86::CMOV_RFP32:
14153 case X86::CMOV_RFP64:
14154 case X86::CMOV_RFP80:
14155 return EmitLoweredSelect(MI, BB);
14157 case X86::FP32_TO_INT16_IN_MEM:
14158 case X86::FP32_TO_INT32_IN_MEM:
14159 case X86::FP32_TO_INT64_IN_MEM:
14160 case X86::FP64_TO_INT16_IN_MEM:
14161 case X86::FP64_TO_INT32_IN_MEM:
14162 case X86::FP64_TO_INT64_IN_MEM:
14163 case X86::FP80_TO_INT16_IN_MEM:
14164 case X86::FP80_TO_INT32_IN_MEM:
14165 case X86::FP80_TO_INT64_IN_MEM: {
14166 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14167 DebugLoc DL = MI->getDebugLoc();
14169 // Change the floating point control register to use "round towards zero"
14170 // mode when truncating to an integer value.
14171 MachineFunction *F = BB->getParent();
14172 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14173 addFrameReference(BuildMI(*BB, MI, DL,
14174 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14176 // Load the old value of the high byte of the control word...
14178 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14179 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14182 // Set the high part to be round to zero...
14183 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14186 // Reload the modified control word now...
14187 addFrameReference(BuildMI(*BB, MI, DL,
14188 TII->get(X86::FLDCW16m)), CWFrameIdx);
14190 // Restore the memory image of control word to original value
14191 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14194 // Get the X86 opcode to use.
14196 switch (MI->getOpcode()) {
14197 default: llvm_unreachable("illegal opcode!");
14198 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14199 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14200 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14201 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14202 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14203 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14204 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14205 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14206 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14210 MachineOperand &Op = MI->getOperand(0);
14212 AM.BaseType = X86AddressMode::RegBase;
14213 AM.Base.Reg = Op.getReg();
14215 AM.BaseType = X86AddressMode::FrameIndexBase;
14216 AM.Base.FrameIndex = Op.getIndex();
14218 Op = MI->getOperand(1);
14220 AM.Scale = Op.getImm();
14221 Op = MI->getOperand(2);
14223 AM.IndexReg = Op.getImm();
14224 Op = MI->getOperand(3);
14225 if (Op.isGlobal()) {
14226 AM.GV = Op.getGlobal();
14228 AM.Disp = Op.getImm();
14230 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14231 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14233 // Reload the original control word now.
14234 addFrameReference(BuildMI(*BB, MI, DL,
14235 TII->get(X86::FLDCW16m)), CWFrameIdx);
14237 MI->eraseFromParent(); // The pseudo instruction is gone now.
14240 // String/text processing lowering.
14241 case X86::PCMPISTRM128REG:
14242 case X86::VPCMPISTRM128REG:
14243 case X86::PCMPISTRM128MEM:
14244 case X86::VPCMPISTRM128MEM:
14245 case X86::PCMPESTRM128REG:
14246 case X86::VPCMPESTRM128REG:
14247 case X86::PCMPESTRM128MEM:
14248 case X86::VPCMPESTRM128MEM:
14249 assert(Subtarget->hasSSE42() &&
14250 "Target must have SSE4.2 or AVX features enabled");
14251 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14253 // String/text processing lowering.
14254 case X86::PCMPISTRIREG:
14255 case X86::VPCMPISTRIREG:
14256 case X86::PCMPISTRIMEM:
14257 case X86::VPCMPISTRIMEM:
14258 case X86::PCMPESTRIREG:
14259 case X86::VPCMPESTRIREG:
14260 case X86::PCMPESTRIMEM:
14261 case X86::VPCMPESTRIMEM:
14262 assert(Subtarget->hasSSE42() &&
14263 "Target must have SSE4.2 or AVX features enabled");
14264 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14266 // Thread synchronization.
14268 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14272 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14274 // Atomic Lowering.
14275 case X86::ATOMAND8:
14276 case X86::ATOMAND16:
14277 case X86::ATOMAND32:
14278 case X86::ATOMAND64:
14281 case X86::ATOMOR16:
14282 case X86::ATOMOR32:
14283 case X86::ATOMOR64:
14285 case X86::ATOMXOR16:
14286 case X86::ATOMXOR8:
14287 case X86::ATOMXOR32:
14288 case X86::ATOMXOR64:
14290 case X86::ATOMNAND8:
14291 case X86::ATOMNAND16:
14292 case X86::ATOMNAND32:
14293 case X86::ATOMNAND64:
14295 case X86::ATOMMAX8:
14296 case X86::ATOMMAX16:
14297 case X86::ATOMMAX32:
14298 case X86::ATOMMAX64:
14300 case X86::ATOMMIN8:
14301 case X86::ATOMMIN16:
14302 case X86::ATOMMIN32:
14303 case X86::ATOMMIN64:
14305 case X86::ATOMUMAX8:
14306 case X86::ATOMUMAX16:
14307 case X86::ATOMUMAX32:
14308 case X86::ATOMUMAX64:
14310 case X86::ATOMUMIN8:
14311 case X86::ATOMUMIN16:
14312 case X86::ATOMUMIN32:
14313 case X86::ATOMUMIN64:
14314 return EmitAtomicLoadArith(MI, BB);
14316 // This group does 64-bit operations on a 32-bit host.
14317 case X86::ATOMAND6432:
14318 case X86::ATOMOR6432:
14319 case X86::ATOMXOR6432:
14320 case X86::ATOMNAND6432:
14321 case X86::ATOMADD6432:
14322 case X86::ATOMSUB6432:
14323 case X86::ATOMMAX6432:
14324 case X86::ATOMMIN6432:
14325 case X86::ATOMUMAX6432:
14326 case X86::ATOMUMIN6432:
14327 case X86::ATOMSWAP6432:
14328 return EmitAtomicLoadArith6432(MI, BB);
14330 case X86::VASTART_SAVE_XMM_REGS:
14331 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14333 case X86::VAARG_64:
14334 return EmitVAARG64WithCustomInserter(MI, BB);
14336 case X86::EH_SjLj_SetJmp32:
14337 case X86::EH_SjLj_SetJmp64:
14338 return emitEHSjLjSetJmp(MI, BB);
14340 case X86::EH_SjLj_LongJmp32:
14341 case X86::EH_SjLj_LongJmp64:
14342 return emitEHSjLjLongJmp(MI, BB);
14346 //===----------------------------------------------------------------------===//
14347 // X86 Optimization Hooks
14348 //===----------------------------------------------------------------------===//
14350 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14353 const SelectionDAG &DAG,
14354 unsigned Depth) const {
14355 unsigned BitWidth = KnownZero.getBitWidth();
14356 unsigned Opc = Op.getOpcode();
14357 assert((Opc >= ISD::BUILTIN_OP_END ||
14358 Opc == ISD::INTRINSIC_WO_CHAIN ||
14359 Opc == ISD::INTRINSIC_W_CHAIN ||
14360 Opc == ISD::INTRINSIC_VOID) &&
14361 "Should use MaskedValueIsZero if you don't know whether Op"
14362 " is a target node!");
14364 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14378 // These nodes' second result is a boolean.
14379 if (Op.getResNo() == 0)
14382 case X86ISD::SETCC:
14383 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14385 case ISD::INTRINSIC_WO_CHAIN: {
14386 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14387 unsigned NumLoBits = 0;
14390 case Intrinsic::x86_sse_movmsk_ps:
14391 case Intrinsic::x86_avx_movmsk_ps_256:
14392 case Intrinsic::x86_sse2_movmsk_pd:
14393 case Intrinsic::x86_avx_movmsk_pd_256:
14394 case Intrinsic::x86_mmx_pmovmskb:
14395 case Intrinsic::x86_sse2_pmovmskb_128:
14396 case Intrinsic::x86_avx2_pmovmskb: {
14397 // High bits of movmskp{s|d}, pmovmskb are known zero.
14399 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14400 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14401 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14402 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14403 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14404 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14405 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14406 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14408 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14417 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14418 unsigned Depth) const {
14419 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14420 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14421 return Op.getValueType().getScalarType().getSizeInBits();
14427 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14428 /// node is a GlobalAddress + offset.
14429 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14430 const GlobalValue* &GA,
14431 int64_t &Offset) const {
14432 if (N->getOpcode() == X86ISD::Wrapper) {
14433 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14434 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14435 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14439 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14442 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14443 /// same as extracting the high 128-bit part of 256-bit vector and then
14444 /// inserting the result into the low part of a new 256-bit vector
14445 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14446 EVT VT = SVOp->getValueType(0);
14447 unsigned NumElems = VT.getVectorNumElements();
14449 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14450 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14451 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14452 SVOp->getMaskElt(j) >= 0)
14458 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14459 /// same as extracting the low 128-bit part of 256-bit vector and then
14460 /// inserting the result into the high part of a new 256-bit vector
14461 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14462 EVT VT = SVOp->getValueType(0);
14463 unsigned NumElems = VT.getVectorNumElements();
14465 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14466 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14467 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14468 SVOp->getMaskElt(j) >= 0)
14474 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14475 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14476 TargetLowering::DAGCombinerInfo &DCI,
14477 const X86Subtarget* Subtarget) {
14478 DebugLoc dl = N->getDebugLoc();
14479 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14480 SDValue V1 = SVOp->getOperand(0);
14481 SDValue V2 = SVOp->getOperand(1);
14482 EVT VT = SVOp->getValueType(0);
14483 unsigned NumElems = VT.getVectorNumElements();
14485 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14486 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14490 // V UNDEF BUILD_VECTOR UNDEF
14492 // CONCAT_VECTOR CONCAT_VECTOR
14495 // RESULT: V + zero extended
14497 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14498 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14499 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14502 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14505 // To match the shuffle mask, the first half of the mask should
14506 // be exactly the first vector, and all the rest a splat with the
14507 // first element of the second one.
14508 for (unsigned i = 0; i != NumElems/2; ++i)
14509 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14510 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14513 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14514 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14515 if (Ld->hasNUsesOfValue(1, 0)) {
14516 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14517 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14519 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14521 Ld->getPointerInfo(),
14522 Ld->getAlignment(),
14523 false/*isVolatile*/, true/*ReadMem*/,
14524 false/*WriteMem*/);
14526 // Make sure the newly-created LOAD is in the same position as Ld in
14527 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14528 // and update uses of Ld's output chain to use the TokenFactor.
14529 if (Ld->hasAnyUseOfValue(1)) {
14530 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14531 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14532 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14533 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14534 SDValue(ResNode.getNode(), 1));
14537 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14541 // Emit a zeroed vector and insert the desired subvector on its
14543 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14544 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14545 return DCI.CombineTo(N, InsV);
14548 //===--------------------------------------------------------------------===//
14549 // Combine some shuffles into subvector extracts and inserts:
14552 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14553 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14554 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14555 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14556 return DCI.CombineTo(N, InsV);
14559 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14560 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14561 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14562 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14563 return DCI.CombineTo(N, InsV);
14569 /// PerformShuffleCombine - Performs several different shuffle combines.
14570 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14571 TargetLowering::DAGCombinerInfo &DCI,
14572 const X86Subtarget *Subtarget) {
14573 DebugLoc dl = N->getDebugLoc();
14574 EVT VT = N->getValueType(0);
14576 // Don't create instructions with illegal types after legalize types has run.
14577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14578 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14581 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14582 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14583 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14584 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14586 // Only handle 128 wide vector from here on.
14587 if (!VT.is128BitVector())
14590 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14591 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14592 // consecutive, non-overlapping, and in the right order.
14593 SmallVector<SDValue, 16> Elts;
14594 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14595 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14597 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14600 /// PerformTruncateCombine - Converts truncate operation to
14601 /// a sequence of vector shuffle operations.
14602 /// It is possible when we truncate 256-bit vector to 128-bit vector
14603 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14604 TargetLowering::DAGCombinerInfo &DCI,
14605 const X86Subtarget *Subtarget) {
14609 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14610 /// specific shuffle of a load can be folded into a single element load.
14611 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14612 /// shuffles have been customed lowered so we need to handle those here.
14613 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14614 TargetLowering::DAGCombinerInfo &DCI) {
14615 if (DCI.isBeforeLegalizeOps())
14618 SDValue InVec = N->getOperand(0);
14619 SDValue EltNo = N->getOperand(1);
14621 if (!isa<ConstantSDNode>(EltNo))
14624 EVT VT = InVec.getValueType();
14626 bool HasShuffleIntoBitcast = false;
14627 if (InVec.getOpcode() == ISD::BITCAST) {
14628 // Don't duplicate a load with other uses.
14629 if (!InVec.hasOneUse())
14631 EVT BCVT = InVec.getOperand(0).getValueType();
14632 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14634 InVec = InVec.getOperand(0);
14635 HasShuffleIntoBitcast = true;
14638 if (!isTargetShuffle(InVec.getOpcode()))
14641 // Don't duplicate a load with other uses.
14642 if (!InVec.hasOneUse())
14645 SmallVector<int, 16> ShuffleMask;
14647 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14651 // Select the input vector, guarding against out of range extract vector.
14652 unsigned NumElems = VT.getVectorNumElements();
14653 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14654 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14655 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14656 : InVec.getOperand(1);
14658 // If inputs to shuffle are the same for both ops, then allow 2 uses
14659 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14661 if (LdNode.getOpcode() == ISD::BITCAST) {
14662 // Don't duplicate a load with other uses.
14663 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14666 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14667 LdNode = LdNode.getOperand(0);
14670 if (!ISD::isNormalLoad(LdNode.getNode()))
14673 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14675 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14678 if (HasShuffleIntoBitcast) {
14679 // If there's a bitcast before the shuffle, check if the load type and
14680 // alignment is valid.
14681 unsigned Align = LN0->getAlignment();
14682 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14683 unsigned NewAlign = TLI.getDataLayout()->
14684 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14686 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14690 // All checks match so transform back to vector_shuffle so that DAG combiner
14691 // can finish the job
14692 DebugLoc dl = N->getDebugLoc();
14694 // Create shuffle node taking into account the case that its a unary shuffle
14695 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14696 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14697 InVec.getOperand(0), Shuffle,
14699 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14700 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14704 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14705 /// generation and convert it from being a bunch of shuffles and extracts
14706 /// to a simple store and scalar loads to extract the elements.
14707 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14708 TargetLowering::DAGCombinerInfo &DCI) {
14709 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14710 if (NewOp.getNode())
14713 SDValue InputVector = N->getOperand(0);
14714 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14715 // from mmx to v2i32 has a single usage.
14716 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14717 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14718 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14719 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14720 N->getValueType(0),
14721 InputVector.getNode()->getOperand(0));
14723 // Only operate on vectors of 4 elements, where the alternative shuffling
14724 // gets to be more expensive.
14725 if (InputVector.getValueType() != MVT::v4i32)
14728 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14729 // single use which is a sign-extend or zero-extend, and all elements are
14731 SmallVector<SDNode *, 4> Uses;
14732 unsigned ExtractedElements = 0;
14733 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14734 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14735 if (UI.getUse().getResNo() != InputVector.getResNo())
14738 SDNode *Extract = *UI;
14739 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14742 if (Extract->getValueType(0) != MVT::i32)
14744 if (!Extract->hasOneUse())
14746 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14747 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14749 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14752 // Record which element was extracted.
14753 ExtractedElements |=
14754 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14756 Uses.push_back(Extract);
14759 // If not all the elements were used, this may not be worthwhile.
14760 if (ExtractedElements != 15)
14763 // Ok, we've now decided to do the transformation.
14764 DebugLoc dl = InputVector.getDebugLoc();
14766 // Store the value to a temporary stack slot.
14767 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14768 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14769 MachinePointerInfo(), false, false, 0);
14771 // Replace each use (extract) with a load of the appropriate element.
14772 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14773 UE = Uses.end(); UI != UE; ++UI) {
14774 SDNode *Extract = *UI;
14776 // cOMpute the element's address.
14777 SDValue Idx = Extract->getOperand(1);
14779 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14780 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14781 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14782 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14784 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14785 StackPtr, OffsetVal);
14787 // Load the scalar.
14788 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14789 ScalarAddr, MachinePointerInfo(),
14790 false, false, false, 0);
14792 // Replace the exact with the load.
14793 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14796 // The replacement was made in place; don't return anything.
14800 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14801 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14802 SDValue RHS, SelectionDAG &DAG,
14803 const X86Subtarget *Subtarget) {
14804 if (!VT.isVector())
14807 switch (VT.getSimpleVT().SimpleTy) {
14812 if (!Subtarget->hasAVX2())
14817 if (!Subtarget->hasSSE2())
14821 // SSE2 has only a small subset of the operations.
14822 bool hasUnsigned = Subtarget->hasSSE41() ||
14823 (Subtarget->hasSSE2() && VT == MVT::v16i8);
14824 bool hasSigned = Subtarget->hasSSE41() ||
14825 (Subtarget->hasSSE2() && VT == MVT::v8i16);
14827 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14829 // Check for x CC y ? x : y.
14830 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14831 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14836 return hasUnsigned ? X86ISD::UMIN : 0;
14839 return hasUnsigned ? X86ISD::UMAX : 0;
14842 return hasSigned ? X86ISD::SMIN : 0;
14845 return hasSigned ? X86ISD::SMAX : 0;
14847 // Check for x CC y ? y : x -- a min/max with reversed arms.
14848 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14849 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14854 return hasUnsigned ? X86ISD::UMAX : 0;
14857 return hasUnsigned ? X86ISD::UMIN : 0;
14860 return hasSigned ? X86ISD::SMAX : 0;
14863 return hasSigned ? X86ISD::SMIN : 0;
14870 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14872 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14873 TargetLowering::DAGCombinerInfo &DCI,
14874 const X86Subtarget *Subtarget) {
14875 DebugLoc DL = N->getDebugLoc();
14876 SDValue Cond = N->getOperand(0);
14877 // Get the LHS/RHS of the select.
14878 SDValue LHS = N->getOperand(1);
14879 SDValue RHS = N->getOperand(2);
14880 EVT VT = LHS.getValueType();
14882 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14883 // instructions match the semantics of the common C idiom x<y?x:y but not
14884 // x<=y?x:y, because of how they handle negative zero (which can be
14885 // ignored in unsafe-math mode).
14886 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14887 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14888 (Subtarget->hasSSE2() ||
14889 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14890 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14892 unsigned Opcode = 0;
14893 // Check for x CC y ? x : y.
14894 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14895 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14899 // Converting this to a min would handle NaNs incorrectly, and swapping
14900 // the operands would cause it to handle comparisons between positive
14901 // and negative zero incorrectly.
14902 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14903 if (!DAG.getTarget().Options.UnsafeFPMath &&
14904 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14906 std::swap(LHS, RHS);
14908 Opcode = X86ISD::FMIN;
14911 // Converting this to a min would handle comparisons between positive
14912 // and negative zero incorrectly.
14913 if (!DAG.getTarget().Options.UnsafeFPMath &&
14914 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14916 Opcode = X86ISD::FMIN;
14919 // Converting this to a min would handle both negative zeros and NaNs
14920 // incorrectly, but we can swap the operands to fix both.
14921 std::swap(LHS, RHS);
14925 Opcode = X86ISD::FMIN;
14929 // Converting this to a max would handle comparisons between positive
14930 // and negative zero incorrectly.
14931 if (!DAG.getTarget().Options.UnsafeFPMath &&
14932 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14934 Opcode = X86ISD::FMAX;
14937 // Converting this to a max would handle NaNs incorrectly, and swapping
14938 // the operands would cause it to handle comparisons between positive
14939 // and negative zero incorrectly.
14940 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14941 if (!DAG.getTarget().Options.UnsafeFPMath &&
14942 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14944 std::swap(LHS, RHS);
14946 Opcode = X86ISD::FMAX;
14949 // Converting this to a max would handle both negative zeros and NaNs
14950 // incorrectly, but we can swap the operands to fix both.
14951 std::swap(LHS, RHS);
14955 Opcode = X86ISD::FMAX;
14958 // Check for x CC y ? y : x -- a min/max with reversed arms.
14959 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14960 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14964 // Converting this to a min would handle comparisons between positive
14965 // and negative zero incorrectly, and swapping the operands would
14966 // cause it to handle NaNs incorrectly.
14967 if (!DAG.getTarget().Options.UnsafeFPMath &&
14968 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14969 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14971 std::swap(LHS, RHS);
14973 Opcode = X86ISD::FMIN;
14976 // Converting this to a min would handle NaNs incorrectly.
14977 if (!DAG.getTarget().Options.UnsafeFPMath &&
14978 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14980 Opcode = X86ISD::FMIN;
14983 // Converting this to a min would handle both negative zeros and NaNs
14984 // incorrectly, but we can swap the operands to fix both.
14985 std::swap(LHS, RHS);
14989 Opcode = X86ISD::FMIN;
14993 // Converting this to a max would handle NaNs incorrectly.
14994 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14996 Opcode = X86ISD::FMAX;
14999 // Converting this to a max would handle comparisons between positive
15000 // and negative zero incorrectly, and swapping the operands would
15001 // cause it to handle NaNs incorrectly.
15002 if (!DAG.getTarget().Options.UnsafeFPMath &&
15003 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15004 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15006 std::swap(LHS, RHS);
15008 Opcode = X86ISD::FMAX;
15011 // Converting this to a max would handle both negative zeros and NaNs
15012 // incorrectly, but we can swap the operands to fix both.
15013 std::swap(LHS, RHS);
15017 Opcode = X86ISD::FMAX;
15023 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15026 // If this is a select between two integer constants, try to do some
15028 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15029 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15030 // Don't do this for crazy integer types.
15031 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15032 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15033 // so that TrueC (the true value) is larger than FalseC.
15034 bool NeedsCondInvert = false;
15036 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15037 // Efficiently invertible.
15038 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15039 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15040 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15041 NeedsCondInvert = true;
15042 std::swap(TrueC, FalseC);
15045 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15046 if (FalseC->getAPIntValue() == 0 &&
15047 TrueC->getAPIntValue().isPowerOf2()) {
15048 if (NeedsCondInvert) // Invert the condition if needed.
15049 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15050 DAG.getConstant(1, Cond.getValueType()));
15052 // Zero extend the condition if needed.
15053 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15055 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15056 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15057 DAG.getConstant(ShAmt, MVT::i8));
15060 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15061 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15062 if (NeedsCondInvert) // Invert the condition if needed.
15063 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15064 DAG.getConstant(1, Cond.getValueType()));
15066 // Zero extend the condition if needed.
15067 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15068 FalseC->getValueType(0), Cond);
15069 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15070 SDValue(FalseC, 0));
15073 // Optimize cases that will turn into an LEA instruction. This requires
15074 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15075 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15076 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15077 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15079 bool isFastMultiplier = false;
15081 switch ((unsigned char)Diff) {
15083 case 1: // result = add base, cond
15084 case 2: // result = lea base( , cond*2)
15085 case 3: // result = lea base(cond, cond*2)
15086 case 4: // result = lea base( , cond*4)
15087 case 5: // result = lea base(cond, cond*4)
15088 case 8: // result = lea base( , cond*8)
15089 case 9: // result = lea base(cond, cond*8)
15090 isFastMultiplier = true;
15095 if (isFastMultiplier) {
15096 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15097 if (NeedsCondInvert) // Invert the condition if needed.
15098 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15099 DAG.getConstant(1, Cond.getValueType()));
15101 // Zero extend the condition if needed.
15102 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15104 // Scale the condition by the difference.
15106 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15107 DAG.getConstant(Diff, Cond.getValueType()));
15109 // Add the base if non-zero.
15110 if (FalseC->getAPIntValue() != 0)
15111 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15112 SDValue(FalseC, 0));
15119 // Canonicalize max and min:
15120 // (x > y) ? x : y -> (x >= y) ? x : y
15121 // (x < y) ? x : y -> (x <= y) ? x : y
15122 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15123 // the need for an extra compare
15124 // against zero. e.g.
15125 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15127 // testl %edi, %edi
15129 // cmovgl %edi, %eax
15133 // cmovsl %eax, %edi
15134 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15135 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15136 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15137 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15142 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15143 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15144 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15145 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15150 // Match VSELECTs into subs with unsigned saturation.
15151 if (!DCI.isBeforeLegalize() &&
15152 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15153 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15154 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15155 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15156 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15158 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15159 // left side invert the predicate to simplify logic below.
15161 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15163 CC = ISD::getSetCCInverse(CC, true);
15164 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15168 if (Other.getNode() && Other->getNumOperands() == 2 &&
15169 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15170 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15171 SDValue CondRHS = Cond->getOperand(1);
15173 // Look for a general sub with unsigned saturation first.
15174 // x >= y ? x-y : 0 --> subus x, y
15175 // x > y ? x-y : 0 --> subus x, y
15176 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15177 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15178 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15180 // If the RHS is a constant we have to reverse the const canonicalization.
15181 // x > C-1 ? x+-C : 0 --> subus x, C
15182 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15183 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15184 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15185 if (CondRHS.getConstantOperandVal(0) == -A-1) {
15186 SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15187 DAG.getConstant(-A, VT.getScalarType()));
15188 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15189 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15190 V.data(), V.size()));
15194 // Another special case: If C was a sign bit, the sub has been
15195 // canonicalized into a xor.
15196 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15197 // it's safe to decanonicalize the xor?
15198 // x s< 0 ? x^C : 0 --> subus x, C
15199 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15200 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15201 isSplatVector(OpRHS.getNode())) {
15202 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15204 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15209 // Try to match a min/max vector operation.
15210 if (!DCI.isBeforeLegalize() &&
15211 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15212 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15213 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15215 // If we know that this node is legal then we know that it is going to be
15216 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15217 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15218 // to simplify previous instructions.
15219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15220 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15221 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15222 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15224 // Don't optimize vector selects that map to mask-registers.
15228 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15229 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15231 APInt KnownZero, KnownOne;
15232 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15233 DCI.isBeforeLegalizeOps());
15234 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15235 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15236 DCI.CommitTargetLoweringOpt(TLO);
15242 // Check whether a boolean test is testing a boolean value generated by
15243 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15246 // Simplify the following patterns:
15247 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15248 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15249 // to (Op EFLAGS Cond)
15251 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15252 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15253 // to (Op EFLAGS !Cond)
15255 // where Op could be BRCOND or CMOV.
15257 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15258 // Quit if not CMP and SUB with its value result used.
15259 if (Cmp.getOpcode() != X86ISD::CMP &&
15260 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15263 // Quit if not used as a boolean value.
15264 if (CC != X86::COND_E && CC != X86::COND_NE)
15267 // Check CMP operands. One of them should be 0 or 1 and the other should be
15268 // an SetCC or extended from it.
15269 SDValue Op1 = Cmp.getOperand(0);
15270 SDValue Op2 = Cmp.getOperand(1);
15273 const ConstantSDNode* C = 0;
15274 bool needOppositeCond = (CC == X86::COND_E);
15276 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15278 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15280 else // Quit if all operands are not constants.
15283 if (C->getZExtValue() == 1)
15284 needOppositeCond = !needOppositeCond;
15285 else if (C->getZExtValue() != 0)
15286 // Quit if the constant is neither 0 or 1.
15289 // Skip 'zext' node.
15290 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15291 SetCC = SetCC.getOperand(0);
15293 switch (SetCC.getOpcode()) {
15294 case X86ISD::SETCC:
15295 // Set the condition code or opposite one if necessary.
15296 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15297 if (needOppositeCond)
15298 CC = X86::GetOppositeBranchCondition(CC);
15299 return SetCC.getOperand(1);
15300 case X86ISD::CMOV: {
15301 // Check whether false/true value has canonical one, i.e. 0 or 1.
15302 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15303 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15304 // Quit if true value is not a constant.
15307 // Quit if false value is not a constant.
15309 // A special case for rdrand, where 0 is set if false cond is found.
15310 SDValue Op = SetCC.getOperand(0);
15311 if (Op.getOpcode() != X86ISD::RDRAND)
15314 // Quit if false value is not the constant 0 or 1.
15315 bool FValIsFalse = true;
15316 if (FVal && FVal->getZExtValue() != 0) {
15317 if (FVal->getZExtValue() != 1)
15319 // If FVal is 1, opposite cond is needed.
15320 needOppositeCond = !needOppositeCond;
15321 FValIsFalse = false;
15323 // Quit if TVal is not the constant opposite of FVal.
15324 if (FValIsFalse && TVal->getZExtValue() != 1)
15326 if (!FValIsFalse && TVal->getZExtValue() != 0)
15328 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15329 if (needOppositeCond)
15330 CC = X86::GetOppositeBranchCondition(CC);
15331 return SetCC.getOperand(3);
15338 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15339 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15340 TargetLowering::DAGCombinerInfo &DCI,
15341 const X86Subtarget *Subtarget) {
15342 DebugLoc DL = N->getDebugLoc();
15344 // If the flag operand isn't dead, don't touch this CMOV.
15345 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15348 SDValue FalseOp = N->getOperand(0);
15349 SDValue TrueOp = N->getOperand(1);
15350 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15351 SDValue Cond = N->getOperand(3);
15353 if (CC == X86::COND_E || CC == X86::COND_NE) {
15354 switch (Cond.getOpcode()) {
15358 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15359 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15360 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15366 Flags = checkBoolTestSetCCCombine(Cond, CC);
15367 if (Flags.getNode() &&
15368 // Extra check as FCMOV only supports a subset of X86 cond.
15369 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15370 SDValue Ops[] = { FalseOp, TrueOp,
15371 DAG.getConstant(CC, MVT::i8), Flags };
15372 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15373 Ops, array_lengthof(Ops));
15376 // If this is a select between two integer constants, try to do some
15377 // optimizations. Note that the operands are ordered the opposite of SELECT
15379 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15380 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15381 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15382 // larger than FalseC (the false value).
15383 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15384 CC = X86::GetOppositeBranchCondition(CC);
15385 std::swap(TrueC, FalseC);
15386 std::swap(TrueOp, FalseOp);
15389 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15390 // This is efficient for any integer data type (including i8/i16) and
15392 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15393 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15394 DAG.getConstant(CC, MVT::i8), Cond);
15396 // Zero extend the condition if needed.
15397 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15399 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15400 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15401 DAG.getConstant(ShAmt, MVT::i8));
15402 if (N->getNumValues() == 2) // Dead flag value?
15403 return DCI.CombineTo(N, Cond, SDValue());
15407 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15408 // for any integer data type, including i8/i16.
15409 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15410 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15411 DAG.getConstant(CC, MVT::i8), Cond);
15413 // Zero extend the condition if needed.
15414 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15415 FalseC->getValueType(0), Cond);
15416 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15417 SDValue(FalseC, 0));
15419 if (N->getNumValues() == 2) // Dead flag value?
15420 return DCI.CombineTo(N, Cond, SDValue());
15424 // Optimize cases that will turn into an LEA instruction. This requires
15425 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15426 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15427 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15428 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15430 bool isFastMultiplier = false;
15432 switch ((unsigned char)Diff) {
15434 case 1: // result = add base, cond
15435 case 2: // result = lea base( , cond*2)
15436 case 3: // result = lea base(cond, cond*2)
15437 case 4: // result = lea base( , cond*4)
15438 case 5: // result = lea base(cond, cond*4)
15439 case 8: // result = lea base( , cond*8)
15440 case 9: // result = lea base(cond, cond*8)
15441 isFastMultiplier = true;
15446 if (isFastMultiplier) {
15447 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15448 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15449 DAG.getConstant(CC, MVT::i8), Cond);
15450 // Zero extend the condition if needed.
15451 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15453 // Scale the condition by the difference.
15455 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15456 DAG.getConstant(Diff, Cond.getValueType()));
15458 // Add the base if non-zero.
15459 if (FalseC->getAPIntValue() != 0)
15460 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15461 SDValue(FalseC, 0));
15462 if (N->getNumValues() == 2) // Dead flag value?
15463 return DCI.CombineTo(N, Cond, SDValue());
15470 // Handle these cases:
15471 // (select (x != c), e, c) -> select (x != c), e, x),
15472 // (select (x == c), c, e) -> select (x == c), x, e)
15473 // where the c is an integer constant, and the "select" is the combination
15474 // of CMOV and CMP.
15476 // The rationale for this change is that the conditional-move from a constant
15477 // needs two instructions, however, conditional-move from a register needs
15478 // only one instruction.
15480 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15481 // some instruction-combining opportunities. This opt needs to be
15482 // postponed as late as possible.
15484 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15485 // the DCI.xxxx conditions are provided to postpone the optimization as
15486 // late as possible.
15488 ConstantSDNode *CmpAgainst = 0;
15489 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15490 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15491 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15493 if (CC == X86::COND_NE &&
15494 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15495 CC = X86::GetOppositeBranchCondition(CC);
15496 std::swap(TrueOp, FalseOp);
15499 if (CC == X86::COND_E &&
15500 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15501 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15502 DAG.getConstant(CC, MVT::i8), Cond };
15503 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15504 array_lengthof(Ops));
15512 /// PerformMulCombine - Optimize a single multiply with constant into two
15513 /// in order to implement it with two cheaper instructions, e.g.
15514 /// LEA + SHL, LEA + LEA.
15515 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15516 TargetLowering::DAGCombinerInfo &DCI) {
15517 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15520 EVT VT = N->getValueType(0);
15521 if (VT != MVT::i64)
15524 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15527 uint64_t MulAmt = C->getZExtValue();
15528 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15531 uint64_t MulAmt1 = 0;
15532 uint64_t MulAmt2 = 0;
15533 if ((MulAmt % 9) == 0) {
15535 MulAmt2 = MulAmt / 9;
15536 } else if ((MulAmt % 5) == 0) {
15538 MulAmt2 = MulAmt / 5;
15539 } else if ((MulAmt % 3) == 0) {
15541 MulAmt2 = MulAmt / 3;
15544 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15545 DebugLoc DL = N->getDebugLoc();
15547 if (isPowerOf2_64(MulAmt2) &&
15548 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15549 // If second multiplifer is pow2, issue it first. We want the multiply by
15550 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15552 std::swap(MulAmt1, MulAmt2);
15555 if (isPowerOf2_64(MulAmt1))
15556 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15557 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15559 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15560 DAG.getConstant(MulAmt1, VT));
15562 if (isPowerOf2_64(MulAmt2))
15563 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15564 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15566 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15567 DAG.getConstant(MulAmt2, VT));
15569 // Do not add new nodes to DAG combiner worklist.
15570 DCI.CombineTo(N, NewMul, false);
15575 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15576 SDValue N0 = N->getOperand(0);
15577 SDValue N1 = N->getOperand(1);
15578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15579 EVT VT = N0.getValueType();
15581 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15582 // since the result of setcc_c is all zero's or all ones.
15583 if (VT.isInteger() && !VT.isVector() &&
15584 N1C && N0.getOpcode() == ISD::AND &&
15585 N0.getOperand(1).getOpcode() == ISD::Constant) {
15586 SDValue N00 = N0.getOperand(0);
15587 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15588 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15589 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15590 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15591 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15592 APInt ShAmt = N1C->getAPIntValue();
15593 Mask = Mask.shl(ShAmt);
15595 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15596 N00, DAG.getConstant(Mask, VT));
15600 // Hardware support for vector shifts is sparse which makes us scalarize the
15601 // vector operations in many cases. Also, on sandybridge ADD is faster than
15603 // (shl V, 1) -> add V,V
15604 if (isSplatVector(N1.getNode())) {
15605 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15606 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15607 // We shift all of the values by one. In many cases we do not have
15608 // hardware support for this operation. This is better expressed as an ADD
15610 if (N1C && (1 == N1C->getZExtValue())) {
15611 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15618 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15620 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15621 TargetLowering::DAGCombinerInfo &DCI,
15622 const X86Subtarget *Subtarget) {
15623 EVT VT = N->getValueType(0);
15624 if (N->getOpcode() == ISD::SHL) {
15625 SDValue V = PerformSHLCombine(N, DAG);
15626 if (V.getNode()) return V;
15629 // On X86 with SSE2 support, we can transform this to a vector shift if
15630 // all elements are shifted by the same amount. We can't do this in legalize
15631 // because the a constant vector is typically transformed to a constant pool
15632 // so we have no knowledge of the shift amount.
15633 if (!Subtarget->hasSSE2())
15636 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15637 (!Subtarget->hasInt256() ||
15638 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15641 SDValue ShAmtOp = N->getOperand(1);
15642 EVT EltVT = VT.getVectorElementType();
15643 DebugLoc DL = N->getDebugLoc();
15644 SDValue BaseShAmt = SDValue();
15645 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15646 unsigned NumElts = VT.getVectorNumElements();
15648 for (; i != NumElts; ++i) {
15649 SDValue Arg = ShAmtOp.getOperand(i);
15650 if (Arg.getOpcode() == ISD::UNDEF) continue;
15654 // Handle the case where the build_vector is all undef
15655 // FIXME: Should DAG allow this?
15659 for (; i != NumElts; ++i) {
15660 SDValue Arg = ShAmtOp.getOperand(i);
15661 if (Arg.getOpcode() == ISD::UNDEF) continue;
15662 if (Arg != BaseShAmt) {
15666 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15667 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15668 SDValue InVec = ShAmtOp.getOperand(0);
15669 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15670 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15672 for (; i != NumElts; ++i) {
15673 SDValue Arg = InVec.getOperand(i);
15674 if (Arg.getOpcode() == ISD::UNDEF) continue;
15678 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15680 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15681 if (C->getZExtValue() == SplatIdx)
15682 BaseShAmt = InVec.getOperand(1);
15685 if (BaseShAmt.getNode() == 0) {
15686 // Don't create instructions with illegal types after legalize
15688 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15689 !DCI.isBeforeLegalize())
15692 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15693 DAG.getIntPtrConstant(0));
15698 // The shift amount is an i32.
15699 if (EltVT.bitsGT(MVT::i32))
15700 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15701 else if (EltVT.bitsLT(MVT::i32))
15702 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15704 // The shift amount is identical so we can do a vector shift.
15705 SDValue ValOp = N->getOperand(0);
15706 switch (N->getOpcode()) {
15708 llvm_unreachable("Unknown shift opcode!");
15710 switch (VT.getSimpleVT().SimpleTy) {
15711 default: return SDValue();
15718 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15721 switch (VT.getSimpleVT().SimpleTy) {
15722 default: return SDValue();
15727 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15730 switch (VT.getSimpleVT().SimpleTy) {
15731 default: return SDValue();
15738 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15743 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15744 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15745 // and friends. Likewise for OR -> CMPNEQSS.
15746 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15747 TargetLowering::DAGCombinerInfo &DCI,
15748 const X86Subtarget *Subtarget) {
15751 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15752 // we're requiring SSE2 for both.
15753 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15754 SDValue N0 = N->getOperand(0);
15755 SDValue N1 = N->getOperand(1);
15756 SDValue CMP0 = N0->getOperand(1);
15757 SDValue CMP1 = N1->getOperand(1);
15758 DebugLoc DL = N->getDebugLoc();
15760 // The SETCCs should both refer to the same CMP.
15761 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15764 SDValue CMP00 = CMP0->getOperand(0);
15765 SDValue CMP01 = CMP0->getOperand(1);
15766 EVT VT = CMP00.getValueType();
15768 if (VT == MVT::f32 || VT == MVT::f64) {
15769 bool ExpectingFlags = false;
15770 // Check for any users that want flags:
15771 for (SDNode::use_iterator UI = N->use_begin(),
15773 !ExpectingFlags && UI != UE; ++UI)
15774 switch (UI->getOpcode()) {
15779 ExpectingFlags = true;
15781 case ISD::CopyToReg:
15782 case ISD::SIGN_EXTEND:
15783 case ISD::ZERO_EXTEND:
15784 case ISD::ANY_EXTEND:
15788 if (!ExpectingFlags) {
15789 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15790 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15792 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15793 X86::CondCode tmp = cc0;
15798 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15799 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15800 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15801 X86ISD::NodeType NTOperator = is64BitFP ?
15802 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15803 // FIXME: need symbolic constants for these magic numbers.
15804 // See X86ATTInstPrinter.cpp:printSSECC().
15805 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15806 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15807 DAG.getConstant(x86cc, MVT::i8));
15808 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15810 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15811 DAG.getConstant(1, MVT::i32));
15812 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15813 return OneBitOfTruth;
15821 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15822 /// so it can be folded inside ANDNP.
15823 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15824 EVT VT = N->getValueType(0);
15826 // Match direct AllOnes for 128 and 256-bit vectors
15827 if (ISD::isBuildVectorAllOnes(N))
15830 // Look through a bit convert.
15831 if (N->getOpcode() == ISD::BITCAST)
15832 N = N->getOperand(0).getNode();
15834 // Sometimes the operand may come from a insert_subvector building a 256-bit
15836 if (VT.is256BitVector() &&
15837 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15838 SDValue V1 = N->getOperand(0);
15839 SDValue V2 = N->getOperand(1);
15841 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15842 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15843 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15844 ISD::isBuildVectorAllOnes(V2.getNode()))
15851 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15852 // register. In most cases we actually compare or select YMM-sized registers
15853 // and mixing the two types creates horrible code. This method optimizes
15854 // some of the transition sequences.
15855 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15856 TargetLowering::DAGCombinerInfo &DCI,
15857 const X86Subtarget *Subtarget) {
15858 EVT VT = N->getValueType(0);
15859 if (VT.getSizeInBits() != 256)
15862 assert((N->getOpcode() == ISD::ANY_EXTEND ||
15863 N->getOpcode() == ISD::ZERO_EXTEND ||
15864 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15866 SDValue Narrow = N->getOperand(0);
15867 EVT NarrowVT = Narrow->getValueType(0);
15868 if (NarrowVT.getSizeInBits() != 128)
15871 if (Narrow->getOpcode() != ISD::XOR &&
15872 Narrow->getOpcode() != ISD::AND &&
15873 Narrow->getOpcode() != ISD::OR)
15876 SDValue N0 = Narrow->getOperand(0);
15877 SDValue N1 = Narrow->getOperand(1);
15878 DebugLoc DL = Narrow->getDebugLoc();
15880 // The Left side has to be a trunc.
15881 if (N0.getOpcode() != ISD::TRUNCATE)
15884 // The type of the truncated inputs.
15885 EVT WideVT = N0->getOperand(0)->getValueType(0);
15889 // The right side has to be a 'trunc' or a constant vector.
15890 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
15891 bool RHSConst = (isSplatVector(N1.getNode()) &&
15892 isa<ConstantSDNode>(N1->getOperand(0)));
15893 if (!RHSTrunc && !RHSConst)
15896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15898 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
15901 // Set N0 and N1 to hold the inputs to the new wide operation.
15902 N0 = N0->getOperand(0);
15904 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
15905 N1->getOperand(0));
15906 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
15907 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
15908 } else if (RHSTrunc) {
15909 N1 = N1->getOperand(0);
15912 // Generate the wide operation.
15913 SDValue Op = DAG.getNode(N->getOpcode(), DL, WideVT, N0, N1);
15914 unsigned Opcode = N->getOpcode();
15916 case ISD::ANY_EXTEND:
15918 case ISD::ZERO_EXTEND: {
15919 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
15920 APInt Mask = APInt::getAllOnesValue(InBits);
15921 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
15922 return DAG.getNode(ISD::AND, DL, VT,
15923 Op, DAG.getConstant(Mask, VT));
15925 case ISD::SIGN_EXTEND:
15926 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
15927 Op, DAG.getValueType(NarrowVT));
15929 llvm_unreachable("Unexpected opcode");
15933 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15934 TargetLowering::DAGCombinerInfo &DCI,
15935 const X86Subtarget *Subtarget) {
15936 EVT VT = N->getValueType(0);
15937 if (DCI.isBeforeLegalizeOps())
15940 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15944 // Create BLSI, and BLSR instructions
15945 // BLSI is X & (-X)
15946 // BLSR is X & (X-1)
15947 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15948 SDValue N0 = N->getOperand(0);
15949 SDValue N1 = N->getOperand(1);
15950 DebugLoc DL = N->getDebugLoc();
15952 // Check LHS for neg
15953 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15954 isZero(N0.getOperand(0)))
15955 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15957 // Check RHS for neg
15958 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15959 isZero(N1.getOperand(0)))
15960 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15962 // Check LHS for X-1
15963 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15964 isAllOnes(N0.getOperand(1)))
15965 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15967 // Check RHS for X-1
15968 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15969 isAllOnes(N1.getOperand(1)))
15970 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15975 // Want to form ANDNP nodes:
15976 // 1) In the hopes of then easily combining them with OR and AND nodes
15977 // to form PBLEND/PSIGN.
15978 // 2) To match ANDN packed intrinsics
15979 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15982 SDValue N0 = N->getOperand(0);
15983 SDValue N1 = N->getOperand(1);
15984 DebugLoc DL = N->getDebugLoc();
15986 // Check LHS for vnot
15987 if (N0.getOpcode() == ISD::XOR &&
15988 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15989 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15990 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15992 // Check RHS for vnot
15993 if (N1.getOpcode() == ISD::XOR &&
15994 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15995 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15996 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16001 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16002 TargetLowering::DAGCombinerInfo &DCI,
16003 const X86Subtarget *Subtarget) {
16004 EVT VT = N->getValueType(0);
16005 if (DCI.isBeforeLegalizeOps())
16008 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16012 SDValue N0 = N->getOperand(0);
16013 SDValue N1 = N->getOperand(1);
16015 // look for psign/blend
16016 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16017 if (!Subtarget->hasSSSE3() ||
16018 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16021 // Canonicalize pandn to RHS
16022 if (N0.getOpcode() == X86ISD::ANDNP)
16024 // or (and (m, y), (pandn m, x))
16025 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16026 SDValue Mask = N1.getOperand(0);
16027 SDValue X = N1.getOperand(1);
16029 if (N0.getOperand(0) == Mask)
16030 Y = N0.getOperand(1);
16031 if (N0.getOperand(1) == Mask)
16032 Y = N0.getOperand(0);
16034 // Check to see if the mask appeared in both the AND and ANDNP and
16038 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16039 // Look through mask bitcast.
16040 if (Mask.getOpcode() == ISD::BITCAST)
16041 Mask = Mask.getOperand(0);
16042 if (X.getOpcode() == ISD::BITCAST)
16043 X = X.getOperand(0);
16044 if (Y.getOpcode() == ISD::BITCAST)
16045 Y = Y.getOperand(0);
16047 EVT MaskVT = Mask.getValueType();
16049 // Validate that the Mask operand is a vector sra node.
16050 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16051 // there is no psrai.b
16052 if (Mask.getOpcode() != X86ISD::VSRAI)
16055 // Check that the SRA is all signbits.
16056 SDValue SraC = Mask.getOperand(1);
16057 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16058 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16059 if ((SraAmt + 1) != EltBits)
16062 DebugLoc DL = N->getDebugLoc();
16064 // We are going to replace the AND, OR, NAND with either BLEND
16065 // or PSIGN, which only look at the MSB. The VSRAI instruction
16066 // does not affect the highest bit, so we can get rid of it.
16067 Mask = Mask.getOperand(0);
16069 // Now we know we at least have a plendvb with the mask val. See if
16070 // we can form a psignb/w/d.
16071 // psign = x.type == y.type == mask.type && y = sub(0, x);
16072 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16073 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16074 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16075 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16076 "Unsupported VT for PSIGN");
16077 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16078 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16080 // PBLENDVB only available on SSE 4.1
16081 if (!Subtarget->hasSSE41())
16084 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16086 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16087 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16088 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16089 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16090 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16094 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16097 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16098 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16100 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16102 if (!N0.hasOneUse() || !N1.hasOneUse())
16105 SDValue ShAmt0 = N0.getOperand(1);
16106 if (ShAmt0.getValueType() != MVT::i8)
16108 SDValue ShAmt1 = N1.getOperand(1);
16109 if (ShAmt1.getValueType() != MVT::i8)
16111 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16112 ShAmt0 = ShAmt0.getOperand(0);
16113 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16114 ShAmt1 = ShAmt1.getOperand(0);
16116 DebugLoc DL = N->getDebugLoc();
16117 unsigned Opc = X86ISD::SHLD;
16118 SDValue Op0 = N0.getOperand(0);
16119 SDValue Op1 = N1.getOperand(0);
16120 if (ShAmt0.getOpcode() == ISD::SUB) {
16121 Opc = X86ISD::SHRD;
16122 std::swap(Op0, Op1);
16123 std::swap(ShAmt0, ShAmt1);
16126 unsigned Bits = VT.getSizeInBits();
16127 if (ShAmt1.getOpcode() == ISD::SUB) {
16128 SDValue Sum = ShAmt1.getOperand(0);
16129 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16130 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16131 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16132 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16133 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16134 return DAG.getNode(Opc, DL, VT,
16136 DAG.getNode(ISD::TRUNCATE, DL,
16139 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16140 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16142 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16143 return DAG.getNode(Opc, DL, VT,
16144 N0.getOperand(0), N1.getOperand(0),
16145 DAG.getNode(ISD::TRUNCATE, DL,
16152 // Generate NEG and CMOV for integer abs.
16153 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16154 EVT VT = N->getValueType(0);
16156 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16157 // 8-bit integer abs to NEG and CMOV.
16158 if (VT.isInteger() && VT.getSizeInBits() == 8)
16161 SDValue N0 = N->getOperand(0);
16162 SDValue N1 = N->getOperand(1);
16163 DebugLoc DL = N->getDebugLoc();
16165 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16166 // and change it to SUB and CMOV.
16167 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16168 N0.getOpcode() == ISD::ADD &&
16169 N0.getOperand(1) == N1 &&
16170 N1.getOpcode() == ISD::SRA &&
16171 N1.getOperand(0) == N0.getOperand(0))
16172 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16173 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16174 // Generate SUB & CMOV.
16175 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16176 DAG.getConstant(0, VT), N0.getOperand(0));
16178 SDValue Ops[] = { N0.getOperand(0), Neg,
16179 DAG.getConstant(X86::COND_GE, MVT::i8),
16180 SDValue(Neg.getNode(), 1) };
16181 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16182 Ops, array_lengthof(Ops));
16187 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16188 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16189 TargetLowering::DAGCombinerInfo &DCI,
16190 const X86Subtarget *Subtarget) {
16191 EVT VT = N->getValueType(0);
16192 if (DCI.isBeforeLegalizeOps())
16195 if (Subtarget->hasCMov()) {
16196 SDValue RV = performIntegerAbsCombine(N, DAG);
16201 // Try forming BMI if it is available.
16202 if (!Subtarget->hasBMI())
16205 if (VT != MVT::i32 && VT != MVT::i64)
16208 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16210 // Create BLSMSK instructions by finding X ^ (X-1)
16211 SDValue N0 = N->getOperand(0);
16212 SDValue N1 = N->getOperand(1);
16213 DebugLoc DL = N->getDebugLoc();
16215 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16216 isAllOnes(N0.getOperand(1)))
16217 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16219 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16220 isAllOnes(N1.getOperand(1)))
16221 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16226 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16227 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16228 TargetLowering::DAGCombinerInfo &DCI,
16229 const X86Subtarget *Subtarget) {
16230 LoadSDNode *Ld = cast<LoadSDNode>(N);
16231 EVT RegVT = Ld->getValueType(0);
16232 EVT MemVT = Ld->getMemoryVT();
16233 DebugLoc dl = Ld->getDebugLoc();
16234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16236 ISD::LoadExtType Ext = Ld->getExtensionType();
16238 // If this is a vector EXT Load then attempt to optimize it using a
16239 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16240 // expansion is still better than scalar code.
16241 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16242 // emit a shuffle and a arithmetic shift.
16243 // TODO: It is possible to support ZExt by zeroing the undef values
16244 // during the shuffle phase or after the shuffle.
16245 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16246 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16247 assert(MemVT != RegVT && "Cannot extend to the same type");
16248 assert(MemVT.isVector() && "Must load a vector from memory");
16250 unsigned NumElems = RegVT.getVectorNumElements();
16251 unsigned RegSz = RegVT.getSizeInBits();
16252 unsigned MemSz = MemVT.getSizeInBits();
16253 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16255 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16258 // All sizes must be a power of two.
16259 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16262 // Attempt to load the original value using scalar loads.
16263 // Find the largest scalar type that divides the total loaded size.
16264 MVT SclrLoadTy = MVT::i8;
16265 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16266 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16267 MVT Tp = (MVT::SimpleValueType)tp;
16268 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16273 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16274 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16276 SclrLoadTy = MVT::f64;
16278 // Calculate the number of scalar loads that we need to perform
16279 // in order to load our vector from memory.
16280 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16281 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16284 unsigned loadRegZize = RegSz;
16285 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16288 // Represent our vector as a sequence of elements which are the
16289 // largest scalar that we can load.
16290 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16291 loadRegZize/SclrLoadTy.getSizeInBits());
16293 // Represent the data using the same element type that is stored in
16294 // memory. In practice, we ''widen'' MemVT.
16296 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16297 loadRegZize/MemVT.getScalarType().getSizeInBits());
16299 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16300 "Invalid vector type");
16302 // We can't shuffle using an illegal type.
16303 if (!TLI.isTypeLegal(WideVecVT))
16306 SmallVector<SDValue, 8> Chains;
16307 SDValue Ptr = Ld->getBasePtr();
16308 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16309 TLI.getPointerTy());
16310 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16312 for (unsigned i = 0; i < NumLoads; ++i) {
16313 // Perform a single load.
16314 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16315 Ptr, Ld->getPointerInfo(),
16316 Ld->isVolatile(), Ld->isNonTemporal(),
16317 Ld->isInvariant(), Ld->getAlignment());
16318 Chains.push_back(ScalarLoad.getValue(1));
16319 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16320 // another round of DAGCombining.
16322 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16324 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16325 ScalarLoad, DAG.getIntPtrConstant(i));
16327 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16330 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16333 // Bitcast the loaded value to a vector of the original element type, in
16334 // the size of the target vector type.
16335 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16336 unsigned SizeRatio = RegSz/MemSz;
16338 if (Ext == ISD::SEXTLOAD) {
16339 // If we have SSE4.1 we can directly emit a VSEXT node.
16340 if (Subtarget->hasSSE41()) {
16341 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16342 return DCI.CombineTo(N, Sext, TF, true);
16345 // Otherwise we'll shuffle the small elements in the high bits of the
16346 // larger type and perform an arithmetic shift. If the shift is not legal
16347 // it's better to scalarize.
16348 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16351 // Redistribute the loaded elements into the different locations.
16352 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16353 for (unsigned i = 0; i != NumElems; ++i)
16354 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16356 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16357 DAG.getUNDEF(WideVecVT),
16360 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16362 // Build the arithmetic shift.
16363 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16364 MemVT.getVectorElementType().getSizeInBits();
16365 SmallVector<SDValue, 8> C(NumElems,
16366 DAG.getConstant(Amt, RegVT.getScalarType()));
16367 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16368 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16370 return DCI.CombineTo(N, Shuff, TF, true);
16373 // Redistribute the loaded elements into the different locations.
16374 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16375 for (unsigned i = 0; i != NumElems; ++i)
16376 ShuffleVec[i*SizeRatio] = i;
16378 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16379 DAG.getUNDEF(WideVecVT),
16382 // Bitcast to the requested type.
16383 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16384 // Replace the original load with the new sequence
16385 // and return the new chain.
16386 return DCI.CombineTo(N, Shuff, TF, true);
16392 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16393 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16394 const X86Subtarget *Subtarget) {
16395 StoreSDNode *St = cast<StoreSDNode>(N);
16396 EVT VT = St->getValue().getValueType();
16397 EVT StVT = St->getMemoryVT();
16398 DebugLoc dl = St->getDebugLoc();
16399 SDValue StoredVal = St->getOperand(1);
16400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16402 // If we are saving a concatenation of two XMM registers, perform two stores.
16403 // On Sandy Bridge, 256-bit memory operations are executed by two
16404 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16405 // memory operation.
16406 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16407 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16408 StoredVal.getNumOperands() == 2) {
16409 SDValue Value0 = StoredVal.getOperand(0);
16410 SDValue Value1 = StoredVal.getOperand(1);
16412 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16413 SDValue Ptr0 = St->getBasePtr();
16414 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16416 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16417 St->getPointerInfo(), St->isVolatile(),
16418 St->isNonTemporal(), St->getAlignment());
16419 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16420 St->getPointerInfo(), St->isVolatile(),
16421 St->isNonTemporal(), St->getAlignment());
16422 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16425 // Optimize trunc store (of multiple scalars) to shuffle and store.
16426 // First, pack all of the elements in one place. Next, store to memory
16427 // in fewer chunks.
16428 if (St->isTruncatingStore() && VT.isVector()) {
16429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16430 unsigned NumElems = VT.getVectorNumElements();
16431 assert(StVT != VT && "Cannot truncate to the same type");
16432 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16433 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16435 // From, To sizes and ElemCount must be pow of two
16436 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16437 // We are going to use the original vector elt for storing.
16438 // Accumulated smaller vector elements must be a multiple of the store size.
16439 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16441 unsigned SizeRatio = FromSz / ToSz;
16443 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16445 // Create a type on which we perform the shuffle
16446 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16447 StVT.getScalarType(), NumElems*SizeRatio);
16449 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16451 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16452 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16453 for (unsigned i = 0; i != NumElems; ++i)
16454 ShuffleVec[i] = i * SizeRatio;
16456 // Can't shuffle using an illegal type.
16457 if (!TLI.isTypeLegal(WideVecVT))
16460 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16461 DAG.getUNDEF(WideVecVT),
16463 // At this point all of the data is stored at the bottom of the
16464 // register. We now need to save it to mem.
16466 // Find the largest store unit
16467 MVT StoreType = MVT::i8;
16468 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16469 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16470 MVT Tp = (MVT::SimpleValueType)tp;
16471 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16475 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16476 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16477 (64 <= NumElems * ToSz))
16478 StoreType = MVT::f64;
16480 // Bitcast the original vector into a vector of store-size units
16481 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16482 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16483 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16484 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16485 SmallVector<SDValue, 8> Chains;
16486 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16487 TLI.getPointerTy());
16488 SDValue Ptr = St->getBasePtr();
16490 // Perform one or more big stores into memory.
16491 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16492 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16493 StoreType, ShuffWide,
16494 DAG.getIntPtrConstant(i));
16495 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16496 St->getPointerInfo(), St->isVolatile(),
16497 St->isNonTemporal(), St->getAlignment());
16498 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16499 Chains.push_back(Ch);
16502 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16506 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16507 // the FP state in cases where an emms may be missing.
16508 // A preferable solution to the general problem is to figure out the right
16509 // places to insert EMMS. This qualifies as a quick hack.
16511 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16512 if (VT.getSizeInBits() != 64)
16515 const Function *F = DAG.getMachineFunction().getFunction();
16516 bool NoImplicitFloatOps = F->getFnAttributes().
16517 hasAttribute(Attribute::NoImplicitFloat);
16518 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16519 && Subtarget->hasSSE2();
16520 if ((VT.isVector() ||
16521 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16522 isa<LoadSDNode>(St->getValue()) &&
16523 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16524 St->getChain().hasOneUse() && !St->isVolatile()) {
16525 SDNode* LdVal = St->getValue().getNode();
16526 LoadSDNode *Ld = 0;
16527 int TokenFactorIndex = -1;
16528 SmallVector<SDValue, 8> Ops;
16529 SDNode* ChainVal = St->getChain().getNode();
16530 // Must be a store of a load. We currently handle two cases: the load
16531 // is a direct child, and it's under an intervening TokenFactor. It is
16532 // possible to dig deeper under nested TokenFactors.
16533 if (ChainVal == LdVal)
16534 Ld = cast<LoadSDNode>(St->getChain());
16535 else if (St->getValue().hasOneUse() &&
16536 ChainVal->getOpcode() == ISD::TokenFactor) {
16537 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16538 if (ChainVal->getOperand(i).getNode() == LdVal) {
16539 TokenFactorIndex = i;
16540 Ld = cast<LoadSDNode>(St->getValue());
16542 Ops.push_back(ChainVal->getOperand(i));
16546 if (!Ld || !ISD::isNormalLoad(Ld))
16549 // If this is not the MMX case, i.e. we are just turning i64 load/store
16550 // into f64 load/store, avoid the transformation if there are multiple
16551 // uses of the loaded value.
16552 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16555 DebugLoc LdDL = Ld->getDebugLoc();
16556 DebugLoc StDL = N->getDebugLoc();
16557 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16558 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16560 if (Subtarget->is64Bit() || F64IsLegal) {
16561 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16562 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16563 Ld->getPointerInfo(), Ld->isVolatile(),
16564 Ld->isNonTemporal(), Ld->isInvariant(),
16565 Ld->getAlignment());
16566 SDValue NewChain = NewLd.getValue(1);
16567 if (TokenFactorIndex != -1) {
16568 Ops.push_back(NewChain);
16569 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16572 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16573 St->getPointerInfo(),
16574 St->isVolatile(), St->isNonTemporal(),
16575 St->getAlignment());
16578 // Otherwise, lower to two pairs of 32-bit loads / stores.
16579 SDValue LoAddr = Ld->getBasePtr();
16580 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16581 DAG.getConstant(4, MVT::i32));
16583 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16584 Ld->getPointerInfo(),
16585 Ld->isVolatile(), Ld->isNonTemporal(),
16586 Ld->isInvariant(), Ld->getAlignment());
16587 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16588 Ld->getPointerInfo().getWithOffset(4),
16589 Ld->isVolatile(), Ld->isNonTemporal(),
16591 MinAlign(Ld->getAlignment(), 4));
16593 SDValue NewChain = LoLd.getValue(1);
16594 if (TokenFactorIndex != -1) {
16595 Ops.push_back(LoLd);
16596 Ops.push_back(HiLd);
16597 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16601 LoAddr = St->getBasePtr();
16602 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16603 DAG.getConstant(4, MVT::i32));
16605 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16606 St->getPointerInfo(),
16607 St->isVolatile(), St->isNonTemporal(),
16608 St->getAlignment());
16609 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16610 St->getPointerInfo().getWithOffset(4),
16612 St->isNonTemporal(),
16613 MinAlign(St->getAlignment(), 4));
16614 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16619 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16620 /// and return the operands for the horizontal operation in LHS and RHS. A
16621 /// horizontal operation performs the binary operation on successive elements
16622 /// of its first operand, then on successive elements of its second operand,
16623 /// returning the resulting values in a vector. For example, if
16624 /// A = < float a0, float a1, float a2, float a3 >
16626 /// B = < float b0, float b1, float b2, float b3 >
16627 /// then the result of doing a horizontal operation on A and B is
16628 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16629 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16630 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16631 /// set to A, RHS to B, and the routine returns 'true'.
16632 /// Note that the binary operation should have the property that if one of the
16633 /// operands is UNDEF then the result is UNDEF.
16634 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16635 // Look for the following pattern: if
16636 // A = < float a0, float a1, float a2, float a3 >
16637 // B = < float b0, float b1, float b2, float b3 >
16639 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16640 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16641 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16642 // which is A horizontal-op B.
16644 // At least one of the operands should be a vector shuffle.
16645 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16646 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16649 EVT VT = LHS.getValueType();
16651 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16652 "Unsupported vector type for horizontal add/sub");
16654 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16655 // operate independently on 128-bit lanes.
16656 unsigned NumElts = VT.getVectorNumElements();
16657 unsigned NumLanes = VT.getSizeInBits()/128;
16658 unsigned NumLaneElts = NumElts / NumLanes;
16659 assert((NumLaneElts % 2 == 0) &&
16660 "Vector type should have an even number of elements in each lane");
16661 unsigned HalfLaneElts = NumLaneElts/2;
16663 // View LHS in the form
16664 // LHS = VECTOR_SHUFFLE A, B, LMask
16665 // If LHS is not a shuffle then pretend it is the shuffle
16666 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16667 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16670 SmallVector<int, 16> LMask(NumElts);
16671 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16672 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16673 A = LHS.getOperand(0);
16674 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16675 B = LHS.getOperand(1);
16676 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16677 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16679 if (LHS.getOpcode() != ISD::UNDEF)
16681 for (unsigned i = 0; i != NumElts; ++i)
16685 // Likewise, view RHS in the form
16686 // RHS = VECTOR_SHUFFLE C, D, RMask
16688 SmallVector<int, 16> RMask(NumElts);
16689 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16690 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16691 C = RHS.getOperand(0);
16692 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16693 D = RHS.getOperand(1);
16694 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16695 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16697 if (RHS.getOpcode() != ISD::UNDEF)
16699 for (unsigned i = 0; i != NumElts; ++i)
16703 // Check that the shuffles are both shuffling the same vectors.
16704 if (!(A == C && B == D) && !(A == D && B == C))
16707 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16708 if (!A.getNode() && !B.getNode())
16711 // If A and B occur in reverse order in RHS, then "swap" them (which means
16712 // rewriting the mask).
16714 CommuteVectorShuffleMask(RMask, NumElts);
16716 // At this point LHS and RHS are equivalent to
16717 // LHS = VECTOR_SHUFFLE A, B, LMask
16718 // RHS = VECTOR_SHUFFLE A, B, RMask
16719 // Check that the masks correspond to performing a horizontal operation.
16720 for (unsigned i = 0; i != NumElts; ++i) {
16721 int LIdx = LMask[i], RIdx = RMask[i];
16723 // Ignore any UNDEF components.
16724 if (LIdx < 0 || RIdx < 0 ||
16725 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16726 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16729 // Check that successive elements are being operated on. If not, this is
16730 // not a horizontal operation.
16731 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16732 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16733 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16734 if (!(LIdx == Index && RIdx == Index + 1) &&
16735 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16739 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16740 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16744 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16745 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16746 const X86Subtarget *Subtarget) {
16747 EVT VT = N->getValueType(0);
16748 SDValue LHS = N->getOperand(0);
16749 SDValue RHS = N->getOperand(1);
16751 // Try to synthesize horizontal adds from adds of shuffles.
16752 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16753 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16754 isHorizontalBinOp(LHS, RHS, true))
16755 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16759 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16760 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16761 const X86Subtarget *Subtarget) {
16762 EVT VT = N->getValueType(0);
16763 SDValue LHS = N->getOperand(0);
16764 SDValue RHS = N->getOperand(1);
16766 // Try to synthesize horizontal subs from subs of shuffles.
16767 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16768 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16769 isHorizontalBinOp(LHS, RHS, false))
16770 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16774 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16775 /// X86ISD::FXOR nodes.
16776 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16777 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16778 // F[X]OR(0.0, x) -> x
16779 // F[X]OR(x, 0.0) -> x
16780 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16781 if (C->getValueAPF().isPosZero())
16782 return N->getOperand(1);
16783 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16784 if (C->getValueAPF().isPosZero())
16785 return N->getOperand(0);
16789 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16790 /// X86ISD::FMAX nodes.
16791 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16792 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16794 // Only perform optimizations if UnsafeMath is used.
16795 if (!DAG.getTarget().Options.UnsafeFPMath)
16798 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16799 // into FMINC and FMAXC, which are Commutative operations.
16800 unsigned NewOp = 0;
16801 switch (N->getOpcode()) {
16802 default: llvm_unreachable("unknown opcode");
16803 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16804 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16807 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16808 N->getOperand(0), N->getOperand(1));
16811 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16812 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16813 // FAND(0.0, x) -> 0.0
16814 // FAND(x, 0.0) -> 0.0
16815 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16816 if (C->getValueAPF().isPosZero())
16817 return N->getOperand(0);
16818 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16819 if (C->getValueAPF().isPosZero())
16820 return N->getOperand(1);
16824 static SDValue PerformBTCombine(SDNode *N,
16826 TargetLowering::DAGCombinerInfo &DCI) {
16827 // BT ignores high bits in the bit index operand.
16828 SDValue Op1 = N->getOperand(1);
16829 if (Op1.hasOneUse()) {
16830 unsigned BitWidth = Op1.getValueSizeInBits();
16831 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16832 APInt KnownZero, KnownOne;
16833 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16834 !DCI.isBeforeLegalizeOps());
16835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16836 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16837 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16838 DCI.CommitTargetLoweringOpt(TLO);
16843 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16844 SDValue Op = N->getOperand(0);
16845 if (Op.getOpcode() == ISD::BITCAST)
16846 Op = Op.getOperand(0);
16847 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16848 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16849 VT.getVectorElementType().getSizeInBits() ==
16850 OpVT.getVectorElementType().getSizeInBits()) {
16851 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16856 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16857 TargetLowering::DAGCombinerInfo &DCI,
16858 const X86Subtarget *Subtarget) {
16859 if (!DCI.isBeforeLegalizeOps())
16862 if (!Subtarget->hasFp256())
16865 EVT VT = N->getValueType(0);
16866 if (VT.isVector() && VT.getSizeInBits() == 256) {
16867 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16875 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16876 const X86Subtarget* Subtarget) {
16877 DebugLoc dl = N->getDebugLoc();
16878 EVT VT = N->getValueType(0);
16880 // Let legalize expand this if it isn't a legal type yet.
16881 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16884 EVT ScalarVT = VT.getScalarType();
16885 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16886 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16889 SDValue A = N->getOperand(0);
16890 SDValue B = N->getOperand(1);
16891 SDValue C = N->getOperand(2);
16893 bool NegA = (A.getOpcode() == ISD::FNEG);
16894 bool NegB = (B.getOpcode() == ISD::FNEG);
16895 bool NegC = (C.getOpcode() == ISD::FNEG);
16897 // Negative multiplication when NegA xor NegB
16898 bool NegMul = (NegA != NegB);
16900 A = A.getOperand(0);
16902 B = B.getOperand(0);
16904 C = C.getOperand(0);
16908 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16910 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16912 return DAG.getNode(Opcode, dl, VT, A, B, C);
16915 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16916 TargetLowering::DAGCombinerInfo &DCI,
16917 const X86Subtarget *Subtarget) {
16918 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16919 // (and (i32 x86isd::setcc_carry), 1)
16920 // This eliminates the zext. This transformation is necessary because
16921 // ISD::SETCC is always legalized to i8.
16922 DebugLoc dl = N->getDebugLoc();
16923 SDValue N0 = N->getOperand(0);
16924 EVT VT = N->getValueType(0);
16926 if (N0.getOpcode() == ISD::AND &&
16928 N0.getOperand(0).hasOneUse()) {
16929 SDValue N00 = N0.getOperand(0);
16930 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
16931 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16932 if (!C || C->getZExtValue() != 1)
16934 return DAG.getNode(ISD::AND, dl, VT,
16935 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16936 N00.getOperand(0), N00.getOperand(1)),
16937 DAG.getConstant(1, VT));
16941 if (VT.isVector() && VT.getSizeInBits() == 256) {
16942 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16950 // Optimize x == -y --> x+y == 0
16951 // x != -y --> x+y != 0
16952 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16953 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16954 SDValue LHS = N->getOperand(0);
16955 SDValue RHS = N->getOperand(1);
16957 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16958 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16959 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16960 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16961 LHS.getValueType(), RHS, LHS.getOperand(1));
16962 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16963 addV, DAG.getConstant(0, addV.getValueType()), CC);
16965 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16966 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16967 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16968 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16969 RHS.getValueType(), LHS, RHS.getOperand(1));
16970 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16971 addV, DAG.getConstant(0, addV.getValueType()), CC);
16976 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
16977 // as "sbb reg,reg", since it can be extended without zext and produces
16978 // an all-ones bit which is more useful than 0/1 in some cases.
16979 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16980 return DAG.getNode(ISD::AND, DL, MVT::i8,
16981 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16982 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16983 DAG.getConstant(1, MVT::i8));
16986 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16987 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16988 TargetLowering::DAGCombinerInfo &DCI,
16989 const X86Subtarget *Subtarget) {
16990 DebugLoc DL = N->getDebugLoc();
16991 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16992 SDValue EFLAGS = N->getOperand(1);
16994 if (CC == X86::COND_A) {
16995 // Try to convert COND_A into COND_B in an attempt to facilitate
16996 // materializing "setb reg".
16998 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16999 // cannot take an immediate as its first operand.
17001 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17002 EFLAGS.getValueType().isInteger() &&
17003 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17004 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17005 EFLAGS.getNode()->getVTList(),
17006 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17007 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17008 return MaterializeSETB(DL, NewEFLAGS, DAG);
17012 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17013 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17015 if (CC == X86::COND_B)
17016 return MaterializeSETB(DL, EFLAGS, DAG);
17020 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17021 if (Flags.getNode()) {
17022 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17023 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17029 // Optimize branch condition evaluation.
17031 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17032 TargetLowering::DAGCombinerInfo &DCI,
17033 const X86Subtarget *Subtarget) {
17034 DebugLoc DL = N->getDebugLoc();
17035 SDValue Chain = N->getOperand(0);
17036 SDValue Dest = N->getOperand(1);
17037 SDValue EFLAGS = N->getOperand(3);
17038 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17042 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17043 if (Flags.getNode()) {
17044 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17045 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17052 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17053 const X86TargetLowering *XTLI) {
17054 SDValue Op0 = N->getOperand(0);
17055 EVT InVT = Op0->getValueType(0);
17057 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17058 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17059 DebugLoc dl = N->getDebugLoc();
17060 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17061 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17062 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17065 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17066 // a 32-bit target where SSE doesn't support i64->FP operations.
17067 if (Op0.getOpcode() == ISD::LOAD) {
17068 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17069 EVT VT = Ld->getValueType(0);
17070 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17071 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17072 !XTLI->getSubtarget()->is64Bit() &&
17073 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17074 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17075 Ld->getChain(), Op0, DAG);
17076 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17083 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17084 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17085 X86TargetLowering::DAGCombinerInfo &DCI) {
17086 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17087 // the result is either zero or one (depending on the input carry bit).
17088 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17089 if (X86::isZeroNode(N->getOperand(0)) &&
17090 X86::isZeroNode(N->getOperand(1)) &&
17091 // We don't have a good way to replace an EFLAGS use, so only do this when
17093 SDValue(N, 1).use_empty()) {
17094 DebugLoc DL = N->getDebugLoc();
17095 EVT VT = N->getValueType(0);
17096 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17097 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17098 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17099 DAG.getConstant(X86::COND_B,MVT::i8),
17101 DAG.getConstant(1, VT));
17102 return DCI.CombineTo(N, Res1, CarryOut);
17108 // fold (add Y, (sete X, 0)) -> adc 0, Y
17109 // (add Y, (setne X, 0)) -> sbb -1, Y
17110 // (sub (sete X, 0), Y) -> sbb 0, Y
17111 // (sub (setne X, 0), Y) -> adc -1, Y
17112 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17113 DebugLoc DL = N->getDebugLoc();
17115 // Look through ZExts.
17116 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17117 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17120 SDValue SetCC = Ext.getOperand(0);
17121 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17124 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17125 if (CC != X86::COND_E && CC != X86::COND_NE)
17128 SDValue Cmp = SetCC.getOperand(1);
17129 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17130 !X86::isZeroNode(Cmp.getOperand(1)) ||
17131 !Cmp.getOperand(0).getValueType().isInteger())
17134 SDValue CmpOp0 = Cmp.getOperand(0);
17135 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17136 DAG.getConstant(1, CmpOp0.getValueType()));
17138 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17139 if (CC == X86::COND_NE)
17140 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17141 DL, OtherVal.getValueType(), OtherVal,
17142 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17143 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17144 DL, OtherVal.getValueType(), OtherVal,
17145 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17148 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17149 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17150 const X86Subtarget *Subtarget) {
17151 EVT VT = N->getValueType(0);
17152 SDValue Op0 = N->getOperand(0);
17153 SDValue Op1 = N->getOperand(1);
17155 // Try to synthesize horizontal adds from adds of shuffles.
17156 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17157 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17158 isHorizontalBinOp(Op0, Op1, true))
17159 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17161 return OptimizeConditionalInDecrement(N, DAG);
17164 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17165 const X86Subtarget *Subtarget) {
17166 SDValue Op0 = N->getOperand(0);
17167 SDValue Op1 = N->getOperand(1);
17169 // X86 can't encode an immediate LHS of a sub. See if we can push the
17170 // negation into a preceding instruction.
17171 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17172 // If the RHS of the sub is a XOR with one use and a constant, invert the
17173 // immediate. Then add one to the LHS of the sub so we can turn
17174 // X-Y -> X+~Y+1, saving one register.
17175 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17176 isa<ConstantSDNode>(Op1.getOperand(1))) {
17177 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17178 EVT VT = Op0.getValueType();
17179 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17181 DAG.getConstant(~XorC, VT));
17182 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17183 DAG.getConstant(C->getAPIntValue()+1, VT));
17187 // Try to synthesize horizontal adds from adds of shuffles.
17188 EVT VT = N->getValueType(0);
17189 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17190 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17191 isHorizontalBinOp(Op0, Op1, true))
17192 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17194 return OptimizeConditionalInDecrement(N, DAG);
17197 /// performVZEXTCombine - Performs build vector combines
17198 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17199 TargetLowering::DAGCombinerInfo &DCI,
17200 const X86Subtarget *Subtarget) {
17201 // (vzext (bitcast (vzext (x)) -> (vzext x)
17202 SDValue In = N->getOperand(0);
17203 while (In.getOpcode() == ISD::BITCAST)
17204 In = In.getOperand(0);
17206 if (In.getOpcode() != X86ISD::VZEXT)
17209 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17212 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17213 DAGCombinerInfo &DCI) const {
17214 SelectionDAG &DAG = DCI.DAG;
17215 switch (N->getOpcode()) {
17217 case ISD::EXTRACT_VECTOR_ELT:
17218 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17220 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17221 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17222 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17223 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17224 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17225 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17228 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17229 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17230 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17231 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17232 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17233 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17234 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17235 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17236 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17238 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17240 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17241 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17242 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17243 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17244 case ISD::ANY_EXTEND:
17245 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17246 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17247 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17248 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17249 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17250 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17251 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17252 case X86ISD::SHUFP: // Handle all target specific shuffles
17253 case X86ISD::PALIGN:
17254 case X86ISD::UNPCKH:
17255 case X86ISD::UNPCKL:
17256 case X86ISD::MOVHLPS:
17257 case X86ISD::MOVLHPS:
17258 case X86ISD::PSHUFD:
17259 case X86ISD::PSHUFHW:
17260 case X86ISD::PSHUFLW:
17261 case X86ISD::MOVSS:
17262 case X86ISD::MOVSD:
17263 case X86ISD::VPERMILP:
17264 case X86ISD::VPERM2X128:
17265 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17266 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17272 /// isTypeDesirableForOp - Return true if the target has native support for
17273 /// the specified value type and it is 'desirable' to use the type for the
17274 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17275 /// instruction encodings are longer and some i16 instructions are slow.
17276 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17277 if (!isTypeLegal(VT))
17279 if (VT != MVT::i16)
17286 case ISD::SIGN_EXTEND:
17287 case ISD::ZERO_EXTEND:
17288 case ISD::ANY_EXTEND:
17301 /// IsDesirableToPromoteOp - This method query the target whether it is
17302 /// beneficial for dag combiner to promote the specified node. If true, it
17303 /// should return the desired promotion type by reference.
17304 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17305 EVT VT = Op.getValueType();
17306 if (VT != MVT::i16)
17309 bool Promote = false;
17310 bool Commute = false;
17311 switch (Op.getOpcode()) {
17314 LoadSDNode *LD = cast<LoadSDNode>(Op);
17315 // If the non-extending load has a single use and it's not live out, then it
17316 // might be folded.
17317 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17318 Op.hasOneUse()*/) {
17319 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17320 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17321 // The only case where we'd want to promote LOAD (rather then it being
17322 // promoted as an operand is when it's only use is liveout.
17323 if (UI->getOpcode() != ISD::CopyToReg)
17330 case ISD::SIGN_EXTEND:
17331 case ISD::ZERO_EXTEND:
17332 case ISD::ANY_EXTEND:
17337 SDValue N0 = Op.getOperand(0);
17338 // Look out for (store (shl (load), x)).
17339 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17352 SDValue N0 = Op.getOperand(0);
17353 SDValue N1 = Op.getOperand(1);
17354 if (!Commute && MayFoldLoad(N1))
17356 // Avoid disabling potential load folding opportunities.
17357 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17359 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17369 //===----------------------------------------------------------------------===//
17370 // X86 Inline Assembly Support
17371 //===----------------------------------------------------------------------===//
17374 // Helper to match a string separated by whitespace.
17375 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17376 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17378 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17379 StringRef piece(*args[i]);
17380 if (!s.startswith(piece)) // Check if the piece matches.
17383 s = s.substr(piece.size());
17384 StringRef::size_type pos = s.find_first_not_of(" \t");
17385 if (pos == 0) // We matched a prefix.
17393 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17396 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17397 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17399 std::string AsmStr = IA->getAsmString();
17401 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17402 if (!Ty || Ty->getBitWidth() % 16 != 0)
17405 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17406 SmallVector<StringRef, 4> AsmPieces;
17407 SplitString(AsmStr, AsmPieces, ";\n");
17409 switch (AsmPieces.size()) {
17410 default: return false;
17412 // FIXME: this should verify that we are targeting a 486 or better. If not,
17413 // we will turn this bswap into something that will be lowered to logical
17414 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17415 // lower so don't worry about this.
17417 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17418 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17419 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17420 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17421 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17422 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17423 // No need to check constraints, nothing other than the equivalent of
17424 // "=r,0" would be valid here.
17425 return IntrinsicLowering::LowerToByteSwap(CI);
17428 // rorw $$8, ${0:w} --> llvm.bswap.i16
17429 if (CI->getType()->isIntegerTy(16) &&
17430 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17431 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17432 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17434 const std::string &ConstraintsStr = IA->getConstraintString();
17435 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17436 std::sort(AsmPieces.begin(), AsmPieces.end());
17437 if (AsmPieces.size() == 4 &&
17438 AsmPieces[0] == "~{cc}" &&
17439 AsmPieces[1] == "~{dirflag}" &&
17440 AsmPieces[2] == "~{flags}" &&
17441 AsmPieces[3] == "~{fpsr}")
17442 return IntrinsicLowering::LowerToByteSwap(CI);
17446 if (CI->getType()->isIntegerTy(32) &&
17447 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17448 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17449 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17450 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17452 const std::string &ConstraintsStr = IA->getConstraintString();
17453 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17454 std::sort(AsmPieces.begin(), AsmPieces.end());
17455 if (AsmPieces.size() == 4 &&
17456 AsmPieces[0] == "~{cc}" &&
17457 AsmPieces[1] == "~{dirflag}" &&
17458 AsmPieces[2] == "~{flags}" &&
17459 AsmPieces[3] == "~{fpsr}")
17460 return IntrinsicLowering::LowerToByteSwap(CI);
17463 if (CI->getType()->isIntegerTy(64)) {
17464 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17465 if (Constraints.size() >= 2 &&
17466 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17467 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17468 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17469 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17470 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17471 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17472 return IntrinsicLowering::LowerToByteSwap(CI);
17480 /// getConstraintType - Given a constraint letter, return the type of
17481 /// constraint it is for this target.
17482 X86TargetLowering::ConstraintType
17483 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17484 if (Constraint.size() == 1) {
17485 switch (Constraint[0]) {
17496 return C_RegisterClass;
17520 return TargetLowering::getConstraintType(Constraint);
17523 /// Examine constraint type and operand type and determine a weight value.
17524 /// This object must already have been set up with the operand type
17525 /// and the current alternative constraint selected.
17526 TargetLowering::ConstraintWeight
17527 X86TargetLowering::getSingleConstraintMatchWeight(
17528 AsmOperandInfo &info, const char *constraint) const {
17529 ConstraintWeight weight = CW_Invalid;
17530 Value *CallOperandVal = info.CallOperandVal;
17531 // If we don't have a value, we can't do a match,
17532 // but allow it at the lowest weight.
17533 if (CallOperandVal == NULL)
17535 Type *type = CallOperandVal->getType();
17536 // Look at the constraint type.
17537 switch (*constraint) {
17539 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17550 if (CallOperandVal->getType()->isIntegerTy())
17551 weight = CW_SpecificReg;
17556 if (type->isFloatingPointTy())
17557 weight = CW_SpecificReg;
17560 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17561 weight = CW_SpecificReg;
17565 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17566 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17567 weight = CW_Register;
17570 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17571 if (C->getZExtValue() <= 31)
17572 weight = CW_Constant;
17576 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17577 if (C->getZExtValue() <= 63)
17578 weight = CW_Constant;
17582 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17583 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17584 weight = CW_Constant;
17588 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17589 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17590 weight = CW_Constant;
17594 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17595 if (C->getZExtValue() <= 3)
17596 weight = CW_Constant;
17600 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17601 if (C->getZExtValue() <= 0xff)
17602 weight = CW_Constant;
17607 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17608 weight = CW_Constant;
17612 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17613 if ((C->getSExtValue() >= -0x80000000LL) &&
17614 (C->getSExtValue() <= 0x7fffffffLL))
17615 weight = CW_Constant;
17619 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17620 if (C->getZExtValue() <= 0xffffffff)
17621 weight = CW_Constant;
17628 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17629 /// with another that has more specific requirements based on the type of the
17630 /// corresponding operand.
17631 const char *X86TargetLowering::
17632 LowerXConstraint(EVT ConstraintVT) const {
17633 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17634 // 'f' like normal targets.
17635 if (ConstraintVT.isFloatingPoint()) {
17636 if (Subtarget->hasSSE2())
17638 if (Subtarget->hasSSE1())
17642 return TargetLowering::LowerXConstraint(ConstraintVT);
17645 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17646 /// vector. If it is invalid, don't add anything to Ops.
17647 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17648 std::string &Constraint,
17649 std::vector<SDValue>&Ops,
17650 SelectionDAG &DAG) const {
17651 SDValue Result(0, 0);
17653 // Only support length 1 constraints for now.
17654 if (Constraint.length() > 1) return;
17656 char ConstraintLetter = Constraint[0];
17657 switch (ConstraintLetter) {
17660 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17661 if (C->getZExtValue() <= 31) {
17662 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17669 if (C->getZExtValue() <= 63) {
17670 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17676 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17677 if (isInt<8>(C->getSExtValue())) {
17678 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17685 if (C->getZExtValue() <= 255) {
17686 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17692 // 32-bit signed value
17693 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17694 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17695 C->getSExtValue())) {
17696 // Widen to 64 bits here to get it sign extended.
17697 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17700 // FIXME gcc accepts some relocatable values here too, but only in certain
17701 // memory models; it's complicated.
17706 // 32-bit unsigned value
17707 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17708 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17709 C->getZExtValue())) {
17710 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17714 // FIXME gcc accepts some relocatable values here too, but only in certain
17715 // memory models; it's complicated.
17719 // Literal immediates are always ok.
17720 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17721 // Widen to 64 bits here to get it sign extended.
17722 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17726 // In any sort of PIC mode addresses need to be computed at runtime by
17727 // adding in a register or some sort of table lookup. These can't
17728 // be used as immediates.
17729 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17732 // If we are in non-pic codegen mode, we allow the address of a global (with
17733 // an optional displacement) to be used with 'i'.
17734 GlobalAddressSDNode *GA = 0;
17735 int64_t Offset = 0;
17737 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17739 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17740 Offset += GA->getOffset();
17742 } else if (Op.getOpcode() == ISD::ADD) {
17743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17744 Offset += C->getZExtValue();
17745 Op = Op.getOperand(0);
17748 } else if (Op.getOpcode() == ISD::SUB) {
17749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17750 Offset += -C->getZExtValue();
17751 Op = Op.getOperand(0);
17756 // Otherwise, this isn't something we can handle, reject it.
17760 const GlobalValue *GV = GA->getGlobal();
17761 // If we require an extra load to get this address, as in PIC mode, we
17762 // can't accept it.
17763 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17764 getTargetMachine())))
17767 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17768 GA->getValueType(0), Offset);
17773 if (Result.getNode()) {
17774 Ops.push_back(Result);
17777 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17780 std::pair<unsigned, const TargetRegisterClass*>
17781 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17783 // First, see if this is a constraint that directly corresponds to an LLVM
17785 if (Constraint.size() == 1) {
17786 // GCC Constraint Letters
17787 switch (Constraint[0]) {
17789 // TODO: Slight differences here in allocation order and leaving
17790 // RIP in the class. Do they matter any more here than they do
17791 // in the normal allocation?
17792 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17793 if (Subtarget->is64Bit()) {
17794 if (VT == MVT::i32 || VT == MVT::f32)
17795 return std::make_pair(0U, &X86::GR32RegClass);
17796 if (VT == MVT::i16)
17797 return std::make_pair(0U, &X86::GR16RegClass);
17798 if (VT == MVT::i8 || VT == MVT::i1)
17799 return std::make_pair(0U, &X86::GR8RegClass);
17800 if (VT == MVT::i64 || VT == MVT::f64)
17801 return std::make_pair(0U, &X86::GR64RegClass);
17804 // 32-bit fallthrough
17805 case 'Q': // Q_REGS
17806 if (VT == MVT::i32 || VT == MVT::f32)
17807 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17808 if (VT == MVT::i16)
17809 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17810 if (VT == MVT::i8 || VT == MVT::i1)
17811 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17812 if (VT == MVT::i64)
17813 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17815 case 'r': // GENERAL_REGS
17816 case 'l': // INDEX_REGS
17817 if (VT == MVT::i8 || VT == MVT::i1)
17818 return std::make_pair(0U, &X86::GR8RegClass);
17819 if (VT == MVT::i16)
17820 return std::make_pair(0U, &X86::GR16RegClass);
17821 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17822 return std::make_pair(0U, &X86::GR32RegClass);
17823 return std::make_pair(0U, &X86::GR64RegClass);
17824 case 'R': // LEGACY_REGS
17825 if (VT == MVT::i8 || VT == MVT::i1)
17826 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17827 if (VT == MVT::i16)
17828 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17829 if (VT == MVT::i32 || !Subtarget->is64Bit())
17830 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17831 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17832 case 'f': // FP Stack registers.
17833 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17834 // value to the correct fpstack register class.
17835 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17836 return std::make_pair(0U, &X86::RFP32RegClass);
17837 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17838 return std::make_pair(0U, &X86::RFP64RegClass);
17839 return std::make_pair(0U, &X86::RFP80RegClass);
17840 case 'y': // MMX_REGS if MMX allowed.
17841 if (!Subtarget->hasMMX()) break;
17842 return std::make_pair(0U, &X86::VR64RegClass);
17843 case 'Y': // SSE_REGS if SSE2 allowed
17844 if (!Subtarget->hasSSE2()) break;
17846 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17847 if (!Subtarget->hasSSE1()) break;
17849 switch (VT.getSimpleVT().SimpleTy) {
17851 // Scalar SSE types.
17854 return std::make_pair(0U, &X86::FR32RegClass);
17857 return std::make_pair(0U, &X86::FR64RegClass);
17865 return std::make_pair(0U, &X86::VR128RegClass);
17873 return std::make_pair(0U, &X86::VR256RegClass);
17879 // Use the default implementation in TargetLowering to convert the register
17880 // constraint into a member of a register class.
17881 std::pair<unsigned, const TargetRegisterClass*> Res;
17882 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17884 // Not found as a standard register?
17885 if (Res.second == 0) {
17886 // Map st(0) -> st(7) -> ST0
17887 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17888 tolower(Constraint[1]) == 's' &&
17889 tolower(Constraint[2]) == 't' &&
17890 Constraint[3] == '(' &&
17891 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17892 Constraint[5] == ')' &&
17893 Constraint[6] == '}') {
17895 Res.first = X86::ST0+Constraint[4]-'0';
17896 Res.second = &X86::RFP80RegClass;
17900 // GCC allows "st(0)" to be called just plain "st".
17901 if (StringRef("{st}").equals_lower(Constraint)) {
17902 Res.first = X86::ST0;
17903 Res.second = &X86::RFP80RegClass;
17908 if (StringRef("{flags}").equals_lower(Constraint)) {
17909 Res.first = X86::EFLAGS;
17910 Res.second = &X86::CCRRegClass;
17914 // 'A' means EAX + EDX.
17915 if (Constraint == "A") {
17916 Res.first = X86::EAX;
17917 Res.second = &X86::GR32_ADRegClass;
17923 // Otherwise, check to see if this is a register class of the wrong value
17924 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17925 // turn into {ax},{dx}.
17926 if (Res.second->hasType(VT))
17927 return Res; // Correct type already, nothing to do.
17929 // All of the single-register GCC register classes map their values onto
17930 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17931 // really want an 8-bit or 32-bit register, map to the appropriate register
17932 // class and return the appropriate register.
17933 if (Res.second == &X86::GR16RegClass) {
17934 if (VT == MVT::i8) {
17935 unsigned DestReg = 0;
17936 switch (Res.first) {
17938 case X86::AX: DestReg = X86::AL; break;
17939 case X86::DX: DestReg = X86::DL; break;
17940 case X86::CX: DestReg = X86::CL; break;
17941 case X86::BX: DestReg = X86::BL; break;
17944 Res.first = DestReg;
17945 Res.second = &X86::GR8RegClass;
17947 } else if (VT == MVT::i32) {
17948 unsigned DestReg = 0;
17949 switch (Res.first) {
17951 case X86::AX: DestReg = X86::EAX; break;
17952 case X86::DX: DestReg = X86::EDX; break;
17953 case X86::CX: DestReg = X86::ECX; break;
17954 case X86::BX: DestReg = X86::EBX; break;
17955 case X86::SI: DestReg = X86::ESI; break;
17956 case X86::DI: DestReg = X86::EDI; break;
17957 case X86::BP: DestReg = X86::EBP; break;
17958 case X86::SP: DestReg = X86::ESP; break;
17961 Res.first = DestReg;
17962 Res.second = &X86::GR32RegClass;
17964 } else if (VT == MVT::i64) {
17965 unsigned DestReg = 0;
17966 switch (Res.first) {
17968 case X86::AX: DestReg = X86::RAX; break;
17969 case X86::DX: DestReg = X86::RDX; break;
17970 case X86::CX: DestReg = X86::RCX; break;
17971 case X86::BX: DestReg = X86::RBX; break;
17972 case X86::SI: DestReg = X86::RSI; break;
17973 case X86::DI: DestReg = X86::RDI; break;
17974 case X86::BP: DestReg = X86::RBP; break;
17975 case X86::SP: DestReg = X86::RSP; break;
17978 Res.first = DestReg;
17979 Res.second = &X86::GR64RegClass;
17982 } else if (Res.second == &X86::FR32RegClass ||
17983 Res.second == &X86::FR64RegClass ||
17984 Res.second == &X86::VR128RegClass) {
17985 // Handle references to XMM physical registers that got mapped into the
17986 // wrong class. This can happen with constraints like {xmm0} where the
17987 // target independent register mapper will just pick the first match it can
17988 // find, ignoring the required type.
17990 if (VT == MVT::f32 || VT == MVT::i32)
17991 Res.second = &X86::FR32RegClass;
17992 else if (VT == MVT::f64 || VT == MVT::i64)
17993 Res.second = &X86::FR64RegClass;
17994 else if (X86::VR128RegClass.hasType(VT))
17995 Res.second = &X86::VR128RegClass;
17996 else if (X86::VR256RegClass.hasType(VT))
17997 Res.second = &X86::VR256RegClass;
18003 //===----------------------------------------------------------------------===//
18007 //===----------------------------------------------------------------------===//
18009 struct X86CostTblEntry {
18016 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
18017 for (unsigned int i = 0; i < len; ++i)
18018 if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
18021 // Could not find an entry.
18025 struct X86TypeConversionCostTblEntry {
18033 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
18034 int ISD, MVT Dst, MVT Src) {
18035 for (unsigned int i = 0; i < len; ++i)
18036 if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
18039 // Could not find an entry.
18043 ScalarTargetTransformInfo::PopcntHwSupport
18044 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
18045 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
18046 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18048 // TODO: Currently the __builtin_popcount() implementation using SSE3
18049 // instructions is inefficient. Once the problem is fixed, we should
18050 // call ST.hasSSE3() instead of ST.hasSSE4().
18051 return ST.hasSSE41() ? Fast : None;
18055 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
18057 // Legalize the type.
18058 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
18060 int ISD = InstructionOpcodeToISD(Opcode);
18061 assert(ISD && "Invalid opcode");
18063 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18065 static const X86CostTblEntry AVX1CostTable[] = {
18066 // We don't have to scalarize unsupported ops. We can issue two half-sized
18067 // operations and we only need to extract the upper YMM half.
18068 // Two ops + 1 extract + 1 insert = 4.
18069 { ISD::MUL, MVT::v8i32, 4 },
18070 { ISD::SUB, MVT::v8i32, 4 },
18071 { ISD::ADD, MVT::v8i32, 4 },
18072 { ISD::MUL, MVT::v4i64, 4 },
18073 { ISD::SUB, MVT::v4i64, 4 },
18074 { ISD::ADD, MVT::v4i64, 4 },
18077 // Look for AVX1 lowering tricks.
18079 int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
18082 return LT.first * AVX1CostTable[Idx].Cost;
18084 // Fallback to the default implementation.
18085 return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
18089 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
18090 unsigned Alignment,
18091 unsigned AddressSpace) const {
18092 // Legalize the type.
18093 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
18094 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
18097 const X86Subtarget &ST =
18098 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18100 // Each load/store unit costs 1.
18101 unsigned Cost = LT.first * 1;
18103 // On Sandybridge 256bit load/stores are double pumped
18104 // (but not on Haswell).
18105 if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18112 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18113 unsigned Index) const {
18114 assert(Val->isVectorTy() && "This must be a vector type");
18116 if (Index != -1U) {
18117 // Legalize the type.
18118 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18120 // This type is legalized to a scalar type.
18121 if (!LT.second.isVector())
18124 // The type may be split. Normalize the index to the new type.
18125 unsigned Width = LT.second.getVectorNumElements();
18126 Index = Index % Width;
18128 // Floating point scalars are already located in index #0.
18129 if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18133 return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18136 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18138 Type *CondTy) const {
18139 // Legalize the type.
18140 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18142 MVT MTy = LT.second;
18144 int ISD = InstructionOpcodeToISD(Opcode);
18145 assert(ISD && "Invalid opcode");
18147 const X86Subtarget &ST =
18148 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18150 static const X86CostTblEntry SSE42CostTbl[] = {
18151 { ISD::SETCC, MVT::v2f64, 1 },
18152 { ISD::SETCC, MVT::v4f32, 1 },
18153 { ISD::SETCC, MVT::v2i64, 1 },
18154 { ISD::SETCC, MVT::v4i32, 1 },
18155 { ISD::SETCC, MVT::v8i16, 1 },
18156 { ISD::SETCC, MVT::v16i8, 1 },
18159 static const X86CostTblEntry AVX1CostTbl[] = {
18160 { ISD::SETCC, MVT::v4f64, 1 },
18161 { ISD::SETCC, MVT::v8f32, 1 },
18162 // AVX1 does not support 8-wide integer compare.
18163 { ISD::SETCC, MVT::v4i64, 4 },
18164 { ISD::SETCC, MVT::v8i32, 4 },
18165 { ISD::SETCC, MVT::v16i16, 4 },
18166 { ISD::SETCC, MVT::v32i8, 4 },
18169 static const X86CostTblEntry AVX2CostTbl[] = {
18170 { ISD::SETCC, MVT::v4i64, 1 },
18171 { ISD::SETCC, MVT::v8i32, 1 },
18172 { ISD::SETCC, MVT::v16i16, 1 },
18173 { ISD::SETCC, MVT::v32i8, 1 },
18176 if (ST.hasAVX2()) {
18177 int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18179 return LT.first * AVX2CostTbl[Idx].Cost;
18183 int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18185 return LT.first * AVX1CostTbl[Idx].Cost;
18188 if (ST.hasSSE42()) {
18189 int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18191 return LT.first * SSE42CostTbl[Idx].Cost;
18194 return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18197 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18200 int ISD = InstructionOpcodeToISD(Opcode);
18201 assert(ISD && "Invalid opcode");
18203 EVT SrcTy = TLI->getValueType(Src);
18204 EVT DstTy = TLI->getValueType(Dst);
18206 if (!SrcTy.isSimple() || !DstTy.isSimple())
18207 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18209 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18211 static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18212 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18213 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18214 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18215 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18216 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1 },
18217 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1 },
18218 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18219 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18220 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18221 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18222 { ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 1 },
18223 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
18224 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 6 },
18225 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 9 },
18226 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 3 },
18230 int Idx = FindInConvertTable(AVXConversionTbl,
18231 array_lengthof(AVXConversionTbl),
18232 ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18234 return AVXConversionTbl[Idx].Cost;
18237 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18241 unsigned X86VectorTargetTransformInfo::getShuffleCost(ShuffleKind Kind, Type *Tp,
18243 // We only estimate the cost of reverse shuffles.
18244 if (Kind != Reverse)
18245 return VectorTargetTransformImpl::getShuffleCost(Kind, Tp, Index);
18247 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Tp);
18249 if (LT.second.getSizeInBits() > 128)
18250 Cost = 3; // Extract + insert + copy.
18252 // Multiple by the number of parts.
18253 return Cost * LT.first;