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"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static SDValue Insert128BitVector(SDValue Result,
69 static SDValue Extract128BitVector(SDValue Vec,
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference. Idx is an index in the 128 bits we
77 /// want. It need not be aligned to a 128-bit bounday. That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
83 EVT VT = Vec.getValueType();
84 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85 EVT ElVT = VT.getVectorElementType();
86 int Factor = VT.getSizeInBits()/128;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94 if (isa<ConstantSDNode>(Idx)) {
95 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
98 // we can match to VEXTRACTF128.
99 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101 // This is the index of the first element of the 128-bit chunk
103 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
106 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference. Idx is an index in the 128 bits
119 /// we want. It need not be aligned to a 128-bit bounday. That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
126 if (isa<ConstantSDNode>(Idx)) {
127 EVT VT = Vec.getValueType();
128 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130 EVT ElVT = VT.getVectorElementType();
131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132 EVT ResultVT = Result.getValueType();
134 // Insert the relevant 128 bits.
135 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137 // This is the index of the first element of the 128-bit chunk
139 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
142 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153 bool is64Bit = Subtarget->is64Bit();
155 if (Subtarget->isTargetEnvMacho()) {
157 return new X8664_MachoTargetObjectFile();
158 return new TargetLoweringObjectFileMachO();
161 if (Subtarget->isTargetELF())
162 return new TargetLoweringObjectFileELF();
163 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164 return new TargetLoweringObjectFileCOFF();
165 llvm_unreachable("unknown subtarget type");
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<X86Subtarget>();
171 X86ScalarSSEf64 = Subtarget->hasXMMInt();
172 X86ScalarSSEf32 = Subtarget->hasXMM();
173 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175 RegInfo = TM.getRegisterInfo();
176 TD = getTargetData();
178 // Set up the TargetLowering object.
179 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181 // X86 is weird, it always uses i8 for shift amounts and setcc results.
182 setBooleanContents(ZeroOrOneBooleanContent);
183 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186 // For 64-bit since we have so many registers use the ILP scheduler, for
187 // 32-bit code use the register pressure specific scheduling.
188 if (Subtarget->is64Bit())
189 setSchedulingPreference(Sched::ILP);
191 setSchedulingPreference(Sched::RegPressure);
192 setStackPointerRegisterToSaveRestore(X86StackPtr);
194 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195 // Setup Windows compiler runtime calls.
196 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198 setLibcallName(RTLIB::SREM_I64, "_allrem");
199 setLibcallName(RTLIB::UREM_I64, "_aullrem");
200 setLibcallName(RTLIB::MUL_I64, "_allmul");
201 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
212 if (Subtarget->isTargetDarwin()) {
213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214 setUseUnderscoreSetJmp(false);
215 setUseUnderscoreLongJmp(false);
216 } else if (Subtarget->isTargetMingw()) {
217 // MS runtime is weird: it exports _setjmp, but longjmp!
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(false);
221 setUseUnderscoreSetJmp(true);
222 setUseUnderscoreLongJmp(true);
225 // Set up the register classes.
226 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229 if (Subtarget->is64Bit())
230 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234 // We don't accept any truncstore of integer registers.
235 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
242 // SETOEQ and SETUNE require checking two conditions.
243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
259 } else if (!UseSoftFloat) {
260 // We have an algorithm for SSE2->double, and we turn this into a
261 // 64-bit FILD followed by conditional FADD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
263 // We have an algorithm for SSE2, and we turn this into a 64-bit
264 // FILD for other targets.
265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 // SSE has no i16 to fp conversion, only i32
275 if (X86ScalarSSEf32) {
276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
277 // f32 and f64 cases are Legal, f80 case is not
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
289 // are Legal, f80 is custom lowered.
290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
298 if (X86ScalarSSEf32) {
299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
300 // f32 and f64 cases are Legal, f80 case is not
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
307 // Handle FP_TO_UINT by promoting the destination to a larger signed
309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
313 if (Subtarget->is64Bit()) {
314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
316 } else if (!UseSoftFloat) {
317 // Since AVX is a superset of SSE3, only check for SSE here.
318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319 // Expand FP_TO_UINT into a select.
320 // FIXME: We would like to use a Custom expander here eventually to do
321 // the optimal thing for SSE vs. the default expansion in the legalizer.
322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
324 // With SSE3 we can use fisttpll to convert to a signed i64; without
325 // SSE, we're stuck with a fistpll.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0, e = 4; i != e; ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 if (Subtarget->hasBMI()) {
382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
385 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
387 if (Subtarget->is64Bit())
388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
391 if (Subtarget->hasLZCNT()) {
392 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
394 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
395 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
396 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
397 if (Subtarget->is64Bit())
398 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
401 if (Subtarget->hasPOPCNT()) {
402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
407 if (Subtarget->is64Bit())
408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
412 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
414 // These should be promoted to a larger select which is supported.
415 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
416 // X86 wants to expand cmov itself.
417 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
418 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
419 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
429 if (Subtarget->is64Bit()) {
430 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
431 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
433 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
436 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
437 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
438 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
440 if (Subtarget->is64Bit())
441 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
443 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
444 if (Subtarget->is64Bit()) {
445 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
446 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
447 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
448 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
449 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
451 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
453 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
454 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
457 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
458 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
461 if (Subtarget->hasXMM())
462 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
464 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
465 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
467 // On X86 and X86-64, atomic operations are lowered to locked instructions.
468 // Locked instructions, in turn, have implicit fence semantics (all memory
469 // operations are flushed before issuing the locked instruction, and they
470 // are not buffered), so we can fold away the common pattern of
471 // fence-atomic-fence.
472 setShouldFoldAtomicFences(true);
474 // Expand certain atomics
475 for (unsigned i = 0, e = 4; i != e; ++i) {
477 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
482 if (!Subtarget->is64Bit()) {
483 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
493 if (Subtarget->hasCmpxchg16b()) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
497 // FIXME - use subtarget debug flags
498 if (!Subtarget->isTargetDarwin() &&
499 !Subtarget->isTargetELF() &&
500 !Subtarget->isTargetCygMing()) {
501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
504 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
506 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
508 if (Subtarget->is64Bit()) {
509 setExceptionPointerRegister(X86::RAX);
510 setExceptionSelectorRegister(X86::RDX);
512 setExceptionPointerRegister(X86::EAX);
513 setExceptionSelectorRegister(X86::EDX);
515 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521 setOperationAction(ISD::TRAP, MVT::Other, Legal);
523 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524 setOperationAction(ISD::VASTART , MVT::Other, Custom);
525 setOperationAction(ISD::VAEND , MVT::Other, Expand);
526 if (Subtarget->is64Bit()) {
527 setOperationAction(ISD::VAARG , MVT::Other, Custom);
528 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
530 setOperationAction(ISD::VAARG , MVT::Other, Expand);
531 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
534 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
535 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
537 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539 MVT::i64 : MVT::i32, Custom);
540 else if (EnableSegmentedStacks)
541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542 MVT::i64 : MVT::i32, Custom);
544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545 MVT::i64 : MVT::i32, Expand);
547 if (!UseSoftFloat && X86ScalarSSEf64) {
548 // f32 and f64 use SSE.
549 // Set up the FP register classes.
550 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553 // Use ANDPD to simulate FABS.
554 setOperationAction(ISD::FABS , MVT::f64, Custom);
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f64, Custom);
559 setOperationAction(ISD::FNEG , MVT::f32, Custom);
561 // Use ANDPD and ORPD to simulate FCOPYSIGN.
562 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565 // Lower this to FGETSIGNx86 plus an AND.
566 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569 // We don't support sin/cos/fmod
570 setOperationAction(ISD::FSIN , MVT::f64, Expand);
571 setOperationAction(ISD::FCOS , MVT::f64, Expand);
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 // Expand FP immediates into loads from the stack, except for the special
577 addLegalFPImmediate(APFloat(+0.0)); // xorpd
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 } else if (!UseSoftFloat && X86ScalarSSEf32) {
580 // Use SSE for f32, x87 for f64.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585 // Use ANDPS to simulate FABS.
586 setOperationAction(ISD::FABS , MVT::f32, Custom);
588 // Use XORP to simulate FNEG.
589 setOperationAction(ISD::FNEG , MVT::f32, Custom);
591 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
593 // Use ANDPS and ORPS to simulate FCOPYSIGN.
594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597 // We don't support sin/cos/fmod
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 // Special cases we handle for FP constants.
602 addLegalFPImmediate(APFloat(+0.0f)); // xorps
603 addLegalFPImmediate(APFloat(+0.0)); // FLD0
604 addLegalFPImmediate(APFloat(+1.0)); // FLD1
605 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
610 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
612 } else if (!UseSoftFloat) {
613 // f32 and f64 in x87.
614 // Set up the FP register classes.
615 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
619 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
624 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
625 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
627 addLegalFPImmediate(APFloat(+0.0)); // FLD0
628 addLegalFPImmediate(APFloat(+1.0)); // FLD1
629 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
637 // We don't support FMA.
638 setOperationAction(ISD::FMA, MVT::f64, Expand);
639 setOperationAction(ISD::FMA, MVT::f32, Expand);
641 // Long double always uses X87.
643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648 addLegalFPImmediate(TmpFlt); // FLD0
650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
653 APFloat TmpFlt2(+1.0);
654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656 addLegalFPImmediate(TmpFlt2); // FLD1
657 TmpFlt2.changeSign();
658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
662 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
663 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
666 setOperationAction(ISD::FMA, MVT::f80, Expand);
669 // Always use a library call for pow.
670 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
674 setOperationAction(ISD::FLOG, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 // First set operation action for all vector types to either promote
681 // (for widening) or expand (for scalarization). Then we will selectively
682 // turn on ones that can be effectively codegen'd.
683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742 setTruncStoreAction((MVT::SimpleValueType)VT,
743 (MVT::SimpleValueType)InnerVT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750 // with -msoft-float, disable use of MMX as well.
751 if (!UseSoftFloat && Subtarget->hasMMX()) {
752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753 // No operations on x86mmx supported, everything uses intrinsics.
756 // MMX-sized vectors (other than x86mmx) are expected to be expanded
757 // into smaller operations.
758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
762 setOperationAction(ISD::AND, MVT::v8i8, Expand);
763 setOperationAction(ISD::AND, MVT::v4i16, Expand);
764 setOperationAction(ISD::AND, MVT::v2i32, Expand);
765 setOperationAction(ISD::AND, MVT::v1i64, Expand);
766 setOperationAction(ISD::OR, MVT::v8i8, Expand);
767 setOperationAction(ISD::OR, MVT::v4i16, Expand);
768 setOperationAction(ISD::OR, MVT::v2i32, Expand);
769 setOperationAction(ISD::OR, MVT::v1i64, Expand);
770 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
771 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
772 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
773 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
788 if (!UseSoftFloat && Subtarget->hasXMM()) {
789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
805 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809 // registers cannot be used even for integer operations.
810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
816 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
817 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
818 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851 EVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR,
859 VT.getSimpleVT().SimpleTy, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE,
861 VT.getSimpleVT().SimpleTy, Custom);
862 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863 VT.getSimpleVT().SimpleTy, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873 if (Subtarget->is64Bit()) {
874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
883 // Do not attempt to promote non-128-bit vectors
884 if (!VT.is128BitVector())
887 setOperationAction(ISD::AND, SVT, Promote);
888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
889 setOperationAction(ISD::OR, SVT, Promote);
890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
891 setOperationAction(ISD::XOR, SVT, Promote);
892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
893 setOperationAction(ISD::LOAD, SVT, Promote);
894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
895 setOperationAction(ISD::SELECT, SVT, Promote);
896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
899 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901 // Custom lower v2i64 and v2f64 selects.
902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
911 if (Subtarget->hasSSE41orAVX()) {
912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915 setOperationAction(ISD::FRINT, MVT::f32, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923 // FIXME: Do we need to handle scalar-to-vector here?
924 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
932 // i8 and i16 vectors are custom , because the source register and source
933 // source memory operand types are not the same width. f32 vectors are
934 // custom since the immediate controlling the insert encodes additional
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946 // FIXME: these should be Legal but thats only for the case where
947 // the index is constant. For now custom expand to deal with that
948 if (Subtarget->is64Bit()) {
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
954 if (Subtarget->hasXMMInt()) {
955 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
956 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
959 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
962 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
964 if (Subtarget->hasAVX2()) {
965 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
966 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
968 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
969 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
971 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
973 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
974 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
976 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
977 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
979 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
983 if (Subtarget->hasSSE42orAVX())
984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
986 if (!UseSoftFloat && Subtarget->hasAVX()) {
987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
998 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1046 if (Subtarget->hasAVX2()) {
1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1060 // Don't lower v32i8 because there is no 128-bit byte mul
1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1085 // Don't lower v32i8 because there is no 128-bit byte mul
1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1096 // Custom lower several nodes for 256-bit types.
1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1102 // Extract subvector is special because the value type
1103 // (result) is 128-bit but the source is 256-bit wide.
1104 if (VT.is128BitVector())
1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1107 // Do not attempt to custom lower other non-256-bit vectors
1108 if (!VT.is256BitVector())
1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1124 // Do not attempt to promote non-256-bit vectors
1125 if (!VT.is256BitVector())
1128 setOperationAction(ISD::AND, SVT, Promote);
1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1130 setOperationAction(ISD::OR, SVT, Promote);
1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1132 setOperationAction(ISD::XOR, SVT, Promote);
1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1134 setOperationAction(ISD::LOAD, SVT, Promote);
1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1136 setOperationAction(ISD::SELECT, SVT, Promote);
1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142 // of this type with custom code.
1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1148 // We want to custom lower some of our intrinsics.
1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153 // handle type legalization for these operations here.
1155 // FIXME: We really should do custom legalization for addition and
1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1157 // than generic legalization for 64-bit multiplication-with-overflow, though.
1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159 // Add/Sub/Mul with overflow operations are custom lowered.
1161 setOperationAction(ISD::SADDO, VT, Custom);
1162 setOperationAction(ISD::UADDO, VT, Custom);
1163 setOperationAction(ISD::SSUBO, VT, Custom);
1164 setOperationAction(ISD::USUBO, VT, Custom);
1165 setOperationAction(ISD::SMULO, VT, Custom);
1166 setOperationAction(ISD::UMULO, VT, Custom);
1169 // There are no 8-bit 3-address imul/mul instructions
1170 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1173 if (!Subtarget->is64Bit()) {
1174 // These libcalls are not available in 32-bit.
1175 setLibcallName(RTLIB::SHL_I128, 0);
1176 setLibcallName(RTLIB::SRL_I128, 0);
1177 setLibcallName(RTLIB::SRA_I128, 0);
1180 // We have target-specific dag combine patterns for the following nodes:
1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183 setTargetDAGCombine(ISD::BUILD_VECTOR);
1184 setTargetDAGCombine(ISD::VSELECT);
1185 setTargetDAGCombine(ISD::SELECT);
1186 setTargetDAGCombine(ISD::SHL);
1187 setTargetDAGCombine(ISD::SRA);
1188 setTargetDAGCombine(ISD::SRL);
1189 setTargetDAGCombine(ISD::OR);
1190 setTargetDAGCombine(ISD::AND);
1191 setTargetDAGCombine(ISD::ADD);
1192 setTargetDAGCombine(ISD::FADD);
1193 setTargetDAGCombine(ISD::FSUB);
1194 setTargetDAGCombine(ISD::SUB);
1195 setTargetDAGCombine(ISD::LOAD);
1196 setTargetDAGCombine(ISD::STORE);
1197 setTargetDAGCombine(ISD::ZERO_EXTEND);
1198 setTargetDAGCombine(ISD::SINT_TO_FP);
1199 if (Subtarget->is64Bit())
1200 setTargetDAGCombine(ISD::MUL);
1201 if (Subtarget->hasBMI())
1202 setTargetDAGCombine(ISD::XOR);
1204 computeRegisterProperties();
1206 // On Darwin, -Os means optimize for size without hurting performance,
1207 // do not reduce the limit.
1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214 setPrefLoopAlignment(16);
1215 benefitFromCodePlacementOpt = true;
1217 setPrefFunctionAlignment(4);
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222 if (!VT.isVector()) return MVT::i8;
1223 return VT.changeVectorElementTypeToInteger();
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233 if (VTy->getBitWidth() == 128)
1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236 unsigned EltAlign = 0;
1237 getMaxByValAlign(ATy->getElementType(), EltAlign);
1238 if (EltAlign > MaxAlign)
1239 MaxAlign = EltAlign;
1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242 unsigned EltAlign = 0;
1243 getMaxByValAlign(STy->getElementType(i), EltAlign);
1244 if (EltAlign > MaxAlign)
1245 MaxAlign = EltAlign;
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258 if (Subtarget->is64Bit()) {
1259 // Max of 8 and alignment of type.
1260 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1267 if (Subtarget->hasXMM())
1268 getMaxByValAlign(Ty, Align);
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286 unsigned DstAlign, unsigned SrcAlign,
1289 MachineFunction &MF) const {
1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291 // linux. This is because the stack realignment code can't handle certain
1292 // cases like PR2962. This should be removed when PR2962 is fixed.
1293 const Function *F = MF.getFunction();
1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1297 (Subtarget->isUnalignedMemAccessFast() ||
1298 ((DstAlign == 0 || DstAlign >= 16) &&
1299 (SrcAlign == 0 || SrcAlign >= 16))) &&
1300 Subtarget->getStackAlignment() >= 16) {
1301 if (Subtarget->hasAVX() &&
1302 Subtarget->getStackAlignment() >= 32)
1304 if (Subtarget->hasXMMInt())
1306 if (Subtarget->hasXMM())
1308 } else if (!MemcpyStrSrc && Size >= 8 &&
1309 !Subtarget->is64Bit() &&
1310 Subtarget->getStackAlignment() >= 8 &&
1311 Subtarget->hasXMMInt()) {
1312 // Do not use f64 to lower memcpy if source is string constant. It's
1313 // better to use i32 to avoid the loads.
1317 if (Subtarget->is64Bit() && Size >= 8)
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function. The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329 Subtarget->isPICStyleGOT())
1330 return MachineJumpTableInfo::EK_Custom32;
1332 // Otherwise, use the normal jump table encoding heuristics.
1333 return TargetLowering::getJumpTableEncoding();
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338 const MachineBasicBlock *MBB,
1339 unsigned uid,MCContext &Ctx) const{
1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341 Subtarget->isPICStyleGOT());
1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1344 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351 SelectionDAG &DAG) const {
1352 if (!Subtarget->is64Bit())
1353 // This doesn't have DebugLoc associated with it, but is not really the
1354 // same as a Register.
1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364 MCContext &Ctx) const {
1365 // X86-64 uses RIP relative addressing based on the jump table label.
1366 if (Subtarget->isPICStyleRIPRel())
1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1369 // Otherwise, the reference is relative to the PIC base.
1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376 const TargetRegisterClass *RRC = 0;
1378 switch (VT.getSimpleVT().SimpleTy) {
1380 return TargetLowering::findRepresentativeClass(VT);
1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382 RRC = (Subtarget->is64Bit()
1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1386 RRC = X86::VR64RegisterClass;
1388 case MVT::f32: case MVT::f64:
1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390 case MVT::v4f32: case MVT::v2f64:
1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1393 RRC = X86::VR128RegisterClass;
1396 return std::make_pair(RRC, Cost);
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400 unsigned &Offset) const {
1401 if (!Subtarget->isTargetLinux())
1404 if (Subtarget->is64Bit()) {
1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1420 //===----------------------------------------------------------------------===//
1421 // Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1424 #include "X86GenCallingConv.inc"
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428 MachineFunction &MF, bool isVarArg,
1429 const SmallVectorImpl<ISD::OutputArg> &Outs,
1430 LLVMContext &Context) const {
1431 SmallVector<CCValAssign, 16> RVLocs;
1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1434 return CCInfo.CheckReturn(Outs, RetCC_X86);
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439 CallingConv::ID CallConv, bool isVarArg,
1440 const SmallVectorImpl<ISD::OutputArg> &Outs,
1441 const SmallVectorImpl<SDValue> &OutVals,
1442 DebugLoc dl, SelectionDAG &DAG) const {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448 RVLocs, *DAG.getContext());
1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1451 // Add the regs to the liveout set for the function.
1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453 for (unsigned i = 0; i != RVLocs.size(); ++i)
1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455 MRI.addLiveOut(RVLocs[i].getLocReg());
1459 SmallVector<SDValue, 6> RetOps;
1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461 // Operand #1 = Bytes To Pop
1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1465 // Copy the result values into the output registers.
1466 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467 CCValAssign &VA = RVLocs[i];
1468 assert(VA.isRegLoc() && "Can only return in registers!");
1469 SDValue ValToCopy = OutVals[i];
1470 EVT ValVT = ValToCopy.getValueType();
1472 // If this is x86-64, and we disabled SSE, we can't return FP values,
1473 // or SSE or MMX vectors.
1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477 report_fatal_error("SSE register return with SSE disabled");
1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1480 // llvm-gcc has never done it right and no one has noticed, so this
1481 // should be OK for now.
1482 if (ValVT == MVT::f64 &&
1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484 report_fatal_error("SSE2 register return with SSE2 disabled");
1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487 // the RET instruction and handled by the FP Stackifier.
1488 if (VA.getLocReg() == X86::ST0 ||
1489 VA.getLocReg() == X86::ST1) {
1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491 // change the value to the FP stack register class.
1492 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494 RetOps.push_back(ValToCopy);
1495 // Don't emit a copytoreg.
1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500 // which is returned in RAX / RDX.
1501 if (Subtarget->is64Bit()) {
1502 if (ValVT == MVT::x86mmx) {
1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1507 // If we don't have SSE2 available, convert to v4f32 so the generated
1508 // register is legal.
1509 if (!Subtarget->hasXMMInt())
1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516 Flag = Chain.getValue(1);
1519 // The x86-64 ABI for returning structs by value requires that we copy
1520 // the sret argument into %rax for the return. We saved the argument into
1521 // a virtual register in the entry block, so now we copy the value out
1523 if (Subtarget->is64Bit() &&
1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525 MachineFunction &MF = DAG.getMachineFunction();
1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527 unsigned Reg = FuncInfo->getSRetReturnReg();
1529 "SRetReturnReg should have been set in LowerFormalArguments().");
1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533 Flag = Chain.getValue(1);
1535 // RAX now acts like a return value.
1536 MRI.addLiveOut(X86::RAX);
1539 RetOps[0] = Chain; // Update chain.
1541 // Add the flag if we have it.
1543 RetOps.push_back(Flag);
1545 return DAG.getNode(X86ISD::RET_FLAG, dl,
1546 MVT::Other, &RetOps[0], RetOps.size());
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550 if (N->getNumValues() != 1)
1552 if (!N->hasNUsesOfValue(1, 0))
1555 SDNode *Copy = *N->use_begin();
1556 if (Copy->getOpcode() != ISD::CopyToReg &&
1557 Copy->getOpcode() != ISD::FP_EXTEND)
1560 bool HasRet = false;
1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1563 if (UI->getOpcode() != X86ISD::RET_FLAG)
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573 ISD::NodeType ExtendKind) const {
1575 // TODO: Is this also valid on 32-bit?
1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577 ReturnMVT = MVT::i8;
1579 ReturnMVT = MVT::i32;
1581 EVT MinVT = getRegisterType(Context, ReturnMVT);
1582 return VT.bitsLT(MinVT) ? MinVT : VT;
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590 CallingConv::ID CallConv, bool isVarArg,
1591 const SmallVectorImpl<ISD::InputArg> &Ins,
1592 DebugLoc dl, SelectionDAG &DAG,
1593 SmallVectorImpl<SDValue> &InVals) const {
1595 // Assign locations to each value returned by this call.
1596 SmallVector<CCValAssign, 16> RVLocs;
1597 bool Is64Bit = Subtarget->is64Bit();
1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599 getTargetMachine(), RVLocs, *DAG.getContext());
1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1602 // Copy all of the result registers out of their specified physreg.
1603 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604 CCValAssign &VA = RVLocs[i];
1605 EVT CopyVT = VA.getValVT();
1607 // If this is x86-64, and we disabled SSE, we can't return FP values
1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610 report_fatal_error("SSE register return with SSE disabled");
1615 // If this is a call to a function that returns an fp value on the floating
1616 // point stack, we must guarantee the the value is popped from the stack, so
1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618 // if the return value is not used. We use the FpPOP_RETVAL instruction
1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621 // If we prefer to use the value in xmm registers, copy it out as f80 and
1622 // use a truncate to move it from fp stack reg to xmm reg.
1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624 SDValue Ops[] = { Chain, InFlag };
1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626 MVT::Other, MVT::Glue, Ops, 2), 1);
1627 Val = Chain.getValue(0);
1629 // Round the f80 to the right size, which also moves it to the appropriate
1631 if (CopyVT != VA.getValVT())
1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633 // This truncation won't change the value.
1634 DAG.getIntPtrConstant(1));
1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637 CopyVT, InFlag).getValue(1);
1638 Val = Chain.getValue(0);
1640 InFlag = Chain.getValue(2);
1641 InVals.push_back(Val);
1648 //===----------------------------------------------------------------------===//
1649 // C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 // StdCall calling convention seems to be standard for many Windows' API
1652 // routines and around. It differs from C calling convention just a little:
1653 // callee should clean up the stack, not caller. Symbols should be also
1654 // decorated in some fancy way :) It doesn't support any vector arguments.
1655 // For info on fast calling convention see Fast Calling Convention (tail call)
1656 // implementation LowerX86_32FastCCCallTo.
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1664 return Outs[0].Flags.isSRet();
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1674 return Ins[0].Flags.isSRet();
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688 /*isVolatile*/false, /*AlwaysInline=*/true,
1689 MachinePointerInfo(), MachinePointerInfo());
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699 if (!CI->isTailCall())
1703 CallingConv::ID CalleeCC = CS.getCallingConv();
1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718 CallingConv::ID CallConv,
1719 const SmallVectorImpl<ISD::InputArg> &Ins,
1720 DebugLoc dl, SelectionDAG &DAG,
1721 const CCValAssign &VA,
1722 MachineFrameInfo *MFI,
1724 // Create the nodes corresponding to a load from this parameter slot.
1725 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1730 // If value is passed by pointer we have address passed instead of the value
1732 if (VA.getLocInfo() == CCValAssign::Indirect)
1733 ValVT = VA.getLocVT();
1735 ValVT = VA.getValVT();
1737 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738 // changed with more analysis.
1739 // In case of tail call optimization mark all arguments mutable. Since they
1740 // could be overwritten by lowering of arguments in case of a tail call.
1741 if (Flags.isByVal()) {
1742 unsigned Bytes = Flags.getByValSize();
1743 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745 return DAG.getFrameIndex(FI, getPointerTy());
1747 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748 VA.getLocMemOffset(), isImmutable);
1749 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750 return DAG.getLoad(ValVT, dl, Chain, FIN,
1751 MachinePointerInfo::getFixedStack(FI),
1752 false, false, false, 0);
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758 CallingConv::ID CallConv,
1760 const SmallVectorImpl<ISD::InputArg> &Ins,
1763 SmallVectorImpl<SDValue> &InVals)
1765 MachineFunction &MF = DAG.getMachineFunction();
1766 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1768 const Function* Fn = MF.getFunction();
1769 if (Fn->hasExternalLinkage() &&
1770 Subtarget->isTargetCygMing() &&
1771 Fn->getName() == "main")
1772 FuncInfo->setForceFramePointer(true);
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 bool Is64Bit = Subtarget->is64Bit();
1776 bool IsWin64 = Subtarget->isTargetWin64();
1778 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779 "Var args not supported with calling convention fastcc or ghc");
1781 // Assign locations to all of the incoming arguments.
1782 SmallVector<CCValAssign, 16> ArgLocs;
1783 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784 ArgLocs, *DAG.getContext());
1786 // Allocate shadow area for Win64
1788 CCInfo.AllocateStack(32, 8);
1791 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1793 unsigned LastVal = ~0U;
1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796 CCValAssign &VA = ArgLocs[i];
1797 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1799 assert(VA.getValNo() != LastVal &&
1800 "Don't support value assigned to multiple locs yet");
1802 LastVal = VA.getValNo();
1804 if (VA.isRegLoc()) {
1805 EVT RegVT = VA.getLocVT();
1806 TargetRegisterClass *RC = NULL;
1807 if (RegVT == MVT::i32)
1808 RC = X86::GR32RegisterClass;
1809 else if (Is64Bit && RegVT == MVT::i64)
1810 RC = X86::GR64RegisterClass;
1811 else if (RegVT == MVT::f32)
1812 RC = X86::FR32RegisterClass;
1813 else if (RegVT == MVT::f64)
1814 RC = X86::FR64RegisterClass;
1815 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816 RC = X86::VR256RegisterClass;
1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818 RC = X86::VR128RegisterClass;
1819 else if (RegVT == MVT::x86mmx)
1820 RC = X86::VR64RegisterClass;
1822 llvm_unreachable("Unknown argument type!");
1824 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1827 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1830 if (VA.getLocInfo() == CCValAssign::SExt)
1831 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832 DAG.getValueType(VA.getValVT()));
1833 else if (VA.getLocInfo() == CCValAssign::ZExt)
1834 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835 DAG.getValueType(VA.getValVT()));
1836 else if (VA.getLocInfo() == CCValAssign::BCvt)
1837 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1839 if (VA.isExtInLoc()) {
1840 // Handle MMX values passed in XMM regs.
1841 if (RegVT.isVector()) {
1842 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1845 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1848 assert(VA.isMemLoc());
1849 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1852 // If value is passed via pointer - do a load.
1853 if (VA.getLocInfo() == CCValAssign::Indirect)
1854 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855 MachinePointerInfo(), false, false, false, 0);
1857 InVals.push_back(ArgValue);
1860 // The x86-64 ABI for returning structs by value requires that we copy
1861 // the sret argument into %rax for the return. Save the argument into
1862 // a virtual register so that we can access it from the return points.
1863 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868 FuncInfo->setSRetReturnReg(Reg);
1870 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1874 unsigned StackSize = CCInfo.getNextStackOffset();
1875 // Align stack specially for tail calls.
1876 if (FuncIsMadeTailCallSafe(CallConv))
1877 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1879 // If the function takes variable number of arguments, make a frame index for
1880 // the start of the first vararg value... for expansion of llvm.va_start.
1882 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883 CallConv != CallingConv::X86_ThisCall)) {
1884 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1887 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1889 // FIXME: We should really autogenerate these arrays
1890 static const unsigned GPR64ArgRegsWin64[] = {
1891 X86::RCX, X86::RDX, X86::R8, X86::R9
1893 static const unsigned GPR64ArgRegs64Bit[] = {
1894 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1896 static const unsigned XMMArgRegs64Bit[] = {
1897 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1900 const unsigned *GPR64ArgRegs;
1901 unsigned NumXMMRegs = 0;
1904 // The XMM registers which might contain var arg parameters are shadowed
1905 // in their paired GPR. So we only need to save the GPR to their home
1907 TotalNumIntRegs = 4;
1908 GPR64ArgRegs = GPR64ArgRegsWin64;
1910 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911 GPR64ArgRegs = GPR64ArgRegs64Bit;
1913 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1915 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1918 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920 "SSE register cannot be used when SSE is disabled!");
1921 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922 "SSE register cannot be used when SSE is disabled!");
1923 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924 // Kernel mode asks for SSE to be disabled, so don't push them
1926 TotalNumXMMRegs = 0;
1929 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930 // Get to the caller-allocated home save location. Add 8 to account
1931 // for the return address.
1932 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933 FuncInfo->setRegSaveFrameIndex(
1934 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935 // Fixup to set vararg frame on shadow area (4 x i64).
1937 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1939 // For X86-64, if there are vararg parameters that are passed via
1940 // registers, then we must store them to their spots on the stack so they
1941 // may be loaded by deferencing the result of va_next.
1942 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944 FuncInfo->setRegSaveFrameIndex(
1945 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1949 // Store the integer parameter registers.
1950 SmallVector<SDValue, 8> MemOps;
1951 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1953 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956 DAG.getIntPtrConstant(Offset));
1957 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958 X86::GR64RegisterClass);
1959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1961 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962 MachinePointerInfo::getFixedStack(
1963 FuncInfo->getRegSaveFrameIndex(), Offset),
1965 MemOps.push_back(Store);
1969 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970 // Now store the XMM (fp + vector) parameter registers.
1971 SmallVector<SDValue, 11> SaveXMMOps;
1972 SaveXMMOps.push_back(Chain);
1974 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976 SaveXMMOps.push_back(ALVal);
1978 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979 FuncInfo->getRegSaveFrameIndex()));
1980 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981 FuncInfo->getVarArgsFPOffset()));
1983 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985 X86::VR128RegisterClass);
1986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987 SaveXMMOps.push_back(Val);
1989 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1991 &SaveXMMOps[0], SaveXMMOps.size()));
1994 if (!MemOps.empty())
1995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996 &MemOps[0], MemOps.size());
2000 // Some CCs need callee pop.
2001 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2004 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005 // If this is an sret function, the return should pop the hidden pointer.
2006 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007 FuncInfo->setBytesToPopOnReturn(4);
2011 // RegSaveFrameIndex is X86-64 only.
2012 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013 if (CallConv == CallingConv::X86_FastCall ||
2014 CallConv == CallingConv::X86_ThisCall)
2015 // fastcc functions can't have varargs.
2016 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2019 FuncInfo->setArgumentStackSize(StackSize);
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026 SDValue StackPtr, SDValue Arg,
2027 DebugLoc dl, SelectionDAG &DAG,
2028 const CCValAssign &VA,
2029 ISD::ArgFlagsTy Flags) const {
2030 unsigned LocMemOffset = VA.getLocMemOffset();
2031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033 if (Flags.isByVal())
2034 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2036 return DAG.getStore(Chain, dl, Arg, PtrOff,
2037 MachinePointerInfo::getStack(LocMemOffset),
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045 SDValue &OutRetAddr, SDValue Chain,
2046 bool IsTailCall, bool Is64Bit,
2047 int FPDiff, DebugLoc dl) const {
2048 // Adjust the Return address stack slot.
2049 EVT VT = getPointerTy();
2050 OutRetAddr = getReturnAddressFrameIndex(DAG);
2052 // Load the "old" Return address.
2053 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054 false, false, false, 0);
2055 return SDValue(OutRetAddr.getNode(), 1);
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062 SDValue Chain, SDValue RetAddrFrIdx,
2063 bool Is64Bit, int FPDiff, DebugLoc dl) {
2064 // Store the return address to the appropriate stack slot.
2065 if (!FPDiff) return Chain;
2066 // Calculate the new stack slot for the return address.
2067 int SlotSize = Is64Bit ? 8 : 4;
2068 int NewReturnAddrFI =
2069 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080 CallingConv::ID CallConv, bool isVarArg,
2082 const SmallVectorImpl<ISD::OutputArg> &Outs,
2083 const SmallVectorImpl<SDValue> &OutVals,
2084 const SmallVectorImpl<ISD::InputArg> &Ins,
2085 DebugLoc dl, SelectionDAG &DAG,
2086 SmallVectorImpl<SDValue> &InVals) const {
2087 MachineFunction &MF = DAG.getMachineFunction();
2088 bool Is64Bit = Subtarget->is64Bit();
2089 bool IsWin64 = Subtarget->isTargetWin64();
2090 bool IsStructRet = CallIsStructReturn(Outs);
2091 bool IsSibcall = false;
2094 // Check if it's really possible to do a tail call.
2095 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097 Outs, OutVals, Ins, DAG);
2099 // Sibcalls are automatically detected tailcalls which do not require
2101 if (!GuaranteedTailCallOpt && isTailCall)
2108 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109 "Var args not supported with calling convention fastcc or ghc");
2111 // Analyze operands of the call, assigning locations to each operand.
2112 SmallVector<CCValAssign, 16> ArgLocs;
2113 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114 ArgLocs, *DAG.getContext());
2116 // Allocate shadow area for Win64
2118 CCInfo.AllocateStack(32, 8);
2121 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2123 // Get a count of how many bytes are to be pushed on the stack.
2124 unsigned NumBytes = CCInfo.getNextStackOffset();
2126 // This is a sibcall. The memory operands are available in caller's
2127 // own caller's stack.
2129 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2133 if (isTailCall && !IsSibcall) {
2134 // Lower arguments at fp - stackoffset + fpdiff.
2135 unsigned NumBytesCallerPushed =
2136 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137 FPDiff = NumBytesCallerPushed - NumBytes;
2139 // Set the delta of movement of the returnaddr stackslot.
2140 // But only set if delta is greater than previous delta.
2141 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2146 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2148 SDValue RetAddrFrIdx;
2149 // Load return address for tail calls.
2150 if (isTailCall && FPDiff)
2151 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152 Is64Bit, FPDiff, dl);
2154 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155 SmallVector<SDValue, 8> MemOpChains;
2158 // Walk the register/memloc assignments, inserting copies/loads. In the case
2159 // of tail call optimization arguments are handle later.
2160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161 CCValAssign &VA = ArgLocs[i];
2162 EVT RegVT = VA.getLocVT();
2163 SDValue Arg = OutVals[i];
2164 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165 bool isByVal = Flags.isByVal();
2167 // Promote the value if needed.
2168 switch (VA.getLocInfo()) {
2169 default: llvm_unreachable("Unknown loc info!");
2170 case CCValAssign::Full: break;
2171 case CCValAssign::SExt:
2172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2174 case CCValAssign::ZExt:
2175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2177 case CCValAssign::AExt:
2178 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179 // Special case: passing MMX values in XMM registers.
2180 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2186 case CCValAssign::BCvt:
2187 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2189 case CCValAssign::Indirect: {
2190 // Store the argument.
2191 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194 MachinePointerInfo::getFixedStack(FI),
2201 if (VA.isRegLoc()) {
2202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203 if (isVarArg && IsWin64) {
2204 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205 // shadow reg if callee is a varargs function.
2206 unsigned ShadowReg = 0;
2207 switch (VA.getLocReg()) {
2208 case X86::XMM0: ShadowReg = X86::RCX; break;
2209 case X86::XMM1: ShadowReg = X86::RDX; break;
2210 case X86::XMM2: ShadowReg = X86::R8; break;
2211 case X86::XMM3: ShadowReg = X86::R9; break;
2214 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2216 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217 assert(VA.isMemLoc());
2218 if (StackPtr.getNode() == 0)
2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221 dl, DAG, VA, Flags));
2225 if (!MemOpChains.empty())
2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227 &MemOpChains[0], MemOpChains.size());
2229 // Build a sequence of copy-to-reg nodes chained together with token chain
2230 // and flag operands which copy the outgoing args into registers.
2232 // Tail call byval lowering might overwrite argument registers so in case of
2233 // tail call optimization the copies to registers are lowered later.
2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237 RegsToPass[i].second, InFlag);
2238 InFlag = Chain.getValue(1);
2241 if (Subtarget->isPICStyleGOT()) {
2242 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2245 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246 DAG.getNode(X86ISD::GlobalBaseReg,
2247 DebugLoc(), getPointerTy()),
2249 InFlag = Chain.getValue(1);
2251 // If we are tail calling and generating PIC/GOT style code load the
2252 // address of the callee into ECX. The value in ecx is used as target of
2253 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254 // for tail calls on PIC/GOT architectures. Normally we would just put the
2255 // address of GOT into ebx and then call target@PLT. But for tail calls
2256 // ebx would be restored (since ebx is callee saved) before jumping to the
2259 // Note: The actual moving to ECX is done further down.
2260 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262 !G->getGlobal()->hasProtectedVisibility())
2263 Callee = LowerGlobalAddress(Callee, DAG);
2264 else if (isa<ExternalSymbolSDNode>(Callee))
2265 Callee = LowerExternalSymbol(Callee, DAG);
2269 if (Is64Bit && isVarArg && !IsWin64) {
2270 // From AMD64 ABI document:
2271 // For calls that may call functions that use varargs or stdargs
2272 // (prototype-less calls or calls to functions containing ellipsis (...) in
2273 // the declaration) %al is used as hidden argument to specify the number
2274 // of SSE registers used. The contents of %al do not need to match exactly
2275 // the number of registers, but must be an ubound on the number of SSE
2276 // registers used and is in the range 0 - 8 inclusive.
2278 // Count the number of XMM registers allocated.
2279 static const unsigned XMMArgRegs[] = {
2280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2283 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284 assert((Subtarget->hasXMM() || !NumXMMRegs)
2285 && "SSE registers cannot be used when SSE is disabled");
2287 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289 InFlag = Chain.getValue(1);
2293 // For tail calls lower the arguments to the 'real' stack slot.
2295 // Force all the incoming stack arguments to be loaded from the stack
2296 // before any new outgoing arguments are stored to the stack, because the
2297 // outgoing stack slots may alias the incoming argument stack slots, and
2298 // the alias isn't otherwise explicit. This is slightly more conservative
2299 // than necessary, because it means that each store effectively depends
2300 // on every argument instead of just those arguments it would clobber.
2301 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2303 SmallVector<SDValue, 8> MemOpChains2;
2306 // Do not flag preceding copytoreg stuff together with the following stuff.
2308 if (GuaranteedTailCallOpt) {
2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310 CCValAssign &VA = ArgLocs[i];
2313 assert(VA.isMemLoc());
2314 SDValue Arg = OutVals[i];
2315 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316 // Create frame index.
2317 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320 FIN = DAG.getFrameIndex(FI, getPointerTy());
2322 if (Flags.isByVal()) {
2323 // Copy relative to framepointer.
2324 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325 if (StackPtr.getNode() == 0)
2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2328 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2330 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2334 // Store relative to framepointer.
2335 MemOpChains2.push_back(
2336 DAG.getStore(ArgChain, dl, Arg, FIN,
2337 MachinePointerInfo::getFixedStack(FI),
2343 if (!MemOpChains2.empty())
2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345 &MemOpChains2[0], MemOpChains2.size());
2347 // Copy arguments to their registers.
2348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350 RegsToPass[i].second, InFlag);
2351 InFlag = Chain.getValue(1);
2355 // Store the return address to the appropriate stack slot.
2356 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2360 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362 // In the 64-bit large code model, we have to make all calls
2363 // through a register, since the call instruction's 32-bit
2364 // pc-relative offset may not be large enough to hold the whole
2366 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367 // If the callee is a GlobalAddress node (quite common, every direct call
2368 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2371 // We should use extra load for direct calls to dllimported functions in
2373 const GlobalValue *GV = G->getGlobal();
2374 if (!GV->hasDLLImportLinkage()) {
2375 unsigned char OpFlags = 0;
2376 bool ExtraLoad = false;
2377 unsigned WrapperKind = ISD::DELETED_NODE;
2379 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380 // external symbols most go through the PLT in PIC mode. If the symbol
2381 // has hidden or protected visibility, or if it is static or local, then
2382 // we don't need to use the PLT - we can directly call it.
2383 if (Subtarget->isTargetELF() &&
2384 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386 OpFlags = X86II::MO_PLT;
2387 } else if (Subtarget->isPICStyleStubAny() &&
2388 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389 (!Subtarget->getTargetTriple().isMacOSX() ||
2390 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391 // PC-relative references to external symbols should go through $stub,
2392 // unless we're building with the leopard linker or later, which
2393 // automatically synthesizes these stubs.
2394 OpFlags = X86II::MO_DARWIN_STUB;
2395 } else if (Subtarget->isPICStyleRIPRel() &&
2396 isa<Function>(GV) &&
2397 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398 // If the function is marked as non-lazy, generate an indirect call
2399 // which loads from the GOT directly. This avoids runtime overhead
2400 // at the cost of eager binding (and one extra byte of encoding).
2401 OpFlags = X86II::MO_GOTPCREL;
2402 WrapperKind = X86ISD::WrapperRIP;
2406 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407 G->getOffset(), OpFlags);
2409 // Add a wrapper if needed.
2410 if (WrapperKind != ISD::DELETED_NODE)
2411 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412 // Add extra indirection if needed.
2414 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415 MachinePointerInfo::getGOT(),
2416 false, false, false, 0);
2418 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419 unsigned char OpFlags = 0;
2421 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422 // external symbols should go through the PLT.
2423 if (Subtarget->isTargetELF() &&
2424 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425 OpFlags = X86II::MO_PLT;
2426 } else if (Subtarget->isPICStyleStubAny() &&
2427 (!Subtarget->getTargetTriple().isMacOSX() ||
2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429 // PC-relative references to external symbols should go through $stub,
2430 // unless we're building with the leopard linker or later, which
2431 // automatically synthesizes these stubs.
2432 OpFlags = X86II::MO_DARWIN_STUB;
2435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2439 // Returns a chain & a flag for retval copy to use.
2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441 SmallVector<SDValue, 8> Ops;
2443 if (!IsSibcall && isTailCall) {
2444 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445 DAG.getIntPtrConstant(0, true), InFlag);
2446 InFlag = Chain.getValue(1);
2449 Ops.push_back(Chain);
2450 Ops.push_back(Callee);
2453 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2455 // Add argument registers to the end of the list so that they are known live
2457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459 RegsToPass[i].second.getValueType()));
2461 // Add an implicit use GOT pointer in EBX.
2462 if (!isTailCall && Subtarget->isPICStyleGOT())
2463 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2465 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466 if (Is64Bit && isVarArg && !IsWin64)
2467 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2469 if (InFlag.getNode())
2470 Ops.push_back(InFlag);
2474 //// If this is the first return lowered for this function, add the regs
2475 //// to the liveout set for the function.
2476 // This isn't right, although it's probably harmless on x86; liveouts
2477 // should be computed from returns not tail calls. Consider a void
2478 // function making a tail call to a function returning int.
2479 return DAG.getNode(X86ISD::TC_RETURN, dl,
2480 NodeTys, &Ops[0], Ops.size());
2483 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484 InFlag = Chain.getValue(1);
2486 // Create the CALLSEQ_END node.
2487 unsigned NumBytesForCalleeToPush;
2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2490 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491 // If this is a call to a struct-return function, the callee
2492 // pops the hidden struct pointer, so we have to push it back.
2493 // This is common for Darwin/X86, Linux & Mingw32 targets.
2494 NumBytesForCalleeToPush = 4;
2496 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2498 // Returns a flag for retval copy to use.
2500 Chain = DAG.getCALLSEQ_END(Chain,
2501 DAG.getIntPtrConstant(NumBytes, true),
2502 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2505 InFlag = Chain.getValue(1);
2508 // Handle result values, copying them out of physregs into vregs that we
2510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511 Ins, dl, DAG, InVals);
2515 //===----------------------------------------------------------------------===//
2516 // Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2519 // Like std call, callee cleans arguments, convention except that ECX is
2520 // reserved for storing the tail called function address. Only 2 registers are
2521 // free for argument passing (inreg). Tail call optimization is performed
2523 // * tailcallopt is enabled
2524 // * caller/callee are fastcc
2525 // On X86_64 architecture with GOT-style position independent code only local
2526 // (within module) calls are supported at the moment.
2527 // To keep the stack aligned according to platform abi the function
2528 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 // If a tail called function callee has more arguments than the caller the
2531 // caller needs to make sure that there is room to move the RETADDR to. This is
2532 // achieved by reserving an area the size of the argument delta right after the
2533 // original REtADDR, but before the saved framepointer or the spilled registers
2534 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550 SelectionDAG& DAG) const {
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 const TargetMachine &TM = MF.getTarget();
2553 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554 unsigned StackAlignment = TFI.getStackAlignment();
2555 uint64_t AlignMask = StackAlignment - 1;
2556 int64_t Offset = StackSize;
2557 uint64_t SlotSize = TD->getPointerSize();
2558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559 // Number smaller than 12 so just add the difference.
2560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2562 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563 Offset = ((~AlignMask) & Offset) + StackAlignment +
2564 (StackAlignment-SlotSize);
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575 const X86InstrInfo *TII) {
2576 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2578 if (Arg.getOpcode() == ISD::CopyFromReg) {
2579 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580 if (!TargetRegisterInfo::isVirtualRegister(VR))
2582 MachineInstr *Def = MRI->getVRegDef(VR);
2585 if (!Flags.isByVal()) {
2586 if (!TII->isLoadFromStackSlot(Def, FI))
2589 unsigned Opcode = Def->getOpcode();
2590 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591 Def->getOperand(1).isFI()) {
2592 FI = Def->getOperand(1).getIndex();
2593 Bytes = Flags.getByValSize();
2597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598 if (Flags.isByVal())
2599 // ByVal argument is passed in as a pointer but it's now being
2600 // dereferenced. e.g.
2601 // define @foo(%struct.X* %A) {
2602 // tail call @bar(%struct.X* byval %A)
2605 SDValue Ptr = Ld->getBasePtr();
2606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2609 FI = FINode->getIndex();
2610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612 FI = FINode->getIndex();
2613 Bytes = Flags.getByValSize();
2617 assert(FI != INT_MAX);
2618 if (!MFI->isFixedObjectIndex(FI))
2620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628 CallingConv::ID CalleeCC,
2630 bool isCalleeStructRet,
2631 bool isCallerStructRet,
2632 const SmallVectorImpl<ISD::OutputArg> &Outs,
2633 const SmallVectorImpl<SDValue> &OutVals,
2634 const SmallVectorImpl<ISD::InputArg> &Ins,
2635 SelectionDAG& DAG) const {
2636 if (!IsTailCallConvention(CalleeCC) &&
2637 CalleeCC != CallingConv::C)
2640 // If -tailcallopt is specified, make fastcc functions tail-callable.
2641 const MachineFunction &MF = DAG.getMachineFunction();
2642 const Function *CallerF = DAG.getMachineFunction().getFunction();
2643 CallingConv::ID CallerCC = CallerF->getCallingConv();
2644 bool CCMatch = CallerCC == CalleeCC;
2646 if (GuaranteedTailCallOpt) {
2647 if (IsTailCallConvention(CalleeCC) && CCMatch)
2652 // Look for obvious safe cases to perform tail call optimization that do not
2653 // require ABI changes. This is what gcc calls sibcall.
2655 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656 // emit a special epilogue.
2657 if (RegInfo->needsStackRealignment(MF))
2660 // Also avoid sibcall optimization if either caller or callee uses struct
2661 // return semantics.
2662 if (isCalleeStructRet || isCallerStructRet)
2665 // An stdcall caller is expected to clean up its arguments; the callee
2666 // isn't going to do that.
2667 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2670 // Do not sibcall optimize vararg calls unless all arguments are passed via
2672 if (isVarArg && !Outs.empty()) {
2674 // Optimizing for varargs on Win64 is unlikely to be safe without
2675 // additional testing.
2676 if (Subtarget->isTargetWin64())
2679 SmallVector<CCValAssign, 16> ArgLocs;
2680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681 getTargetMachine(), ArgLocs, *DAG.getContext());
2683 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685 if (!ArgLocs[i].isRegLoc())
2689 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690 // Therefore if it's not used by the call it is not safe to optimize this into
2692 bool Unused = false;
2693 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2700 SmallVector<CCValAssign, 16> RVLocs;
2701 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702 getTargetMachine(), RVLocs, *DAG.getContext());
2703 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705 CCValAssign &VA = RVLocs[i];
2706 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2711 // If the calling conventions do not match, then we'd better make sure the
2712 // results are returned in the same way as what the caller expects.
2714 SmallVector<CCValAssign, 16> RVLocs1;
2715 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716 getTargetMachine(), RVLocs1, *DAG.getContext());
2717 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2719 SmallVector<CCValAssign, 16> RVLocs2;
2720 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721 getTargetMachine(), RVLocs2, *DAG.getContext());
2722 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2724 if (RVLocs1.size() != RVLocs2.size())
2726 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2729 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2731 if (RVLocs1[i].isRegLoc()) {
2732 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2735 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2741 // If the callee takes no arguments then go on to check the results of the
2743 if (!Outs.empty()) {
2744 // Check if stack adjustment is needed. For now, do not do this if any
2745 // argument is passed on the stack.
2746 SmallVector<CCValAssign, 16> ArgLocs;
2747 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748 getTargetMachine(), ArgLocs, *DAG.getContext());
2750 // Allocate shadow area for Win64
2751 if (Subtarget->isTargetWin64()) {
2752 CCInfo.AllocateStack(32, 8);
2755 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756 if (CCInfo.getNextStackOffset()) {
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2761 // Check if the arguments are already laid out in the right way as
2762 // the caller's fixed stack objects.
2763 MachineFrameInfo *MFI = MF.getFrameInfo();
2764 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765 const X86InstrInfo *TII =
2766 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768 CCValAssign &VA = ArgLocs[i];
2769 SDValue Arg = OutVals[i];
2770 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771 if (VA.getLocInfo() == CCValAssign::Indirect)
2773 if (!VA.isRegLoc()) {
2774 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2781 // If the tailcall address may be in a register, then make sure it's
2782 // possible to register allocate for it. In 32-bit, the call address can
2783 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784 // callee-saved registers are restored. These happen to be the same
2785 // registers used to pass 'inreg' arguments so watch out for those.
2786 if (!Subtarget->is64Bit() &&
2787 !isa<GlobalAddressSDNode>(Callee) &&
2788 !isa<ExternalSymbolSDNode>(Callee)) {
2789 unsigned NumInRegs = 0;
2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791 CCValAssign &VA = ArgLocs[i];
2794 unsigned Reg = VA.getLocReg();
2797 case X86::EAX: case X86::EDX: case X86::ECX:
2798 if (++NumInRegs == 3)
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811 return X86::createFastISel(funcInfo);
2815 //===----------------------------------------------------------------------===//
2816 // Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2819 static bool MayFoldLoad(SDValue Op) {
2820 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2823 static bool MayFoldIntoStore(SDValue Op) {
2824 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2827 static bool isTargetShuffle(unsigned Opcode) {
2829 default: return false;
2830 case X86ISD::PSHUFD:
2831 case X86ISD::PSHUFHW:
2832 case X86ISD::PSHUFLW:
2833 case X86ISD::SHUFPD:
2834 case X86ISD::PALIGN:
2835 case X86ISD::SHUFPS:
2836 case X86ISD::MOVLHPS:
2837 case X86ISD::MOVLHPD:
2838 case X86ISD::MOVHLPS:
2839 case X86ISD::MOVLPS:
2840 case X86ISD::MOVLPD:
2841 case X86ISD::MOVSHDUP:
2842 case X86ISD::MOVSLDUP:
2843 case X86ISD::MOVDDUP:
2846 case X86ISD::UNPCKLP:
2847 case X86ISD::PUNPCKL:
2848 case X86ISD::UNPCKHP:
2849 case X86ISD::PUNPCKH:
2850 case X86ISD::VPERMILPS:
2851 case X86ISD::VPERMILPSY:
2852 case X86ISD::VPERMILPD:
2853 case X86ISD::VPERMILPDY:
2854 case X86ISD::VPERM2F128:
2860 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2861 SDValue V1, SelectionDAG &DAG) {
2863 default: llvm_unreachable("Unknown x86 shuffle node");
2864 case X86ISD::MOVSHDUP:
2865 case X86ISD::MOVSLDUP:
2866 case X86ISD::MOVDDUP:
2867 return DAG.getNode(Opc, dl, VT, V1);
2873 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2874 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2876 default: llvm_unreachable("Unknown x86 shuffle node");
2877 case X86ISD::PSHUFD:
2878 case X86ISD::PSHUFHW:
2879 case X86ISD::PSHUFLW:
2880 case X86ISD::VPERMILPS:
2881 case X86ISD::VPERMILPSY:
2882 case X86ISD::VPERMILPD:
2883 case X86ISD::VPERMILPDY:
2884 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2890 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2891 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2893 default: llvm_unreachable("Unknown x86 shuffle node");
2894 case X86ISD::PALIGN:
2895 case X86ISD::SHUFPD:
2896 case X86ISD::SHUFPS:
2897 case X86ISD::VPERM2F128:
2898 return DAG.getNode(Opc, dl, VT, V1, V2,
2899 DAG.getConstant(TargetMask, MVT::i8));
2904 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2905 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2907 default: llvm_unreachable("Unknown x86 shuffle node");
2908 case X86ISD::MOVLHPS:
2909 case X86ISD::MOVLHPD:
2910 case X86ISD::MOVHLPS:
2911 case X86ISD::MOVLPS:
2912 case X86ISD::MOVLPD:
2915 case X86ISD::UNPCKLP:
2916 case X86ISD::PUNPCKL:
2917 case X86ISD::UNPCKHP:
2918 case X86ISD::PUNPCKH:
2919 return DAG.getNode(Opc, dl, VT, V1, V2);
2924 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2925 MachineFunction &MF = DAG.getMachineFunction();
2926 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2927 int ReturnAddrIndex = FuncInfo->getRAIndex();
2929 if (ReturnAddrIndex == 0) {
2930 // Set up a frame object for the return address.
2931 uint64_t SlotSize = TD->getPointerSize();
2932 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2934 FuncInfo->setRAIndex(ReturnAddrIndex);
2937 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2941 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2942 bool hasSymbolicDisplacement) {
2943 // Offset should fit into 32 bit immediate field.
2944 if (!isInt<32>(Offset))
2947 // If we don't have a symbolic displacement - we don't have any extra
2949 if (!hasSymbolicDisplacement)
2952 // FIXME: Some tweaks might be needed for medium code model.
2953 if (M != CodeModel::Small && M != CodeModel::Kernel)
2956 // For small code model we assume that latest object is 16MB before end of 31
2957 // bits boundary. We may also accept pretty large negative constants knowing
2958 // that all objects are in the positive half of address space.
2959 if (M == CodeModel::Small && Offset < 16*1024*1024)
2962 // For kernel code model we know that all object resist in the negative half
2963 // of 32bits address space. We may not accept negative offsets, since they may
2964 // be just off and we may accept pretty large positive ones.
2965 if (M == CodeModel::Kernel && Offset > 0)
2971 /// isCalleePop - Determines whether the callee is required to pop its
2972 /// own arguments. Callee pop is necessary to support tail calls.
2973 bool X86::isCalleePop(CallingConv::ID CallingConv,
2974 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2978 switch (CallingConv) {
2981 case CallingConv::X86_StdCall:
2983 case CallingConv::X86_FastCall:
2985 case CallingConv::X86_ThisCall:
2987 case CallingConv::Fast:
2989 case CallingConv::GHC:
2994 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2995 /// specific condition code, returning the condition code and the LHS/RHS of the
2996 /// comparison to make.
2997 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2998 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3000 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3001 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3002 // X > -1 -> X == 0, jump !sign.
3003 RHS = DAG.getConstant(0, RHS.getValueType());
3004 return X86::COND_NS;
3005 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3006 // X < 0 -> X == 0, jump on sign.
3008 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3010 RHS = DAG.getConstant(0, RHS.getValueType());
3011 return X86::COND_LE;
3015 switch (SetCCOpcode) {
3016 default: llvm_unreachable("Invalid integer condition!");
3017 case ISD::SETEQ: return X86::COND_E;
3018 case ISD::SETGT: return X86::COND_G;
3019 case ISD::SETGE: return X86::COND_GE;
3020 case ISD::SETLT: return X86::COND_L;
3021 case ISD::SETLE: return X86::COND_LE;
3022 case ISD::SETNE: return X86::COND_NE;
3023 case ISD::SETULT: return X86::COND_B;
3024 case ISD::SETUGT: return X86::COND_A;
3025 case ISD::SETULE: return X86::COND_BE;
3026 case ISD::SETUGE: return X86::COND_AE;
3030 // First determine if it is required or is profitable to flip the operands.
3032 // If LHS is a foldable load, but RHS is not, flip the condition.
3033 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3034 !ISD::isNON_EXTLoad(RHS.getNode())) {
3035 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3036 std::swap(LHS, RHS);
3039 switch (SetCCOpcode) {
3045 std::swap(LHS, RHS);
3049 // On a floating point condition, the flags are set as follows:
3051 // 0 | 0 | 0 | X > Y
3052 // 0 | 0 | 1 | X < Y
3053 // 1 | 0 | 0 | X == Y
3054 // 1 | 1 | 1 | unordered
3055 switch (SetCCOpcode) {
3056 default: llvm_unreachable("Condcode should be pre-legalized away");
3058 case ISD::SETEQ: return X86::COND_E;
3059 case ISD::SETOLT: // flipped
3061 case ISD::SETGT: return X86::COND_A;
3062 case ISD::SETOLE: // flipped
3064 case ISD::SETGE: return X86::COND_AE;
3065 case ISD::SETUGT: // flipped
3067 case ISD::SETLT: return X86::COND_B;
3068 case ISD::SETUGE: // flipped
3070 case ISD::SETLE: return X86::COND_BE;
3072 case ISD::SETNE: return X86::COND_NE;
3073 case ISD::SETUO: return X86::COND_P;
3074 case ISD::SETO: return X86::COND_NP;
3076 case ISD::SETUNE: return X86::COND_INVALID;
3080 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3081 /// code. Current x86 isa includes the following FP cmov instructions:
3082 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3083 static bool hasFPCMov(unsigned X86CC) {
3099 /// isFPImmLegal - Returns true if the target can instruction select the
3100 /// specified FP immediate natively. If false, the legalizer will
3101 /// materialize the FP immediate as a load from a constant pool.
3102 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3103 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3104 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3110 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3111 /// the specified range (L, H].
3112 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3113 return (Val < 0) || (Val >= Low && Val < Hi);
3116 /// isUndefOrInRange - Return true if every element in Mask, begining
3117 /// from position Pos and ending in Pos+Size, falls within the specified
3118 /// range (L, L+Pos]. or is undef.
3119 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3120 int Pos, int Size, int Low, int Hi) {
3121 for (int i = Pos, e = Pos+Size; i != e; ++i)
3122 if (!isUndefOrInRange(Mask[i], Low, Hi))
3127 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3128 /// specified value.
3129 static bool isUndefOrEqual(int Val, int CmpVal) {
3130 if (Val < 0 || Val == CmpVal)
3135 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3136 /// from position Pos and ending in Pos+Size, falls within the specified
3137 /// sequential range (L, L+Pos]. or is undef.
3138 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3139 int Pos, int Size, int Low) {
3140 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3141 if (!isUndefOrEqual(Mask[i], Low))
3146 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3147 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3148 /// the second operand.
3149 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3150 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3151 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3152 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3153 return (Mask[0] < 2 && Mask[1] < 2);
3157 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3158 SmallVector<int, 8> M;
3160 return ::isPSHUFDMask(M, N->getValueType(0));
3163 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3164 /// is suitable for input to PSHUFHW.
3165 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3166 if (VT != MVT::v8i16)
3169 // Lower quadword copied in order or undef.
3170 for (int i = 0; i != 4; ++i)
3171 if (Mask[i] >= 0 && Mask[i] != i)
3174 // Upper quadword shuffled.
3175 for (int i = 4; i != 8; ++i)
3176 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3182 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3183 SmallVector<int, 8> M;
3185 return ::isPSHUFHWMask(M, N->getValueType(0));
3188 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3189 /// is suitable for input to PSHUFLW.
3190 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3191 if (VT != MVT::v8i16)
3194 // Upper quadword copied in order.
3195 for (int i = 4; i != 8; ++i)
3196 if (Mask[i] >= 0 && Mask[i] != i)
3199 // Lower quadword shuffled.
3200 for (int i = 0; i != 4; ++i)
3207 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3208 SmallVector<int, 8> M;
3210 return ::isPSHUFLWMask(M, N->getValueType(0));
3213 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3214 /// is suitable for input to PALIGNR.
3215 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3216 bool hasSSSE3OrAVX) {
3217 int i, e = VT.getVectorNumElements();
3218 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3221 // Do not handle v2i64 / v2f64 shuffles with palignr.
3222 if (e < 4 || !hasSSSE3OrAVX)
3225 for (i = 0; i != e; ++i)
3229 // All undef, not a palignr.
3233 // Make sure we're shifting in the right direction.
3237 int s = Mask[i] - i;
3239 // Check the rest of the elements to see if they are consecutive.
3240 for (++i; i != e; ++i) {
3242 if (m >= 0 && m != s+i)
3248 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3249 /// specifies a shuffle of elements that is suitable for input to 256-bit
3251 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3252 const X86Subtarget *Subtarget) {
3253 int NumElems = VT.getVectorNumElements();
3255 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3261 // VSHUFPSY divides the resulting vector into 4 chunks.
3262 // The sources are also splitted into 4 chunks, and each destination
3263 // chunk must come from a different source chunk.
3265 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3266 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3268 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3269 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3271 int QuarterSize = NumElems/4;
3272 int HalfSize = QuarterSize*2;
3273 for (int i = 0; i < QuarterSize; ++i)
3274 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3276 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3277 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3280 // The mask of the second half must be the same as the first but with
3281 // the appropriate offsets. This works in the same way as VPERMILPS
3282 // works with masks.
3283 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3284 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3286 int FstHalfIdx = i-HalfSize;
3287 if (Mask[FstHalfIdx] < 0)
3289 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3292 for (int i = QuarterSize*3; i < NumElems; ++i) {
3293 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3295 int FstHalfIdx = i-HalfSize;
3296 if (Mask[FstHalfIdx] < 0)
3298 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3306 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3307 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3308 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3309 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3310 EVT VT = SVOp->getValueType(0);
3311 int NumElems = VT.getVectorNumElements();
3313 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3314 "Only supports v8i32 and v8f32 types");
3316 int HalfSize = NumElems/2;
3318 for (int i = 0; i != NumElems ; ++i) {
3319 if (SVOp->getMaskElt(i) < 0)
3321 // The mask of the first half must be equal to the second one.
3322 unsigned Shamt = (i%HalfSize)*2;
3323 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3324 Mask |= Elt << Shamt;
3330 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3331 /// specifies a shuffle of elements that is suitable for input to 256-bit
3332 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3333 /// version and the mask of the second half isn't binded with the first
3335 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3336 const X86Subtarget *Subtarget) {
3337 int NumElems = VT.getVectorNumElements();
3339 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3345 // VSHUFPSY divides the resulting vector into 4 chunks.
3346 // The sources are also splitted into 4 chunks, and each destination
3347 // chunk must come from a different source chunk.
3349 // SRC1 => X3 X2 X1 X0
3350 // SRC2 => Y3 Y2 Y1 Y0
3352 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3354 int QuarterSize = NumElems/4;
3355 int HalfSize = QuarterSize*2;
3356 for (int i = 0; i < QuarterSize; ++i)
3357 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3359 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3360 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3362 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3363 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3365 for (int i = QuarterSize*3; i < NumElems; ++i)
3366 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3372 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3373 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3374 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3375 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3376 EVT VT = SVOp->getValueType(0);
3377 int NumElems = VT.getVectorNumElements();
3379 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3380 "Only supports v4i64 and v4f64 types");
3382 int HalfSize = NumElems/2;
3384 for (int i = 0; i != NumElems ; ++i) {
3385 if (SVOp->getMaskElt(i) < 0)
3387 int Elt = SVOp->getMaskElt(i) % HalfSize;
3394 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3395 /// the two vector operands have swapped position.
3396 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3397 unsigned NumElems = VT.getVectorNumElements();
3398 for (unsigned i = 0; i != NumElems; ++i) {
3402 else if (idx < (int)NumElems)
3403 Mask[i] = idx + NumElems;
3405 Mask[i] = idx - NumElems;
3409 /// isCommutedVSHUFP() - Return true if swapping operands will
3410 /// allow to use the "vshufpd" or "vshufps" instruction
3411 /// for 256-bit vectors
3412 static bool isCommutedVSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3413 const X86Subtarget *Subtarget) {
3415 unsigned NumElems = VT.getVectorNumElements();
3416 if ((VT.getSizeInBits() != 256) || ((NumElems != 4) && (NumElems != 8)))
3419 SmallVector<int, 8> CommutedMask;
3420 for (unsigned i = 0; i < NumElems; ++i)
3421 CommutedMask.push_back(Mask[i]);
3423 CommuteVectorShuffleMask(CommutedMask, VT);
3424 return (NumElems == 4) ? isVSHUFPDYMask(CommutedMask, VT, Subtarget):
3425 isVSHUFPSYMask(CommutedMask, VT, Subtarget);
3429 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3430 /// specifies a shuffle of elements that is suitable for input to 128-bit
3431 /// SHUFPS and SHUFPD.
3432 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3433 int NumElems = VT.getVectorNumElements();
3435 if (VT.getSizeInBits() != 128)
3438 if (NumElems != 2 && NumElems != 4)
3441 int Half = NumElems / 2;
3442 for (int i = 0; i < Half; ++i)
3443 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3445 for (int i = Half; i < NumElems; ++i)
3446 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3452 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3453 SmallVector<int, 8> M;
3455 return ::isSHUFPMask(M, N->getValueType(0));
3458 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3459 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3460 /// half elements to come from vector 1 (which would equal the dest.) and
3461 /// the upper half to come from vector 2.
3462 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3463 int NumElems = VT.getVectorNumElements();
3465 if (NumElems != 2 && NumElems != 4)
3468 int Half = NumElems / 2;
3469 for (int i = 0; i < Half; ++i)
3470 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3472 for (int i = Half; i < NumElems; ++i)
3473 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3478 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3479 SmallVector<int, 8> M;
3481 return isCommutedSHUFPMask(M, N->getValueType(0));
3484 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3485 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3486 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3487 EVT VT = N->getValueType(0);
3488 unsigned NumElems = VT.getVectorNumElements();
3490 if (VT.getSizeInBits() != 128)
3496 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3497 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3498 isUndefOrEqual(N->getMaskElt(1), 7) &&
3499 isUndefOrEqual(N->getMaskElt(2), 2) &&
3500 isUndefOrEqual(N->getMaskElt(3), 3);
3503 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3504 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3506 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3507 EVT VT = N->getValueType(0);
3508 unsigned NumElems = VT.getVectorNumElements();
3510 if (VT.getSizeInBits() != 128)
3516 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3517 isUndefOrEqual(N->getMaskElt(1), 3) &&
3518 isUndefOrEqual(N->getMaskElt(2), 2) &&
3519 isUndefOrEqual(N->getMaskElt(3), 3);
3522 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3523 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3524 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3525 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3527 if (NumElems != 2 && NumElems != 4)
3530 for (unsigned i = 0; i < NumElems/2; ++i)
3531 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3534 for (unsigned i = NumElems/2; i < NumElems; ++i)
3535 if (!isUndefOrEqual(N->getMaskElt(i), i))
3541 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3542 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3543 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3544 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3546 if ((NumElems != 2 && NumElems != 4)
3547 || N->getValueType(0).getSizeInBits() > 128)
3550 for (unsigned i = 0; i < NumElems/2; ++i)
3551 if (!isUndefOrEqual(N->getMaskElt(i), i))
3554 for (unsigned i = 0; i < NumElems/2; ++i)
3555 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3561 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3562 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3563 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3564 bool HasAVX2, bool V2IsSplat = false) {
3565 int NumElts = VT.getVectorNumElements();
3567 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3568 "Unsupported vector type for unpckh");
3570 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3571 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3574 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3575 // independently on 128-bit lanes.
3576 unsigned NumLanes = VT.getSizeInBits()/128;
3577 unsigned NumLaneElts = NumElts/NumLanes;
3580 unsigned End = NumLaneElts;
3581 for (unsigned s = 0; s < NumLanes; ++s) {
3582 for (unsigned i = Start, j = s * NumLaneElts;
3586 int BitI1 = Mask[i+1];
3587 if (!isUndefOrEqual(BitI, j))
3590 if (!isUndefOrEqual(BitI1, NumElts))
3593 if (!isUndefOrEqual(BitI1, j + NumElts))
3597 // Process the next 128 bits.
3598 Start += NumLaneElts;
3605 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3606 SmallVector<int, 8> M;
3608 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3611 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3612 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3613 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3614 bool HasAVX2, bool V2IsSplat = false) {
3615 int NumElts = VT.getVectorNumElements();
3617 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3618 "Unsupported vector type for unpckh");
3620 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3621 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3624 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3625 // independently on 128-bit lanes.
3626 unsigned NumLanes = VT.getSizeInBits()/128;
3627 unsigned NumLaneElts = NumElts/NumLanes;
3630 unsigned End = NumLaneElts;
3631 for (unsigned l = 0; l != NumLanes; ++l) {
3632 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3633 i != End; i += 2, ++j) {
3635 int BitI1 = Mask[i+1];
3636 if (!isUndefOrEqual(BitI, j))
3639 if (isUndefOrEqual(BitI1, NumElts))
3642 if (!isUndefOrEqual(BitI1, j+NumElts))
3646 // Process the next 128 bits.
3647 Start += NumLaneElts;
3653 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3654 SmallVector<int, 8> M;
3656 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3659 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3660 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3662 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3663 int NumElems = VT.getVectorNumElements();
3664 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3667 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3668 // FIXME: Need a better way to get rid of this, there's no latency difference
3669 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3670 // the former later. We should also remove the "_undef" special mask.
3671 if (NumElems == 4 && VT.getSizeInBits() == 256)
3674 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3675 // independently on 128-bit lanes.
3676 unsigned NumLanes = VT.getSizeInBits() / 128;
3677 unsigned NumLaneElts = NumElems / NumLanes;
3679 for (unsigned s = 0; s < NumLanes; ++s) {
3680 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3681 i != NumLaneElts * (s + 1);
3684 int BitI1 = Mask[i+1];
3686 if (!isUndefOrEqual(BitI, j))
3688 if (!isUndefOrEqual(BitI1, j))
3696 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3697 SmallVector<int, 8> M;
3699 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3702 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3703 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3705 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3706 int NumElems = VT.getVectorNumElements();
3707 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3710 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3712 int BitI1 = Mask[i+1];
3713 if (!isUndefOrEqual(BitI, j))
3715 if (!isUndefOrEqual(BitI1, j))
3721 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3722 SmallVector<int, 8> M;
3724 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3727 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3728 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3729 /// MOVSD, and MOVD, i.e. setting the lowest element.
3730 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3731 if (VT.getVectorElementType().getSizeInBits() < 32)
3734 int NumElts = VT.getVectorNumElements();
3736 if (!isUndefOrEqual(Mask[0], NumElts))
3739 for (int i = 1; i < NumElts; ++i)
3740 if (!isUndefOrEqual(Mask[i], i))
3746 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3747 SmallVector<int, 8> M;
3749 return ::isMOVLMask(M, N->getValueType(0));
3752 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3753 /// as permutations between 128-bit chunks or halves. As an example: this
3755 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3756 /// The first half comes from the second half of V1 and the second half from the
3757 /// the second half of V2.
3758 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3759 const X86Subtarget *Subtarget) {
3760 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3763 // The shuffle result is divided into half A and half B. In total the two
3764 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3765 // B must come from C, D, E or F.
3766 int HalfSize = VT.getVectorNumElements()/2;
3767 bool MatchA = false, MatchB = false;
3769 // Check if A comes from one of C, D, E, F.
3770 for (int Half = 0; Half < 4; ++Half) {
3771 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3777 // Check if B comes from one of C, D, E, F.
3778 for (int Half = 0; Half < 4; ++Half) {
3779 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3785 return MatchA && MatchB;
3788 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3789 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3790 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3791 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3792 EVT VT = SVOp->getValueType(0);
3794 int HalfSize = VT.getVectorNumElements()/2;
3796 int FstHalf = 0, SndHalf = 0;
3797 for (int i = 0; i < HalfSize; ++i) {
3798 if (SVOp->getMaskElt(i) > 0) {
3799 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3803 for (int i = HalfSize; i < HalfSize*2; ++i) {
3804 if (SVOp->getMaskElt(i) > 0) {
3805 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3810 return (FstHalf | (SndHalf << 4));
3813 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3814 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3815 /// Note that VPERMIL mask matching is different depending whether theunderlying
3816 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3817 /// to the same elements of the low, but to the higher half of the source.
3818 /// In VPERMILPD the two lanes could be shuffled independently of each other
3819 /// with the same restriction that lanes can't be crossed.
3820 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3821 const X86Subtarget *Subtarget) {
3822 int NumElts = VT.getVectorNumElements();
3823 int NumLanes = VT.getSizeInBits()/128;
3825 if (!Subtarget->hasAVX())
3828 // Only match 256-bit with 64-bit types
3829 if (VT.getSizeInBits() != 256 || NumElts != 4)
3832 // The mask on the high lane is independent of the low. Both can match
3833 // any element in inside its own lane, but can't cross.
3834 int LaneSize = NumElts/NumLanes;
3835 for (int l = 0; l < NumLanes; ++l)
3836 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3837 int LaneStart = l*LaneSize;
3838 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3845 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3846 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3847 /// Note that VPERMIL mask matching is different depending whether theunderlying
3848 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3849 /// to the same elements of the low, but to the higher half of the source.
3850 /// In VPERMILPD the two lanes could be shuffled independently of each other
3851 /// with the same restriction that lanes can't be crossed.
3852 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3853 const X86Subtarget *Subtarget) {
3854 unsigned NumElts = VT.getVectorNumElements();
3855 unsigned NumLanes = VT.getSizeInBits()/128;
3857 if (!Subtarget->hasAVX())
3860 // Only match 256-bit with 32-bit types
3861 if (VT.getSizeInBits() != 256 || NumElts != 8)
3864 // The mask on the high lane should be the same as the low. Actually,
3865 // they can differ if any of the corresponding index in a lane is undef
3866 // and the other stays in range.
3867 int LaneSize = NumElts/NumLanes;
3868 for (int i = 0; i < LaneSize; ++i) {
3869 int HighElt = i+LaneSize;
3870 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3871 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3873 if (!HighValid || !LowValid)
3875 if (Mask[i] < 0 || Mask[HighElt] < 0)
3877 if (Mask[HighElt]-Mask[i] != LaneSize)
3884 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3885 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3886 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3887 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3888 EVT VT = SVOp->getValueType(0);
3890 int NumElts = VT.getVectorNumElements();
3891 int NumLanes = VT.getSizeInBits()/128;
3892 int LaneSize = NumElts/NumLanes;
3894 // Although the mask is equal for both lanes do it twice to get the cases
3895 // where a mask will match because the same mask element is undef on the
3896 // first half but valid on the second. This would get pathological cases
3897 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3899 for (int l = 0; l < NumLanes; ++l) {
3900 for (int i = 0; i < LaneSize; ++i) {
3901 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3904 if (MaskElt >= LaneSize)
3905 MaskElt -= LaneSize;
3906 Mask |= MaskElt << (i*2);
3913 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3914 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3915 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3916 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3917 EVT VT = SVOp->getValueType(0);
3919 int NumElts = VT.getVectorNumElements();
3920 int NumLanes = VT.getSizeInBits()/128;
3923 int LaneSize = NumElts/NumLanes;
3924 for (int l = 0; l < NumLanes; ++l)
3925 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3926 int MaskElt = SVOp->getMaskElt(i);
3929 Mask |= (MaskElt-l*LaneSize) << i;
3935 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3936 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3937 /// element of vector 2 and the other elements to come from vector 1 in order.
3938 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3939 bool V2IsSplat = false, bool V2IsUndef = false) {
3940 int NumOps = VT.getVectorNumElements();
3941 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3944 if (!isUndefOrEqual(Mask[0], 0))
3947 for (int i = 1; i < NumOps; ++i)
3948 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3949 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3950 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3956 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3957 bool V2IsUndef = false) {
3958 SmallVector<int, 8> M;
3960 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3963 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3964 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3965 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3966 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3967 const X86Subtarget *Subtarget) {
3968 if (!Subtarget->hasSSE3orAVX())
3971 // The second vector must be undef
3972 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3975 EVT VT = N->getValueType(0);
3976 unsigned NumElems = VT.getVectorNumElements();
3978 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3979 (VT.getSizeInBits() == 256 && NumElems != 8))
3982 // "i+1" is the value the indexed mask element must have
3983 for (unsigned i = 0; i < NumElems; i += 2)
3984 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3985 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3991 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3992 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3993 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3994 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3995 const X86Subtarget *Subtarget) {
3996 if (!Subtarget->hasSSE3orAVX())
3999 // The second vector must be undef
4000 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4003 EVT VT = N->getValueType(0);
4004 unsigned NumElems = VT.getVectorNumElements();
4006 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4007 (VT.getSizeInBits() == 256 && NumElems != 8))
4010 // "i" is the value the indexed mask element must have
4011 for (unsigned i = 0; i < NumElems; i += 2)
4012 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4013 !isUndefOrEqual(N->getMaskElt(i+1), i))
4019 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4020 /// specifies a shuffle of elements that is suitable for input to 256-bit
4021 /// version of MOVDDUP.
4022 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4023 const X86Subtarget *Subtarget) {
4024 EVT VT = N->getValueType(0);
4025 int NumElts = VT.getVectorNumElements();
4026 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4028 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4029 !V2IsUndef || NumElts != 4)
4032 for (int i = 0; i != NumElts/2; ++i)
4033 if (!isUndefOrEqual(N->getMaskElt(i), 0))
4035 for (int i = NumElts/2; i != NumElts; ++i)
4036 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4041 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4042 /// specifies a shuffle of elements that is suitable for input to 128-bit
4043 /// version of MOVDDUP.
4044 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4045 EVT VT = N->getValueType(0);
4047 if (VT.getSizeInBits() != 128)
4050 int e = VT.getVectorNumElements() / 2;
4051 for (int i = 0; i < e; ++i)
4052 if (!isUndefOrEqual(N->getMaskElt(i), i))
4054 for (int i = 0; i < e; ++i)
4055 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4060 /// isVEXTRACTF128Index - Return true if the specified
4061 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4062 /// suitable for input to VEXTRACTF128.
4063 bool X86::isVEXTRACTF128Index(SDNode *N) {
4064 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4067 // The index should be aligned on a 128-bit boundary.
4069 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4071 unsigned VL = N->getValueType(0).getVectorNumElements();
4072 unsigned VBits = N->getValueType(0).getSizeInBits();
4073 unsigned ElSize = VBits / VL;
4074 bool Result = (Index * ElSize) % 128 == 0;
4079 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4080 /// operand specifies a subvector insert that is suitable for input to
4082 bool X86::isVINSERTF128Index(SDNode *N) {
4083 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4086 // The index should be aligned on a 128-bit boundary.
4088 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4090 unsigned VL = N->getValueType(0).getVectorNumElements();
4091 unsigned VBits = N->getValueType(0).getSizeInBits();
4092 unsigned ElSize = VBits / VL;
4093 bool Result = (Index * ElSize) % 128 == 0;
4098 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4099 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4100 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4102 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4104 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4106 for (int i = 0; i < NumOperands; ++i) {
4107 int Val = SVOp->getMaskElt(NumOperands-i-1);
4108 if (Val < 0) Val = 0;
4109 if (Val >= NumOperands) Val -= NumOperands;
4111 if (i != NumOperands - 1)
4117 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4118 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4119 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4120 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4122 // 8 nodes, but we only care about the last 4.
4123 for (unsigned i = 7; i >= 4; --i) {
4124 int Val = SVOp->getMaskElt(i);
4133 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4134 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4135 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4136 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4138 // 8 nodes, but we only care about the first 4.
4139 for (int i = 3; i >= 0; --i) {
4140 int Val = SVOp->getMaskElt(i);
4149 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4150 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4151 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4152 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4153 EVT VVT = N->getValueType(0);
4154 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4158 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4159 Val = SVOp->getMaskElt(i);
4163 assert(Val - i > 0 && "PALIGNR imm should be positive");
4164 return (Val - i) * EltSize;
4167 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4168 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4170 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4171 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4172 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4175 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4177 EVT VecVT = N->getOperand(0).getValueType();
4178 EVT ElVT = VecVT.getVectorElementType();
4180 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4181 return Index / NumElemsPerChunk;
4184 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4185 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4187 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4188 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4189 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4192 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4194 EVT VecVT = N->getValueType(0);
4195 EVT ElVT = VecVT.getVectorElementType();
4197 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4198 return Index / NumElemsPerChunk;
4201 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4203 bool X86::isZeroNode(SDValue Elt) {
4204 return ((isa<ConstantSDNode>(Elt) &&
4205 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4206 (isa<ConstantFPSDNode>(Elt) &&
4207 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4210 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4211 /// their permute mask.
4212 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4213 SelectionDAG &DAG) {
4214 EVT VT = SVOp->getValueType(0);
4215 unsigned NumElems = VT.getVectorNumElements();
4216 SmallVector<int, 8> MaskVec;
4218 for (unsigned i = 0; i != NumElems; ++i) {
4219 int idx = SVOp->getMaskElt(i);
4221 MaskVec.push_back(idx);
4222 else if (idx < (int)NumElems)
4223 MaskVec.push_back(idx + NumElems);
4225 MaskVec.push_back(idx - NumElems);
4227 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4228 SVOp->getOperand(0), &MaskVec[0]);
4231 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4232 /// match movhlps. The lower half elements should come from upper half of
4233 /// V1 (and in order), and the upper half elements should come from the upper
4234 /// half of V2 (and in order).
4235 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4236 EVT VT = Op->getValueType(0);
4237 if (VT.getSizeInBits() != 128)
4239 if (VT.getVectorNumElements() != 4)
4241 for (unsigned i = 0, e = 2; i != e; ++i)
4242 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4244 for (unsigned i = 2; i != 4; ++i)
4245 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4250 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4251 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4253 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4254 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4256 N = N->getOperand(0).getNode();
4257 if (!ISD::isNON_EXTLoad(N))
4260 *LD = cast<LoadSDNode>(N);
4264 // Test whether the given value is a vector value which will be legalized
4266 static bool WillBeConstantPoolLoad(SDNode *N) {
4267 if (N->getOpcode() != ISD::BUILD_VECTOR)
4270 // Check for any non-constant elements.
4271 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4272 switch (N->getOperand(i).getNode()->getOpcode()) {
4274 case ISD::ConstantFP:
4281 // Vectors of all-zeros and all-ones are materialized with special
4282 // instructions rather than being loaded.
4283 return !ISD::isBuildVectorAllZeros(N) &&
4284 !ISD::isBuildVectorAllOnes(N);
4287 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4288 /// match movlp{s|d}. The lower half elements should come from lower half of
4289 /// V1 (and in order), and the upper half elements should come from the upper
4290 /// half of V2 (and in order). And since V1 will become the source of the
4291 /// MOVLP, it must be either a vector load or a scalar load to vector.
4292 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4293 ShuffleVectorSDNode *Op) {
4294 EVT VT = Op->getValueType(0);
4295 if (VT.getSizeInBits() != 128)
4298 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4300 // Is V2 is a vector load, don't do this transformation. We will try to use
4301 // load folding shufps op.
4302 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4305 unsigned NumElems = VT.getVectorNumElements();
4307 if (NumElems != 2 && NumElems != 4)
4309 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4310 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4312 for (unsigned i = NumElems/2; i != NumElems; ++i)
4313 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4318 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4320 static bool isSplatVector(SDNode *N) {
4321 if (N->getOpcode() != ISD::BUILD_VECTOR)
4324 SDValue SplatValue = N->getOperand(0);
4325 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4326 if (N->getOperand(i) != SplatValue)
4331 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4332 /// to an zero vector.
4333 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4334 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4335 SDValue V1 = N->getOperand(0);
4336 SDValue V2 = N->getOperand(1);
4337 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4338 for (unsigned i = 0; i != NumElems; ++i) {
4339 int Idx = N->getMaskElt(i);
4340 if (Idx >= (int)NumElems) {
4341 unsigned Opc = V2.getOpcode();
4342 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4344 if (Opc != ISD::BUILD_VECTOR ||
4345 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4347 } else if (Idx >= 0) {
4348 unsigned Opc = V1.getOpcode();
4349 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4351 if (Opc != ISD::BUILD_VECTOR ||
4352 !X86::isZeroNode(V1.getOperand(Idx)))
4359 /// getZeroVector - Returns a vector of specified type with all zero elements.
4361 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4363 assert(VT.isVector() && "Expected a vector type");
4365 // Always build SSE zero vectors as <4 x i32> bitcasted
4366 // to their dest type. This ensures they get CSE'd.
4368 if (VT.getSizeInBits() == 128) { // SSE
4369 if (HasXMMInt) { // SSE2
4370 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4371 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4373 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4374 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4376 } else if (VT.getSizeInBits() == 256) { // AVX
4377 // 256-bit logic and arithmetic instructions in AVX are
4378 // all floating-point, no support for integer ops. Default
4379 // to emitting fp zeroed vectors then.
4380 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4381 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4382 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4384 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4387 /// getOnesVector - Returns a vector of specified type with all bits set.
4388 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4389 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4390 /// Then bitcast to their original type, ensuring they get CSE'd.
4391 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4393 assert(VT.isVector() && "Expected a vector type");
4394 assert((VT.is128BitVector() || VT.is256BitVector())
4395 && "Expected a 128-bit or 256-bit vector type");
4397 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4399 if (VT.getSizeInBits() == 256) {
4400 if (HasAVX2) { // AVX2
4401 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4405 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4406 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4407 Vec = Insert128BitVector(InsV, Vec,
4408 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4411 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4414 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4417 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4418 /// that point to V2 points to its first element.
4419 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4420 EVT VT = SVOp->getValueType(0);
4421 unsigned NumElems = VT.getVectorNumElements();
4423 bool Changed = false;
4424 SmallVector<int, 8> MaskVec;
4425 SVOp->getMask(MaskVec);
4427 for (unsigned i = 0; i != NumElems; ++i) {
4428 if (MaskVec[i] > (int)NumElems) {
4429 MaskVec[i] = NumElems;
4434 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4435 SVOp->getOperand(1), &MaskVec[0]);
4436 return SDValue(SVOp, 0);
4439 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4440 /// operation of specified width.
4441 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4443 unsigned NumElems = VT.getVectorNumElements();
4444 SmallVector<int, 8> Mask;
4445 Mask.push_back(NumElems);
4446 for (unsigned i = 1; i != NumElems; ++i)
4448 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4452 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4454 unsigned NumElems = VT.getVectorNumElements();
4455 SmallVector<int, 8> Mask;
4456 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4458 Mask.push_back(i + NumElems);
4460 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4463 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4464 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4466 unsigned NumElems = VT.getVectorNumElements();
4467 unsigned Half = NumElems/2;
4468 SmallVector<int, 8> Mask;
4469 for (unsigned i = 0; i != Half; ++i) {
4470 Mask.push_back(i + Half);
4471 Mask.push_back(i + NumElems + Half);
4473 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4476 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4477 // a generic shuffle instruction because the target has no such instructions.
4478 // Generate shuffles which repeat i16 and i8 several times until they can be
4479 // represented by v4f32 and then be manipulated by target suported shuffles.
4480 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4481 EVT VT = V.getValueType();
4482 int NumElems = VT.getVectorNumElements();
4483 DebugLoc dl = V.getDebugLoc();
4485 while (NumElems > 4) {
4486 if (EltNo < NumElems/2) {
4487 V = getUnpackl(DAG, dl, VT, V, V);
4489 V = getUnpackh(DAG, dl, VT, V, V);
4490 EltNo -= NumElems/2;
4497 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4498 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4499 EVT VT = V.getValueType();
4500 DebugLoc dl = V.getDebugLoc();
4501 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4502 && "Vector size not supported");
4504 if (VT.getSizeInBits() == 128) {
4505 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4506 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4507 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4510 // To use VPERMILPS to splat scalars, the second half of indicies must
4511 // refer to the higher part, which is a duplication of the lower one,
4512 // because VPERMILPS can only handle in-lane permutations.
4513 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4514 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4516 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4517 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4521 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4524 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4525 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4526 EVT SrcVT = SV->getValueType(0);
4527 SDValue V1 = SV->getOperand(0);
4528 DebugLoc dl = SV->getDebugLoc();
4530 int EltNo = SV->getSplatIndex();
4531 int NumElems = SrcVT.getVectorNumElements();
4532 unsigned Size = SrcVT.getSizeInBits();
4534 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4535 "Unknown how to promote splat for type");
4537 // Extract the 128-bit part containing the splat element and update
4538 // the splat element index when it refers to the higher register.
4540 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4541 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4543 EltNo -= NumElems/2;
4546 // All i16 and i8 vector types can't be used directly by a generic shuffle
4547 // instruction because the target has no such instruction. Generate shuffles
4548 // which repeat i16 and i8 several times until they fit in i32, and then can
4549 // be manipulated by target suported shuffles.
4550 EVT EltVT = SrcVT.getVectorElementType();
4551 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4552 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4554 // Recreate the 256-bit vector and place the same 128-bit vector
4555 // into the low and high part. This is necessary because we want
4556 // to use VPERM* to shuffle the vectors
4558 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4559 DAG.getConstant(0, MVT::i32), DAG, dl);
4560 V1 = Insert128BitVector(InsV, V1,
4561 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4564 return getLegalSplat(DAG, V1, EltNo);
4567 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4568 /// vector of zero or undef vector. This produces a shuffle where the low
4569 /// element of V2 is swizzled into the zero/undef vector, landing at element
4570 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4571 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4572 bool isZero, bool HasXMMInt,
4573 SelectionDAG &DAG) {
4574 EVT VT = V2.getValueType();
4576 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4577 unsigned NumElems = VT.getVectorNumElements();
4578 SmallVector<int, 16> MaskVec;
4579 for (unsigned i = 0; i != NumElems; ++i)
4580 // If this is the insertion idx, put the low elt of V2 here.
4581 MaskVec.push_back(i == Idx ? NumElems : i);
4582 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4585 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4586 /// element of the result of the vector shuffle.
4587 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4590 return SDValue(); // Limit search depth.
4592 SDValue V = SDValue(N, 0);
4593 EVT VT = V.getValueType();
4594 unsigned Opcode = V.getOpcode();
4596 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4597 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4598 Index = SV->getMaskElt(Index);
4601 return DAG.getUNDEF(VT.getVectorElementType());
4603 int NumElems = VT.getVectorNumElements();
4604 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4605 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4608 // Recurse into target specific vector shuffles to find scalars.
4609 if (isTargetShuffle(Opcode)) {
4610 int NumElems = VT.getVectorNumElements();
4611 SmallVector<unsigned, 16> ShuffleMask;
4615 case X86ISD::SHUFPS:
4616 case X86ISD::SHUFPD:
4617 ImmN = N->getOperand(N->getNumOperands()-1);
4618 DecodeSHUFPSMask(NumElems,
4619 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4622 case X86ISD::PUNPCKH:
4623 DecodePUNPCKHMask(NumElems, ShuffleMask);
4625 case X86ISD::UNPCKHP:
4626 DecodeUNPCKHPMask(VT, ShuffleMask);
4628 case X86ISD::PUNPCKL:
4629 DecodePUNPCKLMask(VT, ShuffleMask);
4631 case X86ISD::UNPCKLP:
4632 DecodeUNPCKLPMask(VT, ShuffleMask);
4634 case X86ISD::MOVHLPS:
4635 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4637 case X86ISD::MOVLHPS:
4638 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4640 case X86ISD::PSHUFD:
4641 ImmN = N->getOperand(N->getNumOperands()-1);
4642 DecodePSHUFMask(NumElems,
4643 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4646 case X86ISD::PSHUFHW:
4647 ImmN = N->getOperand(N->getNumOperands()-1);
4648 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4651 case X86ISD::PSHUFLW:
4652 ImmN = N->getOperand(N->getNumOperands()-1);
4653 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4657 case X86ISD::MOVSD: {
4658 // The index 0 always comes from the first element of the second source,
4659 // this is why MOVSS and MOVSD are used in the first place. The other
4660 // elements come from the other positions of the first source vector.
4661 unsigned OpNum = (Index == 0) ? 1 : 0;
4662 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4665 case X86ISD::VPERMILPS:
4666 ImmN = N->getOperand(N->getNumOperands()-1);
4667 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4670 case X86ISD::VPERMILPSY:
4671 ImmN = N->getOperand(N->getNumOperands()-1);
4672 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4675 case X86ISD::VPERMILPD:
4676 ImmN = N->getOperand(N->getNumOperands()-1);
4677 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4680 case X86ISD::VPERMILPDY:
4681 ImmN = N->getOperand(N->getNumOperands()-1);
4682 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4685 case X86ISD::VPERM2F128:
4686 ImmN = N->getOperand(N->getNumOperands()-1);
4687 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4690 case X86ISD::MOVDDUP:
4691 case X86ISD::MOVLHPD:
4692 case X86ISD::MOVLPD:
4693 case X86ISD::MOVLPS:
4694 case X86ISD::MOVSHDUP:
4695 case X86ISD::MOVSLDUP:
4696 case X86ISD::PALIGN:
4697 return SDValue(); // Not yet implemented.
4699 assert(0 && "unknown target shuffle node");
4703 Index = ShuffleMask[Index];
4705 return DAG.getUNDEF(VT.getVectorElementType());
4707 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4708 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4712 // Actual nodes that may contain scalar elements
4713 if (Opcode == ISD::BITCAST) {
4714 V = V.getOperand(0);
4715 EVT SrcVT = V.getValueType();
4716 unsigned NumElems = VT.getVectorNumElements();
4718 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4722 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4723 return (Index == 0) ? V.getOperand(0)
4724 : DAG.getUNDEF(VT.getVectorElementType());
4726 if (V.getOpcode() == ISD::BUILD_VECTOR)
4727 return V.getOperand(Index);
4732 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4733 /// shuffle operation which come from a consecutively from a zero. The
4734 /// search can start in two different directions, from left or right.
4736 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4737 bool ZerosFromLeft, SelectionDAG &DAG) {
4740 while (i < NumElems) {
4741 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4742 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4743 if (!(Elt.getNode() &&
4744 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4752 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4753 /// MaskE correspond consecutively to elements from one of the vector operands,
4754 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4756 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4757 int OpIdx, int NumElems, unsigned &OpNum) {
4758 bool SeenV1 = false;
4759 bool SeenV2 = false;
4761 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4762 int Idx = SVOp->getMaskElt(i);
4763 // Ignore undef indicies
4772 // Only accept consecutive elements from the same vector
4773 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4777 OpNum = SeenV1 ? 0 : 1;
4781 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4782 /// logical left shift of a vector.
4783 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4784 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4785 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4786 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4787 false /* check zeros from right */, DAG);
4793 // Considering the elements in the mask that are not consecutive zeros,
4794 // check if they consecutively come from only one of the source vectors.
4796 // V1 = {X, A, B, C} 0
4798 // vector_shuffle V1, V2 <1, 2, 3, X>
4800 if (!isShuffleMaskConsecutive(SVOp,
4801 0, // Mask Start Index
4802 NumElems-NumZeros-1, // Mask End Index
4803 NumZeros, // Where to start looking in the src vector
4804 NumElems, // Number of elements in vector
4805 OpSrc)) // Which source operand ?
4810 ShVal = SVOp->getOperand(OpSrc);
4814 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4815 /// logical left shift of a vector.
4816 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4817 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4818 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4819 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4820 true /* check zeros from left */, DAG);
4826 // Considering the elements in the mask that are not consecutive zeros,
4827 // check if they consecutively come from only one of the source vectors.
4829 // 0 { A, B, X, X } = V2
4831 // vector_shuffle V1, V2 <X, X, 4, 5>
4833 if (!isShuffleMaskConsecutive(SVOp,
4834 NumZeros, // Mask Start Index
4835 NumElems-1, // Mask End Index
4836 0, // Where to start looking in the src vector
4837 NumElems, // Number of elements in vector
4838 OpSrc)) // Which source operand ?
4843 ShVal = SVOp->getOperand(OpSrc);
4847 /// isVectorShift - Returns true if the shuffle can be implemented as a
4848 /// logical left or right shift of a vector.
4849 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4850 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4851 // Although the logic below support any bitwidth size, there are no
4852 // shift instructions which handle more than 128-bit vectors.
4853 if (SVOp->getValueType(0).getSizeInBits() > 128)
4856 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4857 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4863 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4865 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4866 unsigned NumNonZero, unsigned NumZero,
4868 const TargetLowering &TLI) {
4872 DebugLoc dl = Op.getDebugLoc();
4875 for (unsigned i = 0; i < 16; ++i) {
4876 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4877 if (ThisIsNonZero && First) {
4879 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4881 V = DAG.getUNDEF(MVT::v8i16);
4886 SDValue ThisElt(0, 0), LastElt(0, 0);
4887 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4888 if (LastIsNonZero) {
4889 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4890 MVT::i16, Op.getOperand(i-1));
4892 if (ThisIsNonZero) {
4893 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4894 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4895 ThisElt, DAG.getConstant(8, MVT::i8));
4897 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4901 if (ThisElt.getNode())
4902 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4903 DAG.getIntPtrConstant(i/2));
4907 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4910 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4912 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4913 unsigned NumNonZero, unsigned NumZero,
4915 const TargetLowering &TLI) {
4919 DebugLoc dl = Op.getDebugLoc();
4922 for (unsigned i = 0; i < 8; ++i) {
4923 bool isNonZero = (NonZeros & (1 << i)) != 0;
4927 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4929 V = DAG.getUNDEF(MVT::v8i16);
4932 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4933 MVT::v8i16, V, Op.getOperand(i),
4934 DAG.getIntPtrConstant(i));
4941 /// getVShift - Return a vector logical shift node.
4943 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4944 unsigned NumBits, SelectionDAG &DAG,
4945 const TargetLowering &TLI, DebugLoc dl) {
4946 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4947 EVT ShVT = MVT::v2i64;
4948 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4949 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4950 return DAG.getNode(ISD::BITCAST, dl, VT,
4951 DAG.getNode(Opc, dl, ShVT, SrcOp,
4952 DAG.getConstant(NumBits,
4953 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4957 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4958 SelectionDAG &DAG) const {
4960 // Check if the scalar load can be widened into a vector load. And if
4961 // the address is "base + cst" see if the cst can be "absorbed" into
4962 // the shuffle mask.
4963 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4964 SDValue Ptr = LD->getBasePtr();
4965 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4967 EVT PVT = LD->getValueType(0);
4968 if (PVT != MVT::i32 && PVT != MVT::f32)
4973 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4974 FI = FINode->getIndex();
4976 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4977 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4978 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4979 Offset = Ptr.getConstantOperandVal(1);
4980 Ptr = Ptr.getOperand(0);
4985 // FIXME: 256-bit vector instructions don't require a strict alignment,
4986 // improve this code to support it better.
4987 unsigned RequiredAlign = VT.getSizeInBits()/8;
4988 SDValue Chain = LD->getChain();
4989 // Make sure the stack object alignment is at least 16 or 32.
4990 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4991 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4992 if (MFI->isFixedObjectIndex(FI)) {
4993 // Can't change the alignment. FIXME: It's possible to compute
4994 // the exact stack offset and reference FI + adjust offset instead.
4995 // If someone *really* cares about this. That's the way to implement it.
4998 MFI->setObjectAlignment(FI, RequiredAlign);
5002 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5003 // Ptr + (Offset & ~15).
5006 if ((Offset % RequiredAlign) & 3)
5008 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5010 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5011 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5013 int EltNo = (Offset - StartOffset) >> 2;
5014 int NumElems = VT.getVectorNumElements();
5016 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5017 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5018 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5019 LD->getPointerInfo().getWithOffset(StartOffset),
5020 false, false, false, 0);
5022 // Canonicalize it to a v4i32 or v8i32 shuffle.
5023 SmallVector<int, 8> Mask;
5024 for (int i = 0; i < NumElems; ++i)
5025 Mask.push_back(EltNo);
5027 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5028 return DAG.getNode(ISD::BITCAST, dl, NVT,
5029 DAG.getVectorShuffle(CanonVT, dl, V1,
5030 DAG.getUNDEF(CanonVT),&Mask[0]));
5036 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5037 /// vector of type 'VT', see if the elements can be replaced by a single large
5038 /// load which has the same value as a build_vector whose operands are 'elts'.
5040 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5042 /// FIXME: we'd also like to handle the case where the last elements are zero
5043 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5044 /// There's even a handy isZeroNode for that purpose.
5045 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5046 DebugLoc &DL, SelectionDAG &DAG) {
5047 EVT EltVT = VT.getVectorElementType();
5048 unsigned NumElems = Elts.size();
5050 LoadSDNode *LDBase = NULL;
5051 unsigned LastLoadedElt = -1U;
5053 // For each element in the initializer, see if we've found a load or an undef.
5054 // If we don't find an initial load element, or later load elements are
5055 // non-consecutive, bail out.
5056 for (unsigned i = 0; i < NumElems; ++i) {
5057 SDValue Elt = Elts[i];
5059 if (!Elt.getNode() ||
5060 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5063 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5065 LDBase = cast<LoadSDNode>(Elt.getNode());
5069 if (Elt.getOpcode() == ISD::UNDEF)
5072 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5073 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5078 // If we have found an entire vector of loads and undefs, then return a large
5079 // load of the entire vector width starting at the base pointer. If we found
5080 // consecutive loads for the low half, generate a vzext_load node.
5081 if (LastLoadedElt == NumElems - 1) {
5082 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5083 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5084 LDBase->getPointerInfo(),
5085 LDBase->isVolatile(), LDBase->isNonTemporal(),
5086 LDBase->isInvariant(), 0);
5087 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5088 LDBase->getPointerInfo(),
5089 LDBase->isVolatile(), LDBase->isNonTemporal(),
5090 LDBase->isInvariant(), LDBase->getAlignment());
5091 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5092 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5093 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5094 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5096 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5097 LDBase->getPointerInfo(),
5098 LDBase->getAlignment(),
5099 false/*isVolatile*/, true/*ReadMem*/,
5101 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5106 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5107 /// a vbroadcast node. We support two patterns:
5108 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5109 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5111 /// The scalar load node is returned when a pattern is found,
5112 /// or SDValue() otherwise.
5113 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5114 EVT VT = Op.getValueType();
5117 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5118 V = V.getOperand(0);
5120 //A suspected load to be broadcasted.
5123 switch (V.getOpcode()) {
5125 // Unknown pattern found.
5128 case ISD::BUILD_VECTOR: {
5129 // The BUILD_VECTOR node must be a splat.
5130 if (!isSplatVector(V.getNode()))
5133 Ld = V.getOperand(0);
5135 // The suspected load node has several users. Make sure that all
5136 // of its users are from the BUILD_VECTOR node.
5137 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5142 case ISD::VECTOR_SHUFFLE: {
5143 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5145 // Shuffles must have a splat mask where the first element is
5147 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5150 SDValue Sc = Op.getOperand(0);
5151 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5154 Ld = Sc.getOperand(0);
5156 // The scalar_to_vector node and the suspected
5157 // load node must have exactly one user.
5158 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5164 // The scalar source must be a normal load.
5165 if (!ISD::isNormalLoad(Ld.getNode()))
5168 bool Is256 = VT.getSizeInBits() == 256;
5169 bool Is128 = VT.getSizeInBits() == 128;
5170 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5173 // VBroadcast to YMM
5174 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5175 ScalarSize == 32 || ScalarSize == 64 ))
5178 // VBroadcast to XMM
5179 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5180 ScalarSize == 16 || ScalarSize == 64 ))
5184 // VBroadcast to YMM
5185 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5188 // VBroadcast to XMM
5189 if (Is128 && (ScalarSize == 32))
5193 // Unsupported broadcast.
5198 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5199 DebugLoc dl = Op.getDebugLoc();
5201 EVT VT = Op.getValueType();
5202 EVT ExtVT = VT.getVectorElementType();
5203 unsigned NumElems = Op.getNumOperands();
5205 // Vectors containing all zeros can be matched by pxor and xorps later
5206 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5207 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5208 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5209 if (Op.getValueType() == MVT::v4i32 ||
5210 Op.getValueType() == MVT::v8i32)
5213 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5216 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5217 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5218 // vpcmpeqd on 256-bit vectors.
5219 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5220 if (Op.getValueType() == MVT::v4i32 ||
5221 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5224 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5227 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5228 if (Subtarget->hasAVX() && LD.getNode())
5229 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5231 unsigned EVTBits = ExtVT.getSizeInBits();
5233 unsigned NumZero = 0;
5234 unsigned NumNonZero = 0;
5235 unsigned NonZeros = 0;
5236 bool IsAllConstants = true;
5237 SmallSet<SDValue, 8> Values;
5238 for (unsigned i = 0; i < NumElems; ++i) {
5239 SDValue Elt = Op.getOperand(i);
5240 if (Elt.getOpcode() == ISD::UNDEF)
5243 if (Elt.getOpcode() != ISD::Constant &&
5244 Elt.getOpcode() != ISD::ConstantFP)
5245 IsAllConstants = false;
5246 if (X86::isZeroNode(Elt))
5249 NonZeros |= (1 << i);
5254 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5255 if (NumNonZero == 0)
5256 return DAG.getUNDEF(VT);
5258 // Special case for single non-zero, non-undef, element.
5259 if (NumNonZero == 1) {
5260 unsigned Idx = CountTrailingZeros_32(NonZeros);
5261 SDValue Item = Op.getOperand(Idx);
5263 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5264 // the value are obviously zero, truncate the value to i32 and do the
5265 // insertion that way. Only do this if the value is non-constant or if the
5266 // value is a constant being inserted into element 0. It is cheaper to do
5267 // a constant pool load than it is to do a movd + shuffle.
5268 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5269 (!IsAllConstants || Idx == 0)) {
5270 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5272 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5273 EVT VecVT = MVT::v4i32;
5274 unsigned VecElts = 4;
5276 // Truncate the value (which may itself be a constant) to i32, and
5277 // convert it to a vector with movd (S2V+shuffle to zero extend).
5278 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5280 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5281 Subtarget->hasXMMInt(), DAG);
5283 // Now we have our 32-bit value zero extended in the low element of
5284 // a vector. If Idx != 0, swizzle it into place.
5286 SmallVector<int, 4> Mask;
5287 Mask.push_back(Idx);
5288 for (unsigned i = 1; i != VecElts; ++i)
5290 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5291 DAG.getUNDEF(Item.getValueType()),
5294 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5298 // If we have a constant or non-constant insertion into the low element of
5299 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5300 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5301 // depending on what the source datatype is.
5304 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5305 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5306 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5307 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5308 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5309 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5311 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5312 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5313 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5314 EVT MiddleVT = MVT::v4i32;
5315 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5316 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5317 Subtarget->hasXMMInt(), DAG);
5318 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5322 // Is it a vector logical left shift?
5323 if (NumElems == 2 && Idx == 1 &&
5324 X86::isZeroNode(Op.getOperand(0)) &&
5325 !X86::isZeroNode(Op.getOperand(1))) {
5326 unsigned NumBits = VT.getSizeInBits();
5327 return getVShift(true, VT,
5328 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5329 VT, Op.getOperand(1)),
5330 NumBits/2, DAG, *this, dl);
5333 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5336 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5337 // is a non-constant being inserted into an element other than the low one,
5338 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5339 // movd/movss) to move this into the low element, then shuffle it into
5341 if (EVTBits == 32) {
5342 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5344 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5345 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5346 Subtarget->hasXMMInt(), DAG);
5347 SmallVector<int, 8> MaskVec;
5348 for (unsigned i = 0; i < NumElems; i++)
5349 MaskVec.push_back(i == Idx ? 0 : 1);
5350 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5354 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5355 if (Values.size() == 1) {
5356 if (EVTBits == 32) {
5357 // Instead of a shuffle like this:
5358 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5359 // Check if it's possible to issue this instead.
5360 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5361 unsigned Idx = CountTrailingZeros_32(NonZeros);
5362 SDValue Item = Op.getOperand(Idx);
5363 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5364 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5369 // A vector full of immediates; various special cases are already
5370 // handled, so this is best done with a single constant-pool load.
5374 // For AVX-length vectors, build the individual 128-bit pieces and use
5375 // shuffles to put them in place.
5376 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5377 SmallVector<SDValue, 32> V;
5378 for (unsigned i = 0; i < NumElems; ++i)
5379 V.push_back(Op.getOperand(i));
5381 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5383 // Build both the lower and upper subvector.
5384 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5385 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5388 // Recreate the wider vector with the lower and upper part.
5389 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5390 DAG.getConstant(0, MVT::i32), DAG, dl);
5391 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5395 // Let legalizer expand 2-wide build_vectors.
5396 if (EVTBits == 64) {
5397 if (NumNonZero == 1) {
5398 // One half is zero or undef.
5399 unsigned Idx = CountTrailingZeros_32(NonZeros);
5400 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5401 Op.getOperand(Idx));
5402 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5403 Subtarget->hasXMMInt(), DAG);
5408 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5409 if (EVTBits == 8 && NumElems == 16) {
5410 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5412 if (V.getNode()) return V;
5415 if (EVTBits == 16 && NumElems == 8) {
5416 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5418 if (V.getNode()) return V;
5421 // If element VT is == 32 bits, turn it into a number of shuffles.
5422 SmallVector<SDValue, 8> V;
5424 if (NumElems == 4 && NumZero > 0) {
5425 for (unsigned i = 0; i < 4; ++i) {
5426 bool isZero = !(NonZeros & (1 << i));
5428 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5430 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5433 for (unsigned i = 0; i < 2; ++i) {
5434 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5437 V[i] = V[i*2]; // Must be a zero vector.
5440 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5443 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5446 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5451 SmallVector<int, 8> MaskVec;
5452 bool Reverse = (NonZeros & 0x3) == 2;
5453 for (unsigned i = 0; i < 2; ++i)
5454 MaskVec.push_back(Reverse ? 1-i : i);
5455 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5456 for (unsigned i = 0; i < 2; ++i)
5457 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5458 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5461 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5462 // Check for a build vector of consecutive loads.
5463 for (unsigned i = 0; i < NumElems; ++i)
5464 V[i] = Op.getOperand(i);
5466 // Check for elements which are consecutive loads.
5467 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5471 // For SSE 4.1, use insertps to put the high elements into the low element.
5472 if (getSubtarget()->hasSSE41orAVX()) {
5474 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5475 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5477 Result = DAG.getUNDEF(VT);
5479 for (unsigned i = 1; i < NumElems; ++i) {
5480 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5481 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5482 Op.getOperand(i), DAG.getIntPtrConstant(i));
5487 // Otherwise, expand into a number of unpckl*, start by extending each of
5488 // our (non-undef) elements to the full vector width with the element in the
5489 // bottom slot of the vector (which generates no code for SSE).
5490 for (unsigned i = 0; i < NumElems; ++i) {
5491 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5492 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5494 V[i] = DAG.getUNDEF(VT);
5497 // Next, we iteratively mix elements, e.g. for v4f32:
5498 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5499 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5500 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5501 unsigned EltStride = NumElems >> 1;
5502 while (EltStride != 0) {
5503 for (unsigned i = 0; i < EltStride; ++i) {
5504 // If V[i+EltStride] is undef and this is the first round of mixing,
5505 // then it is safe to just drop this shuffle: V[i] is already in the
5506 // right place, the one element (since it's the first round) being
5507 // inserted as undef can be dropped. This isn't safe for successive
5508 // rounds because they will permute elements within both vectors.
5509 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5510 EltStride == NumElems/2)
5513 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5522 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5523 // them in a MMX register. This is better than doing a stack convert.
5524 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5525 DebugLoc dl = Op.getDebugLoc();
5526 EVT ResVT = Op.getValueType();
5528 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5529 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5531 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5532 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5533 InVec = Op.getOperand(1);
5534 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5535 unsigned NumElts = ResVT.getVectorNumElements();
5536 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5537 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5538 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5540 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5541 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5542 Mask[0] = 0; Mask[1] = 2;
5543 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5545 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5548 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5549 // to create 256-bit vectors from two other 128-bit ones.
5550 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5551 DebugLoc dl = Op.getDebugLoc();
5552 EVT ResVT = Op.getValueType();
5554 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5556 SDValue V1 = Op.getOperand(0);
5557 SDValue V2 = Op.getOperand(1);
5558 unsigned NumElems = ResVT.getVectorNumElements();
5560 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5561 DAG.getConstant(0, MVT::i32), DAG, dl);
5562 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5567 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5568 EVT ResVT = Op.getValueType();
5570 assert(Op.getNumOperands() == 2);
5571 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5572 "Unsupported CONCAT_VECTORS for value type");
5574 // We support concatenate two MMX registers and place them in a MMX register.
5575 // This is better than doing a stack convert.
5576 if (ResVT.is128BitVector())
5577 return LowerMMXCONCAT_VECTORS(Op, DAG);
5579 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5580 // from two other 128-bit ones.
5581 return LowerAVXCONCAT_VECTORS(Op, DAG);
5584 // v8i16 shuffles - Prefer shuffles in the following order:
5585 // 1. [all] pshuflw, pshufhw, optional move
5586 // 2. [ssse3] 1 x pshufb
5587 // 3. [ssse3] 2 x pshufb + 1 x por
5588 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5590 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5591 SelectionDAG &DAG) const {
5592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5593 SDValue V1 = SVOp->getOperand(0);
5594 SDValue V2 = SVOp->getOperand(1);
5595 DebugLoc dl = SVOp->getDebugLoc();
5596 SmallVector<int, 8> MaskVals;
5598 // Determine if more than 1 of the words in each of the low and high quadwords
5599 // of the result come from the same quadword of one of the two inputs. Undef
5600 // mask values count as coming from any quadword, for better codegen.
5601 unsigned LoQuad[] = { 0, 0, 0, 0 };
5602 unsigned HiQuad[] = { 0, 0, 0, 0 };
5603 BitVector InputQuads(4);
5604 for (unsigned i = 0; i < 8; ++i) {
5605 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5606 int EltIdx = SVOp->getMaskElt(i);
5607 MaskVals.push_back(EltIdx);
5616 InputQuads.set(EltIdx / 4);
5619 int BestLoQuad = -1;
5620 unsigned MaxQuad = 1;
5621 for (unsigned i = 0; i < 4; ++i) {
5622 if (LoQuad[i] > MaxQuad) {
5624 MaxQuad = LoQuad[i];
5628 int BestHiQuad = -1;
5630 for (unsigned i = 0; i < 4; ++i) {
5631 if (HiQuad[i] > MaxQuad) {
5633 MaxQuad = HiQuad[i];
5637 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5638 // of the two input vectors, shuffle them into one input vector so only a
5639 // single pshufb instruction is necessary. If There are more than 2 input
5640 // quads, disable the next transformation since it does not help SSSE3.
5641 bool V1Used = InputQuads[0] || InputQuads[1];
5642 bool V2Used = InputQuads[2] || InputQuads[3];
5643 if (Subtarget->hasSSSE3orAVX()) {
5644 if (InputQuads.count() == 2 && V1Used && V2Used) {
5645 BestLoQuad = InputQuads.find_first();
5646 BestHiQuad = InputQuads.find_next(BestLoQuad);
5648 if (InputQuads.count() > 2) {
5654 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5655 // the shuffle mask. If a quad is scored as -1, that means that it contains
5656 // words from all 4 input quadwords.
5658 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5659 SmallVector<int, 8> MaskV;
5660 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5661 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5662 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5663 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5664 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5665 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5667 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5668 // source words for the shuffle, to aid later transformations.
5669 bool AllWordsInNewV = true;
5670 bool InOrder[2] = { true, true };
5671 for (unsigned i = 0; i != 8; ++i) {
5672 int idx = MaskVals[i];
5674 InOrder[i/4] = false;
5675 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5677 AllWordsInNewV = false;
5681 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5682 if (AllWordsInNewV) {
5683 for (int i = 0; i != 8; ++i) {
5684 int idx = MaskVals[i];
5687 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5688 if ((idx != i) && idx < 4)
5690 if ((idx != i) && idx > 3)
5699 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5700 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5701 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5702 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5703 unsigned TargetMask = 0;
5704 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5705 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5706 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5707 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5708 V1 = NewV.getOperand(0);
5709 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5713 // If we have SSSE3, and all words of the result are from 1 input vector,
5714 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5715 // is present, fall back to case 4.
5716 if (Subtarget->hasSSSE3orAVX()) {
5717 SmallVector<SDValue,16> pshufbMask;
5719 // If we have elements from both input vectors, set the high bit of the
5720 // shuffle mask element to zero out elements that come from V2 in the V1
5721 // mask, and elements that come from V1 in the V2 mask, so that the two
5722 // results can be OR'd together.
5723 bool TwoInputs = V1Used && V2Used;
5724 for (unsigned i = 0; i != 8; ++i) {
5725 int EltIdx = MaskVals[i] * 2;
5726 if (TwoInputs && (EltIdx >= 16)) {
5727 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5728 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5731 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5732 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5734 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5735 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5736 DAG.getNode(ISD::BUILD_VECTOR, dl,
5737 MVT::v16i8, &pshufbMask[0], 16));
5739 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5741 // Calculate the shuffle mask for the second input, shuffle it, and
5742 // OR it with the first shuffled input.
5744 for (unsigned i = 0; i != 8; ++i) {
5745 int EltIdx = MaskVals[i] * 2;
5747 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5748 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5751 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5752 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5754 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5755 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5756 DAG.getNode(ISD::BUILD_VECTOR, dl,
5757 MVT::v16i8, &pshufbMask[0], 16));
5758 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5759 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5762 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5763 // and update MaskVals with new element order.
5764 BitVector InOrder(8);
5765 if (BestLoQuad >= 0) {
5766 SmallVector<int, 8> MaskV;
5767 for (int i = 0; i != 4; ++i) {
5768 int idx = MaskVals[i];
5770 MaskV.push_back(-1);
5772 } else if ((idx / 4) == BestLoQuad) {
5773 MaskV.push_back(idx & 3);
5776 MaskV.push_back(-1);
5779 for (unsigned i = 4; i != 8; ++i)
5781 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5784 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5785 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5787 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5791 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5792 // and update MaskVals with the new element order.
5793 if (BestHiQuad >= 0) {
5794 SmallVector<int, 8> MaskV;
5795 for (unsigned i = 0; i != 4; ++i)
5797 for (unsigned i = 4; i != 8; ++i) {
5798 int idx = MaskVals[i];
5800 MaskV.push_back(-1);
5802 } else if ((idx / 4) == BestHiQuad) {
5803 MaskV.push_back((idx & 3) + 4);
5806 MaskV.push_back(-1);
5809 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5812 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5813 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5815 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5819 // In case BestHi & BestLo were both -1, which means each quadword has a word
5820 // from each of the four input quadwords, calculate the InOrder bitvector now
5821 // before falling through to the insert/extract cleanup.
5822 if (BestLoQuad == -1 && BestHiQuad == -1) {
5824 for (int i = 0; i != 8; ++i)
5825 if (MaskVals[i] < 0 || MaskVals[i] == i)
5829 // The other elements are put in the right place using pextrw and pinsrw.
5830 for (unsigned i = 0; i != 8; ++i) {
5833 int EltIdx = MaskVals[i];
5836 SDValue ExtOp = (EltIdx < 8)
5837 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5838 DAG.getIntPtrConstant(EltIdx))
5839 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5840 DAG.getIntPtrConstant(EltIdx - 8));
5841 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5842 DAG.getIntPtrConstant(i));
5847 // v16i8 shuffles - Prefer shuffles in the following order:
5848 // 1. [ssse3] 1 x pshufb
5849 // 2. [ssse3] 2 x pshufb + 1 x por
5850 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5852 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5854 const X86TargetLowering &TLI) {
5855 SDValue V1 = SVOp->getOperand(0);
5856 SDValue V2 = SVOp->getOperand(1);
5857 DebugLoc dl = SVOp->getDebugLoc();
5858 SmallVector<int, 16> MaskVals;
5859 SVOp->getMask(MaskVals);
5861 // If we have SSSE3, case 1 is generated when all result bytes come from
5862 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5863 // present, fall back to case 3.
5864 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5867 for (unsigned i = 0; i < 16; ++i) {
5868 int EltIdx = MaskVals[i];
5877 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5878 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5879 SmallVector<SDValue,16> pshufbMask;
5881 // If all result elements are from one input vector, then only translate
5882 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5884 // Otherwise, we have elements from both input vectors, and must zero out
5885 // elements that come from V2 in the first mask, and V1 in the second mask
5886 // so that we can OR them together.
5887 bool TwoInputs = !(V1Only || V2Only);
5888 for (unsigned i = 0; i != 16; ++i) {
5889 int EltIdx = MaskVals[i];
5890 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5891 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5894 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5896 // If all the elements are from V2, assign it to V1 and return after
5897 // building the first pshufb.
5900 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5901 DAG.getNode(ISD::BUILD_VECTOR, dl,
5902 MVT::v16i8, &pshufbMask[0], 16));
5906 // Calculate the shuffle mask for the second input, shuffle it, and
5907 // OR it with the first shuffled input.
5909 for (unsigned i = 0; i != 16; ++i) {
5910 int EltIdx = MaskVals[i];
5912 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5915 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5917 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5918 DAG.getNode(ISD::BUILD_VECTOR, dl,
5919 MVT::v16i8, &pshufbMask[0], 16));
5920 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5923 // No SSSE3 - Calculate in place words and then fix all out of place words
5924 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5925 // the 16 different words that comprise the two doublequadword input vectors.
5926 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5927 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5928 SDValue NewV = V2Only ? V2 : V1;
5929 for (int i = 0; i != 8; ++i) {
5930 int Elt0 = MaskVals[i*2];
5931 int Elt1 = MaskVals[i*2+1];
5933 // This word of the result is all undef, skip it.
5934 if (Elt0 < 0 && Elt1 < 0)
5937 // This word of the result is already in the correct place, skip it.
5938 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5940 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5943 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5944 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5947 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5948 // using a single extract together, load it and store it.
5949 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5950 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5951 DAG.getIntPtrConstant(Elt1 / 2));
5952 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5953 DAG.getIntPtrConstant(i));
5957 // If Elt1 is defined, extract it from the appropriate source. If the
5958 // source byte is not also odd, shift the extracted word left 8 bits
5959 // otherwise clear the bottom 8 bits if we need to do an or.
5961 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5962 DAG.getIntPtrConstant(Elt1 / 2));
5963 if ((Elt1 & 1) == 0)
5964 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5966 TLI.getShiftAmountTy(InsElt.getValueType())));
5968 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5969 DAG.getConstant(0xFF00, MVT::i16));
5971 // If Elt0 is defined, extract it from the appropriate source. If the
5972 // source byte is not also even, shift the extracted word right 8 bits. If
5973 // Elt1 was also defined, OR the extracted values together before
5974 // inserting them in the result.
5976 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5977 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5978 if ((Elt0 & 1) != 0)
5979 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5981 TLI.getShiftAmountTy(InsElt0.getValueType())));
5983 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5984 DAG.getConstant(0x00FF, MVT::i16));
5985 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5988 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5989 DAG.getIntPtrConstant(i));
5991 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5994 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5995 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5996 /// done when every pair / quad of shuffle mask elements point to elements in
5997 /// the right sequence. e.g.
5998 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6000 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6001 SelectionDAG &DAG, DebugLoc dl) {
6002 EVT VT = SVOp->getValueType(0);
6003 SDValue V1 = SVOp->getOperand(0);
6004 SDValue V2 = SVOp->getOperand(1);
6005 unsigned NumElems = VT.getVectorNumElements();
6006 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6008 switch (VT.getSimpleVT().SimpleTy) {
6009 default: assert(false && "Unexpected!");
6010 case MVT::v4f32: NewVT = MVT::v2f64; break;
6011 case MVT::v4i32: NewVT = MVT::v2i64; break;
6012 case MVT::v8i16: NewVT = MVT::v4i32; break;
6013 case MVT::v16i8: NewVT = MVT::v4i32; break;
6016 int Scale = NumElems / NewWidth;
6017 SmallVector<int, 8> MaskVec;
6018 for (unsigned i = 0; i < NumElems; i += Scale) {
6020 for (int j = 0; j < Scale; ++j) {
6021 int EltIdx = SVOp->getMaskElt(i+j);
6025 StartIdx = EltIdx - (EltIdx % Scale);
6026 if (EltIdx != StartIdx + j)
6030 MaskVec.push_back(-1);
6032 MaskVec.push_back(StartIdx / Scale);
6035 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6036 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6037 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6040 /// getVZextMovL - Return a zero-extending vector move low node.
6042 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6043 SDValue SrcOp, SelectionDAG &DAG,
6044 const X86Subtarget *Subtarget, DebugLoc dl) {
6045 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6046 LoadSDNode *LD = NULL;
6047 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6048 LD = dyn_cast<LoadSDNode>(SrcOp);
6050 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6052 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6053 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6054 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6055 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6056 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6058 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6059 return DAG.getNode(ISD::BITCAST, dl, VT,
6060 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6061 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6069 return DAG.getNode(ISD::BITCAST, dl, VT,
6070 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6071 DAG.getNode(ISD::BITCAST, dl,
6075 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6076 /// shuffle node referes to only one lane in the sources.
6077 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6078 EVT VT = SVOp->getValueType(0);
6079 int NumElems = VT.getVectorNumElements();
6080 int HalfSize = NumElems/2;
6081 SmallVector<int, 16> M;
6083 bool MatchA = false, MatchB = false;
6085 for (int l = 0; l < NumElems*2; l += HalfSize) {
6086 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6092 for (int l = 0; l < NumElems*2; l += HalfSize) {
6093 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6099 return MatchA && MatchB;
6102 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6103 /// which could not be matched by any known target speficic shuffle
6105 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6106 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6107 // If each half of a vector shuffle node referes to only one lane in the
6108 // source vectors, extract each used 128-bit lane and shuffle them using
6109 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6110 // the work to the legalizer.
6111 DebugLoc dl = SVOp->getDebugLoc();
6112 EVT VT = SVOp->getValueType(0);
6113 int NumElems = VT.getVectorNumElements();
6114 int HalfSize = NumElems/2;
6116 // Extract the reference for each half
6117 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6118 int FstVecOpNum = 0, SndVecOpNum = 0;
6119 for (int i = 0; i < HalfSize; ++i) {
6120 int Elt = SVOp->getMaskElt(i);
6121 if (SVOp->getMaskElt(i) < 0)
6123 FstVecOpNum = Elt/NumElems;
6124 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6127 for (int i = HalfSize; i < NumElems; ++i) {
6128 int Elt = SVOp->getMaskElt(i);
6129 if (SVOp->getMaskElt(i) < 0)
6131 SndVecOpNum = Elt/NumElems;
6132 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6136 // Extract the subvectors
6137 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6138 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6139 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6140 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6142 // Generate 128-bit shuffles
6143 SmallVector<int, 16> MaskV1, MaskV2;
6144 for (int i = 0; i < HalfSize; ++i) {
6145 int Elt = SVOp->getMaskElt(i);
6146 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6148 for (int i = HalfSize; i < NumElems; ++i) {
6149 int Elt = SVOp->getMaskElt(i);
6150 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6153 EVT NVT = V1.getValueType();
6154 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6155 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6157 // Concatenate the result back
6158 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6159 DAG.getConstant(0, MVT::i32), DAG, dl);
6160 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6167 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6168 /// 4 elements, and match them with several different shuffle types.
6170 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6171 SDValue V1 = SVOp->getOperand(0);
6172 SDValue V2 = SVOp->getOperand(1);
6173 DebugLoc dl = SVOp->getDebugLoc();
6174 EVT VT = SVOp->getValueType(0);
6176 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6178 SmallVector<std::pair<int, int>, 8> Locs;
6180 SmallVector<int, 8> Mask1(4U, -1);
6181 SmallVector<int, 8> PermMask;
6182 SVOp->getMask(PermMask);
6186 for (unsigned i = 0; i != 4; ++i) {
6187 int Idx = PermMask[i];
6189 Locs[i] = std::make_pair(-1, -1);
6191 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6193 Locs[i] = std::make_pair(0, NumLo);
6197 Locs[i] = std::make_pair(1, NumHi);
6199 Mask1[2+NumHi] = Idx;
6205 if (NumLo <= 2 && NumHi <= 2) {
6206 // If no more than two elements come from either vector. This can be
6207 // implemented with two shuffles. First shuffle gather the elements.
6208 // The second shuffle, which takes the first shuffle as both of its
6209 // vector operands, put the elements into the right order.
6210 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6212 SmallVector<int, 8> Mask2(4U, -1);
6214 for (unsigned i = 0; i != 4; ++i) {
6215 if (Locs[i].first == -1)
6218 unsigned Idx = (i < 2) ? 0 : 4;
6219 Idx += Locs[i].first * 2 + Locs[i].second;
6224 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6225 } else if (NumLo == 3 || NumHi == 3) {
6226 // Otherwise, we must have three elements from one vector, call it X, and
6227 // one element from the other, call it Y. First, use a shufps to build an
6228 // intermediate vector with the one element from Y and the element from X
6229 // that will be in the same half in the final destination (the indexes don't
6230 // matter). Then, use a shufps to build the final vector, taking the half
6231 // containing the element from Y from the intermediate, and the other half
6234 // Normalize it so the 3 elements come from V1.
6235 CommuteVectorShuffleMask(PermMask, VT);
6239 // Find the element from V2.
6241 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6242 int Val = PermMask[HiIndex];
6249 Mask1[0] = PermMask[HiIndex];
6251 Mask1[2] = PermMask[HiIndex^1];
6253 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6256 Mask1[0] = PermMask[0];
6257 Mask1[1] = PermMask[1];
6258 Mask1[2] = HiIndex & 1 ? 6 : 4;
6259 Mask1[3] = HiIndex & 1 ? 4 : 6;
6260 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6262 Mask1[0] = HiIndex & 1 ? 2 : 0;
6263 Mask1[1] = HiIndex & 1 ? 0 : 2;
6264 Mask1[2] = PermMask[2];
6265 Mask1[3] = PermMask[3];
6270 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6274 // Break it into (shuffle shuffle_hi, shuffle_lo).
6277 SmallVector<int,8> LoMask(4U, -1);
6278 SmallVector<int,8> HiMask(4U, -1);
6280 SmallVector<int,8> *MaskPtr = &LoMask;
6281 unsigned MaskIdx = 0;
6284 for (unsigned i = 0; i != 4; ++i) {
6291 int Idx = PermMask[i];
6293 Locs[i] = std::make_pair(-1, -1);
6294 } else if (Idx < 4) {
6295 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6296 (*MaskPtr)[LoIdx] = Idx;
6299 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6300 (*MaskPtr)[HiIdx] = Idx;
6305 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6306 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6307 SmallVector<int, 8> MaskOps;
6308 for (unsigned i = 0; i != 4; ++i) {
6309 if (Locs[i].first == -1) {
6310 MaskOps.push_back(-1);
6312 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6313 MaskOps.push_back(Idx);
6316 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6319 static bool MayFoldVectorLoad(SDValue V) {
6320 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6321 V = V.getOperand(0);
6322 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6323 V = V.getOperand(0);
6324 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6325 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6326 // BUILD_VECTOR (load), undef
6327 V = V.getOperand(0);
6333 // FIXME: the version above should always be used. Since there's
6334 // a bug where several vector shuffles can't be folded because the
6335 // DAG is not updated during lowering and a node claims to have two
6336 // uses while it only has one, use this version, and let isel match
6337 // another instruction if the load really happens to have more than
6338 // one use. Remove this version after this bug get fixed.
6339 // rdar://8434668, PR8156
6340 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6341 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6342 V = V.getOperand(0);
6343 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6344 V = V.getOperand(0);
6345 if (ISD::isNormalLoad(V.getNode()))
6350 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6351 /// a vector extract, and if both can be later optimized into a single load.
6352 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6353 /// here because otherwise a target specific shuffle node is going to be
6354 /// emitted for this shuffle, and the optimization not done.
6355 /// FIXME: This is probably not the best approach, but fix the problem
6356 /// until the right path is decided.
6358 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6359 const TargetLowering &TLI) {
6360 EVT VT = V.getValueType();
6361 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6363 // Be sure that the vector shuffle is present in a pattern like this:
6364 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6368 SDNode *N = *V.getNode()->use_begin();
6369 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6372 SDValue EltNo = N->getOperand(1);
6373 if (!isa<ConstantSDNode>(EltNo))
6376 // If the bit convert changed the number of elements, it is unsafe
6377 // to examine the mask.
6378 bool HasShuffleIntoBitcast = false;
6379 if (V.getOpcode() == ISD::BITCAST) {
6380 EVT SrcVT = V.getOperand(0).getValueType();
6381 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6383 V = V.getOperand(0);
6384 HasShuffleIntoBitcast = true;
6387 // Select the input vector, guarding against out of range extract vector.
6388 unsigned NumElems = VT.getVectorNumElements();
6389 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6390 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6391 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6393 // Skip one more bit_convert if necessary
6394 if (V.getOpcode() == ISD::BITCAST)
6395 V = V.getOperand(0);
6397 if (ISD::isNormalLoad(V.getNode())) {
6398 // Is the original load suitable?
6399 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6401 // FIXME: avoid the multi-use bug that is preventing lots of
6402 // of foldings to be detected, this is still wrong of course, but
6403 // give the temporary desired behavior, and if it happens that
6404 // the load has real more uses, during isel it will not fold, and
6405 // will generate poor code.
6406 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6409 if (!HasShuffleIntoBitcast)
6412 // If there's a bitcast before the shuffle, check if the load type and
6413 // alignment is valid.
6414 unsigned Align = LN0->getAlignment();
6416 TLI.getTargetData()->getABITypeAlignment(
6417 VT.getTypeForEVT(*DAG.getContext()));
6419 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6427 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6428 EVT VT = Op.getValueType();
6430 // Canonizalize to v2f64.
6431 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6432 return DAG.getNode(ISD::BITCAST, dl, VT,
6433 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6438 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6440 SDValue V1 = Op.getOperand(0);
6441 SDValue V2 = Op.getOperand(1);
6442 EVT VT = Op.getValueType();
6444 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6446 if (HasXMMInt && VT == MVT::v2f64)
6447 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6449 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6450 return DAG.getNode(ISD::BITCAST, dl, VT,
6451 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6452 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6453 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6457 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6458 SDValue V1 = Op.getOperand(0);
6459 SDValue V2 = Op.getOperand(1);
6460 EVT VT = Op.getValueType();
6462 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6463 "unsupported shuffle type");
6465 if (V2.getOpcode() == ISD::UNDEF)
6469 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6472 static inline unsigned getSHUFPOpcode(EVT VT) {
6473 switch(VT.getSimpleVT().SimpleTy) {
6474 case MVT::v8i32: // Use fp unit for int unpack.
6476 case MVT::v4i32: // Use fp unit for int unpack.
6477 case MVT::v4f32: return X86ISD::SHUFPS;
6478 case MVT::v4i64: // Use fp unit for int unpack.
6480 case MVT::v2i64: // Use fp unit for int unpack.
6481 case MVT::v2f64: return X86ISD::SHUFPD;
6483 llvm_unreachable("Unknown type for shufp*");
6489 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6490 SDValue V1 = Op.getOperand(0);
6491 SDValue V2 = Op.getOperand(1);
6492 EVT VT = Op.getValueType();
6493 unsigned NumElems = VT.getVectorNumElements();
6495 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6496 // operand of these instructions is only memory, so check if there's a
6497 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6499 bool CanFoldLoad = false;
6501 // Trivial case, when V2 comes from a load.
6502 if (MayFoldVectorLoad(V2))
6505 // When V1 is a load, it can be folded later into a store in isel, example:
6506 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6508 // (MOVLPSmr addr:$src1, VR128:$src2)
6509 // So, recognize this potential and also use MOVLPS or MOVLPD
6510 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6513 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6515 if (HasXMMInt && NumElems == 2)
6516 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6519 // If we don't care about the second element, procede to use movss.
6520 if (SVOp->getMaskElt(1) != -1)
6521 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6524 // movl and movlp will both match v2i64, but v2i64 is never matched by
6525 // movl earlier because we make it strict to avoid messing with the movlp load
6526 // folding logic (see the code above getMOVLP call). Match it here then,
6527 // this is horrible, but will stay like this until we move all shuffle
6528 // matching to x86 specific nodes. Note that for the 1st condition all
6529 // types are matched with movsd.
6531 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6532 // as to remove this logic from here, as much as possible
6533 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6534 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6535 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6538 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6540 // Invert the operand order and use SHUFPS to match it.
6541 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6542 X86::getShuffleSHUFImmediate(SVOp), DAG);
6545 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6546 switch(VT.getSimpleVT().SimpleTy) {
6552 case MVT::v2i64: return X86ISD::PUNPCKL;
6555 if (HasAVX2) return X86ISD::PUNPCKL;
6556 // else use fp unit for int unpack.
6560 case MVT::v2f64: return X86ISD::UNPCKLP;
6562 llvm_unreachable("Unknown type for unpckl");
6567 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6568 switch(VT.getSimpleVT().SimpleTy) {
6574 case MVT::v2i64: return X86ISD::PUNPCKH;
6577 if (HasAVX2) return X86ISD::PUNPCKH;
6578 // else use fp unit for int unpack.
6582 case MVT::v2f64: return X86ISD::UNPCKHP;
6584 llvm_unreachable("Unknown type for unpckh");
6589 static inline unsigned getVPERMILOpcode(EVT VT) {
6590 switch(VT.getSimpleVT().SimpleTy) {
6592 case MVT::v4f32: return X86ISD::VPERMILPS;
6594 case MVT::v2f64: return X86ISD::VPERMILPD;
6596 case MVT::v8f32: return X86ISD::VPERMILPSY;
6598 case MVT::v4f64: return X86ISD::VPERMILPDY;
6600 llvm_unreachable("Unknown type for vpermil");
6606 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6607 const TargetLowering &TLI,
6608 const X86Subtarget *Subtarget) {
6609 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6610 EVT VT = Op.getValueType();
6611 DebugLoc dl = Op.getDebugLoc();
6612 SDValue V1 = Op.getOperand(0);
6613 SDValue V2 = Op.getOperand(1);
6615 if (isZeroShuffle(SVOp))
6616 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6618 // Handle splat operations
6619 if (SVOp->isSplat()) {
6620 unsigned NumElem = VT.getVectorNumElements();
6621 int Size = VT.getSizeInBits();
6622 // Special case, this is the only place now where it's allowed to return
6623 // a vector_shuffle operation without using a target specific node, because
6624 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6625 // this be moved to DAGCombine instead?
6626 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6629 // Use vbroadcast whenever the splat comes from a foldable load
6630 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6631 if (Subtarget->hasAVX() && LD.getNode())
6632 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6634 // Handle splats by matching through known shuffle masks
6635 if ((Size == 128 && NumElem <= 4) ||
6636 (Size == 256 && NumElem < 8))
6639 // All remaning splats are promoted to target supported vector shuffles.
6640 return PromoteSplat(SVOp, DAG);
6643 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6645 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6646 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6647 if (NewOp.getNode())
6648 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6649 } else if ((VT == MVT::v4i32 ||
6650 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6651 // FIXME: Figure out a cleaner way to do this.
6652 // Try to make use of movq to zero out the top part.
6653 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6654 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6655 if (NewOp.getNode()) {
6656 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6657 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6658 DAG, Subtarget, dl);
6660 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6661 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6662 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6663 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6664 DAG, Subtarget, dl);
6671 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6673 SDValue V1 = Op.getOperand(0);
6674 SDValue V2 = Op.getOperand(1);
6675 EVT VT = Op.getValueType();
6676 DebugLoc dl = Op.getDebugLoc();
6677 unsigned NumElems = VT.getVectorNumElements();
6678 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6679 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6680 bool V1IsSplat = false;
6681 bool V2IsSplat = false;
6682 bool HasXMMInt = Subtarget->hasXMMInt();
6683 bool HasAVX2 = Subtarget->hasAVX2();
6684 MachineFunction &MF = DAG.getMachineFunction();
6685 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6687 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6689 // Vector shuffle lowering takes 3 steps:
6691 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6692 // narrowing and commutation of operands should be handled.
6693 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6695 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6696 // so the shuffle can be broken into other shuffles and the legalizer can
6697 // try the lowering again.
6699 // The general idea is that no vector_shuffle operation should be left to
6700 // be matched during isel, all of them must be converted to a target specific
6703 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6704 // narrowing and commutation of operands should be handled. The actual code
6705 // doesn't include all of those, work in progress...
6706 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6707 if (NewOp.getNode())
6710 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6711 // unpckh_undef). Only use pshufd if speed is more important than size.
6712 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6713 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6715 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6716 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6719 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6720 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6721 return getMOVDDup(Op, dl, V1, DAG);
6723 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6724 return getMOVHighToLow(Op, dl, DAG);
6726 // Use to match splats
6727 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6728 (VT == MVT::v2f64 || VT == MVT::v2i64))
6729 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6732 if (X86::isPSHUFDMask(SVOp)) {
6733 // The actual implementation will match the mask in the if above and then
6734 // during isel it can match several different instructions, not only pshufd
6735 // as its name says, sad but true, emulate the behavior for now...
6736 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6737 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6739 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6741 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6742 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6744 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6748 // Check if this can be converted into a logical shift.
6749 bool isLeft = false;
6752 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6753 if (isShift && ShVal.hasOneUse()) {
6754 // If the shifted value has multiple uses, it may be cheaper to use
6755 // v_set0 + movlhps or movhlps, etc.
6756 EVT EltVT = VT.getVectorElementType();
6757 ShAmt *= EltVT.getSizeInBits();
6758 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6761 if (X86::isMOVLMask(SVOp)) {
6764 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6765 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6766 if (!X86::isMOVLPMask(SVOp)) {
6767 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6768 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6770 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6771 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6775 // FIXME: fold these into legal mask.
6776 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6777 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6779 if (X86::isMOVHLPSMask(SVOp))
6780 return getMOVHighToLow(Op, dl, DAG);
6782 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6783 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6785 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6786 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6788 if (X86::isMOVLPMask(SVOp))
6789 return getMOVLP(Op, dl, DAG, HasXMMInt);
6791 if (ShouldXformToMOVHLPS(SVOp) ||
6792 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6793 return CommuteVectorShuffle(SVOp, DAG);
6796 // No better options. Use a vshl / vsrl.
6797 EVT EltVT = VT.getVectorElementType();
6798 ShAmt *= EltVT.getSizeInBits();
6799 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6802 bool Commuted = false;
6803 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6804 // 1,1,1,1 -> v8i16 though.
6805 V1IsSplat = isSplatVector(V1.getNode());
6806 V2IsSplat = isSplatVector(V2.getNode());
6808 // Canonicalize the splat or undef, if present, to be on the RHS.
6809 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6810 Op = CommuteVectorShuffle(SVOp, DAG);
6811 SVOp = cast<ShuffleVectorSDNode>(Op);
6812 V1 = SVOp->getOperand(0);
6813 V2 = SVOp->getOperand(1);
6814 std::swap(V1IsSplat, V2IsSplat);
6815 std::swap(V1IsUndef, V2IsUndef);
6819 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6820 // Shuffling low element of v1 into undef, just return v1.
6823 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6824 // the instruction selector will not match, so get a canonical MOVL with
6825 // swapped operands to undo the commute.
6826 return getMOVL(DAG, dl, VT, V2, V1);
6829 if (X86::isUNPCKLMask(SVOp, HasAVX2))
6830 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6833 if (X86::isUNPCKHMask(SVOp, HasAVX2))
6834 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6838 // Normalize mask so all entries that point to V2 points to its first
6839 // element then try to match unpck{h|l} again. If match, return a
6840 // new vector_shuffle with the corrected mask.
6841 SDValue NewMask = NormalizeMask(SVOp, DAG);
6842 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6843 if (NSVOp != SVOp) {
6844 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6846 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6853 // Commute is back and try unpck* again.
6854 // FIXME: this seems wrong.
6855 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6856 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6858 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6859 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6862 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6863 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6867 // Normalize the node to match x86 shuffle ops if needed
6868 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6869 return CommuteVectorShuffle(SVOp, DAG);
6871 // The checks below are all present in isShuffleMaskLegal, but they are
6872 // inlined here right now to enable us to directly emit target specific
6873 // nodes, and remove one by one until they don't return Op anymore.
6874 SmallVector<int, 16> M;
6877 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6878 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6879 X86::getShufflePALIGNRImmediate(SVOp),
6882 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6883 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6884 if (VT == MVT::v2f64)
6885 return getTargetShuffleNode(X86ISD::UNPCKLP, dl, VT, V1, V1, DAG);
6886 if (VT == MVT::v2i64)
6887 return getTargetShuffleNode(X86ISD::PUNPCKL, dl, VT, V1, V1, DAG);
6890 if (isPSHUFHWMask(M, VT))
6891 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6892 X86::getShufflePSHUFHWImmediate(SVOp),
6895 if (isPSHUFLWMask(M, VT))
6896 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6897 X86::getShufflePSHUFLWImmediate(SVOp),
6900 if (isSHUFPMask(M, VT))
6901 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6902 X86::getShuffleSHUFImmediate(SVOp), DAG);
6904 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6905 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6907 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6908 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6911 //===--------------------------------------------------------------------===//
6912 // Generate target specific nodes for 128 or 256-bit shuffles only
6913 // supported in the AVX instruction set.
6916 // Handle VMOVDDUPY permutations
6917 if (isMOVDDUPYMask(SVOp, Subtarget))
6918 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6920 // Handle VPERMILPS* permutations
6921 if (isVPERMILPSMask(M, VT, Subtarget))
6922 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6923 getShuffleVPERMILPSImmediate(SVOp), DAG);
6925 // Handle VPERMILPD* permutations
6926 if (isVPERMILPDMask(M, VT, Subtarget))
6927 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6928 getShuffleVPERMILPDImmediate(SVOp), DAG);
6930 // Handle VPERM2F128 permutations
6931 if (isVPERM2F128Mask(M, VT, Subtarget))
6932 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6933 getShuffleVPERM2F128Immediate(SVOp), DAG);
6935 // Handle VSHUFPSY permutations
6936 if (isVSHUFPSYMask(M, VT, Subtarget))
6937 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6938 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6940 // Handle VSHUFPDY permutations
6941 if (isVSHUFPDYMask(M, VT, Subtarget))
6942 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6943 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6945 // Try to swap operands in the node to match x86 shuffle ops
6946 if (isCommutedVSHUFPMask(M, VT, Subtarget)) {
6947 // Now we need to commute operands.
6948 SVOp = cast<ShuffleVectorSDNode>(CommuteVectorShuffle(SVOp, DAG));
6949 V1 = SVOp->getOperand(0);
6950 V2 = SVOp->getOperand(1);
6951 unsigned Immediate = (NumElems == 4) ? getShuffleVSHUFPDYImmediate(SVOp):
6952 getShuffleVSHUFPSYImmediate(SVOp);
6953 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, Immediate, DAG);
6956 //===--------------------------------------------------------------------===//
6957 // Since no target specific shuffle was selected for this generic one,
6958 // lower it into other known shuffles. FIXME: this isn't true yet, but
6959 // this is the plan.
6962 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6963 if (VT == MVT::v8i16) {
6964 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6965 if (NewOp.getNode())
6969 if (VT == MVT::v16i8) {
6970 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6971 if (NewOp.getNode())
6975 // Handle all 128-bit wide vectors with 4 elements, and match them with
6976 // several different shuffle types.
6977 if (NumElems == 4 && VT.getSizeInBits() == 128)
6978 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6980 // Handle general 256-bit shuffles
6981 if (VT.is256BitVector())
6982 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6988 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6989 SelectionDAG &DAG) const {
6990 EVT VT = Op.getValueType();
6991 DebugLoc dl = Op.getDebugLoc();
6993 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6996 if (VT.getSizeInBits() == 8) {
6997 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6998 Op.getOperand(0), Op.getOperand(1));
6999 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7000 DAG.getValueType(VT));
7001 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7002 } else if (VT.getSizeInBits() == 16) {
7003 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7004 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7006 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7007 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7008 DAG.getNode(ISD::BITCAST, dl,
7012 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7013 Op.getOperand(0), Op.getOperand(1));
7014 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7015 DAG.getValueType(VT));
7016 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7017 } else if (VT == MVT::f32) {
7018 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7019 // the result back to FR32 register. It's only worth matching if the
7020 // result has a single use which is a store or a bitcast to i32. And in
7021 // the case of a store, it's not worth it if the index is a constant 0,
7022 // because a MOVSSmr can be used instead, which is smaller and faster.
7023 if (!Op.hasOneUse())
7025 SDNode *User = *Op.getNode()->use_begin();
7026 if ((User->getOpcode() != ISD::STORE ||
7027 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7028 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7029 (User->getOpcode() != ISD::BITCAST ||
7030 User->getValueType(0) != MVT::i32))
7032 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7033 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7036 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7037 } else if (VT == MVT::i32 || VT == MVT::i64) {
7038 // ExtractPS/pextrq works with constant index.
7039 if (isa<ConstantSDNode>(Op.getOperand(1)))
7047 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7048 SelectionDAG &DAG) const {
7049 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7052 SDValue Vec = Op.getOperand(0);
7053 EVT VecVT = Vec.getValueType();
7055 // If this is a 256-bit vector result, first extract the 128-bit vector and
7056 // then extract the element from the 128-bit vector.
7057 if (VecVT.getSizeInBits() == 256) {
7058 DebugLoc dl = Op.getNode()->getDebugLoc();
7059 unsigned NumElems = VecVT.getVectorNumElements();
7060 SDValue Idx = Op.getOperand(1);
7061 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7063 // Get the 128-bit vector.
7064 bool Upper = IdxVal >= NumElems/2;
7065 Vec = Extract128BitVector(Vec,
7066 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7068 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7069 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7072 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7074 if (Subtarget->hasSSE41orAVX()) {
7075 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7080 EVT VT = Op.getValueType();
7081 DebugLoc dl = Op.getDebugLoc();
7082 // TODO: handle v16i8.
7083 if (VT.getSizeInBits() == 16) {
7084 SDValue Vec = Op.getOperand(0);
7085 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7087 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7088 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7089 DAG.getNode(ISD::BITCAST, dl,
7092 // Transform it so it match pextrw which produces a 32-bit result.
7093 EVT EltVT = MVT::i32;
7094 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7095 Op.getOperand(0), Op.getOperand(1));
7096 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7097 DAG.getValueType(VT));
7098 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7099 } else if (VT.getSizeInBits() == 32) {
7100 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7104 // SHUFPS the element to the lowest double word, then movss.
7105 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7106 EVT VVT = Op.getOperand(0).getValueType();
7107 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7108 DAG.getUNDEF(VVT), Mask);
7109 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7110 DAG.getIntPtrConstant(0));
7111 } else if (VT.getSizeInBits() == 64) {
7112 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7113 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7114 // to match extract_elt for f64.
7115 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7119 // UNPCKHPD the element to the lowest double word, then movsd.
7120 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7121 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7122 int Mask[2] = { 1, -1 };
7123 EVT VVT = Op.getOperand(0).getValueType();
7124 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7125 DAG.getUNDEF(VVT), Mask);
7126 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7127 DAG.getIntPtrConstant(0));
7134 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7135 SelectionDAG &DAG) const {
7136 EVT VT = Op.getValueType();
7137 EVT EltVT = VT.getVectorElementType();
7138 DebugLoc dl = Op.getDebugLoc();
7140 SDValue N0 = Op.getOperand(0);
7141 SDValue N1 = Op.getOperand(1);
7142 SDValue N2 = Op.getOperand(2);
7144 if (VT.getSizeInBits() == 256)
7147 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7148 isa<ConstantSDNode>(N2)) {
7150 if (VT == MVT::v8i16)
7151 Opc = X86ISD::PINSRW;
7152 else if (VT == MVT::v16i8)
7153 Opc = X86ISD::PINSRB;
7155 Opc = X86ISD::PINSRB;
7157 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7159 if (N1.getValueType() != MVT::i32)
7160 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7161 if (N2.getValueType() != MVT::i32)
7162 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7163 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7164 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7165 // Bits [7:6] of the constant are the source select. This will always be
7166 // zero here. The DAG Combiner may combine an extract_elt index into these
7167 // bits. For example (insert (extract, 3), 2) could be matched by putting
7168 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7169 // Bits [5:4] of the constant are the destination select. This is the
7170 // value of the incoming immediate.
7171 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7172 // combine either bitwise AND or insert of float 0.0 to set these bits.
7173 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7174 // Create this as a scalar to vector..
7175 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7176 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7177 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
7178 isa<ConstantSDNode>(N2)) {
7179 // PINSR* works with constant index.
7186 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7187 EVT VT = Op.getValueType();
7188 EVT EltVT = VT.getVectorElementType();
7190 DebugLoc dl = Op.getDebugLoc();
7191 SDValue N0 = Op.getOperand(0);
7192 SDValue N1 = Op.getOperand(1);
7193 SDValue N2 = Op.getOperand(2);
7195 // If this is a 256-bit vector result, first extract the 128-bit vector,
7196 // insert the element into the extracted half and then place it back.
7197 if (VT.getSizeInBits() == 256) {
7198 if (!isa<ConstantSDNode>(N2))
7201 // Get the desired 128-bit vector half.
7202 unsigned NumElems = VT.getVectorNumElements();
7203 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7204 bool Upper = IdxVal >= NumElems/2;
7205 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7206 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7208 // Insert the element into the desired half.
7209 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7210 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7212 // Insert the changed part back to the 256-bit vector
7213 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7216 if (Subtarget->hasSSE41orAVX())
7217 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7219 if (EltVT == MVT::i8)
7222 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7223 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7224 // as its second argument.
7225 if (N1.getValueType() != MVT::i32)
7226 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7227 if (N2.getValueType() != MVT::i32)
7228 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7229 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7235 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7236 LLVMContext *Context = DAG.getContext();
7237 DebugLoc dl = Op.getDebugLoc();
7238 EVT OpVT = Op.getValueType();
7240 // If this is a 256-bit vector result, first insert into a 128-bit
7241 // vector and then insert into the 256-bit vector.
7242 if (OpVT.getSizeInBits() > 128) {
7243 // Insert into a 128-bit vector.
7244 EVT VT128 = EVT::getVectorVT(*Context,
7245 OpVT.getVectorElementType(),
7246 OpVT.getVectorNumElements() / 2);
7248 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7250 // Insert the 128-bit vector.
7251 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7252 DAG.getConstant(0, MVT::i32),
7256 if (Op.getValueType() == MVT::v1i64 &&
7257 Op.getOperand(0).getValueType() == MVT::i64)
7258 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7260 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7261 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7262 "Expected an SSE type!");
7263 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7264 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7267 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7268 // a simple subregister reference or explicit instructions to grab
7269 // upper bits of a vector.
7271 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7272 if (Subtarget->hasAVX()) {
7273 DebugLoc dl = Op.getNode()->getDebugLoc();
7274 SDValue Vec = Op.getNode()->getOperand(0);
7275 SDValue Idx = Op.getNode()->getOperand(1);
7277 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7278 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7279 return Extract128BitVector(Vec, Idx, DAG, dl);
7285 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7286 // simple superregister reference or explicit instructions to insert
7287 // the upper bits of a vector.
7289 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7290 if (Subtarget->hasAVX()) {
7291 DebugLoc dl = Op.getNode()->getDebugLoc();
7292 SDValue Vec = Op.getNode()->getOperand(0);
7293 SDValue SubVec = Op.getNode()->getOperand(1);
7294 SDValue Idx = Op.getNode()->getOperand(2);
7296 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7297 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7298 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7304 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7305 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7306 // one of the above mentioned nodes. It has to be wrapped because otherwise
7307 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7308 // be used to form addressing mode. These wrapped nodes will be selected
7311 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7312 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7314 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7316 unsigned char OpFlag = 0;
7317 unsigned WrapperKind = X86ISD::Wrapper;
7318 CodeModel::Model M = getTargetMachine().getCodeModel();
7320 if (Subtarget->isPICStyleRIPRel() &&
7321 (M == CodeModel::Small || M == CodeModel::Kernel))
7322 WrapperKind = X86ISD::WrapperRIP;
7323 else if (Subtarget->isPICStyleGOT())
7324 OpFlag = X86II::MO_GOTOFF;
7325 else if (Subtarget->isPICStyleStubPIC())
7326 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7328 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7330 CP->getOffset(), OpFlag);
7331 DebugLoc DL = CP->getDebugLoc();
7332 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7333 // With PIC, the address is actually $g + Offset.
7335 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7336 DAG.getNode(X86ISD::GlobalBaseReg,
7337 DebugLoc(), getPointerTy()),
7344 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7345 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7347 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7349 unsigned char OpFlag = 0;
7350 unsigned WrapperKind = X86ISD::Wrapper;
7351 CodeModel::Model M = getTargetMachine().getCodeModel();
7353 if (Subtarget->isPICStyleRIPRel() &&
7354 (M == CodeModel::Small || M == CodeModel::Kernel))
7355 WrapperKind = X86ISD::WrapperRIP;
7356 else if (Subtarget->isPICStyleGOT())
7357 OpFlag = X86II::MO_GOTOFF;
7358 else if (Subtarget->isPICStyleStubPIC())
7359 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7361 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7363 DebugLoc DL = JT->getDebugLoc();
7364 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7366 // With PIC, the address is actually $g + Offset.
7368 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7369 DAG.getNode(X86ISD::GlobalBaseReg,
7370 DebugLoc(), getPointerTy()),
7377 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7378 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7380 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7382 unsigned char OpFlag = 0;
7383 unsigned WrapperKind = X86ISD::Wrapper;
7384 CodeModel::Model M = getTargetMachine().getCodeModel();
7386 if (Subtarget->isPICStyleRIPRel() &&
7387 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7388 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7389 OpFlag = X86II::MO_GOTPCREL;
7390 WrapperKind = X86ISD::WrapperRIP;
7391 } else if (Subtarget->isPICStyleGOT()) {
7392 OpFlag = X86II::MO_GOT;
7393 } else if (Subtarget->isPICStyleStubPIC()) {
7394 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7395 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7396 OpFlag = X86II::MO_DARWIN_NONLAZY;
7399 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7401 DebugLoc DL = Op.getDebugLoc();
7402 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7405 // With PIC, the address is actually $g + Offset.
7406 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7407 !Subtarget->is64Bit()) {
7408 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7409 DAG.getNode(X86ISD::GlobalBaseReg,
7410 DebugLoc(), getPointerTy()),
7414 // For symbols that require a load from a stub to get the address, emit the
7416 if (isGlobalStubReference(OpFlag))
7417 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7418 MachinePointerInfo::getGOT(), false, false, false, 0);
7424 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7425 // Create the TargetBlockAddressAddress node.
7426 unsigned char OpFlags =
7427 Subtarget->ClassifyBlockAddressReference();
7428 CodeModel::Model M = getTargetMachine().getCodeModel();
7429 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7430 DebugLoc dl = Op.getDebugLoc();
7431 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7432 /*isTarget=*/true, OpFlags);
7434 if (Subtarget->isPICStyleRIPRel() &&
7435 (M == CodeModel::Small || M == CodeModel::Kernel))
7436 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7438 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7440 // With PIC, the address is actually $g + Offset.
7441 if (isGlobalRelativeToPICBase(OpFlags)) {
7442 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7443 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7451 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7453 SelectionDAG &DAG) const {
7454 // Create the TargetGlobalAddress node, folding in the constant
7455 // offset if it is legal.
7456 unsigned char OpFlags =
7457 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7458 CodeModel::Model M = getTargetMachine().getCodeModel();
7460 if (OpFlags == X86II::MO_NO_FLAG &&
7461 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7462 // A direct static reference to a global.
7463 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7466 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7469 if (Subtarget->isPICStyleRIPRel() &&
7470 (M == CodeModel::Small || M == CodeModel::Kernel))
7471 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7473 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7475 // With PIC, the address is actually $g + Offset.
7476 if (isGlobalRelativeToPICBase(OpFlags)) {
7477 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7478 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7482 // For globals that require a load from a stub to get the address, emit the
7484 if (isGlobalStubReference(OpFlags))
7485 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7486 MachinePointerInfo::getGOT(), false, false, false, 0);
7488 // If there was a non-zero offset that we didn't fold, create an explicit
7491 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7492 DAG.getConstant(Offset, getPointerTy()));
7498 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7499 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7500 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7501 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7505 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7506 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7507 unsigned char OperandFlags) {
7508 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7509 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7510 DebugLoc dl = GA->getDebugLoc();
7511 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7512 GA->getValueType(0),
7516 SDValue Ops[] = { Chain, TGA, *InFlag };
7517 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7519 SDValue Ops[] = { Chain, TGA };
7520 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7523 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7524 MFI->setAdjustsStack(true);
7526 SDValue Flag = Chain.getValue(1);
7527 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7530 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7532 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7535 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7536 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7537 DAG.getNode(X86ISD::GlobalBaseReg,
7538 DebugLoc(), PtrVT), InFlag);
7539 InFlag = Chain.getValue(1);
7541 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7544 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7546 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7548 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7549 X86::RAX, X86II::MO_TLSGD);
7552 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7553 // "local exec" model.
7554 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7555 const EVT PtrVT, TLSModel::Model model,
7557 DebugLoc dl = GA->getDebugLoc();
7559 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7560 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7561 is64Bit ? 257 : 256));
7563 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7564 DAG.getIntPtrConstant(0),
7565 MachinePointerInfo(Ptr),
7566 false, false, false, 0);
7568 unsigned char OperandFlags = 0;
7569 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7571 unsigned WrapperKind = X86ISD::Wrapper;
7572 if (model == TLSModel::LocalExec) {
7573 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7574 } else if (is64Bit) {
7575 assert(model == TLSModel::InitialExec);
7576 OperandFlags = X86II::MO_GOTTPOFF;
7577 WrapperKind = X86ISD::WrapperRIP;
7579 assert(model == TLSModel::InitialExec);
7580 OperandFlags = X86II::MO_INDNTPOFF;
7583 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7585 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7586 GA->getValueType(0),
7587 GA->getOffset(), OperandFlags);
7588 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7590 if (model == TLSModel::InitialExec)
7591 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7592 MachinePointerInfo::getGOT(), false, false, false, 0);
7594 // The address of the thread local variable is the add of the thread
7595 // pointer with the offset of the variable.
7596 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7600 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7602 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7603 const GlobalValue *GV = GA->getGlobal();
7605 if (Subtarget->isTargetELF()) {
7606 // TODO: implement the "local dynamic" model
7607 // TODO: implement the "initial exec"model for pic executables
7609 // If GV is an alias then use the aliasee for determining
7610 // thread-localness.
7611 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7612 GV = GA->resolveAliasedGlobal(false);
7614 TLSModel::Model model
7615 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7618 case TLSModel::GeneralDynamic:
7619 case TLSModel::LocalDynamic: // not implemented
7620 if (Subtarget->is64Bit())
7621 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7622 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7624 case TLSModel::InitialExec:
7625 case TLSModel::LocalExec:
7626 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7627 Subtarget->is64Bit());
7629 } else if (Subtarget->isTargetDarwin()) {
7630 // Darwin only has one model of TLS. Lower to that.
7631 unsigned char OpFlag = 0;
7632 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7633 X86ISD::WrapperRIP : X86ISD::Wrapper;
7635 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7637 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7638 !Subtarget->is64Bit();
7640 OpFlag = X86II::MO_TLVP_PIC_BASE;
7642 OpFlag = X86II::MO_TLVP;
7643 DebugLoc DL = Op.getDebugLoc();
7644 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7645 GA->getValueType(0),
7646 GA->getOffset(), OpFlag);
7647 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7649 // With PIC32, the address is actually $g + Offset.
7651 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7652 DAG.getNode(X86ISD::GlobalBaseReg,
7653 DebugLoc(), getPointerTy()),
7656 // Lowering the machine isd will make sure everything is in the right
7658 SDValue Chain = DAG.getEntryNode();
7659 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7660 SDValue Args[] = { Chain, Offset };
7661 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7663 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7664 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7665 MFI->setAdjustsStack(true);
7667 // And our return value (tls address) is in the standard call return value
7669 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7670 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7675 "TLS not implemented for this target.");
7677 llvm_unreachable("Unreachable");
7682 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7683 /// take a 2 x i32 value to shift plus a shift amount.
7684 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7685 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7686 EVT VT = Op.getValueType();
7687 unsigned VTBits = VT.getSizeInBits();
7688 DebugLoc dl = Op.getDebugLoc();
7689 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7690 SDValue ShOpLo = Op.getOperand(0);
7691 SDValue ShOpHi = Op.getOperand(1);
7692 SDValue ShAmt = Op.getOperand(2);
7693 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7694 DAG.getConstant(VTBits - 1, MVT::i8))
7695 : DAG.getConstant(0, VT);
7698 if (Op.getOpcode() == ISD::SHL_PARTS) {
7699 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7700 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7702 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7703 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7706 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7707 DAG.getConstant(VTBits, MVT::i8));
7708 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7709 AndNode, DAG.getConstant(0, MVT::i8));
7712 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7713 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7714 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7716 if (Op.getOpcode() == ISD::SHL_PARTS) {
7717 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7718 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7720 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7721 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7724 SDValue Ops[2] = { Lo, Hi };
7725 return DAG.getMergeValues(Ops, 2, dl);
7728 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7729 SelectionDAG &DAG) const {
7730 EVT SrcVT = Op.getOperand(0).getValueType();
7732 if (SrcVT.isVector())
7735 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7736 "Unknown SINT_TO_FP to lower!");
7738 // These are really Legal; return the operand so the caller accepts it as
7740 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7742 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7743 Subtarget->is64Bit()) {
7747 DebugLoc dl = Op.getDebugLoc();
7748 unsigned Size = SrcVT.getSizeInBits()/8;
7749 MachineFunction &MF = DAG.getMachineFunction();
7750 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7751 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7752 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7754 MachinePointerInfo::getFixedStack(SSFI),
7756 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7759 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7761 SelectionDAG &DAG) const {
7763 DebugLoc DL = Op.getDebugLoc();
7765 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7767 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7769 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7771 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7773 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7774 MachineMemOperand *MMO;
7776 int SSFI = FI->getIndex();
7778 DAG.getMachineFunction()
7779 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7780 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7782 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7783 StackSlot = StackSlot.getOperand(1);
7785 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7786 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7788 Tys, Ops, array_lengthof(Ops),
7792 Chain = Result.getValue(1);
7793 SDValue InFlag = Result.getValue(2);
7795 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7796 // shouldn't be necessary except that RFP cannot be live across
7797 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7798 MachineFunction &MF = DAG.getMachineFunction();
7799 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7800 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7801 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7802 Tys = DAG.getVTList(MVT::Other);
7804 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7806 MachineMemOperand *MMO =
7807 DAG.getMachineFunction()
7808 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7809 MachineMemOperand::MOStore, SSFISize, SSFISize);
7811 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7812 Ops, array_lengthof(Ops),
7813 Op.getValueType(), MMO);
7814 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7815 MachinePointerInfo::getFixedStack(SSFI),
7816 false, false, false, 0);
7822 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7823 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7824 SelectionDAG &DAG) const {
7825 // This algorithm is not obvious. Here it is in C code, more or less:
7827 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7828 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7829 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7831 // Copy ints to xmm registers.
7832 __m128i xh = _mm_cvtsi32_si128( hi );
7833 __m128i xl = _mm_cvtsi32_si128( lo );
7835 // Combine into low half of a single xmm register.
7836 __m128i x = _mm_unpacklo_epi32( xh, xl );
7840 // Merge in appropriate exponents to give the integer bits the right
7842 x = _mm_unpacklo_epi32( x, exp );
7844 // Subtract away the biases to deal with the IEEE-754 double precision
7846 d = _mm_sub_pd( (__m128d) x, bias );
7848 // All conversions up to here are exact. The correctly rounded result is
7849 // calculated using the current rounding mode using the following
7851 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7852 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7853 // store doesn't really need to be here (except
7854 // maybe to zero the other double)
7859 DebugLoc dl = Op.getDebugLoc();
7860 LLVMContext *Context = DAG.getContext();
7862 // Build some magic constants.
7863 std::vector<Constant*> CV0;
7864 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7865 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7866 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7867 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7868 Constant *C0 = ConstantVector::get(CV0);
7869 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7871 std::vector<Constant*> CV1;
7873 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7875 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7876 Constant *C1 = ConstantVector::get(CV1);
7877 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7879 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7880 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7882 DAG.getIntPtrConstant(1)));
7883 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7884 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7886 DAG.getIntPtrConstant(0)));
7887 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7888 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7889 MachinePointerInfo::getConstantPool(),
7890 false, false, false, 16);
7891 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7892 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7893 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7894 MachinePointerInfo::getConstantPool(),
7895 false, false, false, 16);
7896 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7898 // Add the halves; easiest way is to swap them into another reg first.
7899 int ShufMask[2] = { 1, -1 };
7900 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7901 DAG.getUNDEF(MVT::v2f64), ShufMask);
7902 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7903 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7904 DAG.getIntPtrConstant(0));
7907 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7908 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7909 SelectionDAG &DAG) const {
7910 DebugLoc dl = Op.getDebugLoc();
7911 // FP constant to bias correct the final result.
7912 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7915 // Load the 32-bit value into an XMM register.
7916 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7919 // Zero out the upper parts of the register.
7920 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7923 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7924 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7925 DAG.getIntPtrConstant(0));
7927 // Or the load with the bias.
7928 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7929 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7930 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7932 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7933 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7934 MVT::v2f64, Bias)));
7935 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7936 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7937 DAG.getIntPtrConstant(0));
7939 // Subtract the bias.
7940 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7942 // Handle final rounding.
7943 EVT DestVT = Op.getValueType();
7945 if (DestVT.bitsLT(MVT::f64)) {
7946 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7947 DAG.getIntPtrConstant(0));
7948 } else if (DestVT.bitsGT(MVT::f64)) {
7949 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7952 // Handle final rounding.
7956 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7957 SelectionDAG &DAG) const {
7958 SDValue N0 = Op.getOperand(0);
7959 DebugLoc dl = Op.getDebugLoc();
7961 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7962 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7963 // the optimization here.
7964 if (DAG.SignBitIsZero(N0))
7965 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7967 EVT SrcVT = N0.getValueType();
7968 EVT DstVT = Op.getValueType();
7969 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7970 return LowerUINT_TO_FP_i64(Op, DAG);
7971 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7972 return LowerUINT_TO_FP_i32(Op, DAG);
7974 // Make a 64-bit buffer, and use it to build an FILD.
7975 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7976 if (SrcVT == MVT::i32) {
7977 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7978 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7979 getPointerTy(), StackSlot, WordOff);
7980 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7981 StackSlot, MachinePointerInfo(),
7983 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7984 OffsetSlot, MachinePointerInfo(),
7986 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7990 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7991 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7992 StackSlot, MachinePointerInfo(),
7994 // For i64 source, we need to add the appropriate power of 2 if the input
7995 // was negative. This is the same as the optimization in
7996 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7997 // we must be careful to do the computation in x87 extended precision, not
7998 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7999 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8000 MachineMemOperand *MMO =
8001 DAG.getMachineFunction()
8002 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8003 MachineMemOperand::MOLoad, 8, 8);
8005 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8006 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8007 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8010 APInt FF(32, 0x5F800000ULL);
8012 // Check whether the sign bit is set.
8013 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8014 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8017 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8018 SDValue FudgePtr = DAG.getConstantPool(
8019 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8022 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8023 SDValue Zero = DAG.getIntPtrConstant(0);
8024 SDValue Four = DAG.getIntPtrConstant(4);
8025 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8027 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8029 // Load the value out, extending it from f32 to f80.
8030 // FIXME: Avoid the extend by constructing the right constant pool?
8031 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8032 FudgePtr, MachinePointerInfo::getConstantPool(),
8033 MVT::f32, false, false, 4);
8034 // Extend everything to 80 bits to force it to be done on x87.
8035 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8036 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8039 std::pair<SDValue,SDValue> X86TargetLowering::
8040 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8041 DebugLoc DL = Op.getDebugLoc();
8043 EVT DstTy = Op.getValueType();
8046 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8050 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8051 DstTy.getSimpleVT() >= MVT::i16 &&
8052 "Unknown FP_TO_SINT to lower!");
8054 // These are really Legal.
8055 if (DstTy == MVT::i32 &&
8056 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8057 return std::make_pair(SDValue(), SDValue());
8058 if (Subtarget->is64Bit() &&
8059 DstTy == MVT::i64 &&
8060 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8061 return std::make_pair(SDValue(), SDValue());
8063 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8065 MachineFunction &MF = DAG.getMachineFunction();
8066 unsigned MemSize = DstTy.getSizeInBits()/8;
8067 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8068 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8073 switch (DstTy.getSimpleVT().SimpleTy) {
8074 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8075 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8076 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8077 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8080 SDValue Chain = DAG.getEntryNode();
8081 SDValue Value = Op.getOperand(0);
8082 EVT TheVT = Op.getOperand(0).getValueType();
8083 if (isScalarFPTypeInSSEReg(TheVT)) {
8084 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8085 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8086 MachinePointerInfo::getFixedStack(SSFI),
8088 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8090 Chain, StackSlot, DAG.getValueType(TheVT)
8093 MachineMemOperand *MMO =
8094 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8095 MachineMemOperand::MOLoad, MemSize, MemSize);
8096 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8098 Chain = Value.getValue(1);
8099 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8100 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8103 MachineMemOperand *MMO =
8104 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8105 MachineMemOperand::MOStore, MemSize, MemSize);
8107 // Build the FP_TO_INT*_IN_MEM
8108 SDValue Ops[] = { Chain, Value, StackSlot };
8109 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8110 Ops, 3, DstTy, MMO);
8112 return std::make_pair(FIST, StackSlot);
8115 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8116 SelectionDAG &DAG) const {
8117 if (Op.getValueType().isVector())
8120 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8121 SDValue FIST = Vals.first, StackSlot = Vals.second;
8122 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8123 if (FIST.getNode() == 0) return Op;
8126 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8127 FIST, StackSlot, MachinePointerInfo(),
8128 false, false, false, 0);
8131 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8132 SelectionDAG &DAG) const {
8133 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8134 SDValue FIST = Vals.first, StackSlot = Vals.second;
8135 assert(FIST.getNode() && "Unexpected failure");
8138 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8139 FIST, StackSlot, MachinePointerInfo(),
8140 false, false, false, 0);
8143 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8144 SelectionDAG &DAG) const {
8145 LLVMContext *Context = DAG.getContext();
8146 DebugLoc dl = Op.getDebugLoc();
8147 EVT VT = Op.getValueType();
8150 EltVT = VT.getVectorElementType();
8151 std::vector<Constant*> CV;
8152 if (EltVT == MVT::f64) {
8153 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8157 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8163 Constant *C = ConstantVector::get(CV);
8164 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8165 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8166 MachinePointerInfo::getConstantPool(),
8167 false, false, false, 16);
8168 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8171 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8172 LLVMContext *Context = DAG.getContext();
8173 DebugLoc dl = Op.getDebugLoc();
8174 EVT VT = Op.getValueType();
8177 EltVT = VT.getVectorElementType();
8178 std::vector<Constant*> CV;
8179 if (EltVT == MVT::f64) {
8180 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8184 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8190 Constant *C = ConstantVector::get(CV);
8191 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8192 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8193 MachinePointerInfo::getConstantPool(),
8194 false, false, false, 16);
8195 if (VT.isVector()) {
8196 return DAG.getNode(ISD::BITCAST, dl, VT,
8197 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8198 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8200 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8202 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8206 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8207 LLVMContext *Context = DAG.getContext();
8208 SDValue Op0 = Op.getOperand(0);
8209 SDValue Op1 = Op.getOperand(1);
8210 DebugLoc dl = Op.getDebugLoc();
8211 EVT VT = Op.getValueType();
8212 EVT SrcVT = Op1.getValueType();
8214 // If second operand is smaller, extend it first.
8215 if (SrcVT.bitsLT(VT)) {
8216 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8219 // And if it is bigger, shrink it first.
8220 if (SrcVT.bitsGT(VT)) {
8221 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8225 // At this point the operands and the result should have the same
8226 // type, and that won't be f80 since that is not custom lowered.
8228 // First get the sign bit of second operand.
8229 std::vector<Constant*> CV;
8230 if (SrcVT == MVT::f64) {
8231 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8232 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8234 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8235 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8236 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8237 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8239 Constant *C = ConstantVector::get(CV);
8240 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8241 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8242 MachinePointerInfo::getConstantPool(),
8243 false, false, false, 16);
8244 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8246 // Shift sign bit right or left if the two operands have different types.
8247 if (SrcVT.bitsGT(VT)) {
8248 // Op0 is MVT::f32, Op1 is MVT::f64.
8249 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8250 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8251 DAG.getConstant(32, MVT::i32));
8252 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8253 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8254 DAG.getIntPtrConstant(0));
8257 // Clear first operand sign bit.
8259 if (VT == MVT::f64) {
8260 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8261 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8263 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8264 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8265 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8266 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8268 C = ConstantVector::get(CV);
8269 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8270 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8271 MachinePointerInfo::getConstantPool(),
8272 false, false, false, 16);
8273 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8275 // Or the value with the sign bit.
8276 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8279 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8280 SDValue N0 = Op.getOperand(0);
8281 DebugLoc dl = Op.getDebugLoc();
8282 EVT VT = Op.getValueType();
8284 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8285 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8286 DAG.getConstant(1, VT));
8287 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8290 /// Emit nodes that will be selected as "test Op0,Op0", or something
8292 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8293 SelectionDAG &DAG) const {
8294 DebugLoc dl = Op.getDebugLoc();
8296 // CF and OF aren't always set the way we want. Determine which
8297 // of these we need.
8298 bool NeedCF = false;
8299 bool NeedOF = false;
8302 case X86::COND_A: case X86::COND_AE:
8303 case X86::COND_B: case X86::COND_BE:
8306 case X86::COND_G: case X86::COND_GE:
8307 case X86::COND_L: case X86::COND_LE:
8308 case X86::COND_O: case X86::COND_NO:
8313 // See if we can use the EFLAGS value from the operand instead of
8314 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8315 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8316 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8317 // Emit a CMP with 0, which is the TEST pattern.
8318 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8319 DAG.getConstant(0, Op.getValueType()));
8321 unsigned Opcode = 0;
8322 unsigned NumOperands = 0;
8323 switch (Op.getNode()->getOpcode()) {
8325 // Due to an isel shortcoming, be conservative if this add is likely to be
8326 // selected as part of a load-modify-store instruction. When the root node
8327 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8328 // uses of other nodes in the match, such as the ADD in this case. This
8329 // leads to the ADD being left around and reselected, with the result being
8330 // two adds in the output. Alas, even if none our users are stores, that
8331 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8332 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8333 // climbing the DAG back to the root, and it doesn't seem to be worth the
8335 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8336 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8337 if (UI->getOpcode() != ISD::CopyToReg &&
8338 UI->getOpcode() != ISD::SETCC &&
8339 UI->getOpcode() != ISD::STORE)
8342 if (ConstantSDNode *C =
8343 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8344 // An add of one will be selected as an INC.
8345 if (C->getAPIntValue() == 1) {
8346 Opcode = X86ISD::INC;
8351 // An add of negative one (subtract of one) will be selected as a DEC.
8352 if (C->getAPIntValue().isAllOnesValue()) {
8353 Opcode = X86ISD::DEC;
8359 // Otherwise use a regular EFLAGS-setting add.
8360 Opcode = X86ISD::ADD;
8364 // If the primary and result isn't used, don't bother using X86ISD::AND,
8365 // because a TEST instruction will be better.
8366 bool NonFlagUse = false;
8367 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8368 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8370 unsigned UOpNo = UI.getOperandNo();
8371 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8372 // Look pass truncate.
8373 UOpNo = User->use_begin().getOperandNo();
8374 User = *User->use_begin();
8377 if (User->getOpcode() != ISD::BRCOND &&
8378 User->getOpcode() != ISD::SETCC &&
8379 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8392 // Due to the ISEL shortcoming noted above, be conservative if this op is
8393 // likely to be selected as part of a load-modify-store instruction.
8394 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8395 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8396 if (UI->getOpcode() == ISD::STORE)
8399 // Otherwise use a regular EFLAGS-setting instruction.
8400 switch (Op.getNode()->getOpcode()) {
8401 default: llvm_unreachable("unexpected operator!");
8402 case ISD::SUB: Opcode = X86ISD::SUB; break;
8403 case ISD::OR: Opcode = X86ISD::OR; break;
8404 case ISD::XOR: Opcode = X86ISD::XOR; break;
8405 case ISD::AND: Opcode = X86ISD::AND; break;
8417 return SDValue(Op.getNode(), 1);
8424 // Emit a CMP with 0, which is the TEST pattern.
8425 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8426 DAG.getConstant(0, Op.getValueType()));
8428 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8429 SmallVector<SDValue, 4> Ops;
8430 for (unsigned i = 0; i != NumOperands; ++i)
8431 Ops.push_back(Op.getOperand(i));
8433 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8434 DAG.ReplaceAllUsesWith(Op, New);
8435 return SDValue(New.getNode(), 1);
8438 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8440 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8441 SelectionDAG &DAG) const {
8442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8443 if (C->getAPIntValue() == 0)
8444 return EmitTest(Op0, X86CC, DAG);
8446 DebugLoc dl = Op0.getDebugLoc();
8447 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8450 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8451 /// if it's possible.
8452 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8453 DebugLoc dl, SelectionDAG &DAG) const {
8454 SDValue Op0 = And.getOperand(0);
8455 SDValue Op1 = And.getOperand(1);
8456 if (Op0.getOpcode() == ISD::TRUNCATE)
8457 Op0 = Op0.getOperand(0);
8458 if (Op1.getOpcode() == ISD::TRUNCATE)
8459 Op1 = Op1.getOperand(0);
8462 if (Op1.getOpcode() == ISD::SHL)
8463 std::swap(Op0, Op1);
8464 if (Op0.getOpcode() == ISD::SHL) {
8465 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8466 if (And00C->getZExtValue() == 1) {
8467 // If we looked past a truncate, check that it's only truncating away
8469 unsigned BitWidth = Op0.getValueSizeInBits();
8470 unsigned AndBitWidth = And.getValueSizeInBits();
8471 if (BitWidth > AndBitWidth) {
8472 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8473 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8474 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8478 RHS = Op0.getOperand(1);
8480 } else if (Op1.getOpcode() == ISD::Constant) {
8481 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8482 uint64_t AndRHSVal = AndRHS->getZExtValue();
8483 SDValue AndLHS = Op0;
8485 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8486 LHS = AndLHS.getOperand(0);
8487 RHS = AndLHS.getOperand(1);
8490 // Use BT if the immediate can't be encoded in a TEST instruction.
8491 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8493 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8497 if (LHS.getNode()) {
8498 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8499 // instruction. Since the shift amount is in-range-or-undefined, we know
8500 // that doing a bittest on the i32 value is ok. We extend to i32 because
8501 // the encoding for the i16 version is larger than the i32 version.
8502 // Also promote i16 to i32 for performance / code size reason.
8503 if (LHS.getValueType() == MVT::i8 ||
8504 LHS.getValueType() == MVT::i16)
8505 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8507 // If the operand types disagree, extend the shift amount to match. Since
8508 // BT ignores high bits (like shifts) we can use anyextend.
8509 if (LHS.getValueType() != RHS.getValueType())
8510 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8512 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8513 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8514 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8515 DAG.getConstant(Cond, MVT::i8), BT);
8521 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8523 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8525 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8526 SDValue Op0 = Op.getOperand(0);
8527 SDValue Op1 = Op.getOperand(1);
8528 DebugLoc dl = Op.getDebugLoc();
8529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8531 // Optimize to BT if possible.
8532 // Lower (X & (1 << N)) == 0 to BT(X, N).
8533 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8534 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8535 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8536 Op1.getOpcode() == ISD::Constant &&
8537 cast<ConstantSDNode>(Op1)->isNullValue() &&
8538 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8539 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8540 if (NewSetCC.getNode())
8544 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8546 if (Op1.getOpcode() == ISD::Constant &&
8547 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8548 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8549 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8551 // If the input is a setcc, then reuse the input setcc or use a new one with
8552 // the inverted condition.
8553 if (Op0.getOpcode() == X86ISD::SETCC) {
8554 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8555 bool Invert = (CC == ISD::SETNE) ^
8556 cast<ConstantSDNode>(Op1)->isNullValue();
8557 if (!Invert) return Op0;
8559 CCode = X86::GetOppositeBranchCondition(CCode);
8560 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8561 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8565 bool isFP = Op1.getValueType().isFloatingPoint();
8566 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8567 if (X86CC == X86::COND_INVALID)
8570 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8571 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8572 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8575 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8576 // ones, and then concatenate the result back.
8577 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8578 EVT VT = Op.getValueType();
8580 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8581 "Unsupported value type for operation");
8583 int NumElems = VT.getVectorNumElements();
8584 DebugLoc dl = Op.getDebugLoc();
8585 SDValue CC = Op.getOperand(2);
8586 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8587 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8589 // Extract the LHS vectors
8590 SDValue LHS = Op.getOperand(0);
8591 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8592 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8594 // Extract the RHS vectors
8595 SDValue RHS = Op.getOperand(1);
8596 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8597 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8599 // Issue the operation on the smaller types and concatenate the result back
8600 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8601 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8602 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8603 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8604 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8608 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8610 SDValue Op0 = Op.getOperand(0);
8611 SDValue Op1 = Op.getOperand(1);
8612 SDValue CC = Op.getOperand(2);
8613 EVT VT = Op.getValueType();
8614 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8615 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8616 DebugLoc dl = Op.getDebugLoc();
8620 EVT EltVT = Op0.getValueType().getVectorElementType();
8621 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8623 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8626 // SSE Condition code mapping:
8635 switch (SetCCOpcode) {
8638 case ISD::SETEQ: SSECC = 0; break;
8640 case ISD::SETGT: Swap = true; // Fallthrough
8642 case ISD::SETOLT: SSECC = 1; break;
8644 case ISD::SETGE: Swap = true; // Fallthrough
8646 case ISD::SETOLE: SSECC = 2; break;
8647 case ISD::SETUO: SSECC = 3; break;
8649 case ISD::SETNE: SSECC = 4; break;
8650 case ISD::SETULE: Swap = true;
8651 case ISD::SETUGE: SSECC = 5; break;
8652 case ISD::SETULT: Swap = true;
8653 case ISD::SETUGT: SSECC = 6; break;
8654 case ISD::SETO: SSECC = 7; break;
8657 std::swap(Op0, Op1);
8659 // In the two special cases we can't handle, emit two comparisons.
8661 if (SetCCOpcode == ISD::SETUEQ) {
8663 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8664 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8665 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8666 } else if (SetCCOpcode == ISD::SETONE) {
8668 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8669 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8670 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8672 llvm_unreachable("Illegal FP comparison");
8674 // Handle all other FP comparisons here.
8675 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8678 // Break 256-bit integer vector compare into smaller ones.
8679 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8680 return Lower256IntVSETCC(Op, DAG);
8682 // We are handling one of the integer comparisons here. Since SSE only has
8683 // GT and EQ comparisons for integer, swapping operands and multiple
8684 // operations may be required for some comparisons.
8685 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8686 bool Swap = false, Invert = false, FlipSigns = false;
8688 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8690 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8691 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8692 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8693 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8696 switch (SetCCOpcode) {
8698 case ISD::SETNE: Invert = true;
8699 case ISD::SETEQ: Opc = EQOpc; break;
8700 case ISD::SETLT: Swap = true;
8701 case ISD::SETGT: Opc = GTOpc; break;
8702 case ISD::SETGE: Swap = true;
8703 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8704 case ISD::SETULT: Swap = true;
8705 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8706 case ISD::SETUGE: Swap = true;
8707 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8710 std::swap(Op0, Op1);
8712 // Check that the operation in question is available (most are plain SSE2,
8713 // but PCMPGTQ and PCMPEQQ have different requirements).
8714 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8716 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8719 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8720 // bits of the inputs before performing those operations.
8722 EVT EltVT = VT.getVectorElementType();
8723 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8725 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8726 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8728 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8729 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8732 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8734 // If the logical-not of the result is required, perform that now.
8736 Result = DAG.getNOT(dl, Result, VT);
8741 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8742 static bool isX86LogicalCmp(SDValue Op) {
8743 unsigned Opc = Op.getNode()->getOpcode();
8744 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8746 if (Op.getResNo() == 1 &&
8747 (Opc == X86ISD::ADD ||
8748 Opc == X86ISD::SUB ||
8749 Opc == X86ISD::ADC ||
8750 Opc == X86ISD::SBB ||
8751 Opc == X86ISD::SMUL ||
8752 Opc == X86ISD::UMUL ||
8753 Opc == X86ISD::INC ||
8754 Opc == X86ISD::DEC ||
8755 Opc == X86ISD::OR ||
8756 Opc == X86ISD::XOR ||
8757 Opc == X86ISD::AND))
8760 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8766 static bool isZero(SDValue V) {
8767 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8768 return C && C->isNullValue();
8771 static bool isAllOnes(SDValue V) {
8772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8773 return C && C->isAllOnesValue();
8776 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8777 bool addTest = true;
8778 SDValue Cond = Op.getOperand(0);
8779 SDValue Op1 = Op.getOperand(1);
8780 SDValue Op2 = Op.getOperand(2);
8781 DebugLoc DL = Op.getDebugLoc();
8784 if (Cond.getOpcode() == ISD::SETCC) {
8785 SDValue NewCond = LowerSETCC(Cond, DAG);
8786 if (NewCond.getNode())
8790 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8791 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8792 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8793 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8794 if (Cond.getOpcode() == X86ISD::SETCC &&
8795 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8796 isZero(Cond.getOperand(1).getOperand(1))) {
8797 SDValue Cmp = Cond.getOperand(1);
8799 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8801 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8802 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8803 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8805 SDValue CmpOp0 = Cmp.getOperand(0);
8806 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8807 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8809 SDValue Res = // Res = 0 or -1.
8810 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8811 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8813 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8814 Res = DAG.getNOT(DL, Res, Res.getValueType());
8816 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8817 if (N2C == 0 || !N2C->isNullValue())
8818 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8823 // Look past (and (setcc_carry (cmp ...)), 1).
8824 if (Cond.getOpcode() == ISD::AND &&
8825 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8826 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8827 if (C && C->getAPIntValue() == 1)
8828 Cond = Cond.getOperand(0);
8831 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8832 // setting operand in place of the X86ISD::SETCC.
8833 unsigned CondOpcode = Cond.getOpcode();
8834 if (CondOpcode == X86ISD::SETCC ||
8835 CondOpcode == X86ISD::SETCC_CARRY) {
8836 CC = Cond.getOperand(0);
8838 SDValue Cmp = Cond.getOperand(1);
8839 unsigned Opc = Cmp.getOpcode();
8840 EVT VT = Op.getValueType();
8842 bool IllegalFPCMov = false;
8843 if (VT.isFloatingPoint() && !VT.isVector() &&
8844 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8845 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8847 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8848 Opc == X86ISD::BT) { // FIXME
8852 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8853 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8854 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8855 Cond.getOperand(0).getValueType() != MVT::i8)) {
8856 SDValue LHS = Cond.getOperand(0);
8857 SDValue RHS = Cond.getOperand(1);
8861 switch (CondOpcode) {
8862 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8863 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8864 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8865 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8866 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8867 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8868 default: llvm_unreachable("unexpected overflowing operator");
8870 if (CondOpcode == ISD::UMULO)
8871 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8874 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8876 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8878 if (CondOpcode == ISD::UMULO)
8879 Cond = X86Op.getValue(2);
8881 Cond = X86Op.getValue(1);
8883 CC = DAG.getConstant(X86Cond, MVT::i8);
8888 // Look pass the truncate.
8889 if (Cond.getOpcode() == ISD::TRUNCATE)
8890 Cond = Cond.getOperand(0);
8892 // We know the result of AND is compared against zero. Try to match
8894 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8895 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8896 if (NewSetCC.getNode()) {
8897 CC = NewSetCC.getOperand(0);
8898 Cond = NewSetCC.getOperand(1);
8905 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8906 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8909 // a < b ? -1 : 0 -> RES = ~setcc_carry
8910 // a < b ? 0 : -1 -> RES = setcc_carry
8911 // a >= b ? -1 : 0 -> RES = setcc_carry
8912 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8913 if (Cond.getOpcode() == X86ISD::CMP) {
8914 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8916 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8917 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8918 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8919 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8920 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8921 return DAG.getNOT(DL, Res, Res.getValueType());
8926 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8927 // condition is true.
8928 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8929 SDValue Ops[] = { Op2, Op1, CC, Cond };
8930 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8933 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8934 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8935 // from the AND / OR.
8936 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8937 Opc = Op.getOpcode();
8938 if (Opc != ISD::OR && Opc != ISD::AND)
8940 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8941 Op.getOperand(0).hasOneUse() &&
8942 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8943 Op.getOperand(1).hasOneUse());
8946 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8947 // 1 and that the SETCC node has a single use.
8948 static bool isXor1OfSetCC(SDValue Op) {
8949 if (Op.getOpcode() != ISD::XOR)
8951 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8952 if (N1C && N1C->getAPIntValue() == 1) {
8953 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8954 Op.getOperand(0).hasOneUse();
8959 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8960 bool addTest = true;
8961 SDValue Chain = Op.getOperand(0);
8962 SDValue Cond = Op.getOperand(1);
8963 SDValue Dest = Op.getOperand(2);
8964 DebugLoc dl = Op.getDebugLoc();
8966 bool Inverted = false;
8968 if (Cond.getOpcode() == ISD::SETCC) {
8969 // Check for setcc([su]{add,sub,mul}o == 0).
8970 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8971 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8972 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8973 Cond.getOperand(0).getResNo() == 1 &&
8974 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8975 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8976 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8977 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8978 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8979 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8981 Cond = Cond.getOperand(0);
8983 SDValue NewCond = LowerSETCC(Cond, DAG);
8984 if (NewCond.getNode())
8989 // FIXME: LowerXALUO doesn't handle these!!
8990 else if (Cond.getOpcode() == X86ISD::ADD ||
8991 Cond.getOpcode() == X86ISD::SUB ||
8992 Cond.getOpcode() == X86ISD::SMUL ||
8993 Cond.getOpcode() == X86ISD::UMUL)
8994 Cond = LowerXALUO(Cond, DAG);
8997 // Look pass (and (setcc_carry (cmp ...)), 1).
8998 if (Cond.getOpcode() == ISD::AND &&
8999 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9000 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9001 if (C && C->getAPIntValue() == 1)
9002 Cond = Cond.getOperand(0);
9005 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9006 // setting operand in place of the X86ISD::SETCC.
9007 unsigned CondOpcode = Cond.getOpcode();
9008 if (CondOpcode == X86ISD::SETCC ||
9009 CondOpcode == X86ISD::SETCC_CARRY) {
9010 CC = Cond.getOperand(0);
9012 SDValue Cmp = Cond.getOperand(1);
9013 unsigned Opc = Cmp.getOpcode();
9014 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9015 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9019 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9023 // These can only come from an arithmetic instruction with overflow,
9024 // e.g. SADDO, UADDO.
9025 Cond = Cond.getNode()->getOperand(1);
9031 CondOpcode = Cond.getOpcode();
9032 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9033 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9034 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9035 Cond.getOperand(0).getValueType() != MVT::i8)) {
9036 SDValue LHS = Cond.getOperand(0);
9037 SDValue RHS = Cond.getOperand(1);
9041 switch (CondOpcode) {
9042 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9043 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9044 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9045 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9046 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9047 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9048 default: llvm_unreachable("unexpected overflowing operator");
9051 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9052 if (CondOpcode == ISD::UMULO)
9053 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9056 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9058 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9060 if (CondOpcode == ISD::UMULO)
9061 Cond = X86Op.getValue(2);
9063 Cond = X86Op.getValue(1);
9065 CC = DAG.getConstant(X86Cond, MVT::i8);
9069 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9070 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9071 if (CondOpc == ISD::OR) {
9072 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9073 // two branches instead of an explicit OR instruction with a
9075 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9076 isX86LogicalCmp(Cmp)) {
9077 CC = Cond.getOperand(0).getOperand(0);
9078 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9079 Chain, Dest, CC, Cmp);
9080 CC = Cond.getOperand(1).getOperand(0);
9084 } else { // ISD::AND
9085 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9086 // two branches instead of an explicit AND instruction with a
9087 // separate test. However, we only do this if this block doesn't
9088 // have a fall-through edge, because this requires an explicit
9089 // jmp when the condition is false.
9090 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9091 isX86LogicalCmp(Cmp) &&
9092 Op.getNode()->hasOneUse()) {
9093 X86::CondCode CCode =
9094 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9095 CCode = X86::GetOppositeBranchCondition(CCode);
9096 CC = DAG.getConstant(CCode, MVT::i8);
9097 SDNode *User = *Op.getNode()->use_begin();
9098 // Look for an unconditional branch following this conditional branch.
9099 // We need this because we need to reverse the successors in order
9100 // to implement FCMP_OEQ.
9101 if (User->getOpcode() == ISD::BR) {
9102 SDValue FalseBB = User->getOperand(1);
9104 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9105 assert(NewBR == User);
9109 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9110 Chain, Dest, CC, Cmp);
9111 X86::CondCode CCode =
9112 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9113 CCode = X86::GetOppositeBranchCondition(CCode);
9114 CC = DAG.getConstant(CCode, MVT::i8);
9120 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9121 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9122 // It should be transformed during dag combiner except when the condition
9123 // is set by a arithmetics with overflow node.
9124 X86::CondCode CCode =
9125 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9126 CCode = X86::GetOppositeBranchCondition(CCode);
9127 CC = DAG.getConstant(CCode, MVT::i8);
9128 Cond = Cond.getOperand(0).getOperand(1);
9130 } else if (Cond.getOpcode() == ISD::SETCC &&
9131 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9132 // For FCMP_OEQ, we can emit
9133 // two branches instead of an explicit AND instruction with a
9134 // separate test. However, we only do this if this block doesn't
9135 // have a fall-through edge, because this requires an explicit
9136 // jmp when the condition is false.
9137 if (Op.getNode()->hasOneUse()) {
9138 SDNode *User = *Op.getNode()->use_begin();
9139 // Look for an unconditional branch following this conditional branch.
9140 // We need this because we need to reverse the successors in order
9141 // to implement FCMP_OEQ.
9142 if (User->getOpcode() == ISD::BR) {
9143 SDValue FalseBB = User->getOperand(1);
9145 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9146 assert(NewBR == User);
9150 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9151 Cond.getOperand(0), Cond.getOperand(1));
9152 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9153 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9154 Chain, Dest, CC, Cmp);
9155 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9160 } else if (Cond.getOpcode() == ISD::SETCC &&
9161 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9162 // For FCMP_UNE, we can emit
9163 // two branches instead of an explicit AND instruction with a
9164 // separate test. However, we only do this if this block doesn't
9165 // have a fall-through edge, because this requires an explicit
9166 // jmp when the condition is false.
9167 if (Op.getNode()->hasOneUse()) {
9168 SDNode *User = *Op.getNode()->use_begin();
9169 // Look for an unconditional branch following this conditional branch.
9170 // We need this because we need to reverse the successors in order
9171 // to implement FCMP_UNE.
9172 if (User->getOpcode() == ISD::BR) {
9173 SDValue FalseBB = User->getOperand(1);
9175 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9176 assert(NewBR == User);
9179 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9180 Cond.getOperand(0), Cond.getOperand(1));
9181 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9182 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9183 Chain, Dest, CC, Cmp);
9184 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9194 // Look pass the truncate.
9195 if (Cond.getOpcode() == ISD::TRUNCATE)
9196 Cond = Cond.getOperand(0);
9198 // We know the result of AND is compared against zero. Try to match
9200 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9201 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9202 if (NewSetCC.getNode()) {
9203 CC = NewSetCC.getOperand(0);
9204 Cond = NewSetCC.getOperand(1);
9211 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9212 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9214 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9215 Chain, Dest, CC, Cond);
9219 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9220 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9221 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9222 // that the guard pages used by the OS virtual memory manager are allocated in
9223 // correct sequence.
9225 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9226 SelectionDAG &DAG) const {
9227 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9228 EnableSegmentedStacks) &&
9229 "This should be used only on Windows targets or when segmented stacks "
9231 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9232 DebugLoc dl = Op.getDebugLoc();
9235 SDValue Chain = Op.getOperand(0);
9236 SDValue Size = Op.getOperand(1);
9237 // FIXME: Ensure alignment here
9239 bool Is64Bit = Subtarget->is64Bit();
9240 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9242 if (EnableSegmentedStacks) {
9243 MachineFunction &MF = DAG.getMachineFunction();
9244 MachineRegisterInfo &MRI = MF.getRegInfo();
9247 // The 64 bit implementation of segmented stacks needs to clobber both r10
9248 // r11. This makes it impossible to use it along with nested parameters.
9249 const Function *F = MF.getFunction();
9251 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9253 if (I->hasNestAttr())
9254 report_fatal_error("Cannot use segmented stacks with functions that "
9255 "have nested arguments.");
9258 const TargetRegisterClass *AddrRegClass =
9259 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9260 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9261 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9262 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9263 DAG.getRegister(Vreg, SPTy));
9264 SDValue Ops1[2] = { Value, Chain };
9265 return DAG.getMergeValues(Ops1, 2, dl);
9268 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9270 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9271 Flag = Chain.getValue(1);
9272 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9274 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9275 Flag = Chain.getValue(1);
9277 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9279 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9280 return DAG.getMergeValues(Ops1, 2, dl);
9284 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9285 MachineFunction &MF = DAG.getMachineFunction();
9286 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9288 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9289 DebugLoc DL = Op.getDebugLoc();
9291 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9292 // vastart just stores the address of the VarArgsFrameIndex slot into the
9293 // memory location argument.
9294 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9296 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9297 MachinePointerInfo(SV), false, false, 0);
9301 // gp_offset (0 - 6 * 8)
9302 // fp_offset (48 - 48 + 8 * 16)
9303 // overflow_arg_area (point to parameters coming in memory).
9305 SmallVector<SDValue, 8> MemOps;
9306 SDValue FIN = Op.getOperand(1);
9308 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9309 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9311 FIN, MachinePointerInfo(SV), false, false, 0);
9312 MemOps.push_back(Store);
9315 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9316 FIN, DAG.getIntPtrConstant(4));
9317 Store = DAG.getStore(Op.getOperand(0), DL,
9318 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9320 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9321 MemOps.push_back(Store);
9323 // Store ptr to overflow_arg_area
9324 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9325 FIN, DAG.getIntPtrConstant(4));
9326 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9328 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9329 MachinePointerInfo(SV, 8),
9331 MemOps.push_back(Store);
9333 // Store ptr to reg_save_area.
9334 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9335 FIN, DAG.getIntPtrConstant(8));
9336 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9338 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9339 MachinePointerInfo(SV, 16), false, false, 0);
9340 MemOps.push_back(Store);
9341 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9342 &MemOps[0], MemOps.size());
9345 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9346 assert(Subtarget->is64Bit() &&
9347 "LowerVAARG only handles 64-bit va_arg!");
9348 assert((Subtarget->isTargetLinux() ||
9349 Subtarget->isTargetDarwin()) &&
9350 "Unhandled target in LowerVAARG");
9351 assert(Op.getNode()->getNumOperands() == 4);
9352 SDValue Chain = Op.getOperand(0);
9353 SDValue SrcPtr = Op.getOperand(1);
9354 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9355 unsigned Align = Op.getConstantOperandVal(3);
9356 DebugLoc dl = Op.getDebugLoc();
9358 EVT ArgVT = Op.getNode()->getValueType(0);
9359 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9360 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9363 // Decide which area this value should be read from.
9364 // TODO: Implement the AMD64 ABI in its entirety. This simple
9365 // selection mechanism works only for the basic types.
9366 if (ArgVT == MVT::f80) {
9367 llvm_unreachable("va_arg for f80 not yet implemented");
9368 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9369 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9370 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9371 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9373 llvm_unreachable("Unhandled argument type in LowerVAARG");
9377 // Sanity Check: Make sure using fp_offset makes sense.
9378 assert(!UseSoftFloat &&
9379 !(DAG.getMachineFunction()
9380 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9381 Subtarget->hasXMM());
9384 // Insert VAARG_64 node into the DAG
9385 // VAARG_64 returns two values: Variable Argument Address, Chain
9386 SmallVector<SDValue, 11> InstOps;
9387 InstOps.push_back(Chain);
9388 InstOps.push_back(SrcPtr);
9389 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9390 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9391 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9392 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9393 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9394 VTs, &InstOps[0], InstOps.size(),
9396 MachinePointerInfo(SV),
9401 Chain = VAARG.getValue(1);
9403 // Load the next argument and return it
9404 return DAG.getLoad(ArgVT, dl,
9407 MachinePointerInfo(),
9408 false, false, false, 0);
9411 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9412 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9413 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9414 SDValue Chain = Op.getOperand(0);
9415 SDValue DstPtr = Op.getOperand(1);
9416 SDValue SrcPtr = Op.getOperand(2);
9417 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9418 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9419 DebugLoc DL = Op.getDebugLoc();
9421 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9422 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9424 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9428 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9429 DebugLoc dl = Op.getDebugLoc();
9430 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9432 default: return SDValue(); // Don't custom lower most intrinsics.
9433 // Comparison intrinsics.
9434 case Intrinsic::x86_sse_comieq_ss:
9435 case Intrinsic::x86_sse_comilt_ss:
9436 case Intrinsic::x86_sse_comile_ss:
9437 case Intrinsic::x86_sse_comigt_ss:
9438 case Intrinsic::x86_sse_comige_ss:
9439 case Intrinsic::x86_sse_comineq_ss:
9440 case Intrinsic::x86_sse_ucomieq_ss:
9441 case Intrinsic::x86_sse_ucomilt_ss:
9442 case Intrinsic::x86_sse_ucomile_ss:
9443 case Intrinsic::x86_sse_ucomigt_ss:
9444 case Intrinsic::x86_sse_ucomige_ss:
9445 case Intrinsic::x86_sse_ucomineq_ss:
9446 case Intrinsic::x86_sse2_comieq_sd:
9447 case Intrinsic::x86_sse2_comilt_sd:
9448 case Intrinsic::x86_sse2_comile_sd:
9449 case Intrinsic::x86_sse2_comigt_sd:
9450 case Intrinsic::x86_sse2_comige_sd:
9451 case Intrinsic::x86_sse2_comineq_sd:
9452 case Intrinsic::x86_sse2_ucomieq_sd:
9453 case Intrinsic::x86_sse2_ucomilt_sd:
9454 case Intrinsic::x86_sse2_ucomile_sd:
9455 case Intrinsic::x86_sse2_ucomigt_sd:
9456 case Intrinsic::x86_sse2_ucomige_sd:
9457 case Intrinsic::x86_sse2_ucomineq_sd: {
9459 ISD::CondCode CC = ISD::SETCC_INVALID;
9462 case Intrinsic::x86_sse_comieq_ss:
9463 case Intrinsic::x86_sse2_comieq_sd:
9467 case Intrinsic::x86_sse_comilt_ss:
9468 case Intrinsic::x86_sse2_comilt_sd:
9472 case Intrinsic::x86_sse_comile_ss:
9473 case Intrinsic::x86_sse2_comile_sd:
9477 case Intrinsic::x86_sse_comigt_ss:
9478 case Intrinsic::x86_sse2_comigt_sd:
9482 case Intrinsic::x86_sse_comige_ss:
9483 case Intrinsic::x86_sse2_comige_sd:
9487 case Intrinsic::x86_sse_comineq_ss:
9488 case Intrinsic::x86_sse2_comineq_sd:
9492 case Intrinsic::x86_sse_ucomieq_ss:
9493 case Intrinsic::x86_sse2_ucomieq_sd:
9494 Opc = X86ISD::UCOMI;
9497 case Intrinsic::x86_sse_ucomilt_ss:
9498 case Intrinsic::x86_sse2_ucomilt_sd:
9499 Opc = X86ISD::UCOMI;
9502 case Intrinsic::x86_sse_ucomile_ss:
9503 case Intrinsic::x86_sse2_ucomile_sd:
9504 Opc = X86ISD::UCOMI;
9507 case Intrinsic::x86_sse_ucomigt_ss:
9508 case Intrinsic::x86_sse2_ucomigt_sd:
9509 Opc = X86ISD::UCOMI;
9512 case Intrinsic::x86_sse_ucomige_ss:
9513 case Intrinsic::x86_sse2_ucomige_sd:
9514 Opc = X86ISD::UCOMI;
9517 case Intrinsic::x86_sse_ucomineq_ss:
9518 case Intrinsic::x86_sse2_ucomineq_sd:
9519 Opc = X86ISD::UCOMI;
9524 SDValue LHS = Op.getOperand(1);
9525 SDValue RHS = Op.getOperand(2);
9526 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9527 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9528 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9529 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9530 DAG.getConstant(X86CC, MVT::i8), Cond);
9531 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9533 // Arithmetic intrinsics.
9534 case Intrinsic::x86_sse3_hadd_ps:
9535 case Intrinsic::x86_sse3_hadd_pd:
9536 case Intrinsic::x86_avx_hadd_ps_256:
9537 case Intrinsic::x86_avx_hadd_pd_256:
9538 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9539 Op.getOperand(1), Op.getOperand(2));
9540 case Intrinsic::x86_sse3_hsub_ps:
9541 case Intrinsic::x86_sse3_hsub_pd:
9542 case Intrinsic::x86_avx_hsub_ps_256:
9543 case Intrinsic::x86_avx_hsub_pd_256:
9544 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9545 Op.getOperand(1), Op.getOperand(2));
9546 case Intrinsic::x86_avx2_psllv_d:
9547 case Intrinsic::x86_avx2_psllv_q:
9548 case Intrinsic::x86_avx2_psllv_d_256:
9549 case Intrinsic::x86_avx2_psllv_q_256:
9550 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9551 Op.getOperand(1), Op.getOperand(2));
9552 case Intrinsic::x86_avx2_psrlv_d:
9553 case Intrinsic::x86_avx2_psrlv_q:
9554 case Intrinsic::x86_avx2_psrlv_d_256:
9555 case Intrinsic::x86_avx2_psrlv_q_256:
9556 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9557 Op.getOperand(1), Op.getOperand(2));
9558 case Intrinsic::x86_avx2_psrav_d:
9559 case Intrinsic::x86_avx2_psrav_d_256:
9560 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9561 Op.getOperand(1), Op.getOperand(2));
9563 // ptest and testp intrinsics. The intrinsic these come from are designed to
9564 // return an integer value, not just an instruction so lower it to the ptest
9565 // or testp pattern and a setcc for the result.
9566 case Intrinsic::x86_sse41_ptestz:
9567 case Intrinsic::x86_sse41_ptestc:
9568 case Intrinsic::x86_sse41_ptestnzc:
9569 case Intrinsic::x86_avx_ptestz_256:
9570 case Intrinsic::x86_avx_ptestc_256:
9571 case Intrinsic::x86_avx_ptestnzc_256:
9572 case Intrinsic::x86_avx_vtestz_ps:
9573 case Intrinsic::x86_avx_vtestc_ps:
9574 case Intrinsic::x86_avx_vtestnzc_ps:
9575 case Intrinsic::x86_avx_vtestz_pd:
9576 case Intrinsic::x86_avx_vtestc_pd:
9577 case Intrinsic::x86_avx_vtestnzc_pd:
9578 case Intrinsic::x86_avx_vtestz_ps_256:
9579 case Intrinsic::x86_avx_vtestc_ps_256:
9580 case Intrinsic::x86_avx_vtestnzc_ps_256:
9581 case Intrinsic::x86_avx_vtestz_pd_256:
9582 case Intrinsic::x86_avx_vtestc_pd_256:
9583 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9584 bool IsTestPacked = false;
9587 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9588 case Intrinsic::x86_avx_vtestz_ps:
9589 case Intrinsic::x86_avx_vtestz_pd:
9590 case Intrinsic::x86_avx_vtestz_ps_256:
9591 case Intrinsic::x86_avx_vtestz_pd_256:
9592 IsTestPacked = true; // Fallthrough
9593 case Intrinsic::x86_sse41_ptestz:
9594 case Intrinsic::x86_avx_ptestz_256:
9596 X86CC = X86::COND_E;
9598 case Intrinsic::x86_avx_vtestc_ps:
9599 case Intrinsic::x86_avx_vtestc_pd:
9600 case Intrinsic::x86_avx_vtestc_ps_256:
9601 case Intrinsic::x86_avx_vtestc_pd_256:
9602 IsTestPacked = true; // Fallthrough
9603 case Intrinsic::x86_sse41_ptestc:
9604 case Intrinsic::x86_avx_ptestc_256:
9606 X86CC = X86::COND_B;
9608 case Intrinsic::x86_avx_vtestnzc_ps:
9609 case Intrinsic::x86_avx_vtestnzc_pd:
9610 case Intrinsic::x86_avx_vtestnzc_ps_256:
9611 case Intrinsic::x86_avx_vtestnzc_pd_256:
9612 IsTestPacked = true; // Fallthrough
9613 case Intrinsic::x86_sse41_ptestnzc:
9614 case Intrinsic::x86_avx_ptestnzc_256:
9616 X86CC = X86::COND_A;
9620 SDValue LHS = Op.getOperand(1);
9621 SDValue RHS = Op.getOperand(2);
9622 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9623 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9624 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9625 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9626 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9629 // Fix vector shift instructions where the last operand is a non-immediate
9631 case Intrinsic::x86_avx2_pslli_w:
9632 case Intrinsic::x86_avx2_pslli_d:
9633 case Intrinsic::x86_avx2_pslli_q:
9634 case Intrinsic::x86_avx2_psrli_w:
9635 case Intrinsic::x86_avx2_psrli_d:
9636 case Intrinsic::x86_avx2_psrli_q:
9637 case Intrinsic::x86_avx2_psrai_w:
9638 case Intrinsic::x86_avx2_psrai_d:
9639 case Intrinsic::x86_sse2_pslli_w:
9640 case Intrinsic::x86_sse2_pslli_d:
9641 case Intrinsic::x86_sse2_pslli_q:
9642 case Intrinsic::x86_sse2_psrli_w:
9643 case Intrinsic::x86_sse2_psrli_d:
9644 case Intrinsic::x86_sse2_psrli_q:
9645 case Intrinsic::x86_sse2_psrai_w:
9646 case Intrinsic::x86_sse2_psrai_d:
9647 case Intrinsic::x86_mmx_pslli_w:
9648 case Intrinsic::x86_mmx_pslli_d:
9649 case Intrinsic::x86_mmx_pslli_q:
9650 case Intrinsic::x86_mmx_psrli_w:
9651 case Intrinsic::x86_mmx_psrli_d:
9652 case Intrinsic::x86_mmx_psrli_q:
9653 case Intrinsic::x86_mmx_psrai_w:
9654 case Intrinsic::x86_mmx_psrai_d: {
9655 SDValue ShAmt = Op.getOperand(2);
9656 if (isa<ConstantSDNode>(ShAmt))
9659 unsigned NewIntNo = 0;
9660 EVT ShAmtVT = MVT::v4i32;
9662 case Intrinsic::x86_sse2_pslli_w:
9663 NewIntNo = Intrinsic::x86_sse2_psll_w;
9665 case Intrinsic::x86_sse2_pslli_d:
9666 NewIntNo = Intrinsic::x86_sse2_psll_d;
9668 case Intrinsic::x86_sse2_pslli_q:
9669 NewIntNo = Intrinsic::x86_sse2_psll_q;
9671 case Intrinsic::x86_sse2_psrli_w:
9672 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9674 case Intrinsic::x86_sse2_psrli_d:
9675 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9677 case Intrinsic::x86_sse2_psrli_q:
9678 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9680 case Intrinsic::x86_sse2_psrai_w:
9681 NewIntNo = Intrinsic::x86_sse2_psra_w;
9683 case Intrinsic::x86_sse2_psrai_d:
9684 NewIntNo = Intrinsic::x86_sse2_psra_d;
9686 case Intrinsic::x86_avx2_pslli_w:
9687 NewIntNo = Intrinsic::x86_avx2_psll_w;
9689 case Intrinsic::x86_avx2_pslli_d:
9690 NewIntNo = Intrinsic::x86_avx2_psll_d;
9692 case Intrinsic::x86_avx2_pslli_q:
9693 NewIntNo = Intrinsic::x86_avx2_psll_q;
9695 case Intrinsic::x86_avx2_psrli_w:
9696 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9698 case Intrinsic::x86_avx2_psrli_d:
9699 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9701 case Intrinsic::x86_avx2_psrli_q:
9702 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9704 case Intrinsic::x86_avx2_psrai_w:
9705 NewIntNo = Intrinsic::x86_avx2_psra_w;
9707 case Intrinsic::x86_avx2_psrai_d:
9708 NewIntNo = Intrinsic::x86_avx2_psra_d;
9711 ShAmtVT = MVT::v2i32;
9713 case Intrinsic::x86_mmx_pslli_w:
9714 NewIntNo = Intrinsic::x86_mmx_psll_w;
9716 case Intrinsic::x86_mmx_pslli_d:
9717 NewIntNo = Intrinsic::x86_mmx_psll_d;
9719 case Intrinsic::x86_mmx_pslli_q:
9720 NewIntNo = Intrinsic::x86_mmx_psll_q;
9722 case Intrinsic::x86_mmx_psrli_w:
9723 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9725 case Intrinsic::x86_mmx_psrli_d:
9726 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9728 case Intrinsic::x86_mmx_psrli_q:
9729 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9731 case Intrinsic::x86_mmx_psrai_w:
9732 NewIntNo = Intrinsic::x86_mmx_psra_w;
9734 case Intrinsic::x86_mmx_psrai_d:
9735 NewIntNo = Intrinsic::x86_mmx_psra_d;
9737 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9743 // The vector shift intrinsics with scalars uses 32b shift amounts but
9744 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9748 ShOps[1] = DAG.getConstant(0, MVT::i32);
9749 if (ShAmtVT == MVT::v4i32) {
9750 ShOps[2] = DAG.getUNDEF(MVT::i32);
9751 ShOps[3] = DAG.getUNDEF(MVT::i32);
9752 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9754 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9755 // FIXME this must be lowered to get rid of the invalid type.
9758 EVT VT = Op.getValueType();
9759 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9760 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9761 DAG.getConstant(NewIntNo, MVT::i32),
9762 Op.getOperand(1), ShAmt);
9767 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9768 SelectionDAG &DAG) const {
9769 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9770 MFI->setReturnAddressIsTaken(true);
9772 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9773 DebugLoc dl = Op.getDebugLoc();
9776 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9778 DAG.getConstant(TD->getPointerSize(),
9779 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9780 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9781 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9783 MachinePointerInfo(), false, false, false, 0);
9786 // Just load the return address.
9787 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9788 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9789 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9792 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9793 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9794 MFI->setFrameAddressIsTaken(true);
9796 EVT VT = Op.getValueType();
9797 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9798 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9799 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9800 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9802 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9803 MachinePointerInfo(),
9804 false, false, false, 0);
9808 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9809 SelectionDAG &DAG) const {
9810 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9813 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9814 MachineFunction &MF = DAG.getMachineFunction();
9815 SDValue Chain = Op.getOperand(0);
9816 SDValue Offset = Op.getOperand(1);
9817 SDValue Handler = Op.getOperand(2);
9818 DebugLoc dl = Op.getDebugLoc();
9820 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9821 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9823 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9825 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9826 DAG.getIntPtrConstant(TD->getPointerSize()));
9827 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9828 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9830 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9831 MF.getRegInfo().addLiveOut(StoreAddrReg);
9833 return DAG.getNode(X86ISD::EH_RETURN, dl,
9835 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9838 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9839 SelectionDAG &DAG) const {
9840 return Op.getOperand(0);
9843 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9844 SelectionDAG &DAG) const {
9845 SDValue Root = Op.getOperand(0);
9846 SDValue Trmp = Op.getOperand(1); // trampoline
9847 SDValue FPtr = Op.getOperand(2); // nested function
9848 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9849 DebugLoc dl = Op.getDebugLoc();
9851 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9853 if (Subtarget->is64Bit()) {
9854 SDValue OutChains[6];
9856 // Large code-model.
9857 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9858 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9860 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9861 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9863 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9865 // Load the pointer to the nested function into R11.
9866 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9867 SDValue Addr = Trmp;
9868 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9869 Addr, MachinePointerInfo(TrmpAddr),
9872 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9873 DAG.getConstant(2, MVT::i64));
9874 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9875 MachinePointerInfo(TrmpAddr, 2),
9878 // Load the 'nest' parameter value into R10.
9879 // R10 is specified in X86CallingConv.td
9880 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9881 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9882 DAG.getConstant(10, MVT::i64));
9883 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9884 Addr, MachinePointerInfo(TrmpAddr, 10),
9887 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9888 DAG.getConstant(12, MVT::i64));
9889 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9890 MachinePointerInfo(TrmpAddr, 12),
9893 // Jump to the nested function.
9894 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9895 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9896 DAG.getConstant(20, MVT::i64));
9897 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9898 Addr, MachinePointerInfo(TrmpAddr, 20),
9901 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9902 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9903 DAG.getConstant(22, MVT::i64));
9904 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9905 MachinePointerInfo(TrmpAddr, 22),
9908 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9910 const Function *Func =
9911 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9912 CallingConv::ID CC = Func->getCallingConv();
9917 llvm_unreachable("Unsupported calling convention");
9918 case CallingConv::C:
9919 case CallingConv::X86_StdCall: {
9920 // Pass 'nest' parameter in ECX.
9921 // Must be kept in sync with X86CallingConv.td
9924 // Check that ECX wasn't needed by an 'inreg' parameter.
9925 FunctionType *FTy = Func->getFunctionType();
9926 const AttrListPtr &Attrs = Func->getAttributes();
9928 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9929 unsigned InRegCount = 0;
9932 for (FunctionType::param_iterator I = FTy->param_begin(),
9933 E = FTy->param_end(); I != E; ++I, ++Idx)
9934 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9935 // FIXME: should only count parameters that are lowered to integers.
9936 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9938 if (InRegCount > 2) {
9939 report_fatal_error("Nest register in use - reduce number of inreg"
9945 case CallingConv::X86_FastCall:
9946 case CallingConv::X86_ThisCall:
9947 case CallingConv::Fast:
9948 // Pass 'nest' parameter in EAX.
9949 // Must be kept in sync with X86CallingConv.td
9954 SDValue OutChains[4];
9957 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9958 DAG.getConstant(10, MVT::i32));
9959 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9961 // This is storing the opcode for MOV32ri.
9962 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9963 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9964 OutChains[0] = DAG.getStore(Root, dl,
9965 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9966 Trmp, MachinePointerInfo(TrmpAddr),
9969 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9970 DAG.getConstant(1, MVT::i32));
9971 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9972 MachinePointerInfo(TrmpAddr, 1),
9975 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9976 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9977 DAG.getConstant(5, MVT::i32));
9978 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9979 MachinePointerInfo(TrmpAddr, 5),
9982 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9983 DAG.getConstant(6, MVT::i32));
9984 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9985 MachinePointerInfo(TrmpAddr, 6),
9988 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9992 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9993 SelectionDAG &DAG) const {
9995 The rounding mode is in bits 11:10 of FPSR, and has the following
10002 FLT_ROUNDS, on the other hand, expects the following:
10009 To perform the conversion, we do:
10010 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10013 MachineFunction &MF = DAG.getMachineFunction();
10014 const TargetMachine &TM = MF.getTarget();
10015 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10016 unsigned StackAlignment = TFI.getStackAlignment();
10017 EVT VT = Op.getValueType();
10018 DebugLoc DL = Op.getDebugLoc();
10020 // Save FP Control Word to stack slot
10021 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10022 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10025 MachineMemOperand *MMO =
10026 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10027 MachineMemOperand::MOStore, 2, 2);
10029 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10030 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10031 DAG.getVTList(MVT::Other),
10032 Ops, 2, MVT::i16, MMO);
10034 // Load FP Control Word from stack slot
10035 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10036 MachinePointerInfo(), false, false, false, 0);
10038 // Transform as necessary
10040 DAG.getNode(ISD::SRL, DL, MVT::i16,
10041 DAG.getNode(ISD::AND, DL, MVT::i16,
10042 CWD, DAG.getConstant(0x800, MVT::i16)),
10043 DAG.getConstant(11, MVT::i8));
10045 DAG.getNode(ISD::SRL, DL, MVT::i16,
10046 DAG.getNode(ISD::AND, DL, MVT::i16,
10047 CWD, DAG.getConstant(0x400, MVT::i16)),
10048 DAG.getConstant(9, MVT::i8));
10051 DAG.getNode(ISD::AND, DL, MVT::i16,
10052 DAG.getNode(ISD::ADD, DL, MVT::i16,
10053 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10054 DAG.getConstant(1, MVT::i16)),
10055 DAG.getConstant(3, MVT::i16));
10058 return DAG.getNode((VT.getSizeInBits() < 16 ?
10059 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10062 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10063 EVT VT = Op.getValueType();
10065 unsigned NumBits = VT.getSizeInBits();
10066 DebugLoc dl = Op.getDebugLoc();
10068 Op = Op.getOperand(0);
10069 if (VT == MVT::i8) {
10070 // Zero extend to i32 since there is not an i8 bsr.
10072 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10075 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10076 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10077 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10079 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10082 DAG.getConstant(NumBits+NumBits-1, OpVT),
10083 DAG.getConstant(X86::COND_E, MVT::i8),
10086 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10088 // Finally xor with NumBits-1.
10089 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10092 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10096 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10097 EVT VT = Op.getValueType();
10099 unsigned NumBits = VT.getSizeInBits();
10100 DebugLoc dl = Op.getDebugLoc();
10102 Op = Op.getOperand(0);
10103 if (VT == MVT::i8) {
10105 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10108 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10109 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10110 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10112 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10115 DAG.getConstant(NumBits, OpVT),
10116 DAG.getConstant(X86::COND_E, MVT::i8),
10119 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10122 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10126 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10127 // ones, and then concatenate the result back.
10128 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10129 EVT VT = Op.getValueType();
10131 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10132 "Unsupported value type for operation");
10134 int NumElems = VT.getVectorNumElements();
10135 DebugLoc dl = Op.getDebugLoc();
10136 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10137 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10139 // Extract the LHS vectors
10140 SDValue LHS = Op.getOperand(0);
10141 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10142 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10144 // Extract the RHS vectors
10145 SDValue RHS = Op.getOperand(1);
10146 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10147 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10149 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10150 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10152 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10153 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10154 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10157 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10158 assert(Op.getValueType().getSizeInBits() == 256 &&
10159 Op.getValueType().isInteger() &&
10160 "Only handle AVX 256-bit vector integer operation");
10161 return Lower256IntArith(Op, DAG);
10164 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10165 assert(Op.getValueType().getSizeInBits() == 256 &&
10166 Op.getValueType().isInteger() &&
10167 "Only handle AVX 256-bit vector integer operation");
10168 return Lower256IntArith(Op, DAG);
10171 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10172 EVT VT = Op.getValueType();
10174 // Decompose 256-bit ops into smaller 128-bit ops.
10175 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10176 return Lower256IntArith(Op, DAG);
10178 DebugLoc dl = Op.getDebugLoc();
10180 SDValue A = Op.getOperand(0);
10181 SDValue B = Op.getOperand(1);
10183 if (VT == MVT::v4i64) {
10184 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10186 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10187 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10188 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10189 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10190 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10192 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10193 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10194 // return AloBlo + AloBhi + AhiBlo;
10196 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10197 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10198 A, DAG.getConstant(32, MVT::i32));
10199 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10200 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10201 B, DAG.getConstant(32, MVT::i32));
10202 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10203 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10205 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10206 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10208 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10209 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10211 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10212 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10213 AloBhi, DAG.getConstant(32, MVT::i32));
10214 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10215 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10216 AhiBlo, DAG.getConstant(32, MVT::i32));
10217 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10218 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10222 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10224 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10225 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10226 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10227 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10228 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10230 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10231 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10232 // return AloBlo + AloBhi + AhiBlo;
10234 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10235 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10236 A, DAG.getConstant(32, MVT::i32));
10237 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10238 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10239 B, DAG.getConstant(32, MVT::i32));
10240 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10241 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10243 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10244 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10246 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10247 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10249 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10250 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10251 AloBhi, DAG.getConstant(32, MVT::i32));
10252 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10253 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10254 AhiBlo, DAG.getConstant(32, MVT::i32));
10255 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10256 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10260 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10262 EVT VT = Op.getValueType();
10263 DebugLoc dl = Op.getDebugLoc();
10264 SDValue R = Op.getOperand(0);
10265 SDValue Amt = Op.getOperand(1);
10266 LLVMContext *Context = DAG.getContext();
10268 if (!Subtarget->hasXMMInt())
10271 // Optimize shl/srl/sra with constant shift amount.
10272 if (isSplatVector(Amt.getNode())) {
10273 SDValue SclrAmt = Amt->getOperand(0);
10274 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10275 uint64_t ShiftAmt = C->getZExtValue();
10277 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10278 // Make a large shift.
10280 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10281 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10282 R, DAG.getConstant(ShiftAmt, MVT::i32));
10283 // Zero out the rightmost bits.
10284 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10286 return DAG.getNode(ISD::AND, dl, VT, SHL,
10287 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10290 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10291 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10292 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10293 R, DAG.getConstant(ShiftAmt, MVT::i32));
10295 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10296 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10297 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10298 R, DAG.getConstant(ShiftAmt, MVT::i32));
10300 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10301 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10302 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10303 R, DAG.getConstant(ShiftAmt, MVT::i32));
10305 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10306 // Make a large shift.
10308 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10309 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10310 R, DAG.getConstant(ShiftAmt, MVT::i32));
10311 // Zero out the leftmost bits.
10312 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10314 return DAG.getNode(ISD::AND, dl, VT, SRL,
10315 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10318 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10319 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10320 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10321 R, DAG.getConstant(ShiftAmt, MVT::i32));
10323 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10324 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10325 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10326 R, DAG.getConstant(ShiftAmt, MVT::i32));
10328 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10329 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10330 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10331 R, DAG.getConstant(ShiftAmt, MVT::i32));
10333 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10334 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10335 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10336 R, DAG.getConstant(ShiftAmt, MVT::i32));
10338 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10339 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10340 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10341 R, DAG.getConstant(ShiftAmt, MVT::i32));
10343 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10344 if (ShiftAmt == 7) {
10345 // R s>> 7 === R s< 0
10346 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10347 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10350 // R s>> a === ((R u>> a) ^ m) - m
10351 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10352 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10354 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10355 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10356 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10360 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10361 if (Op.getOpcode() == ISD::SHL) {
10362 // Make a large shift.
10364 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10365 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10366 R, DAG.getConstant(ShiftAmt, MVT::i32));
10367 // Zero out the rightmost bits.
10368 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10370 return DAG.getNode(ISD::AND, dl, VT, SHL,
10371 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10373 if (Op.getOpcode() == ISD::SRL) {
10374 // Make a large shift.
10376 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10377 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10378 R, DAG.getConstant(ShiftAmt, MVT::i32));
10379 // Zero out the leftmost bits.
10380 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10382 return DAG.getNode(ISD::AND, dl, VT, SRL,
10383 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10385 if (Op.getOpcode() == ISD::SRA) {
10386 if (ShiftAmt == 7) {
10387 // R s>> 7 === R s< 0
10388 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10389 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10392 // R s>> a === ((R u>> a) ^ m) - m
10393 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10394 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10396 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10397 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10398 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10405 // Lower SHL with variable shift amount.
10406 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10407 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10408 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10409 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10411 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10413 std::vector<Constant*> CV(4, CI);
10414 Constant *C = ConstantVector::get(CV);
10415 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10416 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10417 MachinePointerInfo::getConstantPool(),
10418 false, false, false, 16);
10420 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10421 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10422 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10423 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10425 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10427 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10428 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10429 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10431 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10432 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10434 std::vector<Constant*> CVM1(16, CM1);
10435 std::vector<Constant*> CVM2(16, CM2);
10436 Constant *C = ConstantVector::get(CVM1);
10437 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10438 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10439 MachinePointerInfo::getConstantPool(),
10440 false, false, false, 16);
10442 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10443 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10444 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10445 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10446 DAG.getConstant(4, MVT::i32));
10447 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10449 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10451 C = ConstantVector::get(CVM2);
10452 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10453 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10454 MachinePointerInfo::getConstantPool(),
10455 false, false, false, 16);
10457 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10458 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10459 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10460 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10461 DAG.getConstant(2, MVT::i32));
10462 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10464 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10466 // return pblendv(r, r+r, a);
10467 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10468 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10472 // Decompose 256-bit shifts into smaller 128-bit shifts.
10473 if (VT.getSizeInBits() == 256) {
10474 int NumElems = VT.getVectorNumElements();
10475 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10476 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10478 // Extract the two vectors
10479 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10480 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10483 // Recreate the shift amount vectors
10484 SDValue Amt1, Amt2;
10485 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10486 // Constant shift amount
10487 SmallVector<SDValue, 4> Amt1Csts;
10488 SmallVector<SDValue, 4> Amt2Csts;
10489 for (int i = 0; i < NumElems/2; ++i)
10490 Amt1Csts.push_back(Amt->getOperand(i));
10491 for (int i = NumElems/2; i < NumElems; ++i)
10492 Amt2Csts.push_back(Amt->getOperand(i));
10494 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10495 &Amt1Csts[0], NumElems/2);
10496 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10497 &Amt2Csts[0], NumElems/2);
10499 // Variable shift amount
10500 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10501 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10505 // Issue new vector shifts for the smaller types
10506 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10507 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10509 // Concatenate the result back
10510 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10516 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10517 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10518 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10519 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10520 // has only one use.
10521 SDNode *N = Op.getNode();
10522 SDValue LHS = N->getOperand(0);
10523 SDValue RHS = N->getOperand(1);
10524 unsigned BaseOp = 0;
10526 DebugLoc DL = Op.getDebugLoc();
10527 switch (Op.getOpcode()) {
10528 default: llvm_unreachable("Unknown ovf instruction!");
10530 // A subtract of one will be selected as a INC. Note that INC doesn't
10531 // set CF, so we can't do this for UADDO.
10532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10534 BaseOp = X86ISD::INC;
10535 Cond = X86::COND_O;
10538 BaseOp = X86ISD::ADD;
10539 Cond = X86::COND_O;
10542 BaseOp = X86ISD::ADD;
10543 Cond = X86::COND_B;
10546 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10547 // set CF, so we can't do this for USUBO.
10548 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10550 BaseOp = X86ISD::DEC;
10551 Cond = X86::COND_O;
10554 BaseOp = X86ISD::SUB;
10555 Cond = X86::COND_O;
10558 BaseOp = X86ISD::SUB;
10559 Cond = X86::COND_B;
10562 BaseOp = X86ISD::SMUL;
10563 Cond = X86::COND_O;
10565 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10566 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10568 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10571 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10572 DAG.getConstant(X86::COND_O, MVT::i32),
10573 SDValue(Sum.getNode(), 2));
10575 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10579 // Also sets EFLAGS.
10580 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10581 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10584 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10585 DAG.getConstant(Cond, MVT::i32),
10586 SDValue(Sum.getNode(), 1));
10588 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10591 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10592 DebugLoc dl = Op.getDebugLoc();
10593 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10594 EVT VT = Op.getValueType();
10596 if (Subtarget->hasXMMInt() && VT.isVector()) {
10597 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10598 ExtraVT.getScalarType().getSizeInBits();
10599 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10601 unsigned SHLIntrinsicsID = 0;
10602 unsigned SRAIntrinsicsID = 0;
10603 switch (VT.getSimpleVT().SimpleTy) {
10607 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10608 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10611 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10612 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10616 if (!Subtarget->hasAVX())
10618 if (!Subtarget->hasAVX2()) {
10619 // needs to be split
10620 int NumElems = VT.getVectorNumElements();
10621 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10622 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10624 // Extract the LHS vectors
10625 SDValue LHS = Op.getOperand(0);
10626 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10627 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10629 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10630 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10632 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10633 int ExtraNumElems = ExtraVT.getVectorNumElements();
10634 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10636 SDValue Extra = DAG.getValueType(ExtraVT);
10638 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10639 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10641 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10643 if (VT == MVT::v8i32) {
10644 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10645 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10647 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10648 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10652 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10653 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10654 Op.getOperand(0), ShAmt);
10656 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10657 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10665 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10666 DebugLoc dl = Op.getDebugLoc();
10668 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10669 // There isn't any reason to disable it if the target processor supports it.
10670 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10671 SDValue Chain = Op.getOperand(0);
10672 SDValue Zero = DAG.getConstant(0, MVT::i32);
10674 DAG.getRegister(X86::ESP, MVT::i32), // Base
10675 DAG.getTargetConstant(1, MVT::i8), // Scale
10676 DAG.getRegister(0, MVT::i32), // Index
10677 DAG.getTargetConstant(0, MVT::i32), // Disp
10678 DAG.getRegister(0, MVT::i32), // Segment.
10683 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10684 array_lengthof(Ops));
10685 return SDValue(Res, 0);
10688 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10690 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10692 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10693 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10694 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10695 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10697 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10698 if (!Op1 && !Op2 && !Op3 && Op4)
10699 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10701 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10702 if (Op1 && !Op2 && !Op3 && !Op4)
10703 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10705 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10707 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10710 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10711 SelectionDAG &DAG) const {
10712 DebugLoc dl = Op.getDebugLoc();
10713 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10714 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10715 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10716 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10718 // The only fence that needs an instruction is a sequentially-consistent
10719 // cross-thread fence.
10720 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10721 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10722 // no-sse2). There isn't any reason to disable it if the target processor
10724 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10725 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10727 SDValue Chain = Op.getOperand(0);
10728 SDValue Zero = DAG.getConstant(0, MVT::i32);
10730 DAG.getRegister(X86::ESP, MVT::i32), // Base
10731 DAG.getTargetConstant(1, MVT::i8), // Scale
10732 DAG.getRegister(0, MVT::i32), // Index
10733 DAG.getTargetConstant(0, MVT::i32), // Disp
10734 DAG.getRegister(0, MVT::i32), // Segment.
10739 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10740 array_lengthof(Ops));
10741 return SDValue(Res, 0);
10744 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10745 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10749 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10750 EVT T = Op.getValueType();
10751 DebugLoc DL = Op.getDebugLoc();
10754 switch(T.getSimpleVT().SimpleTy) {
10756 assert(false && "Invalid value type!");
10757 case MVT::i8: Reg = X86::AL; size = 1; break;
10758 case MVT::i16: Reg = X86::AX; size = 2; break;
10759 case MVT::i32: Reg = X86::EAX; size = 4; break;
10761 assert(Subtarget->is64Bit() && "Node not type legal!");
10762 Reg = X86::RAX; size = 8;
10765 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10766 Op.getOperand(2), SDValue());
10767 SDValue Ops[] = { cpIn.getValue(0),
10770 DAG.getTargetConstant(size, MVT::i8),
10771 cpIn.getValue(1) };
10772 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10773 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10774 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10777 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10781 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10782 SelectionDAG &DAG) const {
10783 assert(Subtarget->is64Bit() && "Result not type legalized?");
10784 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10785 SDValue TheChain = Op.getOperand(0);
10786 DebugLoc dl = Op.getDebugLoc();
10787 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10788 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10789 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10791 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10792 DAG.getConstant(32, MVT::i8));
10794 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10797 return DAG.getMergeValues(Ops, 2, dl);
10800 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10801 SelectionDAG &DAG) const {
10802 EVT SrcVT = Op.getOperand(0).getValueType();
10803 EVT DstVT = Op.getValueType();
10804 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10805 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10806 assert((DstVT == MVT::i64 ||
10807 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10808 "Unexpected custom BITCAST");
10809 // i64 <=> MMX conversions are Legal.
10810 if (SrcVT==MVT::i64 && DstVT.isVector())
10812 if (DstVT==MVT::i64 && SrcVT.isVector())
10814 // MMX <=> MMX conversions are Legal.
10815 if (SrcVT.isVector() && DstVT.isVector())
10817 // All other conversions need to be expanded.
10821 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10822 SDNode *Node = Op.getNode();
10823 DebugLoc dl = Node->getDebugLoc();
10824 EVT T = Node->getValueType(0);
10825 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10826 DAG.getConstant(0, T), Node->getOperand(2));
10827 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10828 cast<AtomicSDNode>(Node)->getMemoryVT(),
10829 Node->getOperand(0),
10830 Node->getOperand(1), negOp,
10831 cast<AtomicSDNode>(Node)->getSrcValue(),
10832 cast<AtomicSDNode>(Node)->getAlignment(),
10833 cast<AtomicSDNode>(Node)->getOrdering(),
10834 cast<AtomicSDNode>(Node)->getSynchScope());
10837 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10838 SDNode *Node = Op.getNode();
10839 DebugLoc dl = Node->getDebugLoc();
10840 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10842 // Convert seq_cst store -> xchg
10843 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10844 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10845 // (The only way to get a 16-byte store is cmpxchg16b)
10846 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10847 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10848 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10849 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10850 cast<AtomicSDNode>(Node)->getMemoryVT(),
10851 Node->getOperand(0),
10852 Node->getOperand(1), Node->getOperand(2),
10853 cast<AtomicSDNode>(Node)->getMemOperand(),
10854 cast<AtomicSDNode>(Node)->getOrdering(),
10855 cast<AtomicSDNode>(Node)->getSynchScope());
10856 return Swap.getValue(1);
10858 // Other atomic stores have a simple pattern.
10862 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10863 EVT VT = Op.getNode()->getValueType(0);
10865 // Let legalize expand this if it isn't a legal type yet.
10866 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10869 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10872 bool ExtraOp = false;
10873 switch (Op.getOpcode()) {
10874 default: assert(0 && "Invalid code");
10875 case ISD::ADDC: Opc = X86ISD::ADD; break;
10876 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10877 case ISD::SUBC: Opc = X86ISD::SUB; break;
10878 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10882 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10884 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10885 Op.getOperand(1), Op.getOperand(2));
10888 /// LowerOperation - Provide custom lowering hooks for some operations.
10890 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10891 switch (Op.getOpcode()) {
10892 default: llvm_unreachable("Should not custom lower this!");
10893 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10894 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10895 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10896 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10897 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10898 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10899 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10900 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10901 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10902 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10903 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10904 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10905 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10906 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10907 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10908 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10909 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10910 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10911 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10912 case ISD::SHL_PARTS:
10913 case ISD::SRA_PARTS:
10914 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10915 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10916 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10917 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10918 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10919 case ISD::FABS: return LowerFABS(Op, DAG);
10920 case ISD::FNEG: return LowerFNEG(Op, DAG);
10921 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10922 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10923 case ISD::SETCC: return LowerSETCC(Op, DAG);
10924 case ISD::SELECT: return LowerSELECT(Op, DAG);
10925 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10926 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10927 case ISD::VASTART: return LowerVASTART(Op, DAG);
10928 case ISD::VAARG: return LowerVAARG(Op, DAG);
10929 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10930 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10931 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10932 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10933 case ISD::FRAME_TO_ARGS_OFFSET:
10934 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10935 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10936 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10937 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10938 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10939 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10940 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10941 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10942 case ISD::MUL: return LowerMUL(Op, DAG);
10945 case ISD::SHL: return LowerShift(Op, DAG);
10951 case ISD::UMULO: return LowerXALUO(Op, DAG);
10952 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10953 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10957 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10958 case ISD::ADD: return LowerADD(Op, DAG);
10959 case ISD::SUB: return LowerSUB(Op, DAG);
10963 static void ReplaceATOMIC_LOAD(SDNode *Node,
10964 SmallVectorImpl<SDValue> &Results,
10965 SelectionDAG &DAG) {
10966 DebugLoc dl = Node->getDebugLoc();
10967 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10969 // Convert wide load -> cmpxchg8b/cmpxchg16b
10970 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10971 // (The only way to get a 16-byte load is cmpxchg16b)
10972 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10973 SDValue Zero = DAG.getConstant(0, VT);
10974 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10975 Node->getOperand(0),
10976 Node->getOperand(1), Zero, Zero,
10977 cast<AtomicSDNode>(Node)->getMemOperand(),
10978 cast<AtomicSDNode>(Node)->getOrdering(),
10979 cast<AtomicSDNode>(Node)->getSynchScope());
10980 Results.push_back(Swap.getValue(0));
10981 Results.push_back(Swap.getValue(1));
10984 void X86TargetLowering::
10985 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10986 SelectionDAG &DAG, unsigned NewOp) const {
10987 DebugLoc dl = Node->getDebugLoc();
10988 assert (Node->getValueType(0) == MVT::i64 &&
10989 "Only know how to expand i64 atomics");
10991 SDValue Chain = Node->getOperand(0);
10992 SDValue In1 = Node->getOperand(1);
10993 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10994 Node->getOperand(2), DAG.getIntPtrConstant(0));
10995 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10996 Node->getOperand(2), DAG.getIntPtrConstant(1));
10997 SDValue Ops[] = { Chain, In1, In2L, In2H };
10998 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11000 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11001 cast<MemSDNode>(Node)->getMemOperand());
11002 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11003 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11004 Results.push_back(Result.getValue(2));
11007 /// ReplaceNodeResults - Replace a node with an illegal result type
11008 /// with a new node built out of custom code.
11009 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11010 SmallVectorImpl<SDValue>&Results,
11011 SelectionDAG &DAG) const {
11012 DebugLoc dl = N->getDebugLoc();
11013 switch (N->getOpcode()) {
11015 assert(false && "Do not know how to custom type legalize this operation!");
11017 case ISD::SIGN_EXTEND_INREG:
11022 // We don't want to expand or promote these.
11024 case ISD::FP_TO_SINT: {
11025 std::pair<SDValue,SDValue> Vals =
11026 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11027 SDValue FIST = Vals.first, StackSlot = Vals.second;
11028 if (FIST.getNode() != 0) {
11029 EVT VT = N->getValueType(0);
11030 // Return a load from the stack slot.
11031 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11032 MachinePointerInfo(),
11033 false, false, false, 0));
11037 case ISD::READCYCLECOUNTER: {
11038 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11039 SDValue TheChain = N->getOperand(0);
11040 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11041 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11043 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11045 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11046 SDValue Ops[] = { eax, edx };
11047 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11048 Results.push_back(edx.getValue(1));
11051 case ISD::ATOMIC_CMP_SWAP: {
11052 EVT T = N->getValueType(0);
11053 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11054 bool Regs64bit = T == MVT::i128;
11055 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11056 SDValue cpInL, cpInH;
11057 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11058 DAG.getConstant(0, HalfT));
11059 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11060 DAG.getConstant(1, HalfT));
11061 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11062 Regs64bit ? X86::RAX : X86::EAX,
11064 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11065 Regs64bit ? X86::RDX : X86::EDX,
11066 cpInH, cpInL.getValue(1));
11067 SDValue swapInL, swapInH;
11068 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11069 DAG.getConstant(0, HalfT));
11070 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11071 DAG.getConstant(1, HalfT));
11072 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11073 Regs64bit ? X86::RBX : X86::EBX,
11074 swapInL, cpInH.getValue(1));
11075 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11076 Regs64bit ? X86::RCX : X86::ECX,
11077 swapInH, swapInL.getValue(1));
11078 SDValue Ops[] = { swapInH.getValue(0),
11080 swapInH.getValue(1) };
11081 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11082 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11083 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11084 X86ISD::LCMPXCHG8_DAG;
11085 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11087 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11088 Regs64bit ? X86::RAX : X86::EAX,
11089 HalfT, Result.getValue(1));
11090 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11091 Regs64bit ? X86::RDX : X86::EDX,
11092 HalfT, cpOutL.getValue(2));
11093 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11094 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11095 Results.push_back(cpOutH.getValue(1));
11098 case ISD::ATOMIC_LOAD_ADD:
11099 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11101 case ISD::ATOMIC_LOAD_AND:
11102 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11104 case ISD::ATOMIC_LOAD_NAND:
11105 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11107 case ISD::ATOMIC_LOAD_OR:
11108 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11110 case ISD::ATOMIC_LOAD_SUB:
11111 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11113 case ISD::ATOMIC_LOAD_XOR:
11114 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11116 case ISD::ATOMIC_SWAP:
11117 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11119 case ISD::ATOMIC_LOAD:
11120 ReplaceATOMIC_LOAD(N, Results, DAG);
11124 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11126 default: return NULL;
11127 case X86ISD::BSF: return "X86ISD::BSF";
11128 case X86ISD::BSR: return "X86ISD::BSR";
11129 case X86ISD::SHLD: return "X86ISD::SHLD";
11130 case X86ISD::SHRD: return "X86ISD::SHRD";
11131 case X86ISD::FAND: return "X86ISD::FAND";
11132 case X86ISD::FOR: return "X86ISD::FOR";
11133 case X86ISD::FXOR: return "X86ISD::FXOR";
11134 case X86ISD::FSRL: return "X86ISD::FSRL";
11135 case X86ISD::FILD: return "X86ISD::FILD";
11136 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11137 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11138 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11139 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11140 case X86ISD::FLD: return "X86ISD::FLD";
11141 case X86ISD::FST: return "X86ISD::FST";
11142 case X86ISD::CALL: return "X86ISD::CALL";
11143 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11144 case X86ISD::BT: return "X86ISD::BT";
11145 case X86ISD::CMP: return "X86ISD::CMP";
11146 case X86ISD::COMI: return "X86ISD::COMI";
11147 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11148 case X86ISD::SETCC: return "X86ISD::SETCC";
11149 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11150 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11151 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11152 case X86ISD::CMOV: return "X86ISD::CMOV";
11153 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11154 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11155 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11156 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11157 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11158 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11159 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11160 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11161 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11162 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11163 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11164 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11165 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11166 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11167 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11168 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11169 case X86ISD::FHADD: return "X86ISD::FHADD";
11170 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11171 case X86ISD::FMAX: return "X86ISD::FMAX";
11172 case X86ISD::FMIN: return "X86ISD::FMIN";
11173 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11174 case X86ISD::FRCP: return "X86ISD::FRCP";
11175 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11176 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11177 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11178 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11179 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11180 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11181 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11182 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11183 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11184 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11185 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11186 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11187 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11188 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11189 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11190 case X86ISD::VSHL: return "X86ISD::VSHL";
11191 case X86ISD::VSRL: return "X86ISD::VSRL";
11192 case X86ISD::CMPPD: return "X86ISD::CMPPD";
11193 case X86ISD::CMPPS: return "X86ISD::CMPPS";
11194 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
11195 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
11196 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
11197 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
11198 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
11199 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
11200 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
11201 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
11202 case X86ISD::ADD: return "X86ISD::ADD";
11203 case X86ISD::SUB: return "X86ISD::SUB";
11204 case X86ISD::ADC: return "X86ISD::ADC";
11205 case X86ISD::SBB: return "X86ISD::SBB";
11206 case X86ISD::SMUL: return "X86ISD::SMUL";
11207 case X86ISD::UMUL: return "X86ISD::UMUL";
11208 case X86ISD::INC: return "X86ISD::INC";
11209 case X86ISD::DEC: return "X86ISD::DEC";
11210 case X86ISD::OR: return "X86ISD::OR";
11211 case X86ISD::XOR: return "X86ISD::XOR";
11212 case X86ISD::AND: return "X86ISD::AND";
11213 case X86ISD::ANDN: return "X86ISD::ANDN";
11214 case X86ISD::BLSI: return "X86ISD::BLSI";
11215 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11216 case X86ISD::BLSR: return "X86ISD::BLSR";
11217 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11218 case X86ISD::PTEST: return "X86ISD::PTEST";
11219 case X86ISD::TESTP: return "X86ISD::TESTP";
11220 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11221 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11222 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11223 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11224 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11225 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11226 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
11227 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
11228 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11229 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11230 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11231 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
11232 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11233 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11234 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11235 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11236 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11237 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11238 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11239 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11240 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11241 case X86ISD::UNPCKLP: return "X86ISD::UNPCKLP";
11242 case X86ISD::UNPCKHP: return "X86ISD::UNPCKHP";
11243 case X86ISD::PUNPCKL: return "X86ISD::PUNPCKL";
11244 case X86ISD::PUNPCKH: return "X86ISD::PUNPCKH";
11245 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11246 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
11247 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
11248 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
11249 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
11250 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
11251 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11252 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11253 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11254 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11255 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11259 // isLegalAddressingMode - Return true if the addressing mode represented
11260 // by AM is legal for this target, for a load/store of the specified type.
11261 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11263 // X86 supports extremely general addressing modes.
11264 CodeModel::Model M = getTargetMachine().getCodeModel();
11265 Reloc::Model R = getTargetMachine().getRelocationModel();
11267 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11268 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11273 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11275 // If a reference to this global requires an extra load, we can't fold it.
11276 if (isGlobalStubReference(GVFlags))
11279 // If BaseGV requires a register for the PIC base, we cannot also have a
11280 // BaseReg specified.
11281 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11284 // If lower 4G is not available, then we must use rip-relative addressing.
11285 if ((M != CodeModel::Small || R != Reloc::Static) &&
11286 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11290 switch (AM.Scale) {
11296 // These scales always work.
11301 // These scales are formed with basereg+scalereg. Only accept if there is
11306 default: // Other stuff never works.
11314 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11315 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11317 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11318 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11319 if (NumBits1 <= NumBits2)
11324 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11325 if (!VT1.isInteger() || !VT2.isInteger())
11327 unsigned NumBits1 = VT1.getSizeInBits();
11328 unsigned NumBits2 = VT2.getSizeInBits();
11329 if (NumBits1 <= NumBits2)
11334 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11335 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11336 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11339 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11340 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11341 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11344 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11345 // i16 instructions are longer (0x66 prefix) and potentially slower.
11346 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11349 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11350 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11351 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11352 /// are assumed to be legal.
11354 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11356 // Very little shuffling can be done for 64-bit vectors right now.
11357 if (VT.getSizeInBits() == 64)
11358 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11360 // FIXME: pshufb, blends, shifts.
11361 return (VT.getVectorNumElements() == 2 ||
11362 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11363 isMOVLMask(M, VT) ||
11364 isSHUFPMask(M, VT) ||
11365 isPSHUFDMask(M, VT) ||
11366 isPSHUFHWMask(M, VT) ||
11367 isPSHUFLWMask(M, VT) ||
11368 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11369 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11370 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11371 isUNPCKL_v_undef_Mask(M, VT) ||
11372 isUNPCKH_v_undef_Mask(M, VT));
11376 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11378 unsigned NumElts = VT.getVectorNumElements();
11379 // FIXME: This collection of masks seems suspect.
11382 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11383 return (isMOVLMask(Mask, VT) ||
11384 isCommutedMOVLMask(Mask, VT, true) ||
11385 isSHUFPMask(Mask, VT) ||
11386 isCommutedSHUFPMask(Mask, VT));
11391 //===----------------------------------------------------------------------===//
11392 // X86 Scheduler Hooks
11393 //===----------------------------------------------------------------------===//
11395 // private utility function
11396 MachineBasicBlock *
11397 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11398 MachineBasicBlock *MBB,
11405 TargetRegisterClass *RC,
11406 bool invSrc) const {
11407 // For the atomic bitwise operator, we generate
11410 // ld t1 = [bitinstr.addr]
11411 // op t2 = t1, [bitinstr.val]
11413 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11415 // fallthrough -->nextMBB
11416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11417 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11418 MachineFunction::iterator MBBIter = MBB;
11421 /// First build the CFG
11422 MachineFunction *F = MBB->getParent();
11423 MachineBasicBlock *thisMBB = MBB;
11424 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11425 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11426 F->insert(MBBIter, newMBB);
11427 F->insert(MBBIter, nextMBB);
11429 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11430 nextMBB->splice(nextMBB->begin(), thisMBB,
11431 llvm::next(MachineBasicBlock::iterator(bInstr)),
11433 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11435 // Update thisMBB to fall through to newMBB
11436 thisMBB->addSuccessor(newMBB);
11438 // newMBB jumps to itself and fall through to nextMBB
11439 newMBB->addSuccessor(nextMBB);
11440 newMBB->addSuccessor(newMBB);
11442 // Insert instructions into newMBB based on incoming instruction
11443 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11444 "unexpected number of operands");
11445 DebugLoc dl = bInstr->getDebugLoc();
11446 MachineOperand& destOper = bInstr->getOperand(0);
11447 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11448 int numArgs = bInstr->getNumOperands() - 1;
11449 for (int i=0; i < numArgs; ++i)
11450 argOpers[i] = &bInstr->getOperand(i+1);
11452 // x86 address has 4 operands: base, index, scale, and displacement
11453 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11454 int valArgIndx = lastAddrIndx + 1;
11456 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11457 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11458 for (int i=0; i <= lastAddrIndx; ++i)
11459 (*MIB).addOperand(*argOpers[i]);
11461 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11463 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11468 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11469 assert((argOpers[valArgIndx]->isReg() ||
11470 argOpers[valArgIndx]->isImm()) &&
11471 "invalid operand");
11472 if (argOpers[valArgIndx]->isReg())
11473 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11475 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11477 (*MIB).addOperand(*argOpers[valArgIndx]);
11479 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11482 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11483 for (int i=0; i <= lastAddrIndx; ++i)
11484 (*MIB).addOperand(*argOpers[i]);
11486 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11487 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11488 bInstr->memoperands_end());
11490 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11491 MIB.addReg(EAXreg);
11494 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11496 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11500 // private utility function: 64 bit atomics on 32 bit host.
11501 MachineBasicBlock *
11502 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11503 MachineBasicBlock *MBB,
11508 bool invSrc) const {
11509 // For the atomic bitwise operator, we generate
11510 // thisMBB (instructions are in pairs, except cmpxchg8b)
11511 // ld t1,t2 = [bitinstr.addr]
11513 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11514 // op t5, t6 <- out1, out2, [bitinstr.val]
11515 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11516 // mov ECX, EBX <- t5, t6
11517 // mov EAX, EDX <- t1, t2
11518 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11519 // mov t3, t4 <- EAX, EDX
11521 // result in out1, out2
11522 // fallthrough -->nextMBB
11524 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11525 const unsigned LoadOpc = X86::MOV32rm;
11526 const unsigned NotOpc = X86::NOT32r;
11527 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11528 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11529 MachineFunction::iterator MBBIter = MBB;
11532 /// First build the CFG
11533 MachineFunction *F = MBB->getParent();
11534 MachineBasicBlock *thisMBB = MBB;
11535 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11536 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11537 F->insert(MBBIter, newMBB);
11538 F->insert(MBBIter, nextMBB);
11540 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11541 nextMBB->splice(nextMBB->begin(), thisMBB,
11542 llvm::next(MachineBasicBlock::iterator(bInstr)),
11544 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11546 // Update thisMBB to fall through to newMBB
11547 thisMBB->addSuccessor(newMBB);
11549 // newMBB jumps to itself and fall through to nextMBB
11550 newMBB->addSuccessor(nextMBB);
11551 newMBB->addSuccessor(newMBB);
11553 DebugLoc dl = bInstr->getDebugLoc();
11554 // Insert instructions into newMBB based on incoming instruction
11555 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11556 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11557 "unexpected number of operands");
11558 MachineOperand& dest1Oper = bInstr->getOperand(0);
11559 MachineOperand& dest2Oper = bInstr->getOperand(1);
11560 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11561 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11562 argOpers[i] = &bInstr->getOperand(i+2);
11564 // We use some of the operands multiple times, so conservatively just
11565 // clear any kill flags that might be present.
11566 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11567 argOpers[i]->setIsKill(false);
11570 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11571 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11573 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11574 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11575 for (int i=0; i <= lastAddrIndx; ++i)
11576 (*MIB).addOperand(*argOpers[i]);
11577 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11578 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11579 // add 4 to displacement.
11580 for (int i=0; i <= lastAddrIndx-2; ++i)
11581 (*MIB).addOperand(*argOpers[i]);
11582 MachineOperand newOp3 = *(argOpers[3]);
11583 if (newOp3.isImm())
11584 newOp3.setImm(newOp3.getImm()+4);
11586 newOp3.setOffset(newOp3.getOffset()+4);
11587 (*MIB).addOperand(newOp3);
11588 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11590 // t3/4 are defined later, at the bottom of the loop
11591 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11592 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11593 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11594 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11595 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11596 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11598 // The subsequent operations should be using the destination registers of
11599 //the PHI instructions.
11601 t1 = F->getRegInfo().createVirtualRegister(RC);
11602 t2 = F->getRegInfo().createVirtualRegister(RC);
11603 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11604 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11606 t1 = dest1Oper.getReg();
11607 t2 = dest2Oper.getReg();
11610 int valArgIndx = lastAddrIndx + 1;
11611 assert((argOpers[valArgIndx]->isReg() ||
11612 argOpers[valArgIndx]->isImm()) &&
11613 "invalid operand");
11614 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11615 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11616 if (argOpers[valArgIndx]->isReg())
11617 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11619 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11620 if (regOpcL != X86::MOV32rr)
11622 (*MIB).addOperand(*argOpers[valArgIndx]);
11623 assert(argOpers[valArgIndx + 1]->isReg() ==
11624 argOpers[valArgIndx]->isReg());
11625 assert(argOpers[valArgIndx + 1]->isImm() ==
11626 argOpers[valArgIndx]->isImm());
11627 if (argOpers[valArgIndx + 1]->isReg())
11628 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11630 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11631 if (regOpcH != X86::MOV32rr)
11633 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11635 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11637 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11640 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11642 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11645 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11646 for (int i=0; i <= lastAddrIndx; ++i)
11647 (*MIB).addOperand(*argOpers[i]);
11649 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11650 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11651 bInstr->memoperands_end());
11653 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11654 MIB.addReg(X86::EAX);
11655 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11656 MIB.addReg(X86::EDX);
11659 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11661 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11665 // private utility function
11666 MachineBasicBlock *
11667 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11668 MachineBasicBlock *MBB,
11669 unsigned cmovOpc) const {
11670 // For the atomic min/max operator, we generate
11673 // ld t1 = [min/max.addr]
11674 // mov t2 = [min/max.val]
11676 // cmov[cond] t2 = t1
11678 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11680 // fallthrough -->nextMBB
11682 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11683 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11684 MachineFunction::iterator MBBIter = MBB;
11687 /// First build the CFG
11688 MachineFunction *F = MBB->getParent();
11689 MachineBasicBlock *thisMBB = MBB;
11690 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11691 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11692 F->insert(MBBIter, newMBB);
11693 F->insert(MBBIter, nextMBB);
11695 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11696 nextMBB->splice(nextMBB->begin(), thisMBB,
11697 llvm::next(MachineBasicBlock::iterator(mInstr)),
11699 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11701 // Update thisMBB to fall through to newMBB
11702 thisMBB->addSuccessor(newMBB);
11704 // newMBB jumps to newMBB and fall through to nextMBB
11705 newMBB->addSuccessor(nextMBB);
11706 newMBB->addSuccessor(newMBB);
11708 DebugLoc dl = mInstr->getDebugLoc();
11709 // Insert instructions into newMBB based on incoming instruction
11710 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11711 "unexpected number of operands");
11712 MachineOperand& destOper = mInstr->getOperand(0);
11713 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11714 int numArgs = mInstr->getNumOperands() - 1;
11715 for (int i=0; i < numArgs; ++i)
11716 argOpers[i] = &mInstr->getOperand(i+1);
11718 // x86 address has 4 operands: base, index, scale, and displacement
11719 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11720 int valArgIndx = lastAddrIndx + 1;
11722 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11723 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11724 for (int i=0; i <= lastAddrIndx; ++i)
11725 (*MIB).addOperand(*argOpers[i]);
11727 // We only support register and immediate values
11728 assert((argOpers[valArgIndx]->isReg() ||
11729 argOpers[valArgIndx]->isImm()) &&
11730 "invalid operand");
11732 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11733 if (argOpers[valArgIndx]->isReg())
11734 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11736 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11737 (*MIB).addOperand(*argOpers[valArgIndx]);
11739 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11742 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11747 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11748 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11752 // Cmp and exchange if none has modified the memory location
11753 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11754 for (int i=0; i <= lastAddrIndx; ++i)
11755 (*MIB).addOperand(*argOpers[i]);
11757 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11758 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11759 mInstr->memoperands_end());
11761 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11762 MIB.addReg(X86::EAX);
11765 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11767 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11771 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11772 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11773 // in the .td file.
11774 MachineBasicBlock *
11775 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11776 unsigned numArgs, bool memArg) const {
11777 assert(Subtarget->hasSSE42orAVX() &&
11778 "Target must have SSE4.2 or AVX features enabled");
11780 DebugLoc dl = MI->getDebugLoc();
11781 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11783 if (!Subtarget->hasAVX()) {
11785 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11787 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11790 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11792 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11795 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11796 for (unsigned i = 0; i < numArgs; ++i) {
11797 MachineOperand &Op = MI->getOperand(i+1);
11798 if (!(Op.isReg() && Op.isImplicit()))
11799 MIB.addOperand(Op);
11801 BuildMI(*BB, MI, dl,
11802 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11803 MI->getOperand(0).getReg())
11804 .addReg(X86::XMM0);
11806 MI->eraseFromParent();
11810 MachineBasicBlock *
11811 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11812 DebugLoc dl = MI->getDebugLoc();
11813 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11815 // Address into RAX/EAX, other two args into ECX, EDX.
11816 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11817 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11818 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11819 for (int i = 0; i < X86::AddrNumOperands; ++i)
11820 MIB.addOperand(MI->getOperand(i));
11822 unsigned ValOps = X86::AddrNumOperands;
11823 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11824 .addReg(MI->getOperand(ValOps).getReg());
11825 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11826 .addReg(MI->getOperand(ValOps+1).getReg());
11828 // The instruction doesn't actually take any operands though.
11829 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11831 MI->eraseFromParent(); // The pseudo is gone now.
11835 MachineBasicBlock *
11836 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11837 DebugLoc dl = MI->getDebugLoc();
11838 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11840 // First arg in ECX, the second in EAX.
11841 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11842 .addReg(MI->getOperand(0).getReg());
11843 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11844 .addReg(MI->getOperand(1).getReg());
11846 // The instruction doesn't actually take any operands though.
11847 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11849 MI->eraseFromParent(); // The pseudo is gone now.
11853 MachineBasicBlock *
11854 X86TargetLowering::EmitVAARG64WithCustomInserter(
11856 MachineBasicBlock *MBB) const {
11857 // Emit va_arg instruction on X86-64.
11859 // Operands to this pseudo-instruction:
11860 // 0 ) Output : destination address (reg)
11861 // 1-5) Input : va_list address (addr, i64mem)
11862 // 6 ) ArgSize : Size (in bytes) of vararg type
11863 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11864 // 8 ) Align : Alignment of type
11865 // 9 ) EFLAGS (implicit-def)
11867 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11868 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11870 unsigned DestReg = MI->getOperand(0).getReg();
11871 MachineOperand &Base = MI->getOperand(1);
11872 MachineOperand &Scale = MI->getOperand(2);
11873 MachineOperand &Index = MI->getOperand(3);
11874 MachineOperand &Disp = MI->getOperand(4);
11875 MachineOperand &Segment = MI->getOperand(5);
11876 unsigned ArgSize = MI->getOperand(6).getImm();
11877 unsigned ArgMode = MI->getOperand(7).getImm();
11878 unsigned Align = MI->getOperand(8).getImm();
11880 // Memory Reference
11881 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11882 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11883 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11885 // Machine Information
11886 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11888 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11889 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11890 DebugLoc DL = MI->getDebugLoc();
11892 // struct va_list {
11895 // i64 overflow_area (address)
11896 // i64 reg_save_area (address)
11898 // sizeof(va_list) = 24
11899 // alignment(va_list) = 8
11901 unsigned TotalNumIntRegs = 6;
11902 unsigned TotalNumXMMRegs = 8;
11903 bool UseGPOffset = (ArgMode == 1);
11904 bool UseFPOffset = (ArgMode == 2);
11905 unsigned MaxOffset = TotalNumIntRegs * 8 +
11906 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11908 /* Align ArgSize to a multiple of 8 */
11909 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11910 bool NeedsAlign = (Align > 8);
11912 MachineBasicBlock *thisMBB = MBB;
11913 MachineBasicBlock *overflowMBB;
11914 MachineBasicBlock *offsetMBB;
11915 MachineBasicBlock *endMBB;
11917 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11918 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11919 unsigned OffsetReg = 0;
11921 if (!UseGPOffset && !UseFPOffset) {
11922 // If we only pull from the overflow region, we don't create a branch.
11923 // We don't need to alter control flow.
11924 OffsetDestReg = 0; // unused
11925 OverflowDestReg = DestReg;
11928 overflowMBB = thisMBB;
11931 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11932 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11933 // If not, pull from overflow_area. (branch to overflowMBB)
11938 // offsetMBB overflowMBB
11943 // Registers for the PHI in endMBB
11944 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11945 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11947 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11948 MachineFunction *MF = MBB->getParent();
11949 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11950 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11951 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11953 MachineFunction::iterator MBBIter = MBB;
11956 // Insert the new basic blocks
11957 MF->insert(MBBIter, offsetMBB);
11958 MF->insert(MBBIter, overflowMBB);
11959 MF->insert(MBBIter, endMBB);
11961 // Transfer the remainder of MBB and its successor edges to endMBB.
11962 endMBB->splice(endMBB->begin(), thisMBB,
11963 llvm::next(MachineBasicBlock::iterator(MI)),
11965 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11967 // Make offsetMBB and overflowMBB successors of thisMBB
11968 thisMBB->addSuccessor(offsetMBB);
11969 thisMBB->addSuccessor(overflowMBB);
11971 // endMBB is a successor of both offsetMBB and overflowMBB
11972 offsetMBB->addSuccessor(endMBB);
11973 overflowMBB->addSuccessor(endMBB);
11975 // Load the offset value into a register
11976 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11977 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11981 .addDisp(Disp, UseFPOffset ? 4 : 0)
11982 .addOperand(Segment)
11983 .setMemRefs(MMOBegin, MMOEnd);
11985 // Check if there is enough room left to pull this argument.
11986 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11988 .addImm(MaxOffset + 8 - ArgSizeA8);
11990 // Branch to "overflowMBB" if offset >= max
11991 // Fall through to "offsetMBB" otherwise
11992 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11993 .addMBB(overflowMBB);
11996 // In offsetMBB, emit code to use the reg_save_area.
11998 assert(OffsetReg != 0);
12000 // Read the reg_save_area address.
12001 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12002 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12007 .addOperand(Segment)
12008 .setMemRefs(MMOBegin, MMOEnd);
12010 // Zero-extend the offset
12011 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12012 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12015 .addImm(X86::sub_32bit);
12017 // Add the offset to the reg_save_area to get the final address.
12018 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12019 .addReg(OffsetReg64)
12020 .addReg(RegSaveReg);
12022 // Compute the offset for the next argument
12023 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12024 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12026 .addImm(UseFPOffset ? 16 : 8);
12028 // Store it back into the va_list.
12029 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12033 .addDisp(Disp, UseFPOffset ? 4 : 0)
12034 .addOperand(Segment)
12035 .addReg(NextOffsetReg)
12036 .setMemRefs(MMOBegin, MMOEnd);
12039 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12044 // Emit code to use overflow area
12047 // Load the overflow_area address into a register.
12048 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12049 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12054 .addOperand(Segment)
12055 .setMemRefs(MMOBegin, MMOEnd);
12057 // If we need to align it, do so. Otherwise, just copy the address
12058 // to OverflowDestReg.
12060 // Align the overflow address
12061 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12062 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12064 // aligned_addr = (addr + (align-1)) & ~(align-1)
12065 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12066 .addReg(OverflowAddrReg)
12069 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12071 .addImm(~(uint64_t)(Align-1));
12073 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12074 .addReg(OverflowAddrReg);
12077 // Compute the next overflow address after this argument.
12078 // (the overflow address should be kept 8-byte aligned)
12079 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12080 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12081 .addReg(OverflowDestReg)
12082 .addImm(ArgSizeA8);
12084 // Store the new overflow address.
12085 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12090 .addOperand(Segment)
12091 .addReg(NextAddrReg)
12092 .setMemRefs(MMOBegin, MMOEnd);
12094 // If we branched, emit the PHI to the front of endMBB.
12096 BuildMI(*endMBB, endMBB->begin(), DL,
12097 TII->get(X86::PHI), DestReg)
12098 .addReg(OffsetDestReg).addMBB(offsetMBB)
12099 .addReg(OverflowDestReg).addMBB(overflowMBB);
12102 // Erase the pseudo instruction
12103 MI->eraseFromParent();
12108 MachineBasicBlock *
12109 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12111 MachineBasicBlock *MBB) const {
12112 // Emit code to save XMM registers to the stack. The ABI says that the
12113 // number of registers to save is given in %al, so it's theoretically
12114 // possible to do an indirect jump trick to avoid saving all of them,
12115 // however this code takes a simpler approach and just executes all
12116 // of the stores if %al is non-zero. It's less code, and it's probably
12117 // easier on the hardware branch predictor, and stores aren't all that
12118 // expensive anyway.
12120 // Create the new basic blocks. One block contains all the XMM stores,
12121 // and one block is the final destination regardless of whether any
12122 // stores were performed.
12123 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12124 MachineFunction *F = MBB->getParent();
12125 MachineFunction::iterator MBBIter = MBB;
12127 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12128 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12129 F->insert(MBBIter, XMMSaveMBB);
12130 F->insert(MBBIter, EndMBB);
12132 // Transfer the remainder of MBB and its successor edges to EndMBB.
12133 EndMBB->splice(EndMBB->begin(), MBB,
12134 llvm::next(MachineBasicBlock::iterator(MI)),
12136 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12138 // The original block will now fall through to the XMM save block.
12139 MBB->addSuccessor(XMMSaveMBB);
12140 // The XMMSaveMBB will fall through to the end block.
12141 XMMSaveMBB->addSuccessor(EndMBB);
12143 // Now add the instructions.
12144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12145 DebugLoc DL = MI->getDebugLoc();
12147 unsigned CountReg = MI->getOperand(0).getReg();
12148 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12149 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12151 if (!Subtarget->isTargetWin64()) {
12152 // If %al is 0, branch around the XMM save block.
12153 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12154 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12155 MBB->addSuccessor(EndMBB);
12158 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12159 // In the XMM save block, save all the XMM argument registers.
12160 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12161 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12162 MachineMemOperand *MMO =
12163 F->getMachineMemOperand(
12164 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12165 MachineMemOperand::MOStore,
12166 /*Size=*/16, /*Align=*/16);
12167 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12168 .addFrameIndex(RegSaveFrameIndex)
12169 .addImm(/*Scale=*/1)
12170 .addReg(/*IndexReg=*/0)
12171 .addImm(/*Disp=*/Offset)
12172 .addReg(/*Segment=*/0)
12173 .addReg(MI->getOperand(i).getReg())
12174 .addMemOperand(MMO);
12177 MI->eraseFromParent(); // The pseudo instruction is gone now.
12182 MachineBasicBlock *
12183 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12184 MachineBasicBlock *BB) const {
12185 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12186 DebugLoc DL = MI->getDebugLoc();
12188 // To "insert" a SELECT_CC instruction, we actually have to insert the
12189 // diamond control-flow pattern. The incoming instruction knows the
12190 // destination vreg to set, the condition code register to branch on, the
12191 // true/false values to select between, and a branch opcode to use.
12192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12193 MachineFunction::iterator It = BB;
12199 // cmpTY ccX, r1, r2
12201 // fallthrough --> copy0MBB
12202 MachineBasicBlock *thisMBB = BB;
12203 MachineFunction *F = BB->getParent();
12204 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12205 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12206 F->insert(It, copy0MBB);
12207 F->insert(It, sinkMBB);
12209 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12210 // live into the sink and copy blocks.
12211 if (!MI->killsRegister(X86::EFLAGS)) {
12212 copy0MBB->addLiveIn(X86::EFLAGS);
12213 sinkMBB->addLiveIn(X86::EFLAGS);
12216 // Transfer the remainder of BB and its successor edges to sinkMBB.
12217 sinkMBB->splice(sinkMBB->begin(), BB,
12218 llvm::next(MachineBasicBlock::iterator(MI)),
12220 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12222 // Add the true and fallthrough blocks as its successors.
12223 BB->addSuccessor(copy0MBB);
12224 BB->addSuccessor(sinkMBB);
12226 // Create the conditional branch instruction.
12228 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12229 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12232 // %FalseValue = ...
12233 // # fallthrough to sinkMBB
12234 copy0MBB->addSuccessor(sinkMBB);
12237 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12239 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12240 TII->get(X86::PHI), MI->getOperand(0).getReg())
12241 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12242 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12244 MI->eraseFromParent(); // The pseudo instruction is gone now.
12248 MachineBasicBlock *
12249 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12250 bool Is64Bit) const {
12251 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12252 DebugLoc DL = MI->getDebugLoc();
12253 MachineFunction *MF = BB->getParent();
12254 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12256 assert(EnableSegmentedStacks);
12258 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12259 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12262 // ... [Till the alloca]
12263 // If stacklet is not large enough, jump to mallocMBB
12266 // Allocate by subtracting from RSP
12267 // Jump to continueMBB
12270 // Allocate by call to runtime
12274 // [rest of original BB]
12277 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12278 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12279 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12281 MachineRegisterInfo &MRI = MF->getRegInfo();
12282 const TargetRegisterClass *AddrRegClass =
12283 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12285 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12286 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12287 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12288 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12289 sizeVReg = MI->getOperand(1).getReg(),
12290 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12292 MachineFunction::iterator MBBIter = BB;
12295 MF->insert(MBBIter, bumpMBB);
12296 MF->insert(MBBIter, mallocMBB);
12297 MF->insert(MBBIter, continueMBB);
12299 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12300 (MachineBasicBlock::iterator(MI)), BB->end());
12301 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12303 // Add code to the main basic block to check if the stack limit has been hit,
12304 // and if so, jump to mallocMBB otherwise to bumpMBB.
12305 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12306 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12307 .addReg(tmpSPVReg).addReg(sizeVReg);
12308 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12309 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12310 .addReg(SPLimitVReg);
12311 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12313 // bumpMBB simply decreases the stack pointer, since we know the current
12314 // stacklet has enough space.
12315 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12316 .addReg(SPLimitVReg);
12317 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12318 .addReg(SPLimitVReg);
12319 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12321 // Calls into a routine in libgcc to allocate more space from the heap.
12323 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12325 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12326 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12328 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12330 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12331 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12332 .addExternalSymbol("__morestack_allocate_stack_space");
12336 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12339 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12340 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12341 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12343 // Set up the CFG correctly.
12344 BB->addSuccessor(bumpMBB);
12345 BB->addSuccessor(mallocMBB);
12346 mallocMBB->addSuccessor(continueMBB);
12347 bumpMBB->addSuccessor(continueMBB);
12349 // Take care of the PHI nodes.
12350 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12351 MI->getOperand(0).getReg())
12352 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12353 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12355 // Delete the original pseudo instruction.
12356 MI->eraseFromParent();
12359 return continueMBB;
12362 MachineBasicBlock *
12363 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12364 MachineBasicBlock *BB) const {
12365 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12366 DebugLoc DL = MI->getDebugLoc();
12368 assert(!Subtarget->isTargetEnvMacho());
12370 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12371 // non-trivial part is impdef of ESP.
12373 if (Subtarget->isTargetWin64()) {
12374 if (Subtarget->isTargetCygMing()) {
12375 // ___chkstk(Mingw64):
12376 // Clobbers R10, R11, RAX and EFLAGS.
12378 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12379 .addExternalSymbol("___chkstk")
12380 .addReg(X86::RAX, RegState::Implicit)
12381 .addReg(X86::RSP, RegState::Implicit)
12382 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12383 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12384 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12386 // __chkstk(MSVCRT): does not update stack pointer.
12387 // Clobbers R10, R11 and EFLAGS.
12388 // FIXME: RAX(allocated size) might be reused and not killed.
12389 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12390 .addExternalSymbol("__chkstk")
12391 .addReg(X86::RAX, RegState::Implicit)
12392 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12393 // RAX has the offset to subtracted from RSP.
12394 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12399 const char *StackProbeSymbol =
12400 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12402 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12403 .addExternalSymbol(StackProbeSymbol)
12404 .addReg(X86::EAX, RegState::Implicit)
12405 .addReg(X86::ESP, RegState::Implicit)
12406 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12407 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12408 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12411 MI->eraseFromParent(); // The pseudo instruction is gone now.
12415 MachineBasicBlock *
12416 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12417 MachineBasicBlock *BB) const {
12418 // This is pretty easy. We're taking the value that we received from
12419 // our load from the relocation, sticking it in either RDI (x86-64)
12420 // or EAX and doing an indirect call. The return value will then
12421 // be in the normal return register.
12422 const X86InstrInfo *TII
12423 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12424 DebugLoc DL = MI->getDebugLoc();
12425 MachineFunction *F = BB->getParent();
12427 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12428 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12430 if (Subtarget->is64Bit()) {
12431 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12432 TII->get(X86::MOV64rm), X86::RDI)
12434 .addImm(0).addReg(0)
12435 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12436 MI->getOperand(3).getTargetFlags())
12438 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12439 addDirectMem(MIB, X86::RDI);
12440 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12441 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12442 TII->get(X86::MOV32rm), X86::EAX)
12444 .addImm(0).addReg(0)
12445 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12446 MI->getOperand(3).getTargetFlags())
12448 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12449 addDirectMem(MIB, X86::EAX);
12451 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12452 TII->get(X86::MOV32rm), X86::EAX)
12453 .addReg(TII->getGlobalBaseReg(F))
12454 .addImm(0).addReg(0)
12455 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12456 MI->getOperand(3).getTargetFlags())
12458 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12459 addDirectMem(MIB, X86::EAX);
12462 MI->eraseFromParent(); // The pseudo instruction is gone now.
12466 MachineBasicBlock *
12467 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12468 MachineBasicBlock *BB) const {
12469 switch (MI->getOpcode()) {
12470 default: assert(0 && "Unexpected instr type to insert");
12471 case X86::TAILJMPd64:
12472 case X86::TAILJMPr64:
12473 case X86::TAILJMPm64:
12474 assert(0 && "TAILJMP64 would not be touched here.");
12475 case X86::TCRETURNdi64:
12476 case X86::TCRETURNri64:
12477 case X86::TCRETURNmi64:
12478 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12479 // On AMD64, additional defs should be added before register allocation.
12480 if (!Subtarget->isTargetWin64()) {
12481 MI->addRegisterDefined(X86::RSI);
12482 MI->addRegisterDefined(X86::RDI);
12483 MI->addRegisterDefined(X86::XMM6);
12484 MI->addRegisterDefined(X86::XMM7);
12485 MI->addRegisterDefined(X86::XMM8);
12486 MI->addRegisterDefined(X86::XMM9);
12487 MI->addRegisterDefined(X86::XMM10);
12488 MI->addRegisterDefined(X86::XMM11);
12489 MI->addRegisterDefined(X86::XMM12);
12490 MI->addRegisterDefined(X86::XMM13);
12491 MI->addRegisterDefined(X86::XMM14);
12492 MI->addRegisterDefined(X86::XMM15);
12495 case X86::WIN_ALLOCA:
12496 return EmitLoweredWinAlloca(MI, BB);
12497 case X86::SEG_ALLOCA_32:
12498 return EmitLoweredSegAlloca(MI, BB, false);
12499 case X86::SEG_ALLOCA_64:
12500 return EmitLoweredSegAlloca(MI, BB, true);
12501 case X86::TLSCall_32:
12502 case X86::TLSCall_64:
12503 return EmitLoweredTLSCall(MI, BB);
12504 case X86::CMOV_GR8:
12505 case X86::CMOV_FR32:
12506 case X86::CMOV_FR64:
12507 case X86::CMOV_V4F32:
12508 case X86::CMOV_V2F64:
12509 case X86::CMOV_V2I64:
12510 case X86::CMOV_V8F32:
12511 case X86::CMOV_V4F64:
12512 case X86::CMOV_V4I64:
12513 case X86::CMOV_GR16:
12514 case X86::CMOV_GR32:
12515 case X86::CMOV_RFP32:
12516 case X86::CMOV_RFP64:
12517 case X86::CMOV_RFP80:
12518 return EmitLoweredSelect(MI, BB);
12520 case X86::FP32_TO_INT16_IN_MEM:
12521 case X86::FP32_TO_INT32_IN_MEM:
12522 case X86::FP32_TO_INT64_IN_MEM:
12523 case X86::FP64_TO_INT16_IN_MEM:
12524 case X86::FP64_TO_INT32_IN_MEM:
12525 case X86::FP64_TO_INT64_IN_MEM:
12526 case X86::FP80_TO_INT16_IN_MEM:
12527 case X86::FP80_TO_INT32_IN_MEM:
12528 case X86::FP80_TO_INT64_IN_MEM: {
12529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12530 DebugLoc DL = MI->getDebugLoc();
12532 // Change the floating point control register to use "round towards zero"
12533 // mode when truncating to an integer value.
12534 MachineFunction *F = BB->getParent();
12535 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12536 addFrameReference(BuildMI(*BB, MI, DL,
12537 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12539 // Load the old value of the high byte of the control word...
12541 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12542 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12545 // Set the high part to be round to zero...
12546 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12549 // Reload the modified control word now...
12550 addFrameReference(BuildMI(*BB, MI, DL,
12551 TII->get(X86::FLDCW16m)), CWFrameIdx);
12553 // Restore the memory image of control word to original value
12554 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12557 // Get the X86 opcode to use.
12559 switch (MI->getOpcode()) {
12560 default: llvm_unreachable("illegal opcode!");
12561 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12562 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12563 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12564 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12565 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12566 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12567 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12568 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12569 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12573 MachineOperand &Op = MI->getOperand(0);
12575 AM.BaseType = X86AddressMode::RegBase;
12576 AM.Base.Reg = Op.getReg();
12578 AM.BaseType = X86AddressMode::FrameIndexBase;
12579 AM.Base.FrameIndex = Op.getIndex();
12581 Op = MI->getOperand(1);
12583 AM.Scale = Op.getImm();
12584 Op = MI->getOperand(2);
12586 AM.IndexReg = Op.getImm();
12587 Op = MI->getOperand(3);
12588 if (Op.isGlobal()) {
12589 AM.GV = Op.getGlobal();
12591 AM.Disp = Op.getImm();
12593 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12594 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12596 // Reload the original control word now.
12597 addFrameReference(BuildMI(*BB, MI, DL,
12598 TII->get(X86::FLDCW16m)), CWFrameIdx);
12600 MI->eraseFromParent(); // The pseudo instruction is gone now.
12603 // String/text processing lowering.
12604 case X86::PCMPISTRM128REG:
12605 case X86::VPCMPISTRM128REG:
12606 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12607 case X86::PCMPISTRM128MEM:
12608 case X86::VPCMPISTRM128MEM:
12609 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12610 case X86::PCMPESTRM128REG:
12611 case X86::VPCMPESTRM128REG:
12612 return EmitPCMP(MI, BB, 5, false /* in mem */);
12613 case X86::PCMPESTRM128MEM:
12614 case X86::VPCMPESTRM128MEM:
12615 return EmitPCMP(MI, BB, 5, true /* in mem */);
12617 // Thread synchronization.
12619 return EmitMonitor(MI, BB);
12621 return EmitMwait(MI, BB);
12623 // Atomic Lowering.
12624 case X86::ATOMAND32:
12625 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12626 X86::AND32ri, X86::MOV32rm,
12628 X86::NOT32r, X86::EAX,
12629 X86::GR32RegisterClass);
12630 case X86::ATOMOR32:
12631 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12632 X86::OR32ri, X86::MOV32rm,
12634 X86::NOT32r, X86::EAX,
12635 X86::GR32RegisterClass);
12636 case X86::ATOMXOR32:
12637 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12638 X86::XOR32ri, X86::MOV32rm,
12640 X86::NOT32r, X86::EAX,
12641 X86::GR32RegisterClass);
12642 case X86::ATOMNAND32:
12643 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12644 X86::AND32ri, X86::MOV32rm,
12646 X86::NOT32r, X86::EAX,
12647 X86::GR32RegisterClass, true);
12648 case X86::ATOMMIN32:
12649 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12650 case X86::ATOMMAX32:
12651 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12652 case X86::ATOMUMIN32:
12653 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12654 case X86::ATOMUMAX32:
12655 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12657 case X86::ATOMAND16:
12658 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12659 X86::AND16ri, X86::MOV16rm,
12661 X86::NOT16r, X86::AX,
12662 X86::GR16RegisterClass);
12663 case X86::ATOMOR16:
12664 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12665 X86::OR16ri, X86::MOV16rm,
12667 X86::NOT16r, X86::AX,
12668 X86::GR16RegisterClass);
12669 case X86::ATOMXOR16:
12670 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12671 X86::XOR16ri, X86::MOV16rm,
12673 X86::NOT16r, X86::AX,
12674 X86::GR16RegisterClass);
12675 case X86::ATOMNAND16:
12676 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12677 X86::AND16ri, X86::MOV16rm,
12679 X86::NOT16r, X86::AX,
12680 X86::GR16RegisterClass, true);
12681 case X86::ATOMMIN16:
12682 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12683 case X86::ATOMMAX16:
12684 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12685 case X86::ATOMUMIN16:
12686 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12687 case X86::ATOMUMAX16:
12688 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12690 case X86::ATOMAND8:
12691 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12692 X86::AND8ri, X86::MOV8rm,
12694 X86::NOT8r, X86::AL,
12695 X86::GR8RegisterClass);
12697 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12698 X86::OR8ri, X86::MOV8rm,
12700 X86::NOT8r, X86::AL,
12701 X86::GR8RegisterClass);
12702 case X86::ATOMXOR8:
12703 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12704 X86::XOR8ri, X86::MOV8rm,
12706 X86::NOT8r, X86::AL,
12707 X86::GR8RegisterClass);
12708 case X86::ATOMNAND8:
12709 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12710 X86::AND8ri, X86::MOV8rm,
12712 X86::NOT8r, X86::AL,
12713 X86::GR8RegisterClass, true);
12714 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12715 // This group is for 64-bit host.
12716 case X86::ATOMAND64:
12717 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12718 X86::AND64ri32, X86::MOV64rm,
12720 X86::NOT64r, X86::RAX,
12721 X86::GR64RegisterClass);
12722 case X86::ATOMOR64:
12723 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12724 X86::OR64ri32, X86::MOV64rm,
12726 X86::NOT64r, X86::RAX,
12727 X86::GR64RegisterClass);
12728 case X86::ATOMXOR64:
12729 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12730 X86::XOR64ri32, X86::MOV64rm,
12732 X86::NOT64r, X86::RAX,
12733 X86::GR64RegisterClass);
12734 case X86::ATOMNAND64:
12735 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12736 X86::AND64ri32, X86::MOV64rm,
12738 X86::NOT64r, X86::RAX,
12739 X86::GR64RegisterClass, true);
12740 case X86::ATOMMIN64:
12741 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12742 case X86::ATOMMAX64:
12743 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12744 case X86::ATOMUMIN64:
12745 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12746 case X86::ATOMUMAX64:
12747 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12749 // This group does 64-bit operations on a 32-bit host.
12750 case X86::ATOMAND6432:
12751 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12752 X86::AND32rr, X86::AND32rr,
12753 X86::AND32ri, X86::AND32ri,
12755 case X86::ATOMOR6432:
12756 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12757 X86::OR32rr, X86::OR32rr,
12758 X86::OR32ri, X86::OR32ri,
12760 case X86::ATOMXOR6432:
12761 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12762 X86::XOR32rr, X86::XOR32rr,
12763 X86::XOR32ri, X86::XOR32ri,
12765 case X86::ATOMNAND6432:
12766 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12767 X86::AND32rr, X86::AND32rr,
12768 X86::AND32ri, X86::AND32ri,
12770 case X86::ATOMADD6432:
12771 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12772 X86::ADD32rr, X86::ADC32rr,
12773 X86::ADD32ri, X86::ADC32ri,
12775 case X86::ATOMSUB6432:
12776 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12777 X86::SUB32rr, X86::SBB32rr,
12778 X86::SUB32ri, X86::SBB32ri,
12780 case X86::ATOMSWAP6432:
12781 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12782 X86::MOV32rr, X86::MOV32rr,
12783 X86::MOV32ri, X86::MOV32ri,
12785 case X86::VASTART_SAVE_XMM_REGS:
12786 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12788 case X86::VAARG_64:
12789 return EmitVAARG64WithCustomInserter(MI, BB);
12793 //===----------------------------------------------------------------------===//
12794 // X86 Optimization Hooks
12795 //===----------------------------------------------------------------------===//
12797 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12801 const SelectionDAG &DAG,
12802 unsigned Depth) const {
12803 unsigned Opc = Op.getOpcode();
12804 assert((Opc >= ISD::BUILTIN_OP_END ||
12805 Opc == ISD::INTRINSIC_WO_CHAIN ||
12806 Opc == ISD::INTRINSIC_W_CHAIN ||
12807 Opc == ISD::INTRINSIC_VOID) &&
12808 "Should use MaskedValueIsZero if you don't know whether Op"
12809 " is a target node!");
12811 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12825 // These nodes' second result is a boolean.
12826 if (Op.getResNo() == 0)
12829 case X86ISD::SETCC:
12830 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12831 Mask.getBitWidth() - 1);
12833 case ISD::INTRINSIC_WO_CHAIN: {
12834 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12835 unsigned NumLoBits = 0;
12838 case Intrinsic::x86_sse_movmsk_ps:
12839 case Intrinsic::x86_avx_movmsk_ps_256:
12840 case Intrinsic::x86_sse2_movmsk_pd:
12841 case Intrinsic::x86_avx_movmsk_pd_256:
12842 case Intrinsic::x86_mmx_pmovmskb:
12843 case Intrinsic::x86_sse2_pmovmskb_128: {
12844 // High bits of movmskp{s|d}, pmovmskb are known zero.
12846 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12847 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12848 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12849 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12850 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12851 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12853 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12854 Mask.getBitWidth() - NumLoBits);
12863 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12864 unsigned Depth) const {
12865 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12866 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12867 return Op.getValueType().getScalarType().getSizeInBits();
12873 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12874 /// node is a GlobalAddress + offset.
12875 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12876 const GlobalValue* &GA,
12877 int64_t &Offset) const {
12878 if (N->getOpcode() == X86ISD::Wrapper) {
12879 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12880 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12881 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12885 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12888 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12889 /// same as extracting the high 128-bit part of 256-bit vector and then
12890 /// inserting the result into the low part of a new 256-bit vector
12891 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12892 EVT VT = SVOp->getValueType(0);
12893 int NumElems = VT.getVectorNumElements();
12895 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12896 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12897 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12898 SVOp->getMaskElt(j) >= 0)
12904 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12905 /// same as extracting the low 128-bit part of 256-bit vector and then
12906 /// inserting the result into the high part of a new 256-bit vector
12907 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12908 EVT VT = SVOp->getValueType(0);
12909 int NumElems = VT.getVectorNumElements();
12911 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12912 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12913 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12914 SVOp->getMaskElt(j) >= 0)
12920 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12921 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12922 TargetLowering::DAGCombinerInfo &DCI) {
12923 DebugLoc dl = N->getDebugLoc();
12924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12925 SDValue V1 = SVOp->getOperand(0);
12926 SDValue V2 = SVOp->getOperand(1);
12927 EVT VT = SVOp->getValueType(0);
12928 int NumElems = VT.getVectorNumElements();
12930 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12931 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12935 // V UNDEF BUILD_VECTOR UNDEF
12937 // CONCAT_VECTOR CONCAT_VECTOR
12940 // RESULT: V + zero extended
12942 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12943 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12944 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12947 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12950 // To match the shuffle mask, the first half of the mask should
12951 // be exactly the first vector, and all the rest a splat with the
12952 // first element of the second one.
12953 for (int i = 0; i < NumElems/2; ++i)
12954 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12955 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12958 // Emit a zeroed vector and insert the desired subvector on its
12960 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12961 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12962 DAG.getConstant(0, MVT::i32), DAG, dl);
12963 return DCI.CombineTo(N, InsV);
12966 //===--------------------------------------------------------------------===//
12967 // Combine some shuffles into subvector extracts and inserts:
12970 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12971 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12972 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12974 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12975 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12976 return DCI.CombineTo(N, InsV);
12979 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12980 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12981 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12982 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12983 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12984 return DCI.CombineTo(N, InsV);
12990 /// PerformShuffleCombine - Performs several different shuffle combines.
12991 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12992 TargetLowering::DAGCombinerInfo &DCI,
12993 const X86Subtarget *Subtarget) {
12994 DebugLoc dl = N->getDebugLoc();
12995 EVT VT = N->getValueType(0);
12997 // Don't create instructions with illegal types after legalize types has run.
12998 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12999 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13002 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13003 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13004 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13005 return PerformShuffleCombine256(N, DAG, DCI);
13007 // Only handle 128 wide vector from here on.
13008 if (VT.getSizeInBits() != 128)
13011 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13012 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13013 // consecutive, non-overlapping, and in the right order.
13014 SmallVector<SDValue, 16> Elts;
13015 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13016 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13018 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13021 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13022 /// generation and convert it from being a bunch of shuffles and extracts
13023 /// to a simple store and scalar loads to extract the elements.
13024 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13025 const TargetLowering &TLI) {
13026 SDValue InputVector = N->getOperand(0);
13028 // Only operate on vectors of 4 elements, where the alternative shuffling
13029 // gets to be more expensive.
13030 if (InputVector.getValueType() != MVT::v4i32)
13033 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13034 // single use which is a sign-extend or zero-extend, and all elements are
13036 SmallVector<SDNode *, 4> Uses;
13037 unsigned ExtractedElements = 0;
13038 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13039 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13040 if (UI.getUse().getResNo() != InputVector.getResNo())
13043 SDNode *Extract = *UI;
13044 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13047 if (Extract->getValueType(0) != MVT::i32)
13049 if (!Extract->hasOneUse())
13051 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13052 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13054 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13057 // Record which element was extracted.
13058 ExtractedElements |=
13059 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13061 Uses.push_back(Extract);
13064 // If not all the elements were used, this may not be worthwhile.
13065 if (ExtractedElements != 15)
13068 // Ok, we've now decided to do the transformation.
13069 DebugLoc dl = InputVector.getDebugLoc();
13071 // Store the value to a temporary stack slot.
13072 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13073 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13074 MachinePointerInfo(), false, false, 0);
13076 // Replace each use (extract) with a load of the appropriate element.
13077 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13078 UE = Uses.end(); UI != UE; ++UI) {
13079 SDNode *Extract = *UI;
13081 // cOMpute the element's address.
13082 SDValue Idx = Extract->getOperand(1);
13084 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13085 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13086 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13088 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13089 StackPtr, OffsetVal);
13091 // Load the scalar.
13092 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13093 ScalarAddr, MachinePointerInfo(),
13094 false, false, false, 0);
13096 // Replace the exact with the load.
13097 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13100 // The replacement was made in place; don't return anything.
13104 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13106 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13107 const X86Subtarget *Subtarget) {
13108 DebugLoc DL = N->getDebugLoc();
13109 SDValue Cond = N->getOperand(0);
13110 // Get the LHS/RHS of the select.
13111 SDValue LHS = N->getOperand(1);
13112 SDValue RHS = N->getOperand(2);
13113 EVT VT = LHS.getValueType();
13115 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13116 // instructions match the semantics of the common C idiom x<y?x:y but not
13117 // x<=y?x:y, because of how they handle negative zero (which can be
13118 // ignored in unsafe-math mode).
13119 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13120 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13121 (Subtarget->hasXMMInt() ||
13122 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13123 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13125 unsigned Opcode = 0;
13126 // Check for x CC y ? x : y.
13127 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13128 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13132 // Converting this to a min would handle NaNs incorrectly, and swapping
13133 // the operands would cause it to handle comparisons between positive
13134 // and negative zero incorrectly.
13135 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13136 if (!UnsafeFPMath &&
13137 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13139 std::swap(LHS, RHS);
13141 Opcode = X86ISD::FMIN;
13144 // Converting this to a min would handle comparisons between positive
13145 // and negative zero incorrectly.
13146 if (!UnsafeFPMath &&
13147 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13149 Opcode = X86ISD::FMIN;
13152 // Converting this to a min would handle both negative zeros and NaNs
13153 // incorrectly, but we can swap the operands to fix both.
13154 std::swap(LHS, RHS);
13158 Opcode = X86ISD::FMIN;
13162 // Converting this to a max would handle comparisons between positive
13163 // and negative zero incorrectly.
13164 if (!UnsafeFPMath &&
13165 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13167 Opcode = X86ISD::FMAX;
13170 // Converting this to a max would handle NaNs incorrectly, and swapping
13171 // the operands would cause it to handle comparisons between positive
13172 // and negative zero incorrectly.
13173 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13174 if (!UnsafeFPMath &&
13175 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13177 std::swap(LHS, RHS);
13179 Opcode = X86ISD::FMAX;
13182 // Converting this to a max would handle both negative zeros and NaNs
13183 // incorrectly, but we can swap the operands to fix both.
13184 std::swap(LHS, RHS);
13188 Opcode = X86ISD::FMAX;
13191 // Check for x CC y ? y : x -- a min/max with reversed arms.
13192 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13193 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13197 // Converting this to a min would handle comparisons between positive
13198 // and negative zero incorrectly, and swapping the operands would
13199 // cause it to handle NaNs incorrectly.
13200 if (!UnsafeFPMath &&
13201 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13202 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13204 std::swap(LHS, RHS);
13206 Opcode = X86ISD::FMIN;
13209 // Converting this to a min would handle NaNs incorrectly.
13210 if (!UnsafeFPMath &&
13211 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13213 Opcode = X86ISD::FMIN;
13216 // Converting this to a min would handle both negative zeros and NaNs
13217 // incorrectly, but we can swap the operands to fix both.
13218 std::swap(LHS, RHS);
13222 Opcode = X86ISD::FMIN;
13226 // Converting this to a max would handle NaNs incorrectly.
13227 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13229 Opcode = X86ISD::FMAX;
13232 // Converting this to a max would handle comparisons between positive
13233 // and negative zero incorrectly, and swapping the operands would
13234 // cause it to handle NaNs incorrectly.
13235 if (!UnsafeFPMath &&
13236 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13237 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13239 std::swap(LHS, RHS);
13241 Opcode = X86ISD::FMAX;
13244 // Converting this to a max would handle both negative zeros and NaNs
13245 // incorrectly, but we can swap the operands to fix both.
13246 std::swap(LHS, RHS);
13250 Opcode = X86ISD::FMAX;
13256 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13259 // If this is a select between two integer constants, try to do some
13261 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13262 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13263 // Don't do this for crazy integer types.
13264 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13265 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13266 // so that TrueC (the true value) is larger than FalseC.
13267 bool NeedsCondInvert = false;
13269 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13270 // Efficiently invertible.
13271 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13272 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13273 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13274 NeedsCondInvert = true;
13275 std::swap(TrueC, FalseC);
13278 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13279 if (FalseC->getAPIntValue() == 0 &&
13280 TrueC->getAPIntValue().isPowerOf2()) {
13281 if (NeedsCondInvert) // Invert the condition if needed.
13282 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13283 DAG.getConstant(1, Cond.getValueType()));
13285 // Zero extend the condition if needed.
13286 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13288 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13289 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13290 DAG.getConstant(ShAmt, MVT::i8));
13293 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13294 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13295 if (NeedsCondInvert) // Invert the condition if needed.
13296 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13297 DAG.getConstant(1, Cond.getValueType()));
13299 // Zero extend the condition if needed.
13300 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13301 FalseC->getValueType(0), Cond);
13302 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13303 SDValue(FalseC, 0));
13306 // Optimize cases that will turn into an LEA instruction. This requires
13307 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13308 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13309 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13310 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13312 bool isFastMultiplier = false;
13314 switch ((unsigned char)Diff) {
13316 case 1: // result = add base, cond
13317 case 2: // result = lea base( , cond*2)
13318 case 3: // result = lea base(cond, cond*2)
13319 case 4: // result = lea base( , cond*4)
13320 case 5: // result = lea base(cond, cond*4)
13321 case 8: // result = lea base( , cond*8)
13322 case 9: // result = lea base(cond, cond*8)
13323 isFastMultiplier = true;
13328 if (isFastMultiplier) {
13329 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13330 if (NeedsCondInvert) // Invert the condition if needed.
13331 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13332 DAG.getConstant(1, Cond.getValueType()));
13334 // Zero extend the condition if needed.
13335 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13337 // Scale the condition by the difference.
13339 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13340 DAG.getConstant(Diff, Cond.getValueType()));
13342 // Add the base if non-zero.
13343 if (FalseC->getAPIntValue() != 0)
13344 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13345 SDValue(FalseC, 0));
13355 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13356 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13357 TargetLowering::DAGCombinerInfo &DCI) {
13358 DebugLoc DL = N->getDebugLoc();
13360 // If the flag operand isn't dead, don't touch this CMOV.
13361 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13364 SDValue FalseOp = N->getOperand(0);
13365 SDValue TrueOp = N->getOperand(1);
13366 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13367 SDValue Cond = N->getOperand(3);
13368 if (CC == X86::COND_E || CC == X86::COND_NE) {
13369 switch (Cond.getOpcode()) {
13373 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13374 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13375 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13379 // If this is a select between two integer constants, try to do some
13380 // optimizations. Note that the operands are ordered the opposite of SELECT
13382 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13383 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13384 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13385 // larger than FalseC (the false value).
13386 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13387 CC = X86::GetOppositeBranchCondition(CC);
13388 std::swap(TrueC, FalseC);
13391 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13392 // This is efficient for any integer data type (including i8/i16) and
13394 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13395 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13396 DAG.getConstant(CC, MVT::i8), Cond);
13398 // Zero extend the condition if needed.
13399 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13401 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13402 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13403 DAG.getConstant(ShAmt, MVT::i8));
13404 if (N->getNumValues() == 2) // Dead flag value?
13405 return DCI.CombineTo(N, Cond, SDValue());
13409 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13410 // for any integer data type, including i8/i16.
13411 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13412 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13413 DAG.getConstant(CC, MVT::i8), Cond);
13415 // Zero extend the condition if needed.
13416 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13417 FalseC->getValueType(0), Cond);
13418 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13419 SDValue(FalseC, 0));
13421 if (N->getNumValues() == 2) // Dead flag value?
13422 return DCI.CombineTo(N, Cond, SDValue());
13426 // Optimize cases that will turn into an LEA instruction. This requires
13427 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13428 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13429 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13430 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13432 bool isFastMultiplier = false;
13434 switch ((unsigned char)Diff) {
13436 case 1: // result = add base, cond
13437 case 2: // result = lea base( , cond*2)
13438 case 3: // result = lea base(cond, cond*2)
13439 case 4: // result = lea base( , cond*4)
13440 case 5: // result = lea base(cond, cond*4)
13441 case 8: // result = lea base( , cond*8)
13442 case 9: // result = lea base(cond, cond*8)
13443 isFastMultiplier = true;
13448 if (isFastMultiplier) {
13449 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13450 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13451 DAG.getConstant(CC, MVT::i8), Cond);
13452 // Zero extend the condition if needed.
13453 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13455 // Scale the condition by the difference.
13457 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13458 DAG.getConstant(Diff, Cond.getValueType()));
13460 // Add the base if non-zero.
13461 if (FalseC->getAPIntValue() != 0)
13462 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13463 SDValue(FalseC, 0));
13464 if (N->getNumValues() == 2) // Dead flag value?
13465 return DCI.CombineTo(N, Cond, SDValue());
13475 /// PerformMulCombine - Optimize a single multiply with constant into two
13476 /// in order to implement it with two cheaper instructions, e.g.
13477 /// LEA + SHL, LEA + LEA.
13478 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13479 TargetLowering::DAGCombinerInfo &DCI) {
13480 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13483 EVT VT = N->getValueType(0);
13484 if (VT != MVT::i64)
13487 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13490 uint64_t MulAmt = C->getZExtValue();
13491 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13494 uint64_t MulAmt1 = 0;
13495 uint64_t MulAmt2 = 0;
13496 if ((MulAmt % 9) == 0) {
13498 MulAmt2 = MulAmt / 9;
13499 } else if ((MulAmt % 5) == 0) {
13501 MulAmt2 = MulAmt / 5;
13502 } else if ((MulAmt % 3) == 0) {
13504 MulAmt2 = MulAmt / 3;
13507 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13508 DebugLoc DL = N->getDebugLoc();
13510 if (isPowerOf2_64(MulAmt2) &&
13511 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13512 // If second multiplifer is pow2, issue it first. We want the multiply by
13513 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13515 std::swap(MulAmt1, MulAmt2);
13518 if (isPowerOf2_64(MulAmt1))
13519 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13520 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13522 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13523 DAG.getConstant(MulAmt1, VT));
13525 if (isPowerOf2_64(MulAmt2))
13526 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13527 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13529 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13530 DAG.getConstant(MulAmt2, VT));
13532 // Do not add new nodes to DAG combiner worklist.
13533 DCI.CombineTo(N, NewMul, false);
13538 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13539 SDValue N0 = N->getOperand(0);
13540 SDValue N1 = N->getOperand(1);
13541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13542 EVT VT = N0.getValueType();
13544 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13545 // since the result of setcc_c is all zero's or all ones.
13546 if (VT.isInteger() && !VT.isVector() &&
13547 N1C && N0.getOpcode() == ISD::AND &&
13548 N0.getOperand(1).getOpcode() == ISD::Constant) {
13549 SDValue N00 = N0.getOperand(0);
13550 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13551 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13552 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13553 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13554 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13555 APInt ShAmt = N1C->getAPIntValue();
13556 Mask = Mask.shl(ShAmt);
13558 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13559 N00, DAG.getConstant(Mask, VT));
13564 // Hardware support for vector shifts is sparse which makes us scalarize the
13565 // vector operations in many cases. Also, on sandybridge ADD is faster than
13567 // (shl V, 1) -> add V,V
13568 if (isSplatVector(N1.getNode())) {
13569 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13570 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13571 // We shift all of the values by one. In many cases we do not have
13572 // hardware support for this operation. This is better expressed as an ADD
13574 if (N1C && (1 == N1C->getZExtValue())) {
13575 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13582 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13584 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13585 const X86Subtarget *Subtarget) {
13586 EVT VT = N->getValueType(0);
13587 if (N->getOpcode() == ISD::SHL) {
13588 SDValue V = PerformSHLCombine(N, DAG);
13589 if (V.getNode()) return V;
13592 // On X86 with SSE2 support, we can transform this to a vector shift if
13593 // all elements are shifted by the same amount. We can't do this in legalize
13594 // because the a constant vector is typically transformed to a constant pool
13595 // so we have no knowledge of the shift amount.
13596 if (!Subtarget->hasXMMInt())
13599 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13600 (!Subtarget->hasAVX2() ||
13601 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13604 SDValue ShAmtOp = N->getOperand(1);
13605 EVT EltVT = VT.getVectorElementType();
13606 DebugLoc DL = N->getDebugLoc();
13607 SDValue BaseShAmt = SDValue();
13608 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13609 unsigned NumElts = VT.getVectorNumElements();
13611 for (; i != NumElts; ++i) {
13612 SDValue Arg = ShAmtOp.getOperand(i);
13613 if (Arg.getOpcode() == ISD::UNDEF) continue;
13617 for (; i != NumElts; ++i) {
13618 SDValue Arg = ShAmtOp.getOperand(i);
13619 if (Arg.getOpcode() == ISD::UNDEF) continue;
13620 if (Arg != BaseShAmt) {
13624 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13625 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13626 SDValue InVec = ShAmtOp.getOperand(0);
13627 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13628 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13630 for (; i != NumElts; ++i) {
13631 SDValue Arg = InVec.getOperand(i);
13632 if (Arg.getOpcode() == ISD::UNDEF) continue;
13636 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13638 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13639 if (C->getZExtValue() == SplatIdx)
13640 BaseShAmt = InVec.getOperand(1);
13643 if (BaseShAmt.getNode() == 0)
13644 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13645 DAG.getIntPtrConstant(0));
13649 // The shift amount is an i32.
13650 if (EltVT.bitsGT(MVT::i32))
13651 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13652 else if (EltVT.bitsLT(MVT::i32))
13653 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13655 // The shift amount is identical so we can do a vector shift.
13656 SDValue ValOp = N->getOperand(0);
13657 switch (N->getOpcode()) {
13659 llvm_unreachable("Unknown shift opcode!");
13662 if (VT == MVT::v2i64)
13663 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13664 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13666 if (VT == MVT::v4i32)
13667 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13668 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13670 if (VT == MVT::v8i16)
13671 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13672 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13674 if (VT == MVT::v4i64)
13675 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13676 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13678 if (VT == MVT::v8i32)
13679 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13680 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13682 if (VT == MVT::v16i16)
13683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13684 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13688 if (VT == MVT::v4i32)
13689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13690 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13692 if (VT == MVT::v8i16)
13693 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13694 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13696 if (VT == MVT::v8i32)
13697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13698 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13700 if (VT == MVT::v16i16)
13701 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13702 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13706 if (VT == MVT::v2i64)
13707 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13708 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13710 if (VT == MVT::v4i32)
13711 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13712 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13714 if (VT == MVT::v8i16)
13715 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13716 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13718 if (VT == MVT::v4i64)
13719 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13720 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13722 if (VT == MVT::v8i32)
13723 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13724 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13726 if (VT == MVT::v16i16)
13727 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13728 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13736 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13737 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13738 // and friends. Likewise for OR -> CMPNEQSS.
13739 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13740 TargetLowering::DAGCombinerInfo &DCI,
13741 const X86Subtarget *Subtarget) {
13744 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13745 // we're requiring SSE2 for both.
13746 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13747 SDValue N0 = N->getOperand(0);
13748 SDValue N1 = N->getOperand(1);
13749 SDValue CMP0 = N0->getOperand(1);
13750 SDValue CMP1 = N1->getOperand(1);
13751 DebugLoc DL = N->getDebugLoc();
13753 // The SETCCs should both refer to the same CMP.
13754 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13757 SDValue CMP00 = CMP0->getOperand(0);
13758 SDValue CMP01 = CMP0->getOperand(1);
13759 EVT VT = CMP00.getValueType();
13761 if (VT == MVT::f32 || VT == MVT::f64) {
13762 bool ExpectingFlags = false;
13763 // Check for any users that want flags:
13764 for (SDNode::use_iterator UI = N->use_begin(),
13766 !ExpectingFlags && UI != UE; ++UI)
13767 switch (UI->getOpcode()) {
13772 ExpectingFlags = true;
13774 case ISD::CopyToReg:
13775 case ISD::SIGN_EXTEND:
13776 case ISD::ZERO_EXTEND:
13777 case ISD::ANY_EXTEND:
13781 if (!ExpectingFlags) {
13782 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13783 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13785 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13786 X86::CondCode tmp = cc0;
13791 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13792 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13793 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13794 X86ISD::NodeType NTOperator = is64BitFP ?
13795 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13796 // FIXME: need symbolic constants for these magic numbers.
13797 // See X86ATTInstPrinter.cpp:printSSECC().
13798 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13799 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13800 DAG.getConstant(x86cc, MVT::i8));
13801 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13803 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13804 DAG.getConstant(1, MVT::i32));
13805 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13806 return OneBitOfTruth;
13814 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13815 /// so it can be folded inside ANDNP.
13816 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13817 EVT VT = N->getValueType(0);
13819 // Match direct AllOnes for 128 and 256-bit vectors
13820 if (ISD::isBuildVectorAllOnes(N))
13823 // Look through a bit convert.
13824 if (N->getOpcode() == ISD::BITCAST)
13825 N = N->getOperand(0).getNode();
13827 // Sometimes the operand may come from a insert_subvector building a 256-bit
13829 if (VT.getSizeInBits() == 256 &&
13830 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13831 SDValue V1 = N->getOperand(0);
13832 SDValue V2 = N->getOperand(1);
13834 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13835 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13836 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13837 ISD::isBuildVectorAllOnes(V2.getNode()))
13844 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13845 TargetLowering::DAGCombinerInfo &DCI,
13846 const X86Subtarget *Subtarget) {
13847 if (DCI.isBeforeLegalizeOps())
13850 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13854 EVT VT = N->getValueType(0);
13856 // Create ANDN, BLSI, and BLSR instructions
13857 // BLSI is X & (-X)
13858 // BLSR is X & (X-1)
13859 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13860 SDValue N0 = N->getOperand(0);
13861 SDValue N1 = N->getOperand(1);
13862 DebugLoc DL = N->getDebugLoc();
13864 // Check LHS for not
13865 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13866 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13867 // Check RHS for not
13868 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13869 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13871 // Check LHS for neg
13872 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13873 isZero(N0.getOperand(0)))
13874 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13876 // Check RHS for neg
13877 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13878 isZero(N1.getOperand(0)))
13879 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13881 // Check LHS for X-1
13882 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13883 isAllOnes(N0.getOperand(1)))
13884 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13886 // Check RHS for X-1
13887 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13888 isAllOnes(N1.getOperand(1)))
13889 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13894 // Want to form ANDNP nodes:
13895 // 1) In the hopes of then easily combining them with OR and AND nodes
13896 // to form PBLEND/PSIGN.
13897 // 2) To match ANDN packed intrinsics
13898 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13901 SDValue N0 = N->getOperand(0);
13902 SDValue N1 = N->getOperand(1);
13903 DebugLoc DL = N->getDebugLoc();
13905 // Check LHS for vnot
13906 if (N0.getOpcode() == ISD::XOR &&
13907 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13908 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13909 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13911 // Check RHS for vnot
13912 if (N1.getOpcode() == ISD::XOR &&
13913 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13914 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13915 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13920 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13921 TargetLowering::DAGCombinerInfo &DCI,
13922 const X86Subtarget *Subtarget) {
13923 if (DCI.isBeforeLegalizeOps())
13926 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13930 EVT VT = N->getValueType(0);
13932 SDValue N0 = N->getOperand(0);
13933 SDValue N1 = N->getOperand(1);
13935 // look for psign/blend
13936 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13937 if (!Subtarget->hasSSSE3orAVX() ||
13938 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13941 // Canonicalize pandn to RHS
13942 if (N0.getOpcode() == X86ISD::ANDNP)
13944 // or (and (m, x), (pandn m, y))
13945 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13946 SDValue Mask = N1.getOperand(0);
13947 SDValue X = N1.getOperand(1);
13949 if (N0.getOperand(0) == Mask)
13950 Y = N0.getOperand(1);
13951 if (N0.getOperand(1) == Mask)
13952 Y = N0.getOperand(0);
13954 // Check to see if the mask appeared in both the AND and ANDNP and
13958 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13959 if (Mask.getOpcode() != ISD::BITCAST ||
13960 X.getOpcode() != ISD::BITCAST ||
13961 Y.getOpcode() != ISD::BITCAST)
13964 // Look through mask bitcast.
13965 Mask = Mask.getOperand(0);
13966 EVT MaskVT = Mask.getValueType();
13968 // Validate that the Mask operand is a vector sra node. The sra node
13969 // will be an intrinsic.
13970 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13973 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13974 // there is no psrai.b
13975 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13976 case Intrinsic::x86_sse2_psrai_w:
13977 case Intrinsic::x86_sse2_psrai_d:
13978 case Intrinsic::x86_avx2_psrai_w:
13979 case Intrinsic::x86_avx2_psrai_d:
13981 default: return SDValue();
13984 // Check that the SRA is all signbits.
13985 SDValue SraC = Mask.getOperand(2);
13986 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13987 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13988 if ((SraAmt + 1) != EltBits)
13991 DebugLoc DL = N->getDebugLoc();
13993 // Now we know we at least have a plendvb with the mask val. See if
13994 // we can form a psignb/w/d.
13995 // psign = x.type == y.type == mask.type && y = sub(0, x);
13996 X = X.getOperand(0);
13997 Y = Y.getOperand(0);
13998 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13999 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14000 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14001 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14002 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14003 Mask.getOperand(1));
14004 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14006 // PBLENDVB only available on SSE 4.1
14007 if (!Subtarget->hasSSE41orAVX())
14010 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14012 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14013 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14014 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14015 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14016 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14020 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14023 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14024 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14026 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14028 if (!N0.hasOneUse() || !N1.hasOneUse())
14031 SDValue ShAmt0 = N0.getOperand(1);
14032 if (ShAmt0.getValueType() != MVT::i8)
14034 SDValue ShAmt1 = N1.getOperand(1);
14035 if (ShAmt1.getValueType() != MVT::i8)
14037 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14038 ShAmt0 = ShAmt0.getOperand(0);
14039 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14040 ShAmt1 = ShAmt1.getOperand(0);
14042 DebugLoc DL = N->getDebugLoc();
14043 unsigned Opc = X86ISD::SHLD;
14044 SDValue Op0 = N0.getOperand(0);
14045 SDValue Op1 = N1.getOperand(0);
14046 if (ShAmt0.getOpcode() == ISD::SUB) {
14047 Opc = X86ISD::SHRD;
14048 std::swap(Op0, Op1);
14049 std::swap(ShAmt0, ShAmt1);
14052 unsigned Bits = VT.getSizeInBits();
14053 if (ShAmt1.getOpcode() == ISD::SUB) {
14054 SDValue Sum = ShAmt1.getOperand(0);
14055 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14056 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14057 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14058 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14059 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14060 return DAG.getNode(Opc, DL, VT,
14062 DAG.getNode(ISD::TRUNCATE, DL,
14065 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14066 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14068 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14069 return DAG.getNode(Opc, DL, VT,
14070 N0.getOperand(0), N1.getOperand(0),
14071 DAG.getNode(ISD::TRUNCATE, DL,
14078 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14079 TargetLowering::DAGCombinerInfo &DCI,
14080 const X86Subtarget *Subtarget) {
14081 if (DCI.isBeforeLegalizeOps())
14084 EVT VT = N->getValueType(0);
14086 if (VT != MVT::i32 && VT != MVT::i64)
14089 // Create BLSMSK instructions by finding X ^ (X-1)
14090 SDValue N0 = N->getOperand(0);
14091 SDValue N1 = N->getOperand(1);
14092 DebugLoc DL = N->getDebugLoc();
14094 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14095 isAllOnes(N0.getOperand(1)))
14096 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14098 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14099 isAllOnes(N1.getOperand(1)))
14100 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14105 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14106 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14107 const X86Subtarget *Subtarget) {
14108 LoadSDNode *Ld = cast<LoadSDNode>(N);
14109 EVT RegVT = Ld->getValueType(0);
14110 EVT MemVT = Ld->getMemoryVT();
14111 DebugLoc dl = Ld->getDebugLoc();
14112 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14114 ISD::LoadExtType Ext = Ld->getExtensionType();
14116 // If this is a vector EXT Load then attempt to optimize it using a
14117 // shuffle. We need SSE4 for the shuffles.
14118 // TODO: It is possible to support ZExt by zeroing the undef values
14119 // during the shuffle phase or after the shuffle.
14120 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14121 assert(MemVT != RegVT && "Cannot extend to the same type");
14122 assert(MemVT.isVector() && "Must load a vector from memory");
14124 unsigned NumElems = RegVT.getVectorNumElements();
14125 unsigned RegSz = RegVT.getSizeInBits();
14126 unsigned MemSz = MemVT.getSizeInBits();
14127 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14128 // All sizes must be a power of two
14129 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14131 // Attempt to load the original value using a single load op.
14132 // Find a scalar type which is equal to the loaded word size.
14133 MVT SclrLoadTy = MVT::i8;
14134 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14135 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14136 MVT Tp = (MVT::SimpleValueType)tp;
14137 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14143 // Proceed if a load word is found.
14144 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14146 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14147 RegSz/SclrLoadTy.getSizeInBits());
14149 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14150 RegSz/MemVT.getScalarType().getSizeInBits());
14151 // Can't shuffle using an illegal type.
14152 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14154 // Perform a single load.
14155 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14157 Ld->getPointerInfo(), Ld->isVolatile(),
14158 Ld->isNonTemporal(), Ld->isInvariant(),
14159 Ld->getAlignment());
14161 // Insert the word loaded into a vector.
14162 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14163 LoadUnitVecVT, ScalarLoad);
14165 // Bitcast the loaded value to a vector of the original element type, in
14166 // the size of the target vector type.
14167 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14168 unsigned SizeRatio = RegSz/MemSz;
14170 // Redistribute the loaded elements into the different locations.
14171 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14172 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14174 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14175 DAG.getUNDEF(SlicedVec.getValueType()),
14176 ShuffleVec.data());
14178 // Bitcast to the requested type.
14179 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14180 // Replace the original load with the new sequence
14181 // and return the new chain.
14182 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14183 return SDValue(ScalarLoad.getNode(), 1);
14189 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14190 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14191 const X86Subtarget *Subtarget) {
14192 StoreSDNode *St = cast<StoreSDNode>(N);
14193 EVT VT = St->getValue().getValueType();
14194 EVT StVT = St->getMemoryVT();
14195 DebugLoc dl = St->getDebugLoc();
14196 SDValue StoredVal = St->getOperand(1);
14197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14199 // If we are saving a concatination of two XMM registers, perform two stores.
14200 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14201 // 128-bit ones. If in the future the cost becomes only one memory access the
14202 // first version would be better.
14203 if (VT.getSizeInBits() == 256 &&
14204 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14205 StoredVal.getNumOperands() == 2) {
14207 SDValue Value0 = StoredVal.getOperand(0);
14208 SDValue Value1 = StoredVal.getOperand(1);
14210 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14211 SDValue Ptr0 = St->getBasePtr();
14212 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14214 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14215 St->getPointerInfo(), St->isVolatile(),
14216 St->isNonTemporal(), St->getAlignment());
14217 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14218 St->getPointerInfo(), St->isVolatile(),
14219 St->isNonTemporal(), St->getAlignment());
14220 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14223 // Optimize trunc store (of multiple scalars) to shuffle and store.
14224 // First, pack all of the elements in one place. Next, store to memory
14225 // in fewer chunks.
14226 if (St->isTruncatingStore() && VT.isVector()) {
14227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14228 unsigned NumElems = VT.getVectorNumElements();
14229 assert(StVT != VT && "Cannot truncate to the same type");
14230 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14231 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14233 // From, To sizes and ElemCount must be pow of two
14234 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14235 // We are going to use the original vector elt for storing.
14236 // Accumulated smaller vector elements must be a multiple of the store size.
14237 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14239 unsigned SizeRatio = FromSz / ToSz;
14241 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14243 // Create a type on which we perform the shuffle
14244 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14245 StVT.getScalarType(), NumElems*SizeRatio);
14247 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14249 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14250 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14251 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14253 // Can't shuffle using an illegal type
14254 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14256 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14257 DAG.getUNDEF(WideVec.getValueType()),
14258 ShuffleVec.data());
14259 // At this point all of the data is stored at the bottom of the
14260 // register. We now need to save it to mem.
14262 // Find the largest store unit
14263 MVT StoreType = MVT::i8;
14264 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14265 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14266 MVT Tp = (MVT::SimpleValueType)tp;
14267 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14271 // Bitcast the original vector into a vector of store-size units
14272 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14273 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14274 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14275 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14276 SmallVector<SDValue, 8> Chains;
14277 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14278 TLI.getPointerTy());
14279 SDValue Ptr = St->getBasePtr();
14281 // Perform one or more big stores into memory.
14282 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14283 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14284 StoreType, ShuffWide,
14285 DAG.getIntPtrConstant(i));
14286 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14287 St->getPointerInfo(), St->isVolatile(),
14288 St->isNonTemporal(), St->getAlignment());
14289 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14290 Chains.push_back(Ch);
14293 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14298 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14299 // the FP state in cases where an emms may be missing.
14300 // A preferable solution to the general problem is to figure out the right
14301 // places to insert EMMS. This qualifies as a quick hack.
14303 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14304 if (VT.getSizeInBits() != 64)
14307 const Function *F = DAG.getMachineFunction().getFunction();
14308 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14309 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14310 && Subtarget->hasXMMInt();
14311 if ((VT.isVector() ||
14312 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14313 isa<LoadSDNode>(St->getValue()) &&
14314 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14315 St->getChain().hasOneUse() && !St->isVolatile()) {
14316 SDNode* LdVal = St->getValue().getNode();
14317 LoadSDNode *Ld = 0;
14318 int TokenFactorIndex = -1;
14319 SmallVector<SDValue, 8> Ops;
14320 SDNode* ChainVal = St->getChain().getNode();
14321 // Must be a store of a load. We currently handle two cases: the load
14322 // is a direct child, and it's under an intervening TokenFactor. It is
14323 // possible to dig deeper under nested TokenFactors.
14324 if (ChainVal == LdVal)
14325 Ld = cast<LoadSDNode>(St->getChain());
14326 else if (St->getValue().hasOneUse() &&
14327 ChainVal->getOpcode() == ISD::TokenFactor) {
14328 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14329 if (ChainVal->getOperand(i).getNode() == LdVal) {
14330 TokenFactorIndex = i;
14331 Ld = cast<LoadSDNode>(St->getValue());
14333 Ops.push_back(ChainVal->getOperand(i));
14337 if (!Ld || !ISD::isNormalLoad(Ld))
14340 // If this is not the MMX case, i.e. we are just turning i64 load/store
14341 // into f64 load/store, avoid the transformation if there are multiple
14342 // uses of the loaded value.
14343 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14346 DebugLoc LdDL = Ld->getDebugLoc();
14347 DebugLoc StDL = N->getDebugLoc();
14348 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14349 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14351 if (Subtarget->is64Bit() || F64IsLegal) {
14352 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14353 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14354 Ld->getPointerInfo(), Ld->isVolatile(),
14355 Ld->isNonTemporal(), Ld->isInvariant(),
14356 Ld->getAlignment());
14357 SDValue NewChain = NewLd.getValue(1);
14358 if (TokenFactorIndex != -1) {
14359 Ops.push_back(NewChain);
14360 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14363 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14364 St->getPointerInfo(),
14365 St->isVolatile(), St->isNonTemporal(),
14366 St->getAlignment());
14369 // Otherwise, lower to two pairs of 32-bit loads / stores.
14370 SDValue LoAddr = Ld->getBasePtr();
14371 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14372 DAG.getConstant(4, MVT::i32));
14374 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14375 Ld->getPointerInfo(),
14376 Ld->isVolatile(), Ld->isNonTemporal(),
14377 Ld->isInvariant(), Ld->getAlignment());
14378 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14379 Ld->getPointerInfo().getWithOffset(4),
14380 Ld->isVolatile(), Ld->isNonTemporal(),
14382 MinAlign(Ld->getAlignment(), 4));
14384 SDValue NewChain = LoLd.getValue(1);
14385 if (TokenFactorIndex != -1) {
14386 Ops.push_back(LoLd);
14387 Ops.push_back(HiLd);
14388 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14392 LoAddr = St->getBasePtr();
14393 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14394 DAG.getConstant(4, MVT::i32));
14396 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14397 St->getPointerInfo(),
14398 St->isVolatile(), St->isNonTemporal(),
14399 St->getAlignment());
14400 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14401 St->getPointerInfo().getWithOffset(4),
14403 St->isNonTemporal(),
14404 MinAlign(St->getAlignment(), 4));
14405 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14410 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14411 /// and return the operands for the horizontal operation in LHS and RHS. A
14412 /// horizontal operation performs the binary operation on successive elements
14413 /// of its first operand, then on successive elements of its second operand,
14414 /// returning the resulting values in a vector. For example, if
14415 /// A = < float a0, float a1, float a2, float a3 >
14417 /// B = < float b0, float b1, float b2, float b3 >
14418 /// then the result of doing a horizontal operation on A and B is
14419 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14420 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14421 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14422 /// set to A, RHS to B, and the routine returns 'true'.
14423 /// Note that the binary operation should have the property that if one of the
14424 /// operands is UNDEF then the result is UNDEF.
14425 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14426 // Look for the following pattern: if
14427 // A = < float a0, float a1, float a2, float a3 >
14428 // B = < float b0, float b1, float b2, float b3 >
14430 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14431 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14432 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14433 // which is A horizontal-op B.
14435 // At least one of the operands should be a vector shuffle.
14436 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14437 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14440 EVT VT = LHS.getValueType();
14441 unsigned N = VT.getVectorNumElements();
14443 // View LHS in the form
14444 // LHS = VECTOR_SHUFFLE A, B, LMask
14445 // If LHS is not a shuffle then pretend it is the shuffle
14446 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14447 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14450 SmallVector<int, 8> LMask(N);
14451 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14452 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14453 A = LHS.getOperand(0);
14454 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14455 B = LHS.getOperand(1);
14456 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14458 if (LHS.getOpcode() != ISD::UNDEF)
14460 for (unsigned i = 0; i != N; ++i)
14464 // Likewise, view RHS in the form
14465 // RHS = VECTOR_SHUFFLE C, D, RMask
14467 SmallVector<int, 8> RMask(N);
14468 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14469 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14470 C = RHS.getOperand(0);
14471 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14472 D = RHS.getOperand(1);
14473 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14475 if (RHS.getOpcode() != ISD::UNDEF)
14477 for (unsigned i = 0; i != N; ++i)
14481 // Check that the shuffles are both shuffling the same vectors.
14482 if (!(A == C && B == D) && !(A == D && B == C))
14485 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14486 if (!A.getNode() && !B.getNode())
14489 // If A and B occur in reverse order in RHS, then "swap" them (which means
14490 // rewriting the mask).
14492 for (unsigned i = 0; i != N; ++i) {
14493 unsigned Idx = RMask[i];
14496 else if (Idx < 2*N)
14500 // At this point LHS and RHS are equivalent to
14501 // LHS = VECTOR_SHUFFLE A, B, LMask
14502 // RHS = VECTOR_SHUFFLE A, B, RMask
14503 // Check that the masks correspond to performing a horizontal operation.
14504 for (unsigned i = 0; i != N; ++i) {
14505 unsigned LIdx = LMask[i], RIdx = RMask[i];
14507 // Ignore any UNDEF components.
14508 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14509 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14512 // Check that successive elements are being operated on. If not, this is
14513 // not a horizontal operation.
14514 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14515 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14519 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14520 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14524 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14525 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14526 const X86Subtarget *Subtarget) {
14527 EVT VT = N->getValueType(0);
14528 SDValue LHS = N->getOperand(0);
14529 SDValue RHS = N->getOperand(1);
14531 // Try to synthesize horizontal adds from adds of shuffles.
14532 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14533 isHorizontalBinOp(LHS, RHS, true))
14534 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14538 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14539 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14540 const X86Subtarget *Subtarget) {
14541 EVT VT = N->getValueType(0);
14542 SDValue LHS = N->getOperand(0);
14543 SDValue RHS = N->getOperand(1);
14545 // Try to synthesize horizontal subs from subs of shuffles.
14546 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14547 isHorizontalBinOp(LHS, RHS, false))
14548 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14552 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14553 /// X86ISD::FXOR nodes.
14554 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14555 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14556 // F[X]OR(0.0, x) -> x
14557 // F[X]OR(x, 0.0) -> x
14558 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14559 if (C->getValueAPF().isPosZero())
14560 return N->getOperand(1);
14561 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14562 if (C->getValueAPF().isPosZero())
14563 return N->getOperand(0);
14567 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14568 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14569 // FAND(0.0, x) -> 0.0
14570 // FAND(x, 0.0) -> 0.0
14571 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14572 if (C->getValueAPF().isPosZero())
14573 return N->getOperand(0);
14574 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14575 if (C->getValueAPF().isPosZero())
14576 return N->getOperand(1);
14580 static SDValue PerformBTCombine(SDNode *N,
14582 TargetLowering::DAGCombinerInfo &DCI) {
14583 // BT ignores high bits in the bit index operand.
14584 SDValue Op1 = N->getOperand(1);
14585 if (Op1.hasOneUse()) {
14586 unsigned BitWidth = Op1.getValueSizeInBits();
14587 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14588 APInt KnownZero, KnownOne;
14589 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14590 !DCI.isBeforeLegalizeOps());
14591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14592 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14593 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14594 DCI.CommitTargetLoweringOpt(TLO);
14599 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14600 SDValue Op = N->getOperand(0);
14601 if (Op.getOpcode() == ISD::BITCAST)
14602 Op = Op.getOperand(0);
14603 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14604 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14605 VT.getVectorElementType().getSizeInBits() ==
14606 OpVT.getVectorElementType().getSizeInBits()) {
14607 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14612 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14613 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14614 // (and (i32 x86isd::setcc_carry), 1)
14615 // This eliminates the zext. This transformation is necessary because
14616 // ISD::SETCC is always legalized to i8.
14617 DebugLoc dl = N->getDebugLoc();
14618 SDValue N0 = N->getOperand(0);
14619 EVT VT = N->getValueType(0);
14620 if (N0.getOpcode() == ISD::AND &&
14622 N0.getOperand(0).hasOneUse()) {
14623 SDValue N00 = N0.getOperand(0);
14624 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14626 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14627 if (!C || C->getZExtValue() != 1)
14629 return DAG.getNode(ISD::AND, dl, VT,
14630 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14631 N00.getOperand(0), N00.getOperand(1)),
14632 DAG.getConstant(1, VT));
14638 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14639 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14640 unsigned X86CC = N->getConstantOperandVal(0);
14641 SDValue EFLAG = N->getOperand(1);
14642 DebugLoc DL = N->getDebugLoc();
14644 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14645 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14647 if (X86CC == X86::COND_B)
14648 return DAG.getNode(ISD::AND, DL, MVT::i8,
14649 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14650 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14651 DAG.getConstant(1, MVT::i8));
14656 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14657 const X86TargetLowering *XTLI) {
14658 SDValue Op0 = N->getOperand(0);
14659 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14660 // a 32-bit target where SSE doesn't support i64->FP operations.
14661 if (Op0.getOpcode() == ISD::LOAD) {
14662 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14663 EVT VT = Ld->getValueType(0);
14664 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14665 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14666 !XTLI->getSubtarget()->is64Bit() &&
14667 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14668 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14669 Ld->getChain(), Op0, DAG);
14670 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14677 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14678 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14679 X86TargetLowering::DAGCombinerInfo &DCI) {
14680 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14681 // the result is either zero or one (depending on the input carry bit).
14682 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14683 if (X86::isZeroNode(N->getOperand(0)) &&
14684 X86::isZeroNode(N->getOperand(1)) &&
14685 // We don't have a good way to replace an EFLAGS use, so only do this when
14687 SDValue(N, 1).use_empty()) {
14688 DebugLoc DL = N->getDebugLoc();
14689 EVT VT = N->getValueType(0);
14690 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14691 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14692 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14693 DAG.getConstant(X86::COND_B,MVT::i8),
14695 DAG.getConstant(1, VT));
14696 return DCI.CombineTo(N, Res1, CarryOut);
14702 // fold (add Y, (sete X, 0)) -> adc 0, Y
14703 // (add Y, (setne X, 0)) -> sbb -1, Y
14704 // (sub (sete X, 0), Y) -> sbb 0, Y
14705 // (sub (setne X, 0), Y) -> adc -1, Y
14706 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14707 DebugLoc DL = N->getDebugLoc();
14709 // Look through ZExts.
14710 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14711 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14714 SDValue SetCC = Ext.getOperand(0);
14715 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14718 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14719 if (CC != X86::COND_E && CC != X86::COND_NE)
14722 SDValue Cmp = SetCC.getOperand(1);
14723 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14724 !X86::isZeroNode(Cmp.getOperand(1)) ||
14725 !Cmp.getOperand(0).getValueType().isInteger())
14728 SDValue CmpOp0 = Cmp.getOperand(0);
14729 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14730 DAG.getConstant(1, CmpOp0.getValueType()));
14732 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14733 if (CC == X86::COND_NE)
14734 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14735 DL, OtherVal.getValueType(), OtherVal,
14736 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14737 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14738 DL, OtherVal.getValueType(), OtherVal,
14739 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14742 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14743 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14744 const X86Subtarget *Subtarget) {
14745 EVT VT = N->getValueType(0);
14746 SDValue Op0 = N->getOperand(0);
14747 SDValue Op1 = N->getOperand(1);
14749 // Try to synthesize horizontal adds from adds of shuffles.
14750 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14751 isHorizontalBinOp(Op0, Op1, true))
14752 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14754 return OptimizeConditionalInDecrement(N, DAG);
14757 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14758 const X86Subtarget *Subtarget) {
14759 SDValue Op0 = N->getOperand(0);
14760 SDValue Op1 = N->getOperand(1);
14762 // X86 can't encode an immediate LHS of a sub. See if we can push the
14763 // negation into a preceding instruction.
14764 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14765 // If the RHS of the sub is a XOR with one use and a constant, invert the
14766 // immediate. Then add one to the LHS of the sub so we can turn
14767 // X-Y -> X+~Y+1, saving one register.
14768 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14769 isa<ConstantSDNode>(Op1.getOperand(1))) {
14770 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14771 EVT VT = Op0.getValueType();
14772 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14774 DAG.getConstant(~XorC, VT));
14775 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14776 DAG.getConstant(C->getAPIntValue()+1, VT));
14780 // Try to synthesize horizontal adds from adds of shuffles.
14781 EVT VT = N->getValueType(0);
14782 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14783 isHorizontalBinOp(Op0, Op1, false))
14784 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14786 return OptimizeConditionalInDecrement(N, DAG);
14789 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14790 DAGCombinerInfo &DCI) const {
14791 SelectionDAG &DAG = DCI.DAG;
14792 switch (N->getOpcode()) {
14794 case ISD::EXTRACT_VECTOR_ELT:
14795 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14797 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14798 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14799 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14800 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14801 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14802 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14805 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14806 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14807 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14808 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14809 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14810 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14811 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14812 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14813 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14815 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14816 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14817 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14818 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14819 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14820 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14821 case X86ISD::SHUFPS: // Handle all target specific shuffles
14822 case X86ISD::SHUFPD:
14823 case X86ISD::PALIGN:
14824 case X86ISD::PUNPCKH:
14825 case X86ISD::UNPCKHP:
14826 case X86ISD::PUNPCKL:
14827 case X86ISD::UNPCKLP:
14828 case X86ISD::MOVHLPS:
14829 case X86ISD::MOVLHPS:
14830 case X86ISD::PSHUFD:
14831 case X86ISD::PSHUFHW:
14832 case X86ISD::PSHUFLW:
14833 case X86ISD::MOVSS:
14834 case X86ISD::MOVSD:
14835 case X86ISD::VPERMILPS:
14836 case X86ISD::VPERMILPSY:
14837 case X86ISD::VPERMILPD:
14838 case X86ISD::VPERMILPDY:
14839 case X86ISD::VPERM2F128:
14840 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14846 /// isTypeDesirableForOp - Return true if the target has native support for
14847 /// the specified value type and it is 'desirable' to use the type for the
14848 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14849 /// instruction encodings are longer and some i16 instructions are slow.
14850 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14851 if (!isTypeLegal(VT))
14853 if (VT != MVT::i16)
14860 case ISD::SIGN_EXTEND:
14861 case ISD::ZERO_EXTEND:
14862 case ISD::ANY_EXTEND:
14875 /// IsDesirableToPromoteOp - This method query the target whether it is
14876 /// beneficial for dag combiner to promote the specified node. If true, it
14877 /// should return the desired promotion type by reference.
14878 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14879 EVT VT = Op.getValueType();
14880 if (VT != MVT::i16)
14883 bool Promote = false;
14884 bool Commute = false;
14885 switch (Op.getOpcode()) {
14888 LoadSDNode *LD = cast<LoadSDNode>(Op);
14889 // If the non-extending load has a single use and it's not live out, then it
14890 // might be folded.
14891 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14892 Op.hasOneUse()*/) {
14893 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14894 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14895 // The only case where we'd want to promote LOAD (rather then it being
14896 // promoted as an operand is when it's only use is liveout.
14897 if (UI->getOpcode() != ISD::CopyToReg)
14904 case ISD::SIGN_EXTEND:
14905 case ISD::ZERO_EXTEND:
14906 case ISD::ANY_EXTEND:
14911 SDValue N0 = Op.getOperand(0);
14912 // Look out for (store (shl (load), x)).
14913 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14926 SDValue N0 = Op.getOperand(0);
14927 SDValue N1 = Op.getOperand(1);
14928 if (!Commute && MayFoldLoad(N1))
14930 // Avoid disabling potential load folding opportunities.
14931 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14933 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14943 //===----------------------------------------------------------------------===//
14944 // X86 Inline Assembly Support
14945 //===----------------------------------------------------------------------===//
14947 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14948 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14950 std::string AsmStr = IA->getAsmString();
14952 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14953 SmallVector<StringRef, 4> AsmPieces;
14954 SplitString(AsmStr, AsmPieces, ";\n");
14956 switch (AsmPieces.size()) {
14957 default: return false;
14959 AsmStr = AsmPieces[0];
14961 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14963 // FIXME: this should verify that we are targeting a 486 or better. If not,
14964 // we will turn this bswap into something that will be lowered to logical ops
14965 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14966 // so don't worry about this.
14968 if (AsmPieces.size() == 2 &&
14969 (AsmPieces[0] == "bswap" ||
14970 AsmPieces[0] == "bswapq" ||
14971 AsmPieces[0] == "bswapl") &&
14972 (AsmPieces[1] == "$0" ||
14973 AsmPieces[1] == "${0:q}")) {
14974 // No need to check constraints, nothing other than the equivalent of
14975 // "=r,0" would be valid here.
14976 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14977 if (!Ty || Ty->getBitWidth() % 16 != 0)
14979 return IntrinsicLowering::LowerToByteSwap(CI);
14981 // rorw $$8, ${0:w} --> llvm.bswap.i16
14982 if (CI->getType()->isIntegerTy(16) &&
14983 AsmPieces.size() == 3 &&
14984 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14985 AsmPieces[1] == "$$8," &&
14986 AsmPieces[2] == "${0:w}" &&
14987 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14989 const std::string &ConstraintsStr = IA->getConstraintString();
14990 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14991 std::sort(AsmPieces.begin(), AsmPieces.end());
14992 if (AsmPieces.size() == 4 &&
14993 AsmPieces[0] == "~{cc}" &&
14994 AsmPieces[1] == "~{dirflag}" &&
14995 AsmPieces[2] == "~{flags}" &&
14996 AsmPieces[3] == "~{fpsr}") {
14997 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14998 if (!Ty || Ty->getBitWidth() % 16 != 0)
15000 return IntrinsicLowering::LowerToByteSwap(CI);
15005 if (CI->getType()->isIntegerTy(32) &&
15006 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15007 SmallVector<StringRef, 4> Words;
15008 SplitString(AsmPieces[0], Words, " \t,");
15009 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15010 Words[2] == "${0:w}") {
15012 SplitString(AsmPieces[1], Words, " \t,");
15013 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15014 Words[2] == "$0") {
15016 SplitString(AsmPieces[2], Words, " \t,");
15017 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15018 Words[2] == "${0:w}") {
15020 const std::string &ConstraintsStr = IA->getConstraintString();
15021 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15022 std::sort(AsmPieces.begin(), AsmPieces.end());
15023 if (AsmPieces.size() == 4 &&
15024 AsmPieces[0] == "~{cc}" &&
15025 AsmPieces[1] == "~{dirflag}" &&
15026 AsmPieces[2] == "~{flags}" &&
15027 AsmPieces[3] == "~{fpsr}") {
15028 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15029 if (!Ty || Ty->getBitWidth() % 16 != 0)
15031 return IntrinsicLowering::LowerToByteSwap(CI);
15038 if (CI->getType()->isIntegerTy(64)) {
15039 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15040 if (Constraints.size() >= 2 &&
15041 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15042 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15043 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15044 SmallVector<StringRef, 4> Words;
15045 SplitString(AsmPieces[0], Words, " \t");
15046 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15048 SplitString(AsmPieces[1], Words, " \t");
15049 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15051 SplitString(AsmPieces[2], Words, " \t,");
15052 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15053 Words[2] == "%edx") {
15054 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15055 if (!Ty || Ty->getBitWidth() % 16 != 0)
15057 return IntrinsicLowering::LowerToByteSwap(CI);
15070 /// getConstraintType - Given a constraint letter, return the type of
15071 /// constraint it is for this target.
15072 X86TargetLowering::ConstraintType
15073 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15074 if (Constraint.size() == 1) {
15075 switch (Constraint[0]) {
15086 return C_RegisterClass;
15110 return TargetLowering::getConstraintType(Constraint);
15113 /// Examine constraint type and operand type and determine a weight value.
15114 /// This object must already have been set up with the operand type
15115 /// and the current alternative constraint selected.
15116 TargetLowering::ConstraintWeight
15117 X86TargetLowering::getSingleConstraintMatchWeight(
15118 AsmOperandInfo &info, const char *constraint) const {
15119 ConstraintWeight weight = CW_Invalid;
15120 Value *CallOperandVal = info.CallOperandVal;
15121 // If we don't have a value, we can't do a match,
15122 // but allow it at the lowest weight.
15123 if (CallOperandVal == NULL)
15125 Type *type = CallOperandVal->getType();
15126 // Look at the constraint type.
15127 switch (*constraint) {
15129 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15140 if (CallOperandVal->getType()->isIntegerTy())
15141 weight = CW_SpecificReg;
15146 if (type->isFloatingPointTy())
15147 weight = CW_SpecificReg;
15150 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15151 weight = CW_SpecificReg;
15155 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15156 weight = CW_Register;
15159 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15160 if (C->getZExtValue() <= 31)
15161 weight = CW_Constant;
15165 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15166 if (C->getZExtValue() <= 63)
15167 weight = CW_Constant;
15171 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15172 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15173 weight = CW_Constant;
15177 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15178 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15179 weight = CW_Constant;
15183 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15184 if (C->getZExtValue() <= 3)
15185 weight = CW_Constant;
15189 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15190 if (C->getZExtValue() <= 0xff)
15191 weight = CW_Constant;
15196 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15197 weight = CW_Constant;
15201 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15202 if ((C->getSExtValue() >= -0x80000000LL) &&
15203 (C->getSExtValue() <= 0x7fffffffLL))
15204 weight = CW_Constant;
15208 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15209 if (C->getZExtValue() <= 0xffffffff)
15210 weight = CW_Constant;
15217 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15218 /// with another that has more specific requirements based on the type of the
15219 /// corresponding operand.
15220 const char *X86TargetLowering::
15221 LowerXConstraint(EVT ConstraintVT) const {
15222 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15223 // 'f' like normal targets.
15224 if (ConstraintVT.isFloatingPoint()) {
15225 if (Subtarget->hasXMMInt())
15227 if (Subtarget->hasXMM())
15231 return TargetLowering::LowerXConstraint(ConstraintVT);
15234 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15235 /// vector. If it is invalid, don't add anything to Ops.
15236 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15237 std::string &Constraint,
15238 std::vector<SDValue>&Ops,
15239 SelectionDAG &DAG) const {
15240 SDValue Result(0, 0);
15242 // Only support length 1 constraints for now.
15243 if (Constraint.length() > 1) return;
15245 char ConstraintLetter = Constraint[0];
15246 switch (ConstraintLetter) {
15249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15250 if (C->getZExtValue() <= 31) {
15251 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15258 if (C->getZExtValue() <= 63) {
15259 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15266 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15267 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15274 if (C->getZExtValue() <= 255) {
15275 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15281 // 32-bit signed value
15282 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15283 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15284 C->getSExtValue())) {
15285 // Widen to 64 bits here to get it sign extended.
15286 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15289 // FIXME gcc accepts some relocatable values here too, but only in certain
15290 // memory models; it's complicated.
15295 // 32-bit unsigned value
15296 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15297 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15298 C->getZExtValue())) {
15299 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15303 // FIXME gcc accepts some relocatable values here too, but only in certain
15304 // memory models; it's complicated.
15308 // Literal immediates are always ok.
15309 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15310 // Widen to 64 bits here to get it sign extended.
15311 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15315 // In any sort of PIC mode addresses need to be computed at runtime by
15316 // adding in a register or some sort of table lookup. These can't
15317 // be used as immediates.
15318 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15321 // If we are in non-pic codegen mode, we allow the address of a global (with
15322 // an optional displacement) to be used with 'i'.
15323 GlobalAddressSDNode *GA = 0;
15324 int64_t Offset = 0;
15326 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15328 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15329 Offset += GA->getOffset();
15331 } else if (Op.getOpcode() == ISD::ADD) {
15332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15333 Offset += C->getZExtValue();
15334 Op = Op.getOperand(0);
15337 } else if (Op.getOpcode() == ISD::SUB) {
15338 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15339 Offset += -C->getZExtValue();
15340 Op = Op.getOperand(0);
15345 // Otherwise, this isn't something we can handle, reject it.
15349 const GlobalValue *GV = GA->getGlobal();
15350 // If we require an extra load to get this address, as in PIC mode, we
15351 // can't accept it.
15352 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15353 getTargetMachine())))
15356 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15357 GA->getValueType(0), Offset);
15362 if (Result.getNode()) {
15363 Ops.push_back(Result);
15366 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15369 std::pair<unsigned, const TargetRegisterClass*>
15370 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15372 // First, see if this is a constraint that directly corresponds to an LLVM
15374 if (Constraint.size() == 1) {
15375 // GCC Constraint Letters
15376 switch (Constraint[0]) {
15378 // TODO: Slight differences here in allocation order and leaving
15379 // RIP in the class. Do they matter any more here than they do
15380 // in the normal allocation?
15381 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15382 if (Subtarget->is64Bit()) {
15383 if (VT == MVT::i32 || VT == MVT::f32)
15384 return std::make_pair(0U, X86::GR32RegisterClass);
15385 else if (VT == MVT::i16)
15386 return std::make_pair(0U, X86::GR16RegisterClass);
15387 else if (VT == MVT::i8 || VT == MVT::i1)
15388 return std::make_pair(0U, X86::GR8RegisterClass);
15389 else if (VT == MVT::i64 || VT == MVT::f64)
15390 return std::make_pair(0U, X86::GR64RegisterClass);
15393 // 32-bit fallthrough
15394 case 'Q': // Q_REGS
15395 if (VT == MVT::i32 || VT == MVT::f32)
15396 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15397 else if (VT == MVT::i16)
15398 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15399 else if (VT == MVT::i8 || VT == MVT::i1)
15400 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15401 else if (VT == MVT::i64)
15402 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15404 case 'r': // GENERAL_REGS
15405 case 'l': // INDEX_REGS
15406 if (VT == MVT::i8 || VT == MVT::i1)
15407 return std::make_pair(0U, X86::GR8RegisterClass);
15408 if (VT == MVT::i16)
15409 return std::make_pair(0U, X86::GR16RegisterClass);
15410 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15411 return std::make_pair(0U, X86::GR32RegisterClass);
15412 return std::make_pair(0U, X86::GR64RegisterClass);
15413 case 'R': // LEGACY_REGS
15414 if (VT == MVT::i8 || VT == MVT::i1)
15415 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15416 if (VT == MVT::i16)
15417 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15418 if (VT == MVT::i32 || !Subtarget->is64Bit())
15419 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15420 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15421 case 'f': // FP Stack registers.
15422 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15423 // value to the correct fpstack register class.
15424 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15425 return std::make_pair(0U, X86::RFP32RegisterClass);
15426 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15427 return std::make_pair(0U, X86::RFP64RegisterClass);
15428 return std::make_pair(0U, X86::RFP80RegisterClass);
15429 case 'y': // MMX_REGS if MMX allowed.
15430 if (!Subtarget->hasMMX()) break;
15431 return std::make_pair(0U, X86::VR64RegisterClass);
15432 case 'Y': // SSE_REGS if SSE2 allowed
15433 if (!Subtarget->hasXMMInt()) break;
15435 case 'x': // SSE_REGS if SSE1 allowed
15436 if (!Subtarget->hasXMM()) break;
15438 switch (VT.getSimpleVT().SimpleTy) {
15440 // Scalar SSE types.
15443 return std::make_pair(0U, X86::FR32RegisterClass);
15446 return std::make_pair(0U, X86::FR64RegisterClass);
15454 return std::make_pair(0U, X86::VR128RegisterClass);
15460 // Use the default implementation in TargetLowering to convert the register
15461 // constraint into a member of a register class.
15462 std::pair<unsigned, const TargetRegisterClass*> Res;
15463 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15465 // Not found as a standard register?
15466 if (Res.second == 0) {
15467 // Map st(0) -> st(7) -> ST0
15468 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15469 tolower(Constraint[1]) == 's' &&
15470 tolower(Constraint[2]) == 't' &&
15471 Constraint[3] == '(' &&
15472 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15473 Constraint[5] == ')' &&
15474 Constraint[6] == '}') {
15476 Res.first = X86::ST0+Constraint[4]-'0';
15477 Res.second = X86::RFP80RegisterClass;
15481 // GCC allows "st(0)" to be called just plain "st".
15482 if (StringRef("{st}").equals_lower(Constraint)) {
15483 Res.first = X86::ST0;
15484 Res.second = X86::RFP80RegisterClass;
15489 if (StringRef("{flags}").equals_lower(Constraint)) {
15490 Res.first = X86::EFLAGS;
15491 Res.second = X86::CCRRegisterClass;
15495 // 'A' means EAX + EDX.
15496 if (Constraint == "A") {
15497 Res.first = X86::EAX;
15498 Res.second = X86::GR32_ADRegisterClass;
15504 // Otherwise, check to see if this is a register class of the wrong value
15505 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15506 // turn into {ax},{dx}.
15507 if (Res.second->hasType(VT))
15508 return Res; // Correct type already, nothing to do.
15510 // All of the single-register GCC register classes map their values onto
15511 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15512 // really want an 8-bit or 32-bit register, map to the appropriate register
15513 // class and return the appropriate register.
15514 if (Res.second == X86::GR16RegisterClass) {
15515 if (VT == MVT::i8) {
15516 unsigned DestReg = 0;
15517 switch (Res.first) {
15519 case X86::AX: DestReg = X86::AL; break;
15520 case X86::DX: DestReg = X86::DL; break;
15521 case X86::CX: DestReg = X86::CL; break;
15522 case X86::BX: DestReg = X86::BL; break;
15525 Res.first = DestReg;
15526 Res.second = X86::GR8RegisterClass;
15528 } else if (VT == MVT::i32) {
15529 unsigned DestReg = 0;
15530 switch (Res.first) {
15532 case X86::AX: DestReg = X86::EAX; break;
15533 case X86::DX: DestReg = X86::EDX; break;
15534 case X86::CX: DestReg = X86::ECX; break;
15535 case X86::BX: DestReg = X86::EBX; break;
15536 case X86::SI: DestReg = X86::ESI; break;
15537 case X86::DI: DestReg = X86::EDI; break;
15538 case X86::BP: DestReg = X86::EBP; break;
15539 case X86::SP: DestReg = X86::ESP; break;
15542 Res.first = DestReg;
15543 Res.second = X86::GR32RegisterClass;
15545 } else if (VT == MVT::i64) {
15546 unsigned DestReg = 0;
15547 switch (Res.first) {
15549 case X86::AX: DestReg = X86::RAX; break;
15550 case X86::DX: DestReg = X86::RDX; break;
15551 case X86::CX: DestReg = X86::RCX; break;
15552 case X86::BX: DestReg = X86::RBX; break;
15553 case X86::SI: DestReg = X86::RSI; break;
15554 case X86::DI: DestReg = X86::RDI; break;
15555 case X86::BP: DestReg = X86::RBP; break;
15556 case X86::SP: DestReg = X86::RSP; break;
15559 Res.first = DestReg;
15560 Res.second = X86::GR64RegisterClass;
15563 } else if (Res.second == X86::FR32RegisterClass ||
15564 Res.second == X86::FR64RegisterClass ||
15565 Res.second == X86::VR128RegisterClass) {
15566 // Handle references to XMM physical registers that got mapped into the
15567 // wrong class. This can happen with constraints like {xmm0} where the
15568 // target independent register mapper will just pick the first match it can
15569 // find, ignoring the required type.
15570 if (VT == MVT::f32)
15571 Res.second = X86::FR32RegisterClass;
15572 else if (VT == MVT::f64)
15573 Res.second = X86::FR64RegisterClass;
15574 else if (X86::VR128RegisterClass->hasType(VT))
15575 Res.second = X86::VR128RegisterClass;