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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.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 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference. Idx is an index in the 128 bits we
80 /// want. It need not be aligned to a 128-bit bounday. That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
86 EVT VT = Vec.getValueType();
87 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
89 EVT ElVT = VT.getVectorElementType();
91 int Factor = VT.getSizeInBits() / 128;
93 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
95 VT.getVectorNumElements() / Factor);
97 // Extract from UNDEF is UNDEF.
98 if (Vec.getOpcode() == ISD::UNDEF)
99 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
101 if (isa<ConstantSDNode>(Idx)) {
102 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
104 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
105 // we can match to VEXTRACTF128.
106 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
108 // This is the index of the first element of the 128-bit chunk
110 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
113 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
115 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
124 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference. Idx is an index in the 128 bits
127 /// we want. It need not be aligned to a 128-bit bounday. That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
134 if (isa<ConstantSDNode>(Idx)) {
135 EVT VT = Vec.getValueType();
136 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
138 EVT ElVT = VT.getVectorElementType();
140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant 128 bits.
145 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
147 // This is the index of the first element of the 128-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
152 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
154 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164 DebugLoc dl = Lower.getDebugLoc();
166 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
168 EVT VT = EVT::getVectorVT(*DAG.getContext(),
169 Lower.getValueType().getVectorElementType(),
170 Lower.getValueType().getVectorNumElements() * 2);
172 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
175 // Insert the upper subvector.
176 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
178 // This is half the length of the result
179 // vector. Start inserting the upper 128
181 Lower.getValueType().getVectorNumElements(),
185 // Insert the lower subvector.
186 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192 bool is64Bit = Subtarget->is64Bit();
194 if (Subtarget->isTargetEnvMacho()) {
196 return new X8664_MachoTargetObjectFile();
197 return new TargetLoweringObjectFileMachO();
200 if (Subtarget->isTargetELF()) {
202 return new X8664_ELFTargetObjectFile(TM);
203 return new X8632_ELFTargetObjectFile(TM);
205 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206 return new TargetLoweringObjectFileCOFF();
207 llvm_unreachable("unknown subtarget type");
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211 : TargetLowering(TM, createTLOF(TM)) {
212 Subtarget = &TM.getSubtarget<X86Subtarget>();
213 X86ScalarSSEf64 = Subtarget->hasXMMInt();
214 X86ScalarSSEf32 = Subtarget->hasXMM();
215 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
217 RegInfo = TM.getRegisterInfo();
218 TD = getTargetData();
220 // Set up the TargetLowering object.
221 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
223 // X86 is weird, it always uses i8 for shift amounts and setcc results.
224 setBooleanContents(ZeroOrOneBooleanContent);
226 // For 64-bit since we have so many registers use the ILP scheduler, for
227 // 32-bit code use the register pressure specific scheduling.
228 if (Subtarget->is64Bit())
229 setSchedulingPreference(Sched::ILP);
231 setSchedulingPreference(Sched::RegPressure);
232 setStackPointerRegisterToSaveRestore(X86StackPtr);
234 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235 // Setup Windows compiler runtime calls.
236 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
246 if (Subtarget->isTargetDarwin()) {
247 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248 setUseUnderscoreSetJmp(false);
249 setUseUnderscoreLongJmp(false);
250 } else if (Subtarget->isTargetMingw()) {
251 // MS runtime is weird: it exports _setjmp, but longjmp!
252 setUseUnderscoreSetJmp(true);
253 setUseUnderscoreLongJmp(false);
255 setUseUnderscoreSetJmp(true);
256 setUseUnderscoreLongJmp(true);
259 // Set up the register classes.
260 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263 if (Subtarget->is64Bit())
264 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
266 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
268 // We don't accept any truncstore of integer registers.
269 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
276 // SETOEQ and SETUNE require checking two conditions.
277 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
284 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
286 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
288 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
290 if (Subtarget->is64Bit()) {
291 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
293 } else if (!UseSoftFloat) {
294 // We have an algorithm for SSE2->double, and we turn this into a
295 // 64-bit FILD followed by conditional FADD for other targets.
296 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
297 // We have an algorithm for SSE2, and we turn this into a 64-bit
298 // FILD for other targets.
299 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
302 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
304 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
305 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
308 // SSE has no i16 to fp conversion, only i32
309 if (X86ScalarSSEf32) {
310 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
311 // f32 and f64 cases are Legal, f80 case is not
312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
315 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
322 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
323 // are Legal, f80 is custom lowered.
324 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
325 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
327 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
329 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
330 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
332 if (X86ScalarSSEf32) {
333 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
334 // f32 and f64 cases are Legal, f80 case is not
335 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
337 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
338 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
341 // Handle FP_TO_UINT by promoting the destination to a larger signed
343 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
345 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
350 } else if (!UseSoftFloat) {
351 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352 // Expand FP_TO_UINT into a select.
353 // FIXME: We would like to use a Custom expander here eventually to do
354 // the optimal thing for SSE vs. the default expansion in the legalizer.
355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
357 // With SSE3 we can use fisttpll to convert to a signed i64; without
358 // SSE, we're stuck with a fistpll.
359 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
362 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363 if (!X86ScalarSSEf64) {
364 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
365 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
366 if (Subtarget->is64Bit()) {
367 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
368 // Without SSE, i64->f64 goes through memory.
369 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
373 // Scalar integer divide and remainder are lowered to use operations that
374 // produce two results, to match the available instructions. This exposes
375 // the two-result form to trivial CSE, which is able to combine x/y and x%y
376 // into a single instruction.
378 // Scalar integer multiply-high is also lowered to use two-result
379 // operations, to match the available instructions. However, plain multiply
380 // (low) operations are left as Legal, as there are single-result
381 // instructions for this in x86. Using the two-result multiply instructions
382 // when both high and low results are needed must be arranged by dagcombine.
383 for (unsigned i = 0, e = 4; i != e; ++i) {
385 setOperationAction(ISD::MULHS, VT, Expand);
386 setOperationAction(ISD::MULHU, VT, Expand);
387 setOperationAction(ISD::SDIV, VT, Expand);
388 setOperationAction(ISD::UDIV, VT, Expand);
389 setOperationAction(ISD::SREM, VT, Expand);
390 setOperationAction(ISD::UREM, VT, Expand);
392 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393 setOperationAction(ISD::ADDC, VT, Custom);
394 setOperationAction(ISD::ADDE, VT, Custom);
395 setOperationAction(ISD::SUBC, VT, Custom);
396 setOperationAction(ISD::SUBE, VT, Custom);
399 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
400 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
401 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
402 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
408 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
409 setOperationAction(ISD::FREM , MVT::f32 , Expand);
410 setOperationAction(ISD::FREM , MVT::f64 , Expand);
411 setOperationAction(ISD::FREM , MVT::f80 , Expand);
412 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
418 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
419 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
425 if (Subtarget->hasPOPCNT()) {
426 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
428 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
435 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
436 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
438 // These should be promoted to a larger select which is supported.
439 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
440 // X86 wants to expand cmov itself.
441 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
455 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
457 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
461 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
462 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
463 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
467 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
468 if (Subtarget->is64Bit()) {
469 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
472 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
473 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
475 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
477 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
478 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
479 if (Subtarget->is64Bit()) {
480 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
481 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
482 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
485 if (Subtarget->hasXMM())
486 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
488 // We may not have a libcall for MEMBARRIER so we should lower this.
489 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 // On X86 and X86-64, atomic operations are lowered to locked instructions.
492 // Locked instructions, in turn, have implicit fence semantics (all memory
493 // operations are flushed before issuing the locked instruction, and they
494 // are not buffered), so we can fold away the common pattern of
495 // fence-atomic-fence.
496 setShouldFoldAtomicFences(true);
498 // Expand certain atomics
499 for (unsigned i = 0, e = 4; i != e; ++i) {
501 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 if (!Subtarget->is64Bit()) {
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
515 // FIXME - use subtarget debug flags
516 if (!Subtarget->isTargetDarwin() &&
517 !Subtarget->isTargetELF() &&
518 !Subtarget->isTargetCygMing()) {
519 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
522 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
524 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
526 if (Subtarget->is64Bit()) {
527 setExceptionPointerRegister(X86::RAX);
528 setExceptionSelectorRegister(X86::RDX);
530 setExceptionPointerRegister(X86::EAX);
531 setExceptionSelectorRegister(X86::EDX);
533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
536 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
538 setOperationAction(ISD::TRAP, MVT::Other, Legal);
540 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541 setOperationAction(ISD::VASTART , MVT::Other, Custom);
542 setOperationAction(ISD::VAEND , MVT::Other, Expand);
543 if (Subtarget->is64Bit()) {
544 setOperationAction(ISD::VAARG , MVT::Other, Custom);
545 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
547 setOperationAction(ISD::VAARG , MVT::Other, Expand);
548 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
551 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
552 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
553 setOperationAction(ISD::DYNAMIC_STACKALLOC,
554 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555 (Subtarget->isTargetCOFF()
556 && !Subtarget->isTargetEnvMacho()
559 if (!UseSoftFloat && X86ScalarSSEf64) {
560 // f32 and f64 use SSE.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
565 // Use ANDPD to simulate FABS.
566 setOperationAction(ISD::FABS , MVT::f64, Custom);
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f64, Custom);
571 setOperationAction(ISD::FNEG , MVT::f32, Custom);
573 // Use ANDPD and ORPD to simulate FCOPYSIGN.
574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 // We don't support sin/cos/fmod
578 setOperationAction(ISD::FSIN , MVT::f64, Expand);
579 setOperationAction(ISD::FCOS , MVT::f64, Expand);
580 setOperationAction(ISD::FSIN , MVT::f32, Expand);
581 setOperationAction(ISD::FCOS , MVT::f32, Expand);
583 // Expand FP immediates into loads from the stack, except for the special
585 addLegalFPImmediate(APFloat(+0.0)); // xorpd
586 addLegalFPImmediate(APFloat(+0.0f)); // xorps
587 } else if (!UseSoftFloat && X86ScalarSSEf32) {
588 // Use SSE for f32, x87 for f64.
589 // Set up the FP register classes.
590 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
593 // Use ANDPS to simulate FABS.
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
601 // Use ANDPS and ORPS to simulate FCOPYSIGN.
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
605 // We don't support sin/cos/fmod
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 // Special cases we handle for FP constants.
610 addLegalFPImmediate(APFloat(+0.0f)); // xorps
611 addLegalFPImmediate(APFloat(+0.0)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
618 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
620 } else if (!UseSoftFloat) {
621 // f32 and f64 in x87.
622 // Set up the FP register classes.
623 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
626 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
627 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
632 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
633 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
635 addLegalFPImmediate(APFloat(+0.0)); // FLD0
636 addLegalFPImmediate(APFloat(+1.0)); // FLD1
637 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
645 // Long double always uses X87.
647 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
649 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
651 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652 addLegalFPImmediate(TmpFlt); // FLD0
654 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
657 APFloat TmpFlt2(+1.0);
658 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
660 addLegalFPImmediate(TmpFlt2); // FLD1
661 TmpFlt2.changeSign();
662 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
666 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
667 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
671 // Always use a library call for pow.
672 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
674 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
676 setOperationAction(ISD::FLOG, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP, MVT::f80, Expand);
680 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
741 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743 setTruncStoreAction((MVT::SimpleValueType)VT,
744 (MVT::SimpleValueType)InnerVT, Expand);
745 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751 // with -msoft-float, disable use of MMX as well.
752 if (!UseSoftFloat && Subtarget->hasMMX()) {
753 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754 // No operations on x86mmx supported, everything uses intrinsics.
757 // MMX-sized vectors (other than x86mmx) are expected to be expanded
758 // into smaller operations.
759 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
760 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
761 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
762 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
763 setOperationAction(ISD::AND, MVT::v8i8, Expand);
764 setOperationAction(ISD::AND, MVT::v4i16, Expand);
765 setOperationAction(ISD::AND, MVT::v2i32, Expand);
766 setOperationAction(ISD::AND, MVT::v1i64, Expand);
767 setOperationAction(ISD::OR, MVT::v8i8, Expand);
768 setOperationAction(ISD::OR, MVT::v4i16, Expand);
769 setOperationAction(ISD::OR, MVT::v2i32, Expand);
770 setOperationAction(ISD::OR, MVT::v1i64, Expand);
771 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
781 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
782 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
783 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
789 if (!UseSoftFloat && Subtarget->hasXMM()) {
790 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
792 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
793 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
794 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
795 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
796 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
797 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
798 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
803 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
806 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
809 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810 // registers cannot be used even for integer operations.
811 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
816 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
817 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
818 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
819 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
833 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
834 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
850 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852 EVT VT = (MVT::SimpleValueType)i;
853 // Do not attempt to custom lower non-power-of-2 vectors
854 if (!isPowerOf2_32(VT.getVectorNumElements()))
856 // Do not attempt to custom lower non-128-bit vectors
857 if (!VT.is128BitVector())
859 setOperationAction(ISD::BUILD_VECTOR,
860 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE,
862 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
874 if (Subtarget->is64Bit()) {
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
879 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
884 // Do not attempt to promote non-128-bit vectors
885 if (!VT.is128BitVector())
888 setOperationAction(ISD::AND, SVT, Promote);
889 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
890 setOperationAction(ISD::OR, SVT, Promote);
891 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
892 setOperationAction(ISD::XOR, SVT, Promote);
893 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
894 setOperationAction(ISD::LOAD, SVT, Promote);
895 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
896 setOperationAction(ISD::SELECT, SVT, Promote);
897 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
900 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
902 // Custom lower v2i64 and v2f64 selects.
903 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
904 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
905 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
912 if (Subtarget->hasSSE41()) {
913 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
924 // FIXME: Do we need to handle scalar-to-vector here?
925 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
927 // Can turn SHL into an integer multiply.
928 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
929 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
930 setOperationAction(ISD::SRL, MVT::v4i32, 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 if (Subtarget->is64Bit()) {
947 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952 if (Subtarget->hasSSE42())
953 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
955 if (!UseSoftFloat && Subtarget->hasAVX()) {
956 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
957 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
958 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
959 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
960 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
962 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
963 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
964 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
965 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
967 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
968 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
969 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
970 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
971 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
972 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
974 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
975 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
976 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
977 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
978 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
979 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
981 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
982 // insert_vector_elt extract_subvector and extract_vector_elt for
984 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
985 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
987 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
988 // Do not attempt to custom lower non-256-bit vectors
989 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
990 || (MVT(VT).getSizeInBits() < 256))
992 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
993 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
996 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
998 // Custom-lower insert_subvector and extract_subvector based on
1000 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1003 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004 // Do not attempt to custom lower non-256-bit vectors
1005 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1008 if (MVT(VT).getSizeInBits() == 128) {
1009 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1011 else if (MVT(VT).getSizeInBits() == 256) {
1012 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1016 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1017 // Don't promote loads because we need them for VPERM vector index versions.
1019 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1020 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1022 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1023 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1025 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1026 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1027 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1028 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1029 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1030 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1031 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1032 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1033 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1034 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1038 // We want to custom lower some of our intrinsics.
1039 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1042 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1043 // handle type legalization for these operations here.
1045 // FIXME: We really should do custom legalization for addition and
1046 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1047 // than generic legalization for 64-bit multiplication-with-overflow, though.
1048 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1049 // Add/Sub/Mul with overflow operations are custom lowered.
1051 setOperationAction(ISD::SADDO, VT, Custom);
1052 setOperationAction(ISD::UADDO, VT, Custom);
1053 setOperationAction(ISD::SSUBO, VT, Custom);
1054 setOperationAction(ISD::USUBO, VT, Custom);
1055 setOperationAction(ISD::SMULO, VT, Custom);
1056 setOperationAction(ISD::UMULO, VT, Custom);
1059 // There are no 8-bit 3-address imul/mul instructions
1060 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1061 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1063 if (!Subtarget->is64Bit()) {
1064 // These libcalls are not available in 32-bit.
1065 setLibcallName(RTLIB::SHL_I128, 0);
1066 setLibcallName(RTLIB::SRL_I128, 0);
1067 setLibcallName(RTLIB::SRA_I128, 0);
1070 // We have target-specific dag combine patterns for the following nodes:
1071 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1072 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1073 setTargetDAGCombine(ISD::BUILD_VECTOR);
1074 setTargetDAGCombine(ISD::SELECT);
1075 setTargetDAGCombine(ISD::SHL);
1076 setTargetDAGCombine(ISD::SRA);
1077 setTargetDAGCombine(ISD::SRL);
1078 setTargetDAGCombine(ISD::OR);
1079 setTargetDAGCombine(ISD::AND);
1080 setTargetDAGCombine(ISD::ADD);
1081 setTargetDAGCombine(ISD::SUB);
1082 setTargetDAGCombine(ISD::STORE);
1083 setTargetDAGCombine(ISD::ZERO_EXTEND);
1084 if (Subtarget->is64Bit())
1085 setTargetDAGCombine(ISD::MUL);
1087 computeRegisterProperties();
1089 // On Darwin, -Os means optimize for size without hurting performance,
1090 // do not reduce the limit.
1091 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1092 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1093 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1094 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1095 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1096 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1097 setPrefLoopAlignment(16);
1098 benefitFromCodePlacementOpt = true;
1102 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1107 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1108 /// the desired ByVal argument alignment.
1109 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1112 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1113 if (VTy->getBitWidth() == 128)
1115 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1116 unsigned EltAlign = 0;
1117 getMaxByValAlign(ATy->getElementType(), EltAlign);
1118 if (EltAlign > MaxAlign)
1119 MaxAlign = EltAlign;
1120 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1121 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1122 unsigned EltAlign = 0;
1123 getMaxByValAlign(STy->getElementType(i), EltAlign);
1124 if (EltAlign > MaxAlign)
1125 MaxAlign = EltAlign;
1133 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1134 /// function arguments in the caller parameter area. For X86, aggregates
1135 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1136 /// are at 4-byte boundaries.
1137 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1138 if (Subtarget->is64Bit()) {
1139 // Max of 8 and alignment of type.
1140 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1147 if (Subtarget->hasXMM())
1148 getMaxByValAlign(Ty, Align);
1152 /// getOptimalMemOpType - Returns the target specific optimal type for load
1153 /// and store operations as a result of memset, memcpy, and memmove
1154 /// lowering. If DstAlign is zero that means it's safe to destination
1155 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1156 /// means there isn't a need to check it against alignment requirement,
1157 /// probably because the source does not need to be loaded. If
1158 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1159 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1160 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1161 /// constant so it does not need to be loaded.
1162 /// It returns EVT::Other if the type should be determined using generic
1163 /// target-independent logic.
1165 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1166 unsigned DstAlign, unsigned SrcAlign,
1167 bool NonScalarIntSafe,
1169 MachineFunction &MF) const {
1170 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1171 // linux. This is because the stack realignment code can't handle certain
1172 // cases like PR2962. This should be removed when PR2962 is fixed.
1173 const Function *F = MF.getFunction();
1174 if (NonScalarIntSafe &&
1175 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1177 (Subtarget->isUnalignedMemAccessFast() ||
1178 ((DstAlign == 0 || DstAlign >= 16) &&
1179 (SrcAlign == 0 || SrcAlign >= 16))) &&
1180 Subtarget->getStackAlignment() >= 16) {
1181 if (Subtarget->hasSSE2())
1183 if (Subtarget->hasSSE1())
1185 } else if (!MemcpyStrSrc && Size >= 8 &&
1186 !Subtarget->is64Bit() &&
1187 Subtarget->getStackAlignment() >= 8 &&
1188 Subtarget->hasXMMInt()) {
1189 // Do not use f64 to lower memcpy if source is string constant. It's
1190 // better to use i32 to avoid the loads.
1194 if (Subtarget->is64Bit() && Size >= 8)
1199 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1200 /// current function. The returned value is a member of the
1201 /// MachineJumpTableInfo::JTEntryKind enum.
1202 unsigned X86TargetLowering::getJumpTableEncoding() const {
1203 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1205 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1206 Subtarget->isPICStyleGOT())
1207 return MachineJumpTableInfo::EK_Custom32;
1209 // Otherwise, use the normal jump table encoding heuristics.
1210 return TargetLowering::getJumpTableEncoding();
1214 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1215 const MachineBasicBlock *MBB,
1216 unsigned uid,MCContext &Ctx) const{
1217 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1218 Subtarget->isPICStyleGOT());
1219 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1221 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1222 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1225 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1227 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1228 SelectionDAG &DAG) const {
1229 if (!Subtarget->is64Bit())
1230 // This doesn't have DebugLoc associated with it, but is not really the
1231 // same as a Register.
1232 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1236 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1237 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1239 const MCExpr *X86TargetLowering::
1240 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1241 MCContext &Ctx) const {
1242 // X86-64 uses RIP relative addressing based on the jump table label.
1243 if (Subtarget->isPICStyleRIPRel())
1244 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1246 // Otherwise, the reference is relative to the PIC base.
1247 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1250 /// getFunctionAlignment - Return the Log2 alignment of this function.
1251 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1252 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1255 // FIXME: Why this routine is here? Move to RegInfo!
1256 std::pair<const TargetRegisterClass*, uint8_t>
1257 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1258 const TargetRegisterClass *RRC = 0;
1260 switch (VT.getSimpleVT().SimpleTy) {
1262 return TargetLowering::findRepresentativeClass(VT);
1263 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1264 RRC = (Subtarget->is64Bit()
1265 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1268 RRC = X86::VR64RegisterClass;
1270 case MVT::f32: case MVT::f64:
1271 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1272 case MVT::v4f32: case MVT::v2f64:
1273 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1275 RRC = X86::VR128RegisterClass;
1278 return std::make_pair(RRC, Cost);
1281 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1282 unsigned &Offset) const {
1283 if (!Subtarget->isTargetLinux())
1286 if (Subtarget->is64Bit()) {
1287 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1289 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1302 //===----------------------------------------------------------------------===//
1303 // Return Value Calling Convention Implementation
1304 //===----------------------------------------------------------------------===//
1306 #include "X86GenCallingConv.inc"
1309 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1310 const SmallVectorImpl<ISD::OutputArg> &Outs,
1311 LLVMContext &Context) const {
1312 SmallVector<CCValAssign, 16> RVLocs;
1313 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1315 return CCInfo.CheckReturn(Outs, RetCC_X86);
1319 X86TargetLowering::LowerReturn(SDValue Chain,
1320 CallingConv::ID CallConv, bool isVarArg,
1321 const SmallVectorImpl<ISD::OutputArg> &Outs,
1322 const SmallVectorImpl<SDValue> &OutVals,
1323 DebugLoc dl, SelectionDAG &DAG) const {
1324 MachineFunction &MF = DAG.getMachineFunction();
1325 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1327 SmallVector<CCValAssign, 16> RVLocs;
1328 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1329 RVLocs, *DAG.getContext());
1330 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1332 // Add the regs to the liveout set for the function.
1333 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1334 for (unsigned i = 0; i != RVLocs.size(); ++i)
1335 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1336 MRI.addLiveOut(RVLocs[i].getLocReg());
1340 SmallVector<SDValue, 6> RetOps;
1341 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1342 // Operand #1 = Bytes To Pop
1343 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1346 // Copy the result values into the output registers.
1347 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1348 CCValAssign &VA = RVLocs[i];
1349 assert(VA.isRegLoc() && "Can only return in registers!");
1350 SDValue ValToCopy = OutVals[i];
1351 EVT ValVT = ValToCopy.getValueType();
1353 // If this is x86-64, and we disabled SSE, we can't return FP values,
1354 // or SSE or MMX vectors.
1355 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1356 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1357 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1358 report_fatal_error("SSE register return with SSE disabled");
1360 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1361 // llvm-gcc has never done it right and no one has noticed, so this
1362 // should be OK for now.
1363 if (ValVT == MVT::f64 &&
1364 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1365 report_fatal_error("SSE2 register return with SSE2 disabled");
1367 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1368 // the RET instruction and handled by the FP Stackifier.
1369 if (VA.getLocReg() == X86::ST0 ||
1370 VA.getLocReg() == X86::ST1) {
1371 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1372 // change the value to the FP stack register class.
1373 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1374 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1375 RetOps.push_back(ValToCopy);
1376 // Don't emit a copytoreg.
1380 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1381 // which is returned in RAX / RDX.
1382 if (Subtarget->is64Bit()) {
1383 if (ValVT == MVT::x86mmx) {
1384 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1385 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1386 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1388 // If we don't have SSE2 available, convert to v4f32 so the generated
1389 // register is legal.
1390 if (!Subtarget->hasSSE2())
1391 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1396 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1397 Flag = Chain.getValue(1);
1400 // The x86-64 ABI for returning structs by value requires that we copy
1401 // the sret argument into %rax for the return. We saved the argument into
1402 // a virtual register in the entry block, so now we copy the value out
1404 if (Subtarget->is64Bit() &&
1405 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1406 MachineFunction &MF = DAG.getMachineFunction();
1407 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1408 unsigned Reg = FuncInfo->getSRetReturnReg();
1410 "SRetReturnReg should have been set in LowerFormalArguments().");
1411 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1413 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1414 Flag = Chain.getValue(1);
1416 // RAX now acts like a return value.
1417 MRI.addLiveOut(X86::RAX);
1420 RetOps[0] = Chain; // Update chain.
1422 // Add the flag if we have it.
1424 RetOps.push_back(Flag);
1426 return DAG.getNode(X86ISD::RET_FLAG, dl,
1427 MVT::Other, &RetOps[0], RetOps.size());
1430 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1431 if (N->getNumValues() != 1)
1433 if (!N->hasNUsesOfValue(1, 0))
1436 SDNode *Copy = *N->use_begin();
1437 if (Copy->getOpcode() != ISD::CopyToReg &&
1438 Copy->getOpcode() != ISD::FP_EXTEND)
1441 bool HasRet = false;
1442 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1444 if (UI->getOpcode() != X86ISD::RET_FLAG)
1453 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1454 ISD::NodeType ExtendKind) const {
1456 // TODO: Is this also valid on 32-bit?
1457 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1458 ReturnMVT = MVT::i8;
1460 ReturnMVT = MVT::i32;
1462 EVT MinVT = getRegisterType(Context, ReturnMVT);
1463 return VT.bitsLT(MinVT) ? MinVT : VT;
1466 /// LowerCallResult - Lower the result values of a call into the
1467 /// appropriate copies out of appropriate physical registers.
1470 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1471 CallingConv::ID CallConv, bool isVarArg,
1472 const SmallVectorImpl<ISD::InputArg> &Ins,
1473 DebugLoc dl, SelectionDAG &DAG,
1474 SmallVectorImpl<SDValue> &InVals) const {
1476 // Assign locations to each value returned by this call.
1477 SmallVector<CCValAssign, 16> RVLocs;
1478 bool Is64Bit = Subtarget->is64Bit();
1479 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1480 RVLocs, *DAG.getContext());
1481 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1483 // Copy all of the result registers out of their specified physreg.
1484 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1485 CCValAssign &VA = RVLocs[i];
1486 EVT CopyVT = VA.getValVT();
1488 // If this is x86-64, and we disabled SSE, we can't return FP values
1489 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1490 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1491 report_fatal_error("SSE register return with SSE disabled");
1496 // If this is a call to a function that returns an fp value on the floating
1497 // point stack, we must guarantee the the value is popped from the stack, so
1498 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1499 // if the return value is not used. We use the FpGET_ST0 instructions
1501 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1502 // If we prefer to use the value in xmm registers, copy it out as f80 and
1503 // use a truncate to move it from fp stack reg to xmm reg.
1504 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1505 bool isST0 = VA.getLocReg() == X86::ST0;
1507 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1508 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1509 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1510 SDValue Ops[] = { Chain, InFlag };
1511 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1513 Val = Chain.getValue(0);
1515 // Round the f80 to the right size, which also moves it to the appropriate
1517 if (CopyVT != VA.getValVT())
1518 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1519 // This truncation won't change the value.
1520 DAG.getIntPtrConstant(1));
1521 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1522 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1523 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1524 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1525 MVT::v2i64, InFlag).getValue(1);
1526 Val = Chain.getValue(0);
1527 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1528 Val, DAG.getConstant(0, MVT::i64));
1530 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1531 MVT::i64, InFlag).getValue(1);
1532 Val = Chain.getValue(0);
1534 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1536 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1537 CopyVT, InFlag).getValue(1);
1538 Val = Chain.getValue(0);
1540 InFlag = Chain.getValue(2);
1541 InVals.push_back(Val);
1548 //===----------------------------------------------------------------------===//
1549 // C & StdCall & Fast Calling Convention implementation
1550 //===----------------------------------------------------------------------===//
1551 // StdCall calling convention seems to be standard for many Windows' API
1552 // routines and around. It differs from C calling convention just a little:
1553 // callee should clean up the stack, not caller. Symbols should be also
1554 // decorated in some fancy way :) It doesn't support any vector arguments.
1555 // For info on fast calling convention see Fast Calling Convention (tail call)
1556 // implementation LowerX86_32FastCCCallTo.
1558 /// CallIsStructReturn - Determines whether a call uses struct return
1560 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1564 return Outs[0].Flags.isSRet();
1567 /// ArgsAreStructReturn - Determines whether a function uses struct
1568 /// return semantics.
1570 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1574 return Ins[0].Flags.isSRet();
1577 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1578 /// by "Src" to address "Dst" with size and alignment information specified by
1579 /// the specific parameter attribute. The copy will be passed as a byval
1580 /// function parameter.
1582 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1583 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1585 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1587 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1588 /*isVolatile*/false, /*AlwaysInline=*/true,
1589 MachinePointerInfo(), MachinePointerInfo());
1592 /// IsTailCallConvention - Return true if the calling convention is one that
1593 /// supports tail call optimization.
1594 static bool IsTailCallConvention(CallingConv::ID CC) {
1595 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1598 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1599 if (!CI->isTailCall())
1603 CallingConv::ID CalleeCC = CS.getCallingConv();
1604 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1610 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1611 /// a tailcall target by changing its ABI.
1612 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1613 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1617 X86TargetLowering::LowerMemArgument(SDValue Chain,
1618 CallingConv::ID CallConv,
1619 const SmallVectorImpl<ISD::InputArg> &Ins,
1620 DebugLoc dl, SelectionDAG &DAG,
1621 const CCValAssign &VA,
1622 MachineFrameInfo *MFI,
1624 // Create the nodes corresponding to a load from this parameter slot.
1625 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1626 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1627 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1630 // If value is passed by pointer we have address passed instead of the value
1632 if (VA.getLocInfo() == CCValAssign::Indirect)
1633 ValVT = VA.getLocVT();
1635 ValVT = VA.getValVT();
1637 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1638 // changed with more analysis.
1639 // In case of tail call optimization mark all arguments mutable. Since they
1640 // could be overwritten by lowering of arguments in case of a tail call.
1641 if (Flags.isByVal()) {
1642 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1643 VA.getLocMemOffset(), isImmutable);
1644 return DAG.getFrameIndex(FI, getPointerTy());
1646 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1647 VA.getLocMemOffset(), isImmutable);
1648 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1649 return DAG.getLoad(ValVT, dl, Chain, FIN,
1650 MachinePointerInfo::getFixedStack(FI),
1656 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1657 CallingConv::ID CallConv,
1659 const SmallVectorImpl<ISD::InputArg> &Ins,
1662 SmallVectorImpl<SDValue> &InVals)
1664 MachineFunction &MF = DAG.getMachineFunction();
1665 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1667 const Function* Fn = MF.getFunction();
1668 if (Fn->hasExternalLinkage() &&
1669 Subtarget->isTargetCygMing() &&
1670 Fn->getName() == "main")
1671 FuncInfo->setForceFramePointer(true);
1673 MachineFrameInfo *MFI = MF.getFrameInfo();
1674 bool Is64Bit = Subtarget->is64Bit();
1675 bool IsWin64 = Subtarget->isTargetWin64();
1677 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1678 "Var args not supported with calling convention fastcc or ghc");
1680 // Assign locations to all of the incoming arguments.
1681 SmallVector<CCValAssign, 16> ArgLocs;
1682 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1683 ArgLocs, *DAG.getContext());
1685 // Allocate shadow area for Win64
1687 CCInfo.AllocateStack(32, 8);
1690 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1692 unsigned LastVal = ~0U;
1694 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1695 CCValAssign &VA = ArgLocs[i];
1696 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1698 assert(VA.getValNo() != LastVal &&
1699 "Don't support value assigned to multiple locs yet");
1700 LastVal = VA.getValNo();
1702 if (VA.isRegLoc()) {
1703 EVT RegVT = VA.getLocVT();
1704 TargetRegisterClass *RC = NULL;
1705 if (RegVT == MVT::i32)
1706 RC = X86::GR32RegisterClass;
1707 else if (Is64Bit && RegVT == MVT::i64)
1708 RC = X86::GR64RegisterClass;
1709 else if (RegVT == MVT::f32)
1710 RC = X86::FR32RegisterClass;
1711 else if (RegVT == MVT::f64)
1712 RC = X86::FR64RegisterClass;
1713 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1714 RC = X86::VR256RegisterClass;
1715 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1716 RC = X86::VR128RegisterClass;
1717 else if (RegVT == MVT::x86mmx)
1718 RC = X86::VR64RegisterClass;
1720 llvm_unreachable("Unknown argument type!");
1722 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1723 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1725 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1726 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1728 if (VA.getLocInfo() == CCValAssign::SExt)
1729 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1730 DAG.getValueType(VA.getValVT()));
1731 else if (VA.getLocInfo() == CCValAssign::ZExt)
1732 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1733 DAG.getValueType(VA.getValVT()));
1734 else if (VA.getLocInfo() == CCValAssign::BCvt)
1735 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1737 if (VA.isExtInLoc()) {
1738 // Handle MMX values passed in XMM regs.
1739 if (RegVT.isVector()) {
1740 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1743 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1746 assert(VA.isMemLoc());
1747 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1750 // If value is passed via pointer - do a load.
1751 if (VA.getLocInfo() == CCValAssign::Indirect)
1752 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1753 MachinePointerInfo(), false, false, 0);
1755 InVals.push_back(ArgValue);
1758 // The x86-64 ABI for returning structs by value requires that we copy
1759 // the sret argument into %rax for the return. Save the argument into
1760 // a virtual register so that we can access it from the return points.
1761 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1762 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1763 unsigned Reg = FuncInfo->getSRetReturnReg();
1765 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1766 FuncInfo->setSRetReturnReg(Reg);
1768 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1769 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1772 unsigned StackSize = CCInfo.getNextStackOffset();
1773 // Align stack specially for tail calls.
1774 if (FuncIsMadeTailCallSafe(CallConv))
1775 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1777 // If the function takes variable number of arguments, make a frame index for
1778 // the start of the first vararg value... for expansion of llvm.va_start.
1780 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1781 CallConv != CallingConv::X86_ThisCall)) {
1782 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1785 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1787 // FIXME: We should really autogenerate these arrays
1788 static const unsigned GPR64ArgRegsWin64[] = {
1789 X86::RCX, X86::RDX, X86::R8, X86::R9
1791 static const unsigned GPR64ArgRegs64Bit[] = {
1792 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1794 static const unsigned XMMArgRegs64Bit[] = {
1795 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1796 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1798 const unsigned *GPR64ArgRegs;
1799 unsigned NumXMMRegs = 0;
1802 // The XMM registers which might contain var arg parameters are shadowed
1803 // in their paired GPR. So we only need to save the GPR to their home
1805 TotalNumIntRegs = 4;
1806 GPR64ArgRegs = GPR64ArgRegsWin64;
1808 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1809 GPR64ArgRegs = GPR64ArgRegs64Bit;
1811 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1813 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1816 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1817 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1818 "SSE register cannot be used when SSE is disabled!");
1819 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1820 "SSE register cannot be used when SSE is disabled!");
1821 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1822 // Kernel mode asks for SSE to be disabled, so don't push them
1824 TotalNumXMMRegs = 0;
1827 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1828 // Get to the caller-allocated home save location. Add 8 to account
1829 // for the return address.
1830 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1831 FuncInfo->setRegSaveFrameIndex(
1832 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1833 // Fixup to set vararg frame on shadow area (4 x i64).
1835 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1837 // For X86-64, if there are vararg parameters that are passed via
1838 // registers, then we must store them to their spots on the stack so they
1839 // may be loaded by deferencing the result of va_next.
1840 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1841 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1842 FuncInfo->setRegSaveFrameIndex(
1843 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1847 // Store the integer parameter registers.
1848 SmallVector<SDValue, 8> MemOps;
1849 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1851 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1852 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1853 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1854 DAG.getIntPtrConstant(Offset));
1855 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1856 X86::GR64RegisterClass);
1857 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1859 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1860 MachinePointerInfo::getFixedStack(
1861 FuncInfo->getRegSaveFrameIndex(), Offset),
1863 MemOps.push_back(Store);
1867 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1868 // Now store the XMM (fp + vector) parameter registers.
1869 SmallVector<SDValue, 11> SaveXMMOps;
1870 SaveXMMOps.push_back(Chain);
1872 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1873 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1874 SaveXMMOps.push_back(ALVal);
1876 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1877 FuncInfo->getRegSaveFrameIndex()));
1878 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879 FuncInfo->getVarArgsFPOffset()));
1881 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1882 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1883 X86::VR128RegisterClass);
1884 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1885 SaveXMMOps.push_back(Val);
1887 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1889 &SaveXMMOps[0], SaveXMMOps.size()));
1892 if (!MemOps.empty())
1893 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1894 &MemOps[0], MemOps.size());
1898 // Some CCs need callee pop.
1899 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1900 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1902 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1903 // If this is an sret function, the return should pop the hidden pointer.
1904 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1905 FuncInfo->setBytesToPopOnReturn(4);
1909 // RegSaveFrameIndex is X86-64 only.
1910 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1911 if (CallConv == CallingConv::X86_FastCall ||
1912 CallConv == CallingConv::X86_ThisCall)
1913 // fastcc functions can't have varargs.
1914 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1921 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1922 SDValue StackPtr, SDValue Arg,
1923 DebugLoc dl, SelectionDAG &DAG,
1924 const CCValAssign &VA,
1925 ISD::ArgFlagsTy Flags) const {
1926 unsigned LocMemOffset = VA.getLocMemOffset();
1927 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1928 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1929 if (Flags.isByVal())
1930 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1932 return DAG.getStore(Chain, dl, Arg, PtrOff,
1933 MachinePointerInfo::getStack(LocMemOffset),
1937 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1938 /// optimization is performed and it is required.
1940 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1941 SDValue &OutRetAddr, SDValue Chain,
1942 bool IsTailCall, bool Is64Bit,
1943 int FPDiff, DebugLoc dl) const {
1944 // Adjust the Return address stack slot.
1945 EVT VT = getPointerTy();
1946 OutRetAddr = getReturnAddressFrameIndex(DAG);
1948 // Load the "old" Return address.
1949 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1951 return SDValue(OutRetAddr.getNode(), 1);
1954 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1955 /// optimization is performed and it is required (FPDiff!=0).
1957 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1958 SDValue Chain, SDValue RetAddrFrIdx,
1959 bool Is64Bit, int FPDiff, DebugLoc dl) {
1960 // Store the return address to the appropriate stack slot.
1961 if (!FPDiff) return Chain;
1962 // Calculate the new stack slot for the return address.
1963 int SlotSize = Is64Bit ? 8 : 4;
1964 int NewReturnAddrFI =
1965 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1966 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1967 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1968 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1969 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1975 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1976 CallingConv::ID CallConv, bool isVarArg,
1978 const SmallVectorImpl<ISD::OutputArg> &Outs,
1979 const SmallVectorImpl<SDValue> &OutVals,
1980 const SmallVectorImpl<ISD::InputArg> &Ins,
1981 DebugLoc dl, SelectionDAG &DAG,
1982 SmallVectorImpl<SDValue> &InVals) const {
1983 MachineFunction &MF = DAG.getMachineFunction();
1984 bool Is64Bit = Subtarget->is64Bit();
1985 bool IsWin64 = Subtarget->isTargetWin64();
1986 bool IsStructRet = CallIsStructReturn(Outs);
1987 bool IsSibcall = false;
1990 // Check if it's really possible to do a tail call.
1991 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1992 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1993 Outs, OutVals, Ins, DAG);
1995 // Sibcalls are automatically detected tailcalls which do not require
1997 if (!GuaranteedTailCallOpt && isTailCall)
2004 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2005 "Var args not supported with calling convention fastcc or ghc");
2007 // Analyze operands of the call, assigning locations to each operand.
2008 SmallVector<CCValAssign, 16> ArgLocs;
2009 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2010 ArgLocs, *DAG.getContext());
2012 // Allocate shadow area for Win64
2014 CCInfo.AllocateStack(32, 8);
2017 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2019 // Get a count of how many bytes are to be pushed on the stack.
2020 unsigned NumBytes = CCInfo.getNextStackOffset();
2022 // This is a sibcall. The memory operands are available in caller's
2023 // own caller's stack.
2025 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2026 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2029 if (isTailCall && !IsSibcall) {
2030 // Lower arguments at fp - stackoffset + fpdiff.
2031 unsigned NumBytesCallerPushed =
2032 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2033 FPDiff = NumBytesCallerPushed - NumBytes;
2035 // Set the delta of movement of the returnaddr stackslot.
2036 // But only set if delta is greater than previous delta.
2037 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2038 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2042 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2044 SDValue RetAddrFrIdx;
2045 // Load return adress for tail calls.
2046 if (isTailCall && FPDiff)
2047 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2048 Is64Bit, FPDiff, dl);
2050 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2051 SmallVector<SDValue, 8> MemOpChains;
2054 // Walk the register/memloc assignments, inserting copies/loads. In the case
2055 // of tail call optimization arguments are handle later.
2056 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2057 CCValAssign &VA = ArgLocs[i];
2058 EVT RegVT = VA.getLocVT();
2059 SDValue Arg = OutVals[i];
2060 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2061 bool isByVal = Flags.isByVal();
2063 // Promote the value if needed.
2064 switch (VA.getLocInfo()) {
2065 default: llvm_unreachable("Unknown loc info!");
2066 case CCValAssign::Full: break;
2067 case CCValAssign::SExt:
2068 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2070 case CCValAssign::ZExt:
2071 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2073 case CCValAssign::AExt:
2074 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2075 // Special case: passing MMX values in XMM registers.
2076 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2077 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2078 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2080 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2082 case CCValAssign::BCvt:
2083 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2085 case CCValAssign::Indirect: {
2086 // Store the argument.
2087 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2088 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2089 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2090 MachinePointerInfo::getFixedStack(FI),
2097 if (VA.isRegLoc()) {
2098 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2099 if (isVarArg && IsWin64) {
2100 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2101 // shadow reg if callee is a varargs function.
2102 unsigned ShadowReg = 0;
2103 switch (VA.getLocReg()) {
2104 case X86::XMM0: ShadowReg = X86::RCX; break;
2105 case X86::XMM1: ShadowReg = X86::RDX; break;
2106 case X86::XMM2: ShadowReg = X86::R8; break;
2107 case X86::XMM3: ShadowReg = X86::R9; break;
2110 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2112 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2113 assert(VA.isMemLoc());
2114 if (StackPtr.getNode() == 0)
2115 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2116 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2117 dl, DAG, VA, Flags));
2121 if (!MemOpChains.empty())
2122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2123 &MemOpChains[0], MemOpChains.size());
2125 // Build a sequence of copy-to-reg nodes chained together with token chain
2126 // and flag operands which copy the outgoing args into registers.
2128 // Tail call byval lowering might overwrite argument registers so in case of
2129 // tail call optimization the copies to registers are lowered later.
2131 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2132 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2133 RegsToPass[i].second, InFlag);
2134 InFlag = Chain.getValue(1);
2137 if (Subtarget->isPICStyleGOT()) {
2138 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2141 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2142 DAG.getNode(X86ISD::GlobalBaseReg,
2143 DebugLoc(), getPointerTy()),
2145 InFlag = Chain.getValue(1);
2147 // If we are tail calling and generating PIC/GOT style code load the
2148 // address of the callee into ECX. The value in ecx is used as target of
2149 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2150 // for tail calls on PIC/GOT architectures. Normally we would just put the
2151 // address of GOT into ebx and then call target@PLT. But for tail calls
2152 // ebx would be restored (since ebx is callee saved) before jumping to the
2155 // Note: The actual moving to ECX is done further down.
2156 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2157 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2158 !G->getGlobal()->hasProtectedVisibility())
2159 Callee = LowerGlobalAddress(Callee, DAG);
2160 else if (isa<ExternalSymbolSDNode>(Callee))
2161 Callee = LowerExternalSymbol(Callee, DAG);
2165 if (Is64Bit && isVarArg && !IsWin64) {
2166 // From AMD64 ABI document:
2167 // For calls that may call functions that use varargs or stdargs
2168 // (prototype-less calls or calls to functions containing ellipsis (...) in
2169 // the declaration) %al is used as hidden argument to specify the number
2170 // of SSE registers used. The contents of %al do not need to match exactly
2171 // the number of registers, but must be an ubound on the number of SSE
2172 // registers used and is in the range 0 - 8 inclusive.
2174 // Count the number of XMM registers allocated.
2175 static const unsigned XMMArgRegs[] = {
2176 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2177 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2179 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2180 assert((Subtarget->hasXMM() || !NumXMMRegs)
2181 && "SSE registers cannot be used when SSE is disabled");
2183 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2184 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2185 InFlag = Chain.getValue(1);
2189 // For tail calls lower the arguments to the 'real' stack slot.
2191 // Force all the incoming stack arguments to be loaded from the stack
2192 // before any new outgoing arguments are stored to the stack, because the
2193 // outgoing stack slots may alias the incoming argument stack slots, and
2194 // the alias isn't otherwise explicit. This is slightly more conservative
2195 // than necessary, because it means that each store effectively depends
2196 // on every argument instead of just those arguments it would clobber.
2197 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2199 SmallVector<SDValue, 8> MemOpChains2;
2202 // Do not flag preceeding copytoreg stuff together with the following stuff.
2204 if (GuaranteedTailCallOpt) {
2205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2206 CCValAssign &VA = ArgLocs[i];
2209 assert(VA.isMemLoc());
2210 SDValue Arg = OutVals[i];
2211 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2212 // Create frame index.
2213 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2214 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2215 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2216 FIN = DAG.getFrameIndex(FI, getPointerTy());
2218 if (Flags.isByVal()) {
2219 // Copy relative to framepointer.
2220 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2221 if (StackPtr.getNode() == 0)
2222 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2224 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2226 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2230 // Store relative to framepointer.
2231 MemOpChains2.push_back(
2232 DAG.getStore(ArgChain, dl, Arg, FIN,
2233 MachinePointerInfo::getFixedStack(FI),
2239 if (!MemOpChains2.empty())
2240 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2241 &MemOpChains2[0], MemOpChains2.size());
2243 // Copy arguments to their registers.
2244 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2245 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2246 RegsToPass[i].second, InFlag);
2247 InFlag = Chain.getValue(1);
2251 // Store the return address to the appropriate stack slot.
2252 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2256 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2257 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2258 // In the 64-bit large code model, we have to make all calls
2259 // through a register, since the call instruction's 32-bit
2260 // pc-relative offset may not be large enough to hold the whole
2262 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2263 // If the callee is a GlobalAddress node (quite common, every direct call
2264 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2267 // We should use extra load for direct calls to dllimported functions in
2269 const GlobalValue *GV = G->getGlobal();
2270 if (!GV->hasDLLImportLinkage()) {
2271 unsigned char OpFlags = 0;
2273 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2274 // external symbols most go through the PLT in PIC mode. If the symbol
2275 // has hidden or protected visibility, or if it is static or local, then
2276 // we don't need to use the PLT - we can directly call it.
2277 if (Subtarget->isTargetELF() &&
2278 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2279 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2280 OpFlags = X86II::MO_PLT;
2281 } else if (Subtarget->isPICStyleStubAny() &&
2282 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2283 Subtarget->getDarwinVers() < 9) {
2284 // PC-relative references to external symbols should go through $stub,
2285 // unless we're building with the leopard linker or later, which
2286 // automatically synthesizes these stubs.
2287 OpFlags = X86II::MO_DARWIN_STUB;
2290 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2291 G->getOffset(), OpFlags);
2293 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2294 unsigned char OpFlags = 0;
2296 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2297 // external symbols should go through the PLT.
2298 if (Subtarget->isTargetELF() &&
2299 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2300 OpFlags = X86II::MO_PLT;
2301 } else if (Subtarget->isPICStyleStubAny() &&
2302 Subtarget->getDarwinVers() < 9) {
2303 // PC-relative references to external symbols should go through $stub,
2304 // unless we're building with the leopard linker or later, which
2305 // automatically synthesizes these stubs.
2306 OpFlags = X86II::MO_DARWIN_STUB;
2309 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2313 // Returns a chain & a flag for retval copy to use.
2314 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2315 SmallVector<SDValue, 8> Ops;
2317 if (!IsSibcall && isTailCall) {
2318 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2319 DAG.getIntPtrConstant(0, true), InFlag);
2320 InFlag = Chain.getValue(1);
2323 Ops.push_back(Chain);
2324 Ops.push_back(Callee);
2327 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2329 // Add argument registers to the end of the list so that they are known live
2331 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2332 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2333 RegsToPass[i].second.getValueType()));
2335 // Add an implicit use GOT pointer in EBX.
2336 if (!isTailCall && Subtarget->isPICStyleGOT())
2337 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2339 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2340 if (Is64Bit && isVarArg && !IsWin64)
2341 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2343 if (InFlag.getNode())
2344 Ops.push_back(InFlag);
2348 //// If this is the first return lowered for this function, add the regs
2349 //// to the liveout set for the function.
2350 // This isn't right, although it's probably harmless on x86; liveouts
2351 // should be computed from returns not tail calls. Consider a void
2352 // function making a tail call to a function returning int.
2353 return DAG.getNode(X86ISD::TC_RETURN, dl,
2354 NodeTys, &Ops[0], Ops.size());
2357 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2358 InFlag = Chain.getValue(1);
2360 // Create the CALLSEQ_END node.
2361 unsigned NumBytesForCalleeToPush;
2362 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2363 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2364 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2365 // If this is a call to a struct-return function, the callee
2366 // pops the hidden struct pointer, so we have to push it back.
2367 // This is common for Darwin/X86, Linux & Mingw32 targets.
2368 NumBytesForCalleeToPush = 4;
2370 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2372 // Returns a flag for retval copy to use.
2374 Chain = DAG.getCALLSEQ_END(Chain,
2375 DAG.getIntPtrConstant(NumBytes, true),
2376 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2379 InFlag = Chain.getValue(1);
2382 // Handle result values, copying them out of physregs into vregs that we
2384 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2385 Ins, dl, DAG, InVals);
2389 //===----------------------------------------------------------------------===//
2390 // Fast Calling Convention (tail call) implementation
2391 //===----------------------------------------------------------------------===//
2393 // Like std call, callee cleans arguments, convention except that ECX is
2394 // reserved for storing the tail called function address. Only 2 registers are
2395 // free for argument passing (inreg). Tail call optimization is performed
2397 // * tailcallopt is enabled
2398 // * caller/callee are fastcc
2399 // On X86_64 architecture with GOT-style position independent code only local
2400 // (within module) calls are supported at the moment.
2401 // To keep the stack aligned according to platform abi the function
2402 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2403 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2404 // If a tail called function callee has more arguments than the caller the
2405 // caller needs to make sure that there is room to move the RETADDR to. This is
2406 // achieved by reserving an area the size of the argument delta right after the
2407 // original REtADDR, but before the saved framepointer or the spilled registers
2408 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2420 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2421 /// for a 16 byte align requirement.
2423 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2424 SelectionDAG& DAG) const {
2425 MachineFunction &MF = DAG.getMachineFunction();
2426 const TargetMachine &TM = MF.getTarget();
2427 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2428 unsigned StackAlignment = TFI.getStackAlignment();
2429 uint64_t AlignMask = StackAlignment - 1;
2430 int64_t Offset = StackSize;
2431 uint64_t SlotSize = TD->getPointerSize();
2432 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2433 // Number smaller than 12 so just add the difference.
2434 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2436 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2437 Offset = ((~AlignMask) & Offset) + StackAlignment +
2438 (StackAlignment-SlotSize);
2443 /// MatchingStackOffset - Return true if the given stack call argument is
2444 /// already available in the same position (relatively) of the caller's
2445 /// incoming argument stack.
2447 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2448 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2449 const X86InstrInfo *TII) {
2450 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2452 if (Arg.getOpcode() == ISD::CopyFromReg) {
2453 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2454 if (!TargetRegisterInfo::isVirtualRegister(VR))
2456 MachineInstr *Def = MRI->getVRegDef(VR);
2459 if (!Flags.isByVal()) {
2460 if (!TII->isLoadFromStackSlot(Def, FI))
2463 unsigned Opcode = Def->getOpcode();
2464 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2465 Def->getOperand(1).isFI()) {
2466 FI = Def->getOperand(1).getIndex();
2467 Bytes = Flags.getByValSize();
2471 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2472 if (Flags.isByVal())
2473 // ByVal argument is passed in as a pointer but it's now being
2474 // dereferenced. e.g.
2475 // define @foo(%struct.X* %A) {
2476 // tail call @bar(%struct.X* byval %A)
2479 SDValue Ptr = Ld->getBasePtr();
2480 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2483 FI = FINode->getIndex();
2487 assert(FI != INT_MAX);
2488 if (!MFI->isFixedObjectIndex(FI))
2490 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2493 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2494 /// for tail call optimization. Targets which want to do tail call
2495 /// optimization should implement this function.
2497 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2498 CallingConv::ID CalleeCC,
2500 bool isCalleeStructRet,
2501 bool isCallerStructRet,
2502 const SmallVectorImpl<ISD::OutputArg> &Outs,
2503 const SmallVectorImpl<SDValue> &OutVals,
2504 const SmallVectorImpl<ISD::InputArg> &Ins,
2505 SelectionDAG& DAG) const {
2506 if (!IsTailCallConvention(CalleeCC) &&
2507 CalleeCC != CallingConv::C)
2510 // If -tailcallopt is specified, make fastcc functions tail-callable.
2511 const MachineFunction &MF = DAG.getMachineFunction();
2512 const Function *CallerF = DAG.getMachineFunction().getFunction();
2513 CallingConv::ID CallerCC = CallerF->getCallingConv();
2514 bool CCMatch = CallerCC == CalleeCC;
2516 if (GuaranteedTailCallOpt) {
2517 if (IsTailCallConvention(CalleeCC) && CCMatch)
2522 // Look for obvious safe cases to perform tail call optimization that do not
2523 // require ABI changes. This is what gcc calls sibcall.
2525 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2526 // emit a special epilogue.
2527 if (RegInfo->needsStackRealignment(MF))
2530 // Do not sibcall optimize vararg calls unless the call site is not passing
2532 if (isVarArg && !Outs.empty())
2535 // Also avoid sibcall optimization if either caller or callee uses struct
2536 // return semantics.
2537 if (isCalleeStructRet || isCallerStructRet)
2540 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2541 // Therefore if it's not used by the call it is not safe to optimize this into
2543 bool Unused = false;
2544 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2551 SmallVector<CCValAssign, 16> RVLocs;
2552 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2553 RVLocs, *DAG.getContext());
2554 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2555 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2556 CCValAssign &VA = RVLocs[i];
2557 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2562 // If the calling conventions do not match, then we'd better make sure the
2563 // results are returned in the same way as what the caller expects.
2565 SmallVector<CCValAssign, 16> RVLocs1;
2566 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2567 RVLocs1, *DAG.getContext());
2568 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2570 SmallVector<CCValAssign, 16> RVLocs2;
2571 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2572 RVLocs2, *DAG.getContext());
2573 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2575 if (RVLocs1.size() != RVLocs2.size())
2577 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2578 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2580 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2582 if (RVLocs1[i].isRegLoc()) {
2583 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2586 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2592 // If the callee takes no arguments then go on to check the results of the
2594 if (!Outs.empty()) {
2595 // Check if stack adjustment is needed. For now, do not do this if any
2596 // argument is passed on the stack.
2597 SmallVector<CCValAssign, 16> ArgLocs;
2598 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2599 ArgLocs, *DAG.getContext());
2601 // Allocate shadow area for Win64
2602 if (Subtarget->isTargetWin64()) {
2603 CCInfo.AllocateStack(32, 8);
2606 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2607 if (CCInfo.getNextStackOffset()) {
2608 MachineFunction &MF = DAG.getMachineFunction();
2609 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2612 // Check if the arguments are already laid out in the right way as
2613 // the caller's fixed stack objects.
2614 MachineFrameInfo *MFI = MF.getFrameInfo();
2615 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2616 const X86InstrInfo *TII =
2617 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2618 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2619 CCValAssign &VA = ArgLocs[i];
2620 SDValue Arg = OutVals[i];
2621 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2622 if (VA.getLocInfo() == CCValAssign::Indirect)
2624 if (!VA.isRegLoc()) {
2625 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2632 // If the tailcall address may be in a register, then make sure it's
2633 // possible to register allocate for it. In 32-bit, the call address can
2634 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2635 // callee-saved registers are restored. These happen to be the same
2636 // registers used to pass 'inreg' arguments so watch out for those.
2637 if (!Subtarget->is64Bit() &&
2638 !isa<GlobalAddressSDNode>(Callee) &&
2639 !isa<ExternalSymbolSDNode>(Callee)) {
2640 unsigned NumInRegs = 0;
2641 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2642 CCValAssign &VA = ArgLocs[i];
2645 unsigned Reg = VA.getLocReg();
2648 case X86::EAX: case X86::EDX: case X86::ECX:
2649 if (++NumInRegs == 3)
2657 // An stdcall caller is expected to clean up its arguments; the callee
2658 // isn't going to do that.
2659 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2666 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2667 return X86::createFastISel(funcInfo);
2671 //===----------------------------------------------------------------------===//
2672 // Other Lowering Hooks
2673 //===----------------------------------------------------------------------===//
2675 static bool MayFoldLoad(SDValue Op) {
2676 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2679 static bool MayFoldIntoStore(SDValue Op) {
2680 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2683 static bool isTargetShuffle(unsigned Opcode) {
2685 default: return false;
2686 case X86ISD::PSHUFD:
2687 case X86ISD::PSHUFHW:
2688 case X86ISD::PSHUFLW:
2689 case X86ISD::SHUFPD:
2690 case X86ISD::PALIGN:
2691 case X86ISD::SHUFPS:
2692 case X86ISD::MOVLHPS:
2693 case X86ISD::MOVLHPD:
2694 case X86ISD::MOVHLPS:
2695 case X86ISD::MOVLPS:
2696 case X86ISD::MOVLPD:
2697 case X86ISD::MOVSHDUP:
2698 case X86ISD::MOVSLDUP:
2699 case X86ISD::MOVDDUP:
2702 case X86ISD::UNPCKLPS:
2703 case X86ISD::UNPCKLPD:
2704 case X86ISD::VUNPCKLPS:
2705 case X86ISD::VUNPCKLPD:
2706 case X86ISD::VUNPCKLPSY:
2707 case X86ISD::VUNPCKLPDY:
2708 case X86ISD::PUNPCKLWD:
2709 case X86ISD::PUNPCKLBW:
2710 case X86ISD::PUNPCKLDQ:
2711 case X86ISD::PUNPCKLQDQ:
2712 case X86ISD::UNPCKHPS:
2713 case X86ISD::UNPCKHPD:
2714 case X86ISD::PUNPCKHWD:
2715 case X86ISD::PUNPCKHBW:
2716 case X86ISD::PUNPCKHDQ:
2717 case X86ISD::PUNPCKHQDQ:
2723 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2724 SDValue V1, SelectionDAG &DAG) {
2726 default: llvm_unreachable("Unknown x86 shuffle node");
2727 case X86ISD::MOVSHDUP:
2728 case X86ISD::MOVSLDUP:
2729 case X86ISD::MOVDDUP:
2730 return DAG.getNode(Opc, dl, VT, V1);
2736 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2737 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2739 default: llvm_unreachable("Unknown x86 shuffle node");
2740 case X86ISD::PSHUFD:
2741 case X86ISD::PSHUFHW:
2742 case X86ISD::PSHUFLW:
2743 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2749 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2750 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2752 default: llvm_unreachable("Unknown x86 shuffle node");
2753 case X86ISD::PALIGN:
2754 case X86ISD::SHUFPD:
2755 case X86ISD::SHUFPS:
2756 return DAG.getNode(Opc, dl, VT, V1, V2,
2757 DAG.getConstant(TargetMask, MVT::i8));
2762 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2763 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2765 default: llvm_unreachable("Unknown x86 shuffle node");
2766 case X86ISD::MOVLHPS:
2767 case X86ISD::MOVLHPD:
2768 case X86ISD::MOVHLPS:
2769 case X86ISD::MOVLPS:
2770 case X86ISD::MOVLPD:
2773 case X86ISD::UNPCKLPS:
2774 case X86ISD::UNPCKLPD:
2775 case X86ISD::VUNPCKLPS:
2776 case X86ISD::VUNPCKLPD:
2777 case X86ISD::VUNPCKLPSY:
2778 case X86ISD::VUNPCKLPDY:
2779 case X86ISD::PUNPCKLWD:
2780 case X86ISD::PUNPCKLBW:
2781 case X86ISD::PUNPCKLDQ:
2782 case X86ISD::PUNPCKLQDQ:
2783 case X86ISD::UNPCKHPS:
2784 case X86ISD::UNPCKHPD:
2785 case X86ISD::PUNPCKHWD:
2786 case X86ISD::PUNPCKHBW:
2787 case X86ISD::PUNPCKHDQ:
2788 case X86ISD::PUNPCKHQDQ:
2789 return DAG.getNode(Opc, dl, VT, V1, V2);
2794 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2795 MachineFunction &MF = DAG.getMachineFunction();
2796 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2797 int ReturnAddrIndex = FuncInfo->getRAIndex();
2799 if (ReturnAddrIndex == 0) {
2800 // Set up a frame object for the return address.
2801 uint64_t SlotSize = TD->getPointerSize();
2802 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2804 FuncInfo->setRAIndex(ReturnAddrIndex);
2807 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2811 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2812 bool hasSymbolicDisplacement) {
2813 // Offset should fit into 32 bit immediate field.
2814 if (!isInt<32>(Offset))
2817 // If we don't have a symbolic displacement - we don't have any extra
2819 if (!hasSymbolicDisplacement)
2822 // FIXME: Some tweaks might be needed for medium code model.
2823 if (M != CodeModel::Small && M != CodeModel::Kernel)
2826 // For small code model we assume that latest object is 16MB before end of 31
2827 // bits boundary. We may also accept pretty large negative constants knowing
2828 // that all objects are in the positive half of address space.
2829 if (M == CodeModel::Small && Offset < 16*1024*1024)
2832 // For kernel code model we know that all object resist in the negative half
2833 // of 32bits address space. We may not accept negative offsets, since they may
2834 // be just off and we may accept pretty large positive ones.
2835 if (M == CodeModel::Kernel && Offset > 0)
2841 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2842 /// specific condition code, returning the condition code and the LHS/RHS of the
2843 /// comparison to make.
2844 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2845 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2847 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2848 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2849 // X > -1 -> X == 0, jump !sign.
2850 RHS = DAG.getConstant(0, RHS.getValueType());
2851 return X86::COND_NS;
2852 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2853 // X < 0 -> X == 0, jump on sign.
2855 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2857 RHS = DAG.getConstant(0, RHS.getValueType());
2858 return X86::COND_LE;
2862 switch (SetCCOpcode) {
2863 default: llvm_unreachable("Invalid integer condition!");
2864 case ISD::SETEQ: return X86::COND_E;
2865 case ISD::SETGT: return X86::COND_G;
2866 case ISD::SETGE: return X86::COND_GE;
2867 case ISD::SETLT: return X86::COND_L;
2868 case ISD::SETLE: return X86::COND_LE;
2869 case ISD::SETNE: return X86::COND_NE;
2870 case ISD::SETULT: return X86::COND_B;
2871 case ISD::SETUGT: return X86::COND_A;
2872 case ISD::SETULE: return X86::COND_BE;
2873 case ISD::SETUGE: return X86::COND_AE;
2877 // First determine if it is required or is profitable to flip the operands.
2879 // If LHS is a foldable load, but RHS is not, flip the condition.
2880 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2881 !ISD::isNON_EXTLoad(RHS.getNode())) {
2882 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2883 std::swap(LHS, RHS);
2886 switch (SetCCOpcode) {
2892 std::swap(LHS, RHS);
2896 // On a floating point condition, the flags are set as follows:
2898 // 0 | 0 | 0 | X > Y
2899 // 0 | 0 | 1 | X < Y
2900 // 1 | 0 | 0 | X == Y
2901 // 1 | 1 | 1 | unordered
2902 switch (SetCCOpcode) {
2903 default: llvm_unreachable("Condcode should be pre-legalized away");
2905 case ISD::SETEQ: return X86::COND_E;
2906 case ISD::SETOLT: // flipped
2908 case ISD::SETGT: return X86::COND_A;
2909 case ISD::SETOLE: // flipped
2911 case ISD::SETGE: return X86::COND_AE;
2912 case ISD::SETUGT: // flipped
2914 case ISD::SETLT: return X86::COND_B;
2915 case ISD::SETUGE: // flipped
2917 case ISD::SETLE: return X86::COND_BE;
2919 case ISD::SETNE: return X86::COND_NE;
2920 case ISD::SETUO: return X86::COND_P;
2921 case ISD::SETO: return X86::COND_NP;
2923 case ISD::SETUNE: return X86::COND_INVALID;
2927 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2928 /// code. Current x86 isa includes the following FP cmov instructions:
2929 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2930 static bool hasFPCMov(unsigned X86CC) {
2946 /// isFPImmLegal - Returns true if the target can instruction select the
2947 /// specified FP immediate natively. If false, the legalizer will
2948 /// materialize the FP immediate as a load from a constant pool.
2949 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2950 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2951 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2957 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2958 /// the specified range (L, H].
2959 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2960 return (Val < 0) || (Val >= Low && Val < Hi);
2963 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2964 /// specified value.
2965 static bool isUndefOrEqual(int Val, int CmpVal) {
2966 if (Val < 0 || Val == CmpVal)
2971 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2972 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2973 /// the second operand.
2974 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2976 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2977 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2978 return (Mask[0] < 2 && Mask[1] < 2);
2982 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2983 SmallVector<int, 8> M;
2985 return ::isPSHUFDMask(M, N->getValueType(0));
2988 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2989 /// is suitable for input to PSHUFHW.
2990 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991 if (VT != MVT::v8i16)
2994 // Lower quadword copied in order or undef.
2995 for (int i = 0; i != 4; ++i)
2996 if (Mask[i] >= 0 && Mask[i] != i)
2999 // Upper quadword shuffled.
3000 for (int i = 4; i != 8; ++i)
3001 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3007 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3008 SmallVector<int, 8> M;
3010 return ::isPSHUFHWMask(M, N->getValueType(0));
3013 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3014 /// is suitable for input to PSHUFLW.
3015 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3016 if (VT != MVT::v8i16)
3019 // Upper quadword copied in order.
3020 for (int i = 4; i != 8; ++i)
3021 if (Mask[i] >= 0 && Mask[i] != i)
3024 // Lower quadword shuffled.
3025 for (int i = 0; i != 4; ++i)
3032 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3033 SmallVector<int, 8> M;
3035 return ::isPSHUFLWMask(M, N->getValueType(0));
3038 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3039 /// is suitable for input to PALIGNR.
3040 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3042 int i, e = VT.getVectorNumElements();
3044 // Do not handle v2i64 / v2f64 shuffles with palignr.
3045 if (e < 4 || !hasSSSE3)
3048 for (i = 0; i != e; ++i)
3052 // All undef, not a palignr.
3056 // Determine if it's ok to perform a palignr with only the LHS, since we
3057 // don't have access to the actual shuffle elements to see if RHS is undef.
3058 bool Unary = Mask[i] < (int)e;
3059 bool NeedsUnary = false;
3061 int s = Mask[i] - i;
3063 // Check the rest of the elements to see if they are consecutive.
3064 for (++i; i != e; ++i) {
3069 Unary = Unary && (m < (int)e);
3070 NeedsUnary = NeedsUnary || (m < s);
3072 if (NeedsUnary && !Unary)
3074 if (Unary && m != ((s+i) & (e-1)))
3076 if (!Unary && m != (s+i))
3082 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3083 SmallVector<int, 8> M;
3085 return ::isPALIGNRMask(M, N->getValueType(0), true);
3088 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3089 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3090 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3091 int NumElems = VT.getVectorNumElements();
3092 if (NumElems != 2 && NumElems != 4)
3095 int Half = NumElems / 2;
3096 for (int i = 0; i < Half; ++i)
3097 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3099 for (int i = Half; i < NumElems; ++i)
3100 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3106 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3107 SmallVector<int, 8> M;
3109 return ::isSHUFPMask(M, N->getValueType(0));
3112 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3113 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3114 /// half elements to come from vector 1 (which would equal the dest.) and
3115 /// the upper half to come from vector 2.
3116 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3117 int NumElems = VT.getVectorNumElements();
3119 if (NumElems != 2 && NumElems != 4)
3122 int Half = NumElems / 2;
3123 for (int i = 0; i < Half; ++i)
3124 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3126 for (int i = Half; i < NumElems; ++i)
3127 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3132 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3133 SmallVector<int, 8> M;
3135 return isCommutedSHUFPMask(M, N->getValueType(0));
3138 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3139 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3140 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3141 if (N->getValueType(0).getVectorNumElements() != 4)
3144 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3145 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3146 isUndefOrEqual(N->getMaskElt(1), 7) &&
3147 isUndefOrEqual(N->getMaskElt(2), 2) &&
3148 isUndefOrEqual(N->getMaskElt(3), 3);
3151 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3152 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3154 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3155 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3160 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3161 isUndefOrEqual(N->getMaskElt(1), 3) &&
3162 isUndefOrEqual(N->getMaskElt(2), 2) &&
3163 isUndefOrEqual(N->getMaskElt(3), 3);
3166 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3167 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3168 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3169 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3171 if (NumElems != 2 && NumElems != 4)
3174 for (unsigned i = 0; i < NumElems/2; ++i)
3175 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3178 for (unsigned i = NumElems/2; i < NumElems; ++i)
3179 if (!isUndefOrEqual(N->getMaskElt(i), i))
3185 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3186 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3187 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3188 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3190 if ((NumElems != 2 && NumElems != 4)
3191 || N->getValueType(0).getSizeInBits() > 128)
3194 for (unsigned i = 0; i < NumElems/2; ++i)
3195 if (!isUndefOrEqual(N->getMaskElt(i), i))
3198 for (unsigned i = 0; i < NumElems/2; ++i)
3199 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3205 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3206 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3207 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3208 bool V2IsSplat = false) {
3209 int NumElts = VT.getVectorNumElements();
3210 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3213 // Handle vector lengths > 128 bits. Define a "section" as a set of
3214 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3216 unsigned NumSections = VT.getSizeInBits() / 128;
3217 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3218 unsigned NumSectionElts = NumElts / NumSections;
3221 unsigned End = NumSectionElts;
3222 for (unsigned s = 0; s < NumSections; ++s) {
3223 for (unsigned i = Start, j = s * NumSectionElts;
3227 int BitI1 = Mask[i+1];
3228 if (!isUndefOrEqual(BitI, j))
3231 if (!isUndefOrEqual(BitI1, NumElts))
3234 if (!isUndefOrEqual(BitI1, j + NumElts))
3238 // Process the next 128 bits.
3239 Start += NumSectionElts;
3240 End += NumSectionElts;
3246 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3247 SmallVector<int, 8> M;
3249 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3252 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3253 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3254 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3255 bool V2IsSplat = false) {
3256 int NumElts = VT.getVectorNumElements();
3257 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3260 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3262 int BitI1 = Mask[i+1];
3263 if (!isUndefOrEqual(BitI, j + NumElts/2))
3266 if (isUndefOrEqual(BitI1, NumElts))
3269 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3276 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3277 SmallVector<int, 8> M;
3279 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3282 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3283 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3285 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3286 int NumElems = VT.getVectorNumElements();
3287 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3290 // Handle vector lengths > 128 bits. Define a "section" as a set of
3291 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3293 unsigned NumSections = VT.getSizeInBits() / 128;
3294 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3295 unsigned NumSectionElts = NumElems / NumSections;
3297 for (unsigned s = 0; s < NumSections; ++s) {
3298 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3299 i != NumSectionElts * (s + 1);
3302 int BitI1 = Mask[i+1];
3304 if (!isUndefOrEqual(BitI, j))
3306 if (!isUndefOrEqual(BitI1, j))
3314 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3315 SmallVector<int, 8> M;
3317 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3320 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3321 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3323 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3324 int NumElems = VT.getVectorNumElements();
3325 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3328 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3330 int BitI1 = Mask[i+1];
3331 if (!isUndefOrEqual(BitI, j))
3333 if (!isUndefOrEqual(BitI1, j))
3339 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3340 SmallVector<int, 8> M;
3342 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3345 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3346 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3347 /// MOVSD, and MOVD, i.e. setting the lowest element.
3348 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3349 if (VT.getVectorElementType().getSizeInBits() < 32)
3352 int NumElts = VT.getVectorNumElements();
3354 if (!isUndefOrEqual(Mask[0], NumElts))
3357 for (int i = 1; i < NumElts; ++i)
3358 if (!isUndefOrEqual(Mask[i], i))
3364 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3365 SmallVector<int, 8> M;
3367 return ::isMOVLMask(M, N->getValueType(0));
3370 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3371 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3372 /// element of vector 2 and the other elements to come from vector 1 in order.
3373 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3374 bool V2IsSplat = false, bool V2IsUndef = false) {
3375 int NumOps = VT.getVectorNumElements();
3376 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3379 if (!isUndefOrEqual(Mask[0], 0))
3382 for (int i = 1; i < NumOps; ++i)
3383 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3384 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3385 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3391 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3392 bool V2IsUndef = false) {
3393 SmallVector<int, 8> M;
3395 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3398 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3399 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3400 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3401 if (N->getValueType(0).getVectorNumElements() != 4)
3404 // Expect 1, 1, 3, 3
3405 for (unsigned i = 0; i < 2; ++i) {
3406 int Elt = N->getMaskElt(i);
3407 if (Elt >= 0 && Elt != 1)
3412 for (unsigned i = 2; i < 4; ++i) {
3413 int Elt = N->getMaskElt(i);
3414 if (Elt >= 0 && Elt != 3)
3419 // Don't use movshdup if it can be done with a shufps.
3420 // FIXME: verify that matching u, u, 3, 3 is what we want.
3424 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3425 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3426 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3427 if (N->getValueType(0).getVectorNumElements() != 4)
3430 // Expect 0, 0, 2, 2
3431 for (unsigned i = 0; i < 2; ++i)
3432 if (N->getMaskElt(i) > 0)
3436 for (unsigned i = 2; i < 4; ++i) {
3437 int Elt = N->getMaskElt(i);
3438 if (Elt >= 0 && Elt != 2)
3443 // Don't use movsldup if it can be done with a shufps.
3447 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3448 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3449 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3450 int e = N->getValueType(0).getVectorNumElements() / 2;
3452 for (int i = 0; i < e; ++i)
3453 if (!isUndefOrEqual(N->getMaskElt(i), i))
3455 for (int i = 0; i < e; ++i)
3456 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3461 /// isVEXTRACTF128Index - Return true if the specified
3462 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3463 /// suitable for input to VEXTRACTF128.
3464 bool X86::isVEXTRACTF128Index(SDNode *N) {
3465 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3468 // The index should be aligned on a 128-bit boundary.
3470 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3472 unsigned VL = N->getValueType(0).getVectorNumElements();
3473 unsigned VBits = N->getValueType(0).getSizeInBits();
3474 unsigned ElSize = VBits / VL;
3475 bool Result = (Index * ElSize) % 128 == 0;
3480 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3481 /// operand specifies a subvector insert that is suitable for input to
3483 bool X86::isVINSERTF128Index(SDNode *N) {
3484 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3487 // The index should be aligned on a 128-bit boundary.
3489 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3491 unsigned VL = N->getValueType(0).getVectorNumElements();
3492 unsigned VBits = N->getValueType(0).getSizeInBits();
3493 unsigned ElSize = VBits / VL;
3494 bool Result = (Index * ElSize) % 128 == 0;
3499 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3500 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3501 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3502 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3503 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3505 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3507 for (int i = 0; i < NumOperands; ++i) {
3508 int Val = SVOp->getMaskElt(NumOperands-i-1);
3509 if (Val < 0) Val = 0;
3510 if (Val >= NumOperands) Val -= NumOperands;
3512 if (i != NumOperands - 1)
3518 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3519 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3520 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3521 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3523 // 8 nodes, but we only care about the last 4.
3524 for (unsigned i = 7; i >= 4; --i) {
3525 int Val = SVOp->getMaskElt(i);
3534 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3535 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3536 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3537 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3539 // 8 nodes, but we only care about the first 4.
3540 for (int i = 3; i >= 0; --i) {
3541 int Val = SVOp->getMaskElt(i);
3550 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3551 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3552 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3553 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3554 EVT VVT = N->getValueType(0);
3555 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3559 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3560 Val = SVOp->getMaskElt(i);
3564 return (Val - i) * EltSize;
3567 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3568 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3570 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3571 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3572 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3575 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3577 EVT VecVT = N->getOperand(0).getValueType();
3578 EVT ElVT = VecVT.getVectorElementType();
3580 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3582 return Index / NumElemsPerChunk;
3585 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3586 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3588 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3589 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3590 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3593 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3595 EVT VecVT = N->getValueType(0);
3596 EVT ElVT = VecVT.getVectorElementType();
3598 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3600 return Index / NumElemsPerChunk;
3603 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3605 bool X86::isZeroNode(SDValue Elt) {
3606 return ((isa<ConstantSDNode>(Elt) &&
3607 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3608 (isa<ConstantFPSDNode>(Elt) &&
3609 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3612 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3613 /// their permute mask.
3614 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3615 SelectionDAG &DAG) {
3616 EVT VT = SVOp->getValueType(0);
3617 unsigned NumElems = VT.getVectorNumElements();
3618 SmallVector<int, 8> MaskVec;
3620 for (unsigned i = 0; i != NumElems; ++i) {
3621 int idx = SVOp->getMaskElt(i);
3623 MaskVec.push_back(idx);
3624 else if (idx < (int)NumElems)
3625 MaskVec.push_back(idx + NumElems);
3627 MaskVec.push_back(idx - NumElems);
3629 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3630 SVOp->getOperand(0), &MaskVec[0]);
3633 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3634 /// the two vector operands have swapped position.
3635 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3636 unsigned NumElems = VT.getVectorNumElements();
3637 for (unsigned i = 0; i != NumElems; ++i) {
3641 else if (idx < (int)NumElems)
3642 Mask[i] = idx + NumElems;
3644 Mask[i] = idx - NumElems;
3648 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3649 /// match movhlps. The lower half elements should come from upper half of
3650 /// V1 (and in order), and the upper half elements should come from the upper
3651 /// half of V2 (and in order).
3652 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3653 if (Op->getValueType(0).getVectorNumElements() != 4)
3655 for (unsigned i = 0, e = 2; i != e; ++i)
3656 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3658 for (unsigned i = 2; i != 4; ++i)
3659 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3664 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3665 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3667 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3668 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3670 N = N->getOperand(0).getNode();
3671 if (!ISD::isNON_EXTLoad(N))
3674 *LD = cast<LoadSDNode>(N);
3678 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3679 /// match movlp{s|d}. The lower half elements should come from lower half of
3680 /// V1 (and in order), and the upper half elements should come from the upper
3681 /// half of V2 (and in order). And since V1 will become the source of the
3682 /// MOVLP, it must be either a vector load or a scalar load to vector.
3683 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3684 ShuffleVectorSDNode *Op) {
3685 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3687 // Is V2 is a vector load, don't do this transformation. We will try to use
3688 // load folding shufps op.
3689 if (ISD::isNON_EXTLoad(V2))
3692 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3694 if (NumElems != 2 && NumElems != 4)
3696 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3697 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3699 for (unsigned i = NumElems/2; i != NumElems; ++i)
3700 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3705 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3707 static bool isSplatVector(SDNode *N) {
3708 if (N->getOpcode() != ISD::BUILD_VECTOR)
3711 SDValue SplatValue = N->getOperand(0);
3712 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3713 if (N->getOperand(i) != SplatValue)
3718 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3719 /// to an zero vector.
3720 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3721 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3722 SDValue V1 = N->getOperand(0);
3723 SDValue V2 = N->getOperand(1);
3724 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3725 for (unsigned i = 0; i != NumElems; ++i) {
3726 int Idx = N->getMaskElt(i);
3727 if (Idx >= (int)NumElems) {
3728 unsigned Opc = V2.getOpcode();
3729 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3731 if (Opc != ISD::BUILD_VECTOR ||
3732 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3734 } else if (Idx >= 0) {
3735 unsigned Opc = V1.getOpcode();
3736 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3738 if (Opc != ISD::BUILD_VECTOR ||
3739 !X86::isZeroNode(V1.getOperand(Idx)))
3746 /// getZeroVector - Returns a vector of specified type with all zero elements.
3748 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3750 assert(VT.isVector() && "Expected a vector type");
3752 // Always build SSE zero vectors as <4 x i32> bitcasted
3753 // to their dest type. This ensures they get CSE'd.
3755 if (VT.getSizeInBits() == 128) { // SSE
3756 if (HasSSE2) { // SSE2
3757 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3758 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3760 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3761 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3763 } else if (VT.getSizeInBits() == 256) { // AVX
3764 // 256-bit logic and arithmetic instructions in AVX are
3765 // all floating-point, no support for integer ops. Default
3766 // to emitting fp zeroed vectors then.
3767 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3768 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3769 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3771 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3774 /// getOnesVector - Returns a vector of specified type with all bits set.
3776 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3777 assert(VT.isVector() && "Expected a vector type");
3779 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3780 // type. This ensures they get CSE'd.
3781 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3783 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3784 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3788 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3789 /// that point to V2 points to its first element.
3790 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3791 EVT VT = SVOp->getValueType(0);
3792 unsigned NumElems = VT.getVectorNumElements();
3794 bool Changed = false;
3795 SmallVector<int, 8> MaskVec;
3796 SVOp->getMask(MaskVec);
3798 for (unsigned i = 0; i != NumElems; ++i) {
3799 if (MaskVec[i] > (int)NumElems) {
3800 MaskVec[i] = NumElems;
3805 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3806 SVOp->getOperand(1), &MaskVec[0]);
3807 return SDValue(SVOp, 0);
3810 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3811 /// operation of specified width.
3812 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3814 unsigned NumElems = VT.getVectorNumElements();
3815 SmallVector<int, 8> Mask;
3816 Mask.push_back(NumElems);
3817 for (unsigned i = 1; i != NumElems; ++i)
3819 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3822 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3823 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3825 unsigned NumElems = VT.getVectorNumElements();
3826 SmallVector<int, 8> Mask;
3827 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3829 Mask.push_back(i + NumElems);
3831 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3834 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3835 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3837 unsigned NumElems = VT.getVectorNumElements();
3838 unsigned Half = NumElems/2;
3839 SmallVector<int, 8> Mask;
3840 for (unsigned i = 0; i != Half; ++i) {
3841 Mask.push_back(i + Half);
3842 Mask.push_back(i + NumElems + Half);
3844 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3847 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3848 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3849 EVT PVT = MVT::v4f32;
3850 EVT VT = SV->getValueType(0);
3851 DebugLoc dl = SV->getDebugLoc();
3852 SDValue V1 = SV->getOperand(0);
3853 int NumElems = VT.getVectorNumElements();
3854 int EltNo = SV->getSplatIndex();
3856 // unpack elements to the correct location
3857 while (NumElems > 4) {
3858 if (EltNo < NumElems/2) {
3859 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3861 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3862 EltNo -= NumElems/2;
3867 // Perform the splat.
3868 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3869 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3870 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3871 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3874 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3875 /// vector of zero or undef vector. This produces a shuffle where the low
3876 /// element of V2 is swizzled into the zero/undef vector, landing at element
3877 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3878 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3879 bool isZero, bool HasSSE2,
3880 SelectionDAG &DAG) {
3881 EVT VT = V2.getValueType();
3883 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3884 unsigned NumElems = VT.getVectorNumElements();
3885 SmallVector<int, 16> MaskVec;
3886 for (unsigned i = 0; i != NumElems; ++i)
3887 // If this is the insertion idx, put the low elt of V2 here.
3888 MaskVec.push_back(i == Idx ? NumElems : i);
3889 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3892 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3893 /// element of the result of the vector shuffle.
3894 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3897 return SDValue(); // Limit search depth.
3899 SDValue V = SDValue(N, 0);
3900 EVT VT = V.getValueType();
3901 unsigned Opcode = V.getOpcode();
3903 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3904 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3905 Index = SV->getMaskElt(Index);
3908 return DAG.getUNDEF(VT.getVectorElementType());
3910 int NumElems = VT.getVectorNumElements();
3911 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3912 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3915 // Recurse into target specific vector shuffles to find scalars.
3916 if (isTargetShuffle(Opcode)) {
3917 int NumElems = VT.getVectorNumElements();
3918 SmallVector<unsigned, 16> ShuffleMask;
3922 case X86ISD::SHUFPS:
3923 case X86ISD::SHUFPD:
3924 ImmN = N->getOperand(N->getNumOperands()-1);
3925 DecodeSHUFPSMask(NumElems,
3926 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3929 case X86ISD::PUNPCKHBW:
3930 case X86ISD::PUNPCKHWD:
3931 case X86ISD::PUNPCKHDQ:
3932 case X86ISD::PUNPCKHQDQ:
3933 DecodePUNPCKHMask(NumElems, ShuffleMask);
3935 case X86ISD::UNPCKHPS:
3936 case X86ISD::UNPCKHPD:
3937 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3939 case X86ISD::PUNPCKLBW:
3940 case X86ISD::PUNPCKLWD:
3941 case X86ISD::PUNPCKLDQ:
3942 case X86ISD::PUNPCKLQDQ:
3943 DecodePUNPCKLMask(VT, ShuffleMask);
3945 case X86ISD::UNPCKLPS:
3946 case X86ISD::UNPCKLPD:
3947 case X86ISD::VUNPCKLPS:
3948 case X86ISD::VUNPCKLPD:
3949 case X86ISD::VUNPCKLPSY:
3950 case X86ISD::VUNPCKLPDY:
3951 DecodeUNPCKLPMask(VT, ShuffleMask);
3953 case X86ISD::MOVHLPS:
3954 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3956 case X86ISD::MOVLHPS:
3957 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3959 case X86ISD::PSHUFD:
3960 ImmN = N->getOperand(N->getNumOperands()-1);
3961 DecodePSHUFMask(NumElems,
3962 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3965 case X86ISD::PSHUFHW:
3966 ImmN = N->getOperand(N->getNumOperands()-1);
3967 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3970 case X86ISD::PSHUFLW:
3971 ImmN = N->getOperand(N->getNumOperands()-1);
3972 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3976 case X86ISD::MOVSD: {
3977 // The index 0 always comes from the first element of the second source,
3978 // this is why MOVSS and MOVSD are used in the first place. The other
3979 // elements come from the other positions of the first source vector.
3980 unsigned OpNum = (Index == 0) ? 1 : 0;
3981 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3985 assert("not implemented for target shuffle node");
3989 Index = ShuffleMask[Index];
3991 return DAG.getUNDEF(VT.getVectorElementType());
3993 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3994 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3998 // Actual nodes that may contain scalar elements
3999 if (Opcode == ISD::BITCAST) {
4000 V = V.getOperand(0);
4001 EVT SrcVT = V.getValueType();
4002 unsigned NumElems = VT.getVectorNumElements();
4004 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4008 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4009 return (Index == 0) ? V.getOperand(0)
4010 : DAG.getUNDEF(VT.getVectorElementType());
4012 if (V.getOpcode() == ISD::BUILD_VECTOR)
4013 return V.getOperand(Index);
4018 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4019 /// shuffle operation which come from a consecutively from a zero. The
4020 /// search can start in two diferent directions, from left or right.
4022 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4023 bool ZerosFromLeft, SelectionDAG &DAG) {
4026 while (i < NumElems) {
4027 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4028 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4029 if (!(Elt.getNode() &&
4030 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4038 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4039 /// MaskE correspond consecutively to elements from one of the vector operands,
4040 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4042 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4043 int OpIdx, int NumElems, unsigned &OpNum) {
4044 bool SeenV1 = false;
4045 bool SeenV2 = false;
4047 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4048 int Idx = SVOp->getMaskElt(i);
4049 // Ignore undef indicies
4058 // Only accept consecutive elements from the same vector
4059 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4063 OpNum = SeenV1 ? 0 : 1;
4067 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4068 /// logical left shift of a vector.
4069 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4070 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4071 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4072 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4073 false /* check zeros from right */, DAG);
4079 // Considering the elements in the mask that are not consecutive zeros,
4080 // check if they consecutively come from only one of the source vectors.
4082 // V1 = {X, A, B, C} 0
4084 // vector_shuffle V1, V2 <1, 2, 3, X>
4086 if (!isShuffleMaskConsecutive(SVOp,
4087 0, // Mask Start Index
4088 NumElems-NumZeros-1, // Mask End Index
4089 NumZeros, // Where to start looking in the src vector
4090 NumElems, // Number of elements in vector
4091 OpSrc)) // Which source operand ?
4096 ShVal = SVOp->getOperand(OpSrc);
4100 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4101 /// logical left shift of a vector.
4102 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4103 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4104 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4105 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4106 true /* check zeros from left */, DAG);
4112 // Considering the elements in the mask that are not consecutive zeros,
4113 // check if they consecutively come from only one of the source vectors.
4115 // 0 { A, B, X, X } = V2
4117 // vector_shuffle V1, V2 <X, X, 4, 5>
4119 if (!isShuffleMaskConsecutive(SVOp,
4120 NumZeros, // Mask Start Index
4121 NumElems-1, // Mask End Index
4122 0, // Where to start looking in the src vector
4123 NumElems, // Number of elements in vector
4124 OpSrc)) // Which source operand ?
4129 ShVal = SVOp->getOperand(OpSrc);
4133 /// isVectorShift - Returns true if the shuffle can be implemented as a
4134 /// logical left or right shift of a vector.
4135 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4136 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4137 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4138 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4144 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4146 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4147 unsigned NumNonZero, unsigned NumZero,
4149 const TargetLowering &TLI) {
4153 DebugLoc dl = Op.getDebugLoc();
4156 for (unsigned i = 0; i < 16; ++i) {
4157 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4158 if (ThisIsNonZero && First) {
4160 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4162 V = DAG.getUNDEF(MVT::v8i16);
4167 SDValue ThisElt(0, 0), LastElt(0, 0);
4168 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4169 if (LastIsNonZero) {
4170 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4171 MVT::i16, Op.getOperand(i-1));
4173 if (ThisIsNonZero) {
4174 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4175 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4176 ThisElt, DAG.getConstant(8, MVT::i8));
4178 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4182 if (ThisElt.getNode())
4183 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4184 DAG.getIntPtrConstant(i/2));
4188 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4191 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4193 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4194 unsigned NumNonZero, unsigned NumZero,
4196 const TargetLowering &TLI) {
4200 DebugLoc dl = Op.getDebugLoc();
4203 for (unsigned i = 0; i < 8; ++i) {
4204 bool isNonZero = (NonZeros & (1 << i)) != 0;
4208 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4210 V = DAG.getUNDEF(MVT::v8i16);
4213 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4214 MVT::v8i16, V, Op.getOperand(i),
4215 DAG.getIntPtrConstant(i));
4222 /// getVShift - Return a vector logical shift node.
4224 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4225 unsigned NumBits, SelectionDAG &DAG,
4226 const TargetLowering &TLI, DebugLoc dl) {
4227 EVT ShVT = MVT::v2i64;
4228 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4229 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4230 return DAG.getNode(ISD::BITCAST, dl, VT,
4231 DAG.getNode(Opc, dl, ShVT, SrcOp,
4232 DAG.getConstant(NumBits,
4233 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4237 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4238 SelectionDAG &DAG) const {
4240 // Check if the scalar load can be widened into a vector load. And if
4241 // the address is "base + cst" see if the cst can be "absorbed" into
4242 // the shuffle mask.
4243 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4244 SDValue Ptr = LD->getBasePtr();
4245 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4247 EVT PVT = LD->getValueType(0);
4248 if (PVT != MVT::i32 && PVT != MVT::f32)
4253 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4254 FI = FINode->getIndex();
4256 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4257 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4258 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4259 Offset = Ptr.getConstantOperandVal(1);
4260 Ptr = Ptr.getOperand(0);
4265 SDValue Chain = LD->getChain();
4266 // Make sure the stack object alignment is at least 16.
4267 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4268 if (DAG.InferPtrAlignment(Ptr) < 16) {
4269 if (MFI->isFixedObjectIndex(FI)) {
4270 // Can't change the alignment. FIXME: It's possible to compute
4271 // the exact stack offset and reference FI + adjust offset instead.
4272 // If someone *really* cares about this. That's the way to implement it.
4275 MFI->setObjectAlignment(FI, 16);
4279 // (Offset % 16) must be multiple of 4. Then address is then
4280 // Ptr + (Offset & ~15).
4283 if ((Offset % 16) & 3)
4285 int64_t StartOffset = Offset & ~15;
4287 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4288 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4290 int EltNo = (Offset - StartOffset) >> 2;
4291 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4292 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4293 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4294 LD->getPointerInfo().getWithOffset(StartOffset),
4296 // Canonicalize it to a v4i32 shuffle.
4297 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4298 return DAG.getNode(ISD::BITCAST, dl, VT,
4299 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4300 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4306 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4307 /// vector of type 'VT', see if the elements can be replaced by a single large
4308 /// load which has the same value as a build_vector whose operands are 'elts'.
4310 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4312 /// FIXME: we'd also like to handle the case where the last elements are zero
4313 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4314 /// There's even a handy isZeroNode for that purpose.
4315 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4316 DebugLoc &DL, SelectionDAG &DAG) {
4317 EVT EltVT = VT.getVectorElementType();
4318 unsigned NumElems = Elts.size();
4320 LoadSDNode *LDBase = NULL;
4321 unsigned LastLoadedElt = -1U;
4323 // For each element in the initializer, see if we've found a load or an undef.
4324 // If we don't find an initial load element, or later load elements are
4325 // non-consecutive, bail out.
4326 for (unsigned i = 0; i < NumElems; ++i) {
4327 SDValue Elt = Elts[i];
4329 if (!Elt.getNode() ||
4330 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4333 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4335 LDBase = cast<LoadSDNode>(Elt.getNode());
4339 if (Elt.getOpcode() == ISD::UNDEF)
4342 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4343 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4348 // If we have found an entire vector of loads and undefs, then return a large
4349 // load of the entire vector width starting at the base pointer. If we found
4350 // consecutive loads for the low half, generate a vzext_load node.
4351 if (LastLoadedElt == NumElems - 1) {
4352 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4353 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4354 LDBase->getPointerInfo(),
4355 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4356 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4357 LDBase->getPointerInfo(),
4358 LDBase->isVolatile(), LDBase->isNonTemporal(),
4359 LDBase->getAlignment());
4360 } else if (NumElems == 4 && LastLoadedElt == 1) {
4361 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4362 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4363 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4365 LDBase->getMemOperand());
4366 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4372 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4373 DebugLoc dl = Op.getDebugLoc();
4375 EVT VT = Op.getValueType();
4376 EVT ExtVT = VT.getVectorElementType();
4378 unsigned NumElems = Op.getNumOperands();
4380 // For AVX-length vectors, build the individual 128-bit pieces and
4381 // use shuffles to put them in place.
4382 if (VT.getSizeInBits() > 256 &&
4383 Subtarget->hasAVX() &&
4384 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4385 SmallVector<SDValue, 8> V;
4387 for (unsigned i = 0; i < NumElems; ++i) {
4388 V[i] = Op.getOperand(i);
4391 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4393 // Build the lower subvector.
4394 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4395 // Build the upper subvector.
4396 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4399 return ConcatVectors(Lower, Upper, DAG);
4402 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4403 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4404 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4405 // is present, so AllOnes is ignored.
4406 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4407 (Op.getValueType().getSizeInBits() != 256 &&
4408 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4409 // Canonicalize this to <4 x i32> (SSE) to
4410 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4411 // eliminated on x86-32 hosts.
4412 if (Op.getValueType() == MVT::v4i32)
4415 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4416 return getOnesVector(Op.getValueType(), DAG, dl);
4417 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4420 unsigned EVTBits = ExtVT.getSizeInBits();
4422 unsigned NumZero = 0;
4423 unsigned NumNonZero = 0;
4424 unsigned NonZeros = 0;
4425 bool IsAllConstants = true;
4426 SmallSet<SDValue, 8> Values;
4427 for (unsigned i = 0; i < NumElems; ++i) {
4428 SDValue Elt = Op.getOperand(i);
4429 if (Elt.getOpcode() == ISD::UNDEF)
4432 if (Elt.getOpcode() != ISD::Constant &&
4433 Elt.getOpcode() != ISD::ConstantFP)
4434 IsAllConstants = false;
4435 if (X86::isZeroNode(Elt))
4438 NonZeros |= (1 << i);
4443 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4444 if (NumNonZero == 0)
4445 return DAG.getUNDEF(VT);
4447 // Special case for single non-zero, non-undef, element.
4448 if (NumNonZero == 1) {
4449 unsigned Idx = CountTrailingZeros_32(NonZeros);
4450 SDValue Item = Op.getOperand(Idx);
4452 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4453 // the value are obviously zero, truncate the value to i32 and do the
4454 // insertion that way. Only do this if the value is non-constant or if the
4455 // value is a constant being inserted into element 0. It is cheaper to do
4456 // a constant pool load than it is to do a movd + shuffle.
4457 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4458 (!IsAllConstants || Idx == 0)) {
4459 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4461 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4462 EVT VecVT = MVT::v4i32;
4463 unsigned VecElts = 4;
4465 // Truncate the value (which may itself be a constant) to i32, and
4466 // convert it to a vector with movd (S2V+shuffle to zero extend).
4467 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4468 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4469 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4470 Subtarget->hasSSE2(), DAG);
4472 // Now we have our 32-bit value zero extended in the low element of
4473 // a vector. If Idx != 0, swizzle it into place.
4475 SmallVector<int, 4> Mask;
4476 Mask.push_back(Idx);
4477 for (unsigned i = 1; i != VecElts; ++i)
4479 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4480 DAG.getUNDEF(Item.getValueType()),
4483 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4487 // If we have a constant or non-constant insertion into the low element of
4488 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4489 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4490 // depending on what the source datatype is.
4493 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4494 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4495 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4496 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4497 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4498 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4500 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4501 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4502 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4503 EVT MiddleVT = MVT::v4i32;
4504 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4505 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4506 Subtarget->hasSSE2(), DAG);
4507 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4511 // Is it a vector logical left shift?
4512 if (NumElems == 2 && Idx == 1 &&
4513 X86::isZeroNode(Op.getOperand(0)) &&
4514 !X86::isZeroNode(Op.getOperand(1))) {
4515 unsigned NumBits = VT.getSizeInBits();
4516 return getVShift(true, VT,
4517 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4518 VT, Op.getOperand(1)),
4519 NumBits/2, DAG, *this, dl);
4522 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4525 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4526 // is a non-constant being inserted into an element other than the low one,
4527 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4528 // movd/movss) to move this into the low element, then shuffle it into
4530 if (EVTBits == 32) {
4531 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4533 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4534 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4535 Subtarget->hasSSE2(), DAG);
4536 SmallVector<int, 8> MaskVec;
4537 for (unsigned i = 0; i < NumElems; i++)
4538 MaskVec.push_back(i == Idx ? 0 : 1);
4539 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4543 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4544 if (Values.size() == 1) {
4545 if (EVTBits == 32) {
4546 // Instead of a shuffle like this:
4547 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4548 // Check if it's possible to issue this instead.
4549 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4550 unsigned Idx = CountTrailingZeros_32(NonZeros);
4551 SDValue Item = Op.getOperand(Idx);
4552 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4553 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4558 // A vector full of immediates; various special cases are already
4559 // handled, so this is best done with a single constant-pool load.
4563 // Let legalizer expand 2-wide build_vectors.
4564 if (EVTBits == 64) {
4565 if (NumNonZero == 1) {
4566 // One half is zero or undef.
4567 unsigned Idx = CountTrailingZeros_32(NonZeros);
4568 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4569 Op.getOperand(Idx));
4570 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4571 Subtarget->hasSSE2(), DAG);
4576 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4577 if (EVTBits == 8 && NumElems == 16) {
4578 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4580 if (V.getNode()) return V;
4583 if (EVTBits == 16 && NumElems == 8) {
4584 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4586 if (V.getNode()) return V;
4589 // If element VT is == 32 bits, turn it into a number of shuffles.
4590 SmallVector<SDValue, 8> V;
4592 if (NumElems == 4 && NumZero > 0) {
4593 for (unsigned i = 0; i < 4; ++i) {
4594 bool isZero = !(NonZeros & (1 << i));
4596 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4598 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4601 for (unsigned i = 0; i < 2; ++i) {
4602 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4605 V[i] = V[i*2]; // Must be a zero vector.
4608 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4611 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4614 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4619 SmallVector<int, 8> MaskVec;
4620 bool Reverse = (NonZeros & 0x3) == 2;
4621 for (unsigned i = 0; i < 2; ++i)
4622 MaskVec.push_back(Reverse ? 1-i : i);
4623 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4624 for (unsigned i = 0; i < 2; ++i)
4625 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4626 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4629 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4630 // Check for a build vector of consecutive loads.
4631 for (unsigned i = 0; i < NumElems; ++i)
4632 V[i] = Op.getOperand(i);
4634 // Check for elements which are consecutive loads.
4635 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4639 // For SSE 4.1, use insertps to put the high elements into the low element.
4640 if (getSubtarget()->hasSSE41()) {
4642 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4643 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4645 Result = DAG.getUNDEF(VT);
4647 for (unsigned i = 1; i < NumElems; ++i) {
4648 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4649 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4650 Op.getOperand(i), DAG.getIntPtrConstant(i));
4655 // Otherwise, expand into a number of unpckl*, start by extending each of
4656 // our (non-undef) elements to the full vector width with the element in the
4657 // bottom slot of the vector (which generates no code for SSE).
4658 for (unsigned i = 0; i < NumElems; ++i) {
4659 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4660 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4662 V[i] = DAG.getUNDEF(VT);
4665 // Next, we iteratively mix elements, e.g. for v4f32:
4666 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4667 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4668 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4669 unsigned EltStride = NumElems >> 1;
4670 while (EltStride != 0) {
4671 for (unsigned i = 0; i < EltStride; ++i) {
4672 // If V[i+EltStride] is undef and this is the first round of mixing,
4673 // then it is safe to just drop this shuffle: V[i] is already in the
4674 // right place, the one element (since it's the first round) being
4675 // inserted as undef can be dropped. This isn't safe for successive
4676 // rounds because they will permute elements within both vectors.
4677 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4678 EltStride == NumElems/2)
4681 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4691 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4692 // We support concatenate two MMX registers and place them in a MMX
4693 // register. This is better than doing a stack convert.
4694 DebugLoc dl = Op.getDebugLoc();
4695 EVT ResVT = Op.getValueType();
4696 assert(Op.getNumOperands() == 2);
4697 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4698 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4700 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4701 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4702 InVec = Op.getOperand(1);
4703 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4704 unsigned NumElts = ResVT.getVectorNumElements();
4705 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4706 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4707 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4709 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4710 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4711 Mask[0] = 0; Mask[1] = 2;
4712 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4714 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4717 // v8i16 shuffles - Prefer shuffles in the following order:
4718 // 1. [all] pshuflw, pshufhw, optional move
4719 // 2. [ssse3] 1 x pshufb
4720 // 3. [ssse3] 2 x pshufb + 1 x por
4721 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4723 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4724 SelectionDAG &DAG) const {
4725 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4726 SDValue V1 = SVOp->getOperand(0);
4727 SDValue V2 = SVOp->getOperand(1);
4728 DebugLoc dl = SVOp->getDebugLoc();
4729 SmallVector<int, 8> MaskVals;
4731 // Determine if more than 1 of the words in each of the low and high quadwords
4732 // of the result come from the same quadword of one of the two inputs. Undef
4733 // mask values count as coming from any quadword, for better codegen.
4734 SmallVector<unsigned, 4> LoQuad(4);
4735 SmallVector<unsigned, 4> HiQuad(4);
4736 BitVector InputQuads(4);
4737 for (unsigned i = 0; i < 8; ++i) {
4738 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4739 int EltIdx = SVOp->getMaskElt(i);
4740 MaskVals.push_back(EltIdx);
4749 InputQuads.set(EltIdx / 4);
4752 int BestLoQuad = -1;
4753 unsigned MaxQuad = 1;
4754 for (unsigned i = 0; i < 4; ++i) {
4755 if (LoQuad[i] > MaxQuad) {
4757 MaxQuad = LoQuad[i];
4761 int BestHiQuad = -1;
4763 for (unsigned i = 0; i < 4; ++i) {
4764 if (HiQuad[i] > MaxQuad) {
4766 MaxQuad = HiQuad[i];
4770 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4771 // of the two input vectors, shuffle them into one input vector so only a
4772 // single pshufb instruction is necessary. If There are more than 2 input
4773 // quads, disable the next transformation since it does not help SSSE3.
4774 bool V1Used = InputQuads[0] || InputQuads[1];
4775 bool V2Used = InputQuads[2] || InputQuads[3];
4776 if (Subtarget->hasSSSE3()) {
4777 if (InputQuads.count() == 2 && V1Used && V2Used) {
4778 BestLoQuad = InputQuads.find_first();
4779 BestHiQuad = InputQuads.find_next(BestLoQuad);
4781 if (InputQuads.count() > 2) {
4787 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4788 // the shuffle mask. If a quad is scored as -1, that means that it contains
4789 // words from all 4 input quadwords.
4791 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4792 SmallVector<int, 8> MaskV;
4793 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4794 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4795 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4796 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4797 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4798 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4800 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4801 // source words for the shuffle, to aid later transformations.
4802 bool AllWordsInNewV = true;
4803 bool InOrder[2] = { true, true };
4804 for (unsigned i = 0; i != 8; ++i) {
4805 int idx = MaskVals[i];
4807 InOrder[i/4] = false;
4808 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4810 AllWordsInNewV = false;
4814 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4815 if (AllWordsInNewV) {
4816 for (int i = 0; i != 8; ++i) {
4817 int idx = MaskVals[i];
4820 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4821 if ((idx != i) && idx < 4)
4823 if ((idx != i) && idx > 3)
4832 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4833 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4834 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4835 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4836 unsigned TargetMask = 0;
4837 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4838 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4839 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4840 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4841 V1 = NewV.getOperand(0);
4842 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4846 // If we have SSSE3, and all words of the result are from 1 input vector,
4847 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4848 // is present, fall back to case 4.
4849 if (Subtarget->hasSSSE3()) {
4850 SmallVector<SDValue,16> pshufbMask;
4852 // If we have elements from both input vectors, set the high bit of the
4853 // shuffle mask element to zero out elements that come from V2 in the V1
4854 // mask, and elements that come from V1 in the V2 mask, so that the two
4855 // results can be OR'd together.
4856 bool TwoInputs = V1Used && V2Used;
4857 for (unsigned i = 0; i != 8; ++i) {
4858 int EltIdx = MaskVals[i] * 2;
4859 if (TwoInputs && (EltIdx >= 16)) {
4860 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4861 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4864 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4865 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4867 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4868 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4869 DAG.getNode(ISD::BUILD_VECTOR, dl,
4870 MVT::v16i8, &pshufbMask[0], 16));
4872 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4874 // Calculate the shuffle mask for the second input, shuffle it, and
4875 // OR it with the first shuffled input.
4877 for (unsigned i = 0; i != 8; ++i) {
4878 int EltIdx = MaskVals[i] * 2;
4880 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4881 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4884 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4885 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4887 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4888 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4889 DAG.getNode(ISD::BUILD_VECTOR, dl,
4890 MVT::v16i8, &pshufbMask[0], 16));
4891 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4892 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4895 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4896 // and update MaskVals with new element order.
4897 BitVector InOrder(8);
4898 if (BestLoQuad >= 0) {
4899 SmallVector<int, 8> MaskV;
4900 for (int i = 0; i != 4; ++i) {
4901 int idx = MaskVals[i];
4903 MaskV.push_back(-1);
4905 } else if ((idx / 4) == BestLoQuad) {
4906 MaskV.push_back(idx & 3);
4909 MaskV.push_back(-1);
4912 for (unsigned i = 4; i != 8; ++i)
4914 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4917 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4918 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4920 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4924 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4925 // and update MaskVals with the new element order.
4926 if (BestHiQuad >= 0) {
4927 SmallVector<int, 8> MaskV;
4928 for (unsigned i = 0; i != 4; ++i)
4930 for (unsigned i = 4; i != 8; ++i) {
4931 int idx = MaskVals[i];
4933 MaskV.push_back(-1);
4935 } else if ((idx / 4) == BestHiQuad) {
4936 MaskV.push_back((idx & 3) + 4);
4939 MaskV.push_back(-1);
4942 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4945 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4946 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4948 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4952 // In case BestHi & BestLo were both -1, which means each quadword has a word
4953 // from each of the four input quadwords, calculate the InOrder bitvector now
4954 // before falling through to the insert/extract cleanup.
4955 if (BestLoQuad == -1 && BestHiQuad == -1) {
4957 for (int i = 0; i != 8; ++i)
4958 if (MaskVals[i] < 0 || MaskVals[i] == i)
4962 // The other elements are put in the right place using pextrw and pinsrw.
4963 for (unsigned i = 0; i != 8; ++i) {
4966 int EltIdx = MaskVals[i];
4969 SDValue ExtOp = (EltIdx < 8)
4970 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4971 DAG.getIntPtrConstant(EltIdx))
4972 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4973 DAG.getIntPtrConstant(EltIdx - 8));
4974 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4975 DAG.getIntPtrConstant(i));
4980 // v16i8 shuffles - Prefer shuffles in the following order:
4981 // 1. [ssse3] 1 x pshufb
4982 // 2. [ssse3] 2 x pshufb + 1 x por
4983 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4985 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4987 const X86TargetLowering &TLI) {
4988 SDValue V1 = SVOp->getOperand(0);
4989 SDValue V2 = SVOp->getOperand(1);
4990 DebugLoc dl = SVOp->getDebugLoc();
4991 SmallVector<int, 16> MaskVals;
4992 SVOp->getMask(MaskVals);
4994 // If we have SSSE3, case 1 is generated when all result bytes come from
4995 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4996 // present, fall back to case 3.
4997 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5000 for (unsigned i = 0; i < 16; ++i) {
5001 int EltIdx = MaskVals[i];
5010 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5011 if (TLI.getSubtarget()->hasSSSE3()) {
5012 SmallVector<SDValue,16> pshufbMask;
5014 // If all result elements are from one input vector, then only translate
5015 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5017 // Otherwise, we have elements from both input vectors, and must zero out
5018 // elements that come from V2 in the first mask, and V1 in the second mask
5019 // so that we can OR them together.
5020 bool TwoInputs = !(V1Only || V2Only);
5021 for (unsigned i = 0; i != 16; ++i) {
5022 int EltIdx = MaskVals[i];
5023 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5024 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5027 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5029 // If all the elements are from V2, assign it to V1 and return after
5030 // building the first pshufb.
5033 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5034 DAG.getNode(ISD::BUILD_VECTOR, dl,
5035 MVT::v16i8, &pshufbMask[0], 16));
5039 // Calculate the shuffle mask for the second input, shuffle it, and
5040 // OR it with the first shuffled input.
5042 for (unsigned i = 0; i != 16; ++i) {
5043 int EltIdx = MaskVals[i];
5045 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5048 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5050 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5051 DAG.getNode(ISD::BUILD_VECTOR, dl,
5052 MVT::v16i8, &pshufbMask[0], 16));
5053 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5056 // No SSSE3 - Calculate in place words and then fix all out of place words
5057 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5058 // the 16 different words that comprise the two doublequadword input vectors.
5059 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5060 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5061 SDValue NewV = V2Only ? V2 : V1;
5062 for (int i = 0; i != 8; ++i) {
5063 int Elt0 = MaskVals[i*2];
5064 int Elt1 = MaskVals[i*2+1];
5066 // This word of the result is all undef, skip it.
5067 if (Elt0 < 0 && Elt1 < 0)
5070 // This word of the result is already in the correct place, skip it.
5071 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5073 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5076 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5077 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5080 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5081 // using a single extract together, load it and store it.
5082 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5083 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5084 DAG.getIntPtrConstant(Elt1 / 2));
5085 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5086 DAG.getIntPtrConstant(i));
5090 // If Elt1 is defined, extract it from the appropriate source. If the
5091 // source byte is not also odd, shift the extracted word left 8 bits
5092 // otherwise clear the bottom 8 bits if we need to do an or.
5094 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5095 DAG.getIntPtrConstant(Elt1 / 2));
5096 if ((Elt1 & 1) == 0)
5097 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5099 TLI.getShiftAmountTy(InsElt.getValueType())));
5101 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5102 DAG.getConstant(0xFF00, MVT::i16));
5104 // If Elt0 is defined, extract it from the appropriate source. If the
5105 // source byte is not also even, shift the extracted word right 8 bits. If
5106 // Elt1 was also defined, OR the extracted values together before
5107 // inserting them in the result.
5109 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5110 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5111 if ((Elt0 & 1) != 0)
5112 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5114 TLI.getShiftAmountTy(InsElt0.getValueType())));
5116 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5117 DAG.getConstant(0x00FF, MVT::i16));
5118 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5121 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5122 DAG.getIntPtrConstant(i));
5124 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5127 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5128 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5129 /// done when every pair / quad of shuffle mask elements point to elements in
5130 /// the right sequence. e.g.
5131 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5133 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5134 SelectionDAG &DAG, DebugLoc dl) {
5135 EVT VT = SVOp->getValueType(0);
5136 SDValue V1 = SVOp->getOperand(0);
5137 SDValue V2 = SVOp->getOperand(1);
5138 unsigned NumElems = VT.getVectorNumElements();
5139 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5141 switch (VT.getSimpleVT().SimpleTy) {
5142 default: assert(false && "Unexpected!");
5143 case MVT::v4f32: NewVT = MVT::v2f64; break;
5144 case MVT::v4i32: NewVT = MVT::v2i64; break;
5145 case MVT::v8i16: NewVT = MVT::v4i32; break;
5146 case MVT::v16i8: NewVT = MVT::v4i32; break;
5149 int Scale = NumElems / NewWidth;
5150 SmallVector<int, 8> MaskVec;
5151 for (unsigned i = 0; i < NumElems; i += Scale) {
5153 for (int j = 0; j < Scale; ++j) {
5154 int EltIdx = SVOp->getMaskElt(i+j);
5158 StartIdx = EltIdx - (EltIdx % Scale);
5159 if (EltIdx != StartIdx + j)
5163 MaskVec.push_back(-1);
5165 MaskVec.push_back(StartIdx / Scale);
5168 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5169 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5170 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5173 /// getVZextMovL - Return a zero-extending vector move low node.
5175 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5176 SDValue SrcOp, SelectionDAG &DAG,
5177 const X86Subtarget *Subtarget, DebugLoc dl) {
5178 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5179 LoadSDNode *LD = NULL;
5180 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5181 LD = dyn_cast<LoadSDNode>(SrcOp);
5183 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5185 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5186 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5187 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5188 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5189 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5191 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5192 return DAG.getNode(ISD::BITCAST, dl, VT,
5193 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5194 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5202 return DAG.getNode(ISD::BITCAST, dl, VT,
5203 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5204 DAG.getNode(ISD::BITCAST, dl,
5208 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5211 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5212 SDValue V1 = SVOp->getOperand(0);
5213 SDValue V2 = SVOp->getOperand(1);
5214 DebugLoc dl = SVOp->getDebugLoc();
5215 EVT VT = SVOp->getValueType(0);
5217 SmallVector<std::pair<int, int>, 8> Locs;
5219 SmallVector<int, 8> Mask1(4U, -1);
5220 SmallVector<int, 8> PermMask;
5221 SVOp->getMask(PermMask);
5225 for (unsigned i = 0; i != 4; ++i) {
5226 int Idx = PermMask[i];
5228 Locs[i] = std::make_pair(-1, -1);
5230 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5232 Locs[i] = std::make_pair(0, NumLo);
5236 Locs[i] = std::make_pair(1, NumHi);
5238 Mask1[2+NumHi] = Idx;
5244 if (NumLo <= 2 && NumHi <= 2) {
5245 // If no more than two elements come from either vector. This can be
5246 // implemented with two shuffles. First shuffle gather the elements.
5247 // The second shuffle, which takes the first shuffle as both of its
5248 // vector operands, put the elements into the right order.
5249 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5251 SmallVector<int, 8> Mask2(4U, -1);
5253 for (unsigned i = 0; i != 4; ++i) {
5254 if (Locs[i].first == -1)
5257 unsigned Idx = (i < 2) ? 0 : 4;
5258 Idx += Locs[i].first * 2 + Locs[i].second;
5263 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5264 } else if (NumLo == 3 || NumHi == 3) {
5265 // Otherwise, we must have three elements from one vector, call it X, and
5266 // one element from the other, call it Y. First, use a shufps to build an
5267 // intermediate vector with the one element from Y and the element from X
5268 // that will be in the same half in the final destination (the indexes don't
5269 // matter). Then, use a shufps to build the final vector, taking the half
5270 // containing the element from Y from the intermediate, and the other half
5273 // Normalize it so the 3 elements come from V1.
5274 CommuteVectorShuffleMask(PermMask, VT);
5278 // Find the element from V2.
5280 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5281 int Val = PermMask[HiIndex];
5288 Mask1[0] = PermMask[HiIndex];
5290 Mask1[2] = PermMask[HiIndex^1];
5292 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5295 Mask1[0] = PermMask[0];
5296 Mask1[1] = PermMask[1];
5297 Mask1[2] = HiIndex & 1 ? 6 : 4;
5298 Mask1[3] = HiIndex & 1 ? 4 : 6;
5299 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5301 Mask1[0] = HiIndex & 1 ? 2 : 0;
5302 Mask1[1] = HiIndex & 1 ? 0 : 2;
5303 Mask1[2] = PermMask[2];
5304 Mask1[3] = PermMask[3];
5309 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5313 // Break it into (shuffle shuffle_hi, shuffle_lo).
5316 SmallVector<int,8> LoMask(4U, -1);
5317 SmallVector<int,8> HiMask(4U, -1);
5319 SmallVector<int,8> *MaskPtr = &LoMask;
5320 unsigned MaskIdx = 0;
5323 for (unsigned i = 0; i != 4; ++i) {
5330 int Idx = PermMask[i];
5332 Locs[i] = std::make_pair(-1, -1);
5333 } else if (Idx < 4) {
5334 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5335 (*MaskPtr)[LoIdx] = Idx;
5338 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5339 (*MaskPtr)[HiIdx] = Idx;
5344 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5345 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5346 SmallVector<int, 8> MaskOps;
5347 for (unsigned i = 0; i != 4; ++i) {
5348 if (Locs[i].first == -1) {
5349 MaskOps.push_back(-1);
5351 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5352 MaskOps.push_back(Idx);
5355 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5358 static bool MayFoldVectorLoad(SDValue V) {
5359 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5360 V = V.getOperand(0);
5361 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5362 V = V.getOperand(0);
5368 // FIXME: the version above should always be used. Since there's
5369 // a bug where several vector shuffles can't be folded because the
5370 // DAG is not updated during lowering and a node claims to have two
5371 // uses while it only has one, use this version, and let isel match
5372 // another instruction if the load really happens to have more than
5373 // one use. Remove this version after this bug get fixed.
5374 // rdar://8434668, PR8156
5375 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5376 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5377 V = V.getOperand(0);
5378 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5379 V = V.getOperand(0);
5380 if (ISD::isNormalLoad(V.getNode()))
5385 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5386 /// a vector extract, and if both can be later optimized into a single load.
5387 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5388 /// here because otherwise a target specific shuffle node is going to be
5389 /// emitted for this shuffle, and the optimization not done.
5390 /// FIXME: This is probably not the best approach, but fix the problem
5391 /// until the right path is decided.
5393 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5394 const TargetLowering &TLI) {
5395 EVT VT = V.getValueType();
5396 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5398 // Be sure that the vector shuffle is present in a pattern like this:
5399 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5403 SDNode *N = *V.getNode()->use_begin();
5404 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5407 SDValue EltNo = N->getOperand(1);
5408 if (!isa<ConstantSDNode>(EltNo))
5411 // If the bit convert changed the number of elements, it is unsafe
5412 // to examine the mask.
5413 bool HasShuffleIntoBitcast = false;
5414 if (V.getOpcode() == ISD::BITCAST) {
5415 EVT SrcVT = V.getOperand(0).getValueType();
5416 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5418 V = V.getOperand(0);
5419 HasShuffleIntoBitcast = true;
5422 // Select the input vector, guarding against out of range extract vector.
5423 unsigned NumElems = VT.getVectorNumElements();
5424 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5425 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5426 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5428 // Skip one more bit_convert if necessary
5429 if (V.getOpcode() == ISD::BITCAST)
5430 V = V.getOperand(0);
5432 if (ISD::isNormalLoad(V.getNode())) {
5433 // Is the original load suitable?
5434 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5436 // FIXME: avoid the multi-use bug that is preventing lots of
5437 // of foldings to be detected, this is still wrong of course, but
5438 // give the temporary desired behavior, and if it happens that
5439 // the load has real more uses, during isel it will not fold, and
5440 // will generate poor code.
5441 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5444 if (!HasShuffleIntoBitcast)
5447 // If there's a bitcast before the shuffle, check if the load type and
5448 // alignment is valid.
5449 unsigned Align = LN0->getAlignment();
5451 TLI.getTargetData()->getABITypeAlignment(
5452 VT.getTypeForEVT(*DAG.getContext()));
5454 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5462 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5463 EVT VT = Op.getValueType();
5465 // Canonizalize to v2f64.
5466 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5467 return DAG.getNode(ISD::BITCAST, dl, VT,
5468 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5473 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5475 SDValue V1 = Op.getOperand(0);
5476 SDValue V2 = Op.getOperand(1);
5477 EVT VT = Op.getValueType();
5479 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5481 if (HasSSE2 && VT == MVT::v2f64)
5482 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5485 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5489 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5490 SDValue V1 = Op.getOperand(0);
5491 SDValue V2 = Op.getOperand(1);
5492 EVT VT = Op.getValueType();
5494 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5495 "unsupported shuffle type");
5497 if (V2.getOpcode() == ISD::UNDEF)
5501 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5505 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5506 SDValue V1 = Op.getOperand(0);
5507 SDValue V2 = Op.getOperand(1);
5508 EVT VT = Op.getValueType();
5509 unsigned NumElems = VT.getVectorNumElements();
5511 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5512 // operand of these instructions is only memory, so check if there's a
5513 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5515 bool CanFoldLoad = false;
5517 // Trivial case, when V2 comes from a load.
5518 if (MayFoldVectorLoad(V2))
5521 // When V1 is a load, it can be folded later into a store in isel, example:
5522 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5524 // (MOVLPSmr addr:$src1, VR128:$src2)
5525 // So, recognize this potential and also use MOVLPS or MOVLPD
5526 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5529 // Both of them can't be memory operations though.
5530 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5531 CanFoldLoad = false;
5534 if (HasSSE2 && NumElems == 2)
5535 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5538 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5541 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5542 // movl and movlp will both match v2i64, but v2i64 is never matched by
5543 // movl earlier because we make it strict to avoid messing with the movlp load
5544 // folding logic (see the code above getMOVLP call). Match it here then,
5545 // this is horrible, but will stay like this until we move all shuffle
5546 // matching to x86 specific nodes. Note that for the 1st condition all
5547 // types are matched with movsd.
5548 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5549 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5551 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5554 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5556 // Invert the operand order and use SHUFPS to match it.
5557 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5558 X86::getShuffleSHUFImmediate(SVOp), DAG);
5561 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5562 switch(VT.getSimpleVT().SimpleTy) {
5563 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5564 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5566 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5568 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5569 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5570 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5571 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5572 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5574 llvm_unreachable("Unknown type for unpckl");
5579 static inline unsigned getUNPCKHOpcode(EVT VT) {
5580 switch(VT.getSimpleVT().SimpleTy) {
5581 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5582 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5583 case MVT::v4f32: return X86ISD::UNPCKHPS;
5584 case MVT::v2f64: return X86ISD::UNPCKHPD;
5585 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5586 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5588 llvm_unreachable("Unknown type for unpckh");
5594 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5595 const TargetLowering &TLI,
5596 const X86Subtarget *Subtarget) {
5597 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5598 EVT VT = Op.getValueType();
5599 DebugLoc dl = Op.getDebugLoc();
5600 SDValue V1 = Op.getOperand(0);
5601 SDValue V2 = Op.getOperand(1);
5603 if (isZeroShuffle(SVOp))
5604 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5606 // Handle splat operations
5607 if (SVOp->isSplat()) {
5608 // Special case, this is the only place now where it's
5609 // allowed to return a vector_shuffle operation without
5610 // using a target specific node, because *hopefully* it
5611 // will be optimized away by the dag combiner.
5612 if (VT.getVectorNumElements() <= 4 &&
5613 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5616 // Handle splats by matching through known masks
5617 if (VT.getVectorNumElements() <= 4)
5620 // Canonicalize all of the remaining to v4f32.
5621 return PromoteSplat(SVOp, DAG);
5624 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5626 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5627 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5628 if (NewOp.getNode())
5629 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5630 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5631 // FIXME: Figure out a cleaner way to do this.
5632 // Try to make use of movq to zero out the top part.
5633 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5634 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5635 if (NewOp.getNode()) {
5636 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5637 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5638 DAG, Subtarget, dl);
5640 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5641 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5642 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5643 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5644 DAG, Subtarget, dl);
5651 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5653 SDValue V1 = Op.getOperand(0);
5654 SDValue V2 = Op.getOperand(1);
5655 EVT VT = Op.getValueType();
5656 DebugLoc dl = Op.getDebugLoc();
5657 unsigned NumElems = VT.getVectorNumElements();
5658 bool isMMX = VT.getSizeInBits() == 64;
5659 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5660 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5661 bool V1IsSplat = false;
5662 bool V2IsSplat = false;
5663 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5664 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5665 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5666 MachineFunction &MF = DAG.getMachineFunction();
5667 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5669 // Shuffle operations on MMX not supported.
5673 // Vector shuffle lowering takes 3 steps:
5675 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5676 // narrowing and commutation of operands should be handled.
5677 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5679 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5680 // so the shuffle can be broken into other shuffles and the legalizer can
5681 // try the lowering again.
5683 // The general ideia is that no vector_shuffle operation should be left to
5684 // be matched during isel, all of them must be converted to a target specific
5687 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5688 // narrowing and commutation of operands should be handled. The actual code
5689 // doesn't include all of those, work in progress...
5690 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5691 if (NewOp.getNode())
5694 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5695 // unpckh_undef). Only use pshufd if speed is more important than size.
5696 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5697 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5698 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5699 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5700 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5701 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5703 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5704 RelaxedMayFoldVectorLoad(V1))
5705 return getMOVDDup(Op, dl, V1, DAG);
5707 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5708 return getMOVHighToLow(Op, dl, DAG);
5710 // Use to match splats
5711 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5712 (VT == MVT::v2f64 || VT == MVT::v2i64))
5713 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5715 if (X86::isPSHUFDMask(SVOp)) {
5716 // The actual implementation will match the mask in the if above and then
5717 // during isel it can match several different instructions, not only pshufd
5718 // as its name says, sad but true, emulate the behavior for now...
5719 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5720 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5722 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5724 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5725 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5727 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5728 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5731 if (VT == MVT::v4f32)
5732 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5736 // Check if this can be converted into a logical shift.
5737 bool isLeft = false;
5740 bool isShift = getSubtarget()->hasSSE2() &&
5741 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5742 if (isShift && ShVal.hasOneUse()) {
5743 // If the shifted value has multiple uses, it may be cheaper to use
5744 // v_set0 + movlhps or movhlps, etc.
5745 EVT EltVT = VT.getVectorElementType();
5746 ShAmt *= EltVT.getSizeInBits();
5747 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5750 if (X86::isMOVLMask(SVOp)) {
5753 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5754 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5755 if (!X86::isMOVLPMask(SVOp)) {
5756 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5757 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5759 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5760 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5764 // FIXME: fold these into legal mask.
5765 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5766 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5768 if (X86::isMOVHLPSMask(SVOp))
5769 return getMOVHighToLow(Op, dl, DAG);
5771 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5772 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5774 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5775 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5777 if (X86::isMOVLPMask(SVOp))
5778 return getMOVLP(Op, dl, DAG, HasSSE2);
5780 if (ShouldXformToMOVHLPS(SVOp) ||
5781 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5782 return CommuteVectorShuffle(SVOp, DAG);
5785 // No better options. Use a vshl / vsrl.
5786 EVT EltVT = VT.getVectorElementType();
5787 ShAmt *= EltVT.getSizeInBits();
5788 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5791 bool Commuted = false;
5792 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5793 // 1,1,1,1 -> v8i16 though.
5794 V1IsSplat = isSplatVector(V1.getNode());
5795 V2IsSplat = isSplatVector(V2.getNode());
5797 // Canonicalize the splat or undef, if present, to be on the RHS.
5798 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5799 Op = CommuteVectorShuffle(SVOp, DAG);
5800 SVOp = cast<ShuffleVectorSDNode>(Op);
5801 V1 = SVOp->getOperand(0);
5802 V2 = SVOp->getOperand(1);
5803 std::swap(V1IsSplat, V2IsSplat);
5804 std::swap(V1IsUndef, V2IsUndef);
5808 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5809 // Shuffling low element of v1 into undef, just return v1.
5812 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5813 // the instruction selector will not match, so get a canonical MOVL with
5814 // swapped operands to undo the commute.
5815 return getMOVL(DAG, dl, VT, V2, V1);
5818 if (X86::isUNPCKLMask(SVOp))
5819 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5820 dl, VT, V1, V2, DAG);
5822 if (X86::isUNPCKHMask(SVOp))
5823 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5826 // Normalize mask so all entries that point to V2 points to its first
5827 // element then try to match unpck{h|l} again. If match, return a
5828 // new vector_shuffle with the corrected mask.
5829 SDValue NewMask = NormalizeMask(SVOp, DAG);
5830 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5831 if (NSVOp != SVOp) {
5832 if (X86::isUNPCKLMask(NSVOp, true)) {
5834 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5841 // Commute is back and try unpck* again.
5842 // FIXME: this seems wrong.
5843 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5844 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5846 if (X86::isUNPCKLMask(NewSVOp))
5847 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5848 dl, VT, V2, V1, DAG);
5850 if (X86::isUNPCKHMask(NewSVOp))
5851 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5854 // Normalize the node to match x86 shuffle ops if needed
5855 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5856 return CommuteVectorShuffle(SVOp, DAG);
5858 // The checks below are all present in isShuffleMaskLegal, but they are
5859 // inlined here right now to enable us to directly emit target specific
5860 // nodes, and remove one by one until they don't return Op anymore.
5861 SmallVector<int, 16> M;
5864 if (isPALIGNRMask(M, VT, HasSSSE3))
5865 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5866 X86::getShufflePALIGNRImmediate(SVOp),
5869 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5870 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5871 if (VT == MVT::v2f64) {
5872 X86ISD::NodeType Opcode =
5873 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5874 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5876 if (VT == MVT::v2i64)
5877 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5880 if (isPSHUFHWMask(M, VT))
5881 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5882 X86::getShufflePSHUFHWImmediate(SVOp),
5885 if (isPSHUFLWMask(M, VT))
5886 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5887 X86::getShufflePSHUFLWImmediate(SVOp),
5890 if (isSHUFPMask(M, VT)) {
5891 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5892 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5893 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5895 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5896 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5900 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5901 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5902 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5903 dl, VT, V1, V1, DAG);
5904 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5905 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5906 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5908 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5909 if (VT == MVT::v8i16) {
5910 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5911 if (NewOp.getNode())
5915 if (VT == MVT::v16i8) {
5916 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5917 if (NewOp.getNode())
5921 // Handle all 4 wide cases with a number of shuffles.
5923 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5929 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5930 SelectionDAG &DAG) const {
5931 EVT VT = Op.getValueType();
5932 DebugLoc dl = Op.getDebugLoc();
5933 if (VT.getSizeInBits() == 8) {
5934 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5935 Op.getOperand(0), Op.getOperand(1));
5936 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5937 DAG.getValueType(VT));
5938 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5939 } else if (VT.getSizeInBits() == 16) {
5940 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5941 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5943 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5944 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5945 DAG.getNode(ISD::BITCAST, dl,
5949 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5950 Op.getOperand(0), Op.getOperand(1));
5951 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5952 DAG.getValueType(VT));
5953 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5954 } else if (VT == MVT::f32) {
5955 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5956 // the result back to FR32 register. It's only worth matching if the
5957 // result has a single use which is a store or a bitcast to i32. And in
5958 // the case of a store, it's not worth it if the index is a constant 0,
5959 // because a MOVSSmr can be used instead, which is smaller and faster.
5960 if (!Op.hasOneUse())
5962 SDNode *User = *Op.getNode()->use_begin();
5963 if ((User->getOpcode() != ISD::STORE ||
5964 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5965 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5966 (User->getOpcode() != ISD::BITCAST ||
5967 User->getValueType(0) != MVT::i32))
5969 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5970 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5973 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5974 } else if (VT == MVT::i32) {
5975 // ExtractPS works with constant index.
5976 if (isa<ConstantSDNode>(Op.getOperand(1)))
5984 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5985 SelectionDAG &DAG) const {
5986 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5989 SDValue Vec = Op.getOperand(0);
5990 EVT VecVT = Vec.getValueType();
5992 // If this is a 256-bit vector result, first extract the 128-bit
5993 // vector and then extract from the 128-bit vector.
5994 if (VecVT.getSizeInBits() > 128) {
5995 DebugLoc dl = Op.getNode()->getDebugLoc();
5996 unsigned NumElems = VecVT.getVectorNumElements();
5997 SDValue Idx = Op.getOperand(1);
5999 if (!isa<ConstantSDNode>(Idx))
6002 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6003 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6005 // Get the 128-bit vector.
6006 bool Upper = IdxVal >= ExtractNumElems;
6007 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6010 SDValue ScaledIdx = Idx;
6012 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6013 DAG.getConstant(ExtractNumElems,
6014 Idx.getValueType()));
6015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6019 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6021 if (Subtarget->hasSSE41()) {
6022 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6027 EVT VT = Op.getValueType();
6028 DebugLoc dl = Op.getDebugLoc();
6029 // TODO: handle v16i8.
6030 if (VT.getSizeInBits() == 16) {
6031 SDValue Vec = Op.getOperand(0);
6032 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6034 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6035 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6036 DAG.getNode(ISD::BITCAST, dl,
6039 // Transform it so it match pextrw which produces a 32-bit result.
6040 EVT EltVT = MVT::i32;
6041 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6042 Op.getOperand(0), Op.getOperand(1));
6043 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6044 DAG.getValueType(VT));
6045 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6046 } else if (VT.getSizeInBits() == 32) {
6047 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6051 // SHUFPS the element to the lowest double word, then movss.
6052 int Mask[4] = { Idx, -1, -1, -1 };
6053 EVT VVT = Op.getOperand(0).getValueType();
6054 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6055 DAG.getUNDEF(VVT), Mask);
6056 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6057 DAG.getIntPtrConstant(0));
6058 } else if (VT.getSizeInBits() == 64) {
6059 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6060 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6061 // to match extract_elt for f64.
6062 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6066 // UNPCKHPD the element to the lowest double word, then movsd.
6067 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6068 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6069 int Mask[2] = { 1, -1 };
6070 EVT VVT = Op.getOperand(0).getValueType();
6071 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6072 DAG.getUNDEF(VVT), Mask);
6073 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6074 DAG.getIntPtrConstant(0));
6081 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6082 SelectionDAG &DAG) const {
6083 EVT VT = Op.getValueType();
6084 EVT EltVT = VT.getVectorElementType();
6085 DebugLoc dl = Op.getDebugLoc();
6087 SDValue N0 = Op.getOperand(0);
6088 SDValue N1 = Op.getOperand(1);
6089 SDValue N2 = Op.getOperand(2);
6091 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6092 isa<ConstantSDNode>(N2)) {
6094 if (VT == MVT::v8i16)
6095 Opc = X86ISD::PINSRW;
6096 else if (VT == MVT::v16i8)
6097 Opc = X86ISD::PINSRB;
6099 Opc = X86ISD::PINSRB;
6101 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6103 if (N1.getValueType() != MVT::i32)
6104 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6105 if (N2.getValueType() != MVT::i32)
6106 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6107 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6108 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6109 // Bits [7:6] of the constant are the source select. This will always be
6110 // zero here. The DAG Combiner may combine an extract_elt index into these
6111 // bits. For example (insert (extract, 3), 2) could be matched by putting
6112 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6113 // Bits [5:4] of the constant are the destination select. This is the
6114 // value of the incoming immediate.
6115 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6116 // combine either bitwise AND or insert of float 0.0 to set these bits.
6117 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6118 // Create this as a scalar to vector..
6119 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6120 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6121 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6122 // PINSR* works with constant index.
6129 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6130 EVT VT = Op.getValueType();
6131 EVT EltVT = VT.getVectorElementType();
6133 DebugLoc dl = Op.getDebugLoc();
6134 SDValue N0 = Op.getOperand(0);
6135 SDValue N1 = Op.getOperand(1);
6136 SDValue N2 = Op.getOperand(2);
6138 // If this is a 256-bit vector result, first insert into a 128-bit
6139 // vector and then insert into the 256-bit vector.
6140 if (VT.getSizeInBits() > 128) {
6141 if (!isa<ConstantSDNode>(N2))
6144 // Get the 128-bit vector.
6145 unsigned NumElems = VT.getVectorNumElements();
6146 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6147 bool Upper = IdxVal >= NumElems / 2;
6149 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6152 SDValue ScaledN2 = N2;
6154 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6155 DAG.getConstant(NumElems /
6156 (VT.getSizeInBits() / 128),
6157 N2.getValueType()));
6158 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6161 // Insert the 128-bit vector
6162 // FIXME: Why UNDEF?
6163 return Insert128BitVector(N0, Op, N2, DAG, dl);
6166 if (Subtarget->hasSSE41())
6167 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6169 if (EltVT == MVT::i8)
6172 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6173 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6174 // as its second argument.
6175 if (N1.getValueType() != MVT::i32)
6176 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6177 if (N2.getValueType() != MVT::i32)
6178 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6179 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6185 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6186 LLVMContext *Context = DAG.getContext();
6187 DebugLoc dl = Op.getDebugLoc();
6188 EVT OpVT = Op.getValueType();
6190 // If this is a 256-bit vector result, first insert into a 128-bit
6191 // vector and then insert into the 256-bit vector.
6192 if (OpVT.getSizeInBits() > 128) {
6193 // Insert into a 128-bit vector.
6194 EVT VT128 = EVT::getVectorVT(*Context,
6195 OpVT.getVectorElementType(),
6196 OpVT.getVectorNumElements() / 2);
6198 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6200 // Insert the 128-bit vector.
6201 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6202 DAG.getConstant(0, MVT::i32),
6206 if (Op.getValueType() == MVT::v1i64 &&
6207 Op.getOperand(0).getValueType() == MVT::i64)
6208 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6210 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6211 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6212 "Expected an SSE type!");
6213 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6214 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6217 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6218 // a simple subregister reference or explicit instructions to grab
6219 // upper bits of a vector.
6221 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6222 if (Subtarget->hasAVX()) {
6223 DebugLoc dl = Op.getNode()->getDebugLoc();
6224 SDValue Vec = Op.getNode()->getOperand(0);
6225 SDValue Idx = Op.getNode()->getOperand(1);
6227 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6228 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6229 return Extract128BitVector(Vec, Idx, DAG, dl);
6235 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6236 // simple superregister reference or explicit instructions to insert
6237 // the upper bits of a vector.
6239 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6240 if (Subtarget->hasAVX()) {
6241 DebugLoc dl = Op.getNode()->getDebugLoc();
6242 SDValue Vec = Op.getNode()->getOperand(0);
6243 SDValue SubVec = Op.getNode()->getOperand(1);
6244 SDValue Idx = Op.getNode()->getOperand(2);
6246 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6247 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6248 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6254 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6255 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6256 // one of the above mentioned nodes. It has to be wrapped because otherwise
6257 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6258 // be used to form addressing mode. These wrapped nodes will be selected
6261 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6262 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6264 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6266 unsigned char OpFlag = 0;
6267 unsigned WrapperKind = X86ISD::Wrapper;
6268 CodeModel::Model M = getTargetMachine().getCodeModel();
6270 if (Subtarget->isPICStyleRIPRel() &&
6271 (M == CodeModel::Small || M == CodeModel::Kernel))
6272 WrapperKind = X86ISD::WrapperRIP;
6273 else if (Subtarget->isPICStyleGOT())
6274 OpFlag = X86II::MO_GOTOFF;
6275 else if (Subtarget->isPICStyleStubPIC())
6276 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6278 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6280 CP->getOffset(), OpFlag);
6281 DebugLoc DL = CP->getDebugLoc();
6282 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6283 // With PIC, the address is actually $g + Offset.
6285 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6286 DAG.getNode(X86ISD::GlobalBaseReg,
6287 DebugLoc(), getPointerTy()),
6294 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6295 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6297 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6299 unsigned char OpFlag = 0;
6300 unsigned WrapperKind = X86ISD::Wrapper;
6301 CodeModel::Model M = getTargetMachine().getCodeModel();
6303 if (Subtarget->isPICStyleRIPRel() &&
6304 (M == CodeModel::Small || M == CodeModel::Kernel))
6305 WrapperKind = X86ISD::WrapperRIP;
6306 else if (Subtarget->isPICStyleGOT())
6307 OpFlag = X86II::MO_GOTOFF;
6308 else if (Subtarget->isPICStyleStubPIC())
6309 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6311 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6313 DebugLoc DL = JT->getDebugLoc();
6314 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6316 // With PIC, the address is actually $g + Offset.
6318 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6319 DAG.getNode(X86ISD::GlobalBaseReg,
6320 DebugLoc(), getPointerTy()),
6327 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6328 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6330 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6332 unsigned char OpFlag = 0;
6333 unsigned WrapperKind = X86ISD::Wrapper;
6334 CodeModel::Model M = getTargetMachine().getCodeModel();
6336 if (Subtarget->isPICStyleRIPRel() &&
6337 (M == CodeModel::Small || M == CodeModel::Kernel))
6338 WrapperKind = X86ISD::WrapperRIP;
6339 else if (Subtarget->isPICStyleGOT())
6340 OpFlag = X86II::MO_GOTOFF;
6341 else if (Subtarget->isPICStyleStubPIC())
6342 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6344 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6346 DebugLoc DL = Op.getDebugLoc();
6347 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6350 // With PIC, the address is actually $g + Offset.
6351 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6352 !Subtarget->is64Bit()) {
6353 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6354 DAG.getNode(X86ISD::GlobalBaseReg,
6355 DebugLoc(), getPointerTy()),
6363 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6364 // Create the TargetBlockAddressAddress node.
6365 unsigned char OpFlags =
6366 Subtarget->ClassifyBlockAddressReference();
6367 CodeModel::Model M = getTargetMachine().getCodeModel();
6368 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6369 DebugLoc dl = Op.getDebugLoc();
6370 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6371 /*isTarget=*/true, OpFlags);
6373 if (Subtarget->isPICStyleRIPRel() &&
6374 (M == CodeModel::Small || M == CodeModel::Kernel))
6375 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6377 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6379 // With PIC, the address is actually $g + Offset.
6380 if (isGlobalRelativeToPICBase(OpFlags)) {
6381 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6382 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6390 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6392 SelectionDAG &DAG) const {
6393 // Create the TargetGlobalAddress node, folding in the constant
6394 // offset if it is legal.
6395 unsigned char OpFlags =
6396 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6397 CodeModel::Model M = getTargetMachine().getCodeModel();
6399 if (OpFlags == X86II::MO_NO_FLAG &&
6400 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6401 // A direct static reference to a global.
6402 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6405 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6408 if (Subtarget->isPICStyleRIPRel() &&
6409 (M == CodeModel::Small || M == CodeModel::Kernel))
6410 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6412 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6414 // With PIC, the address is actually $g + Offset.
6415 if (isGlobalRelativeToPICBase(OpFlags)) {
6416 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6417 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6421 // For globals that require a load from a stub to get the address, emit the
6423 if (isGlobalStubReference(OpFlags))
6424 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6425 MachinePointerInfo::getGOT(), false, false, 0);
6427 // If there was a non-zero offset that we didn't fold, create an explicit
6430 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6431 DAG.getConstant(Offset, getPointerTy()));
6437 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6438 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6439 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6440 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6444 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6445 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6446 unsigned char OperandFlags) {
6447 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6448 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6449 DebugLoc dl = GA->getDebugLoc();
6450 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6451 GA->getValueType(0),
6455 SDValue Ops[] = { Chain, TGA, *InFlag };
6456 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6458 SDValue Ops[] = { Chain, TGA };
6459 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6462 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6463 MFI->setAdjustsStack(true);
6465 SDValue Flag = Chain.getValue(1);
6466 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6469 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6471 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6474 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6475 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6476 DAG.getNode(X86ISD::GlobalBaseReg,
6477 DebugLoc(), PtrVT), InFlag);
6478 InFlag = Chain.getValue(1);
6480 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6483 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6485 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6487 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6488 X86::RAX, X86II::MO_TLSGD);
6491 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6492 // "local exec" model.
6493 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6494 const EVT PtrVT, TLSModel::Model model,
6496 DebugLoc dl = GA->getDebugLoc();
6498 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6499 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6500 is64Bit ? 257 : 256));
6502 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6503 DAG.getIntPtrConstant(0),
6504 MachinePointerInfo(Ptr), false, false, 0);
6506 unsigned char OperandFlags = 0;
6507 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6509 unsigned WrapperKind = X86ISD::Wrapper;
6510 if (model == TLSModel::LocalExec) {
6511 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6512 } else if (is64Bit) {
6513 assert(model == TLSModel::InitialExec);
6514 OperandFlags = X86II::MO_GOTTPOFF;
6515 WrapperKind = X86ISD::WrapperRIP;
6517 assert(model == TLSModel::InitialExec);
6518 OperandFlags = X86II::MO_INDNTPOFF;
6521 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6523 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6524 GA->getValueType(0),
6525 GA->getOffset(), OperandFlags);
6526 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6528 if (model == TLSModel::InitialExec)
6529 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6530 MachinePointerInfo::getGOT(), false, false, 0);
6532 // The address of the thread local variable is the add of the thread
6533 // pointer with the offset of the variable.
6534 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6538 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6540 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6541 const GlobalValue *GV = GA->getGlobal();
6543 if (Subtarget->isTargetELF()) {
6544 // TODO: implement the "local dynamic" model
6545 // TODO: implement the "initial exec"model for pic executables
6547 // If GV is an alias then use the aliasee for determining
6548 // thread-localness.
6549 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6550 GV = GA->resolveAliasedGlobal(false);
6552 TLSModel::Model model
6553 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6556 case TLSModel::GeneralDynamic:
6557 case TLSModel::LocalDynamic: // not implemented
6558 if (Subtarget->is64Bit())
6559 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6560 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6562 case TLSModel::InitialExec:
6563 case TLSModel::LocalExec:
6564 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6565 Subtarget->is64Bit());
6567 } else if (Subtarget->isTargetDarwin()) {
6568 // Darwin only has one model of TLS. Lower to that.
6569 unsigned char OpFlag = 0;
6570 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6571 X86ISD::WrapperRIP : X86ISD::Wrapper;
6573 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6575 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6576 !Subtarget->is64Bit();
6578 OpFlag = X86II::MO_TLVP_PIC_BASE;
6580 OpFlag = X86II::MO_TLVP;
6581 DebugLoc DL = Op.getDebugLoc();
6582 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6583 GA->getValueType(0),
6584 GA->getOffset(), OpFlag);
6585 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6587 // With PIC32, the address is actually $g + Offset.
6589 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6590 DAG.getNode(X86ISD::GlobalBaseReg,
6591 DebugLoc(), getPointerTy()),
6594 // Lowering the machine isd will make sure everything is in the right
6596 SDValue Chain = DAG.getEntryNode();
6597 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6598 SDValue Args[] = { Chain, Offset };
6599 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6601 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6602 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6603 MFI->setAdjustsStack(true);
6605 // And our return value (tls address) is in the standard call return value
6607 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6608 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6612 "TLS not implemented for this target.");
6614 llvm_unreachable("Unreachable");
6619 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6620 /// take a 2 x i32 value to shift plus a shift amount.
6621 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6622 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6623 EVT VT = Op.getValueType();
6624 unsigned VTBits = VT.getSizeInBits();
6625 DebugLoc dl = Op.getDebugLoc();
6626 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6627 SDValue ShOpLo = Op.getOperand(0);
6628 SDValue ShOpHi = Op.getOperand(1);
6629 SDValue ShAmt = Op.getOperand(2);
6630 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6631 DAG.getConstant(VTBits - 1, MVT::i8))
6632 : DAG.getConstant(0, VT);
6635 if (Op.getOpcode() == ISD::SHL_PARTS) {
6636 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6637 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6639 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6640 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6643 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6644 DAG.getConstant(VTBits, MVT::i8));
6645 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6646 AndNode, DAG.getConstant(0, MVT::i8));
6649 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6650 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6651 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6653 if (Op.getOpcode() == ISD::SHL_PARTS) {
6654 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6655 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6657 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6658 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6661 SDValue Ops[2] = { Lo, Hi };
6662 return DAG.getMergeValues(Ops, 2, dl);
6665 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6666 SelectionDAG &DAG) const {
6667 EVT SrcVT = Op.getOperand(0).getValueType();
6669 if (SrcVT.isVector())
6672 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6673 "Unknown SINT_TO_FP to lower!");
6675 // These are really Legal; return the operand so the caller accepts it as
6677 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6679 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6680 Subtarget->is64Bit()) {
6684 DebugLoc dl = Op.getDebugLoc();
6685 unsigned Size = SrcVT.getSizeInBits()/8;
6686 MachineFunction &MF = DAG.getMachineFunction();
6687 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6688 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6689 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6691 MachinePointerInfo::getFixedStack(SSFI),
6693 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6696 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6698 SelectionDAG &DAG) const {
6700 DebugLoc DL = Op.getDebugLoc();
6702 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6704 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6706 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6708 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6710 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6711 MachineMemOperand *MMO =
6712 DAG.getMachineFunction()
6713 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6714 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6716 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6717 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6719 Tys, Ops, array_lengthof(Ops),
6723 Chain = Result.getValue(1);
6724 SDValue InFlag = Result.getValue(2);
6726 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6727 // shouldn't be necessary except that RFP cannot be live across
6728 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6729 MachineFunction &MF = DAG.getMachineFunction();
6730 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6731 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6732 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6733 Tys = DAG.getVTList(MVT::Other);
6735 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6737 MachineMemOperand *MMO =
6738 DAG.getMachineFunction()
6739 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6740 MachineMemOperand::MOStore, SSFISize, SSFISize);
6742 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6743 Ops, array_lengthof(Ops),
6744 Op.getValueType(), MMO);
6745 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6746 MachinePointerInfo::getFixedStack(SSFI),
6753 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6754 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6755 SelectionDAG &DAG) const {
6756 // This algorithm is not obvious. Here it is in C code, more or less:
6758 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6759 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6760 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6762 // Copy ints to xmm registers.
6763 __m128i xh = _mm_cvtsi32_si128( hi );
6764 __m128i xl = _mm_cvtsi32_si128( lo );
6766 // Combine into low half of a single xmm register.
6767 __m128i x = _mm_unpacklo_epi32( xh, xl );
6771 // Merge in appropriate exponents to give the integer bits the right
6773 x = _mm_unpacklo_epi32( x, exp );
6775 // Subtract away the biases to deal with the IEEE-754 double precision
6777 d = _mm_sub_pd( (__m128d) x, bias );
6779 // All conversions up to here are exact. The correctly rounded result is
6780 // calculated using the current rounding mode using the following
6782 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6783 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6784 // store doesn't really need to be here (except
6785 // maybe to zero the other double)
6790 DebugLoc dl = Op.getDebugLoc();
6791 LLVMContext *Context = DAG.getContext();
6793 // Build some magic constants.
6794 std::vector<Constant*> CV0;
6795 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6796 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6797 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6798 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6799 Constant *C0 = ConstantVector::get(CV0);
6800 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6802 std::vector<Constant*> CV1;
6804 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6806 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6807 Constant *C1 = ConstantVector::get(CV1);
6808 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6810 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6811 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6813 DAG.getIntPtrConstant(1)));
6814 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6815 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6817 DAG.getIntPtrConstant(0)));
6818 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6819 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6820 MachinePointerInfo::getConstantPool(),
6822 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6823 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6824 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6825 MachinePointerInfo::getConstantPool(),
6827 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6829 // Add the halves; easiest way is to swap them into another reg first.
6830 int ShufMask[2] = { 1, -1 };
6831 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6832 DAG.getUNDEF(MVT::v2f64), ShufMask);
6833 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6835 DAG.getIntPtrConstant(0));
6838 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6839 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6840 SelectionDAG &DAG) const {
6841 DebugLoc dl = Op.getDebugLoc();
6842 // FP constant to bias correct the final result.
6843 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6846 // Load the 32-bit value into an XMM register.
6847 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6848 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6850 DAG.getIntPtrConstant(0)));
6852 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6853 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6854 DAG.getIntPtrConstant(0));
6856 // Or the load with the bias.
6857 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6858 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6859 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6861 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6862 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6863 MVT::v2f64, Bias)));
6864 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6865 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6866 DAG.getIntPtrConstant(0));
6868 // Subtract the bias.
6869 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6871 // Handle final rounding.
6872 EVT DestVT = Op.getValueType();
6874 if (DestVT.bitsLT(MVT::f64)) {
6875 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6876 DAG.getIntPtrConstant(0));
6877 } else if (DestVT.bitsGT(MVT::f64)) {
6878 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6881 // Handle final rounding.
6885 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6886 SelectionDAG &DAG) const {
6887 SDValue N0 = Op.getOperand(0);
6888 DebugLoc dl = Op.getDebugLoc();
6890 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6891 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6892 // the optimization here.
6893 if (DAG.SignBitIsZero(N0))
6894 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6896 EVT SrcVT = N0.getValueType();
6897 EVT DstVT = Op.getValueType();
6898 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6899 return LowerUINT_TO_FP_i64(Op, DAG);
6900 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6901 return LowerUINT_TO_FP_i32(Op, DAG);
6903 // Make a 64-bit buffer, and use it to build an FILD.
6904 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6905 if (SrcVT == MVT::i32) {
6906 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6907 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6908 getPointerTy(), StackSlot, WordOff);
6909 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6910 StackSlot, MachinePointerInfo(),
6912 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6913 OffsetSlot, MachinePointerInfo(),
6915 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6919 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6920 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6921 StackSlot, MachinePointerInfo(),
6923 // For i64 source, we need to add the appropriate power of 2 if the input
6924 // was negative. This is the same as the optimization in
6925 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6926 // we must be careful to do the computation in x87 extended precision, not
6927 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6928 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6929 MachineMemOperand *MMO =
6930 DAG.getMachineFunction()
6931 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6932 MachineMemOperand::MOLoad, 8, 8);
6934 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6935 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6936 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6939 APInt FF(32, 0x5F800000ULL);
6941 // Check whether the sign bit is set.
6942 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6943 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6946 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6947 SDValue FudgePtr = DAG.getConstantPool(
6948 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6951 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6952 SDValue Zero = DAG.getIntPtrConstant(0);
6953 SDValue Four = DAG.getIntPtrConstant(4);
6954 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6956 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6958 // Load the value out, extending it from f32 to f80.
6959 // FIXME: Avoid the extend by constructing the right constant pool?
6960 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6961 FudgePtr, MachinePointerInfo::getConstantPool(),
6962 MVT::f32, false, false, 4);
6963 // Extend everything to 80 bits to force it to be done on x87.
6964 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6965 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6968 std::pair<SDValue,SDValue> X86TargetLowering::
6969 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6970 DebugLoc DL = Op.getDebugLoc();
6972 EVT DstTy = Op.getValueType();
6975 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6979 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6980 DstTy.getSimpleVT() >= MVT::i16 &&
6981 "Unknown FP_TO_SINT to lower!");
6983 // These are really Legal.
6984 if (DstTy == MVT::i32 &&
6985 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6986 return std::make_pair(SDValue(), SDValue());
6987 if (Subtarget->is64Bit() &&
6988 DstTy == MVT::i64 &&
6989 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6990 return std::make_pair(SDValue(), SDValue());
6992 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6994 MachineFunction &MF = DAG.getMachineFunction();
6995 unsigned MemSize = DstTy.getSizeInBits()/8;
6996 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6997 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7002 switch (DstTy.getSimpleVT().SimpleTy) {
7003 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7004 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7005 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7006 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7009 SDValue Chain = DAG.getEntryNode();
7010 SDValue Value = Op.getOperand(0);
7011 EVT TheVT = Op.getOperand(0).getValueType();
7012 if (isScalarFPTypeInSSEReg(TheVT)) {
7013 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7014 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7015 MachinePointerInfo::getFixedStack(SSFI),
7017 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7019 Chain, StackSlot, DAG.getValueType(TheVT)
7022 MachineMemOperand *MMO =
7023 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7024 MachineMemOperand::MOLoad, MemSize, MemSize);
7025 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7027 Chain = Value.getValue(1);
7028 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7029 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7032 MachineMemOperand *MMO =
7033 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7034 MachineMemOperand::MOStore, MemSize, MemSize);
7036 // Build the FP_TO_INT*_IN_MEM
7037 SDValue Ops[] = { Chain, Value, StackSlot };
7038 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7039 Ops, 3, DstTy, MMO);
7041 return std::make_pair(FIST, StackSlot);
7044 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7045 SelectionDAG &DAG) const {
7046 if (Op.getValueType().isVector())
7049 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7050 SDValue FIST = Vals.first, StackSlot = Vals.second;
7051 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7052 if (FIST.getNode() == 0) return Op;
7055 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7056 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7059 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7060 SelectionDAG &DAG) const {
7061 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7062 SDValue FIST = Vals.first, StackSlot = Vals.second;
7063 assert(FIST.getNode() && "Unexpected failure");
7066 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7067 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7070 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7071 SelectionDAG &DAG) const {
7072 LLVMContext *Context = DAG.getContext();
7073 DebugLoc dl = Op.getDebugLoc();
7074 EVT VT = Op.getValueType();
7077 EltVT = VT.getVectorElementType();
7078 std::vector<Constant*> CV;
7079 if (EltVT == MVT::f64) {
7080 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7084 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7090 Constant *C = ConstantVector::get(CV);
7091 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7092 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7093 MachinePointerInfo::getConstantPool(),
7095 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7098 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7099 LLVMContext *Context = DAG.getContext();
7100 DebugLoc dl = Op.getDebugLoc();
7101 EVT VT = Op.getValueType();
7104 EltVT = VT.getVectorElementType();
7105 std::vector<Constant*> CV;
7106 if (EltVT == MVT::f64) {
7107 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7111 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7117 Constant *C = ConstantVector::get(CV);
7118 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7119 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7120 MachinePointerInfo::getConstantPool(),
7122 if (VT.isVector()) {
7123 return DAG.getNode(ISD::BITCAST, dl, VT,
7124 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7125 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7127 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7129 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7133 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7134 LLVMContext *Context = DAG.getContext();
7135 SDValue Op0 = Op.getOperand(0);
7136 SDValue Op1 = Op.getOperand(1);
7137 DebugLoc dl = Op.getDebugLoc();
7138 EVT VT = Op.getValueType();
7139 EVT SrcVT = Op1.getValueType();
7141 // If second operand is smaller, extend it first.
7142 if (SrcVT.bitsLT(VT)) {
7143 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7146 // And if it is bigger, shrink it first.
7147 if (SrcVT.bitsGT(VT)) {
7148 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7152 // At this point the operands and the result should have the same
7153 // type, and that won't be f80 since that is not custom lowered.
7155 // First get the sign bit of second operand.
7156 std::vector<Constant*> CV;
7157 if (SrcVT == MVT::f64) {
7158 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7159 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7161 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7162 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7163 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7164 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7166 Constant *C = ConstantVector::get(CV);
7167 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7168 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7169 MachinePointerInfo::getConstantPool(),
7171 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7173 // Shift sign bit right or left if the two operands have different types.
7174 if (SrcVT.bitsGT(VT)) {
7175 // Op0 is MVT::f32, Op1 is MVT::f64.
7176 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7177 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7178 DAG.getConstant(32, MVT::i32));
7179 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7180 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7181 DAG.getIntPtrConstant(0));
7184 // Clear first operand sign bit.
7186 if (VT == MVT::f64) {
7187 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7188 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7190 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7191 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7192 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7193 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7195 C = ConstantVector::get(CV);
7196 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7197 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7198 MachinePointerInfo::getConstantPool(),
7200 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7202 // Or the value with the sign bit.
7203 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7206 /// Emit nodes that will be selected as "test Op0,Op0", or something
7208 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7209 SelectionDAG &DAG) const {
7210 DebugLoc dl = Op.getDebugLoc();
7212 // CF and OF aren't always set the way we want. Determine which
7213 // of these we need.
7214 bool NeedCF = false;
7215 bool NeedOF = false;
7218 case X86::COND_A: case X86::COND_AE:
7219 case X86::COND_B: case X86::COND_BE:
7222 case X86::COND_G: case X86::COND_GE:
7223 case X86::COND_L: case X86::COND_LE:
7224 case X86::COND_O: case X86::COND_NO:
7229 // See if we can use the EFLAGS value from the operand instead of
7230 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7231 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7232 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7233 // Emit a CMP with 0, which is the TEST pattern.
7234 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7235 DAG.getConstant(0, Op.getValueType()));
7237 unsigned Opcode = 0;
7238 unsigned NumOperands = 0;
7239 switch (Op.getNode()->getOpcode()) {
7241 // Due to an isel shortcoming, be conservative if this add is likely to be
7242 // selected as part of a load-modify-store instruction. When the root node
7243 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7244 // uses of other nodes in the match, such as the ADD in this case. This
7245 // leads to the ADD being left around and reselected, with the result being
7246 // two adds in the output. Alas, even if none our users are stores, that
7247 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7248 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7249 // climbing the DAG back to the root, and it doesn't seem to be worth the
7251 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7252 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7253 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7256 if (ConstantSDNode *C =
7257 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7258 // An add of one will be selected as an INC.
7259 if (C->getAPIntValue() == 1) {
7260 Opcode = X86ISD::INC;
7265 // An add of negative one (subtract of one) will be selected as a DEC.
7266 if (C->getAPIntValue().isAllOnesValue()) {
7267 Opcode = X86ISD::DEC;
7273 // Otherwise use a regular EFLAGS-setting add.
7274 Opcode = X86ISD::ADD;
7278 // If the primary and result isn't used, don't bother using X86ISD::AND,
7279 // because a TEST instruction will be better.
7280 bool NonFlagUse = false;
7281 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7282 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7284 unsigned UOpNo = UI.getOperandNo();
7285 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7286 // Look pass truncate.
7287 UOpNo = User->use_begin().getOperandNo();
7288 User = *User->use_begin();
7291 if (User->getOpcode() != ISD::BRCOND &&
7292 User->getOpcode() != ISD::SETCC &&
7293 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7306 // Due to the ISEL shortcoming noted above, be conservative if this op is
7307 // likely to be selected as part of a load-modify-store instruction.
7308 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7309 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7310 if (UI->getOpcode() == ISD::STORE)
7313 // Otherwise use a regular EFLAGS-setting instruction.
7314 switch (Op.getNode()->getOpcode()) {
7315 default: llvm_unreachable("unexpected operator!");
7316 case ISD::SUB: Opcode = X86ISD::SUB; break;
7317 case ISD::OR: Opcode = X86ISD::OR; break;
7318 case ISD::XOR: Opcode = X86ISD::XOR; break;
7319 case ISD::AND: Opcode = X86ISD::AND; break;
7331 return SDValue(Op.getNode(), 1);
7338 // Emit a CMP with 0, which is the TEST pattern.
7339 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7340 DAG.getConstant(0, Op.getValueType()));
7342 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7343 SmallVector<SDValue, 4> Ops;
7344 for (unsigned i = 0; i != NumOperands; ++i)
7345 Ops.push_back(Op.getOperand(i));
7347 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7348 DAG.ReplaceAllUsesWith(Op, New);
7349 return SDValue(New.getNode(), 1);
7352 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7354 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7355 SelectionDAG &DAG) const {
7356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7357 if (C->getAPIntValue() == 0)
7358 return EmitTest(Op0, X86CC, DAG);
7360 DebugLoc dl = Op0.getDebugLoc();
7361 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7364 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7365 /// if it's possible.
7366 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7367 DebugLoc dl, SelectionDAG &DAG) const {
7368 SDValue Op0 = And.getOperand(0);
7369 SDValue Op1 = And.getOperand(1);
7370 if (Op0.getOpcode() == ISD::TRUNCATE)
7371 Op0 = Op0.getOperand(0);
7372 if (Op1.getOpcode() == ISD::TRUNCATE)
7373 Op1 = Op1.getOperand(0);
7376 if (Op1.getOpcode() == ISD::SHL)
7377 std::swap(Op0, Op1);
7378 if (Op0.getOpcode() == ISD::SHL) {
7379 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7380 if (And00C->getZExtValue() == 1) {
7381 // If we looked past a truncate, check that it's only truncating away
7383 unsigned BitWidth = Op0.getValueSizeInBits();
7384 unsigned AndBitWidth = And.getValueSizeInBits();
7385 if (BitWidth > AndBitWidth) {
7386 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7387 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7388 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7392 RHS = Op0.getOperand(1);
7394 } else if (Op1.getOpcode() == ISD::Constant) {
7395 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7396 SDValue AndLHS = Op0;
7397 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7398 LHS = AndLHS.getOperand(0);
7399 RHS = AndLHS.getOperand(1);
7403 if (LHS.getNode()) {
7404 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7405 // instruction. Since the shift amount is in-range-or-undefined, we know
7406 // that doing a bittest on the i32 value is ok. We extend to i32 because
7407 // the encoding for the i16 version is larger than the i32 version.
7408 // Also promote i16 to i32 for performance / code size reason.
7409 if (LHS.getValueType() == MVT::i8 ||
7410 LHS.getValueType() == MVT::i16)
7411 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7413 // If the operand types disagree, extend the shift amount to match. Since
7414 // BT ignores high bits (like shifts) we can use anyextend.
7415 if (LHS.getValueType() != RHS.getValueType())
7416 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7418 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7419 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7420 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7421 DAG.getConstant(Cond, MVT::i8), BT);
7427 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7428 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7429 SDValue Op0 = Op.getOperand(0);
7430 SDValue Op1 = Op.getOperand(1);
7431 DebugLoc dl = Op.getDebugLoc();
7432 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7434 // Optimize to BT if possible.
7435 // Lower (X & (1 << N)) == 0 to BT(X, N).
7436 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7437 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7438 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7439 Op1.getOpcode() == ISD::Constant &&
7440 cast<ConstantSDNode>(Op1)->isNullValue() &&
7441 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7442 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7443 if (NewSetCC.getNode())
7447 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7449 if (Op1.getOpcode() == ISD::Constant &&
7450 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7451 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7452 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7454 // If the input is a setcc, then reuse the input setcc or use a new one with
7455 // the inverted condition.
7456 if (Op0.getOpcode() == X86ISD::SETCC) {
7457 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7458 bool Invert = (CC == ISD::SETNE) ^
7459 cast<ConstantSDNode>(Op1)->isNullValue();
7460 if (!Invert) return Op0;
7462 CCode = X86::GetOppositeBranchCondition(CCode);
7463 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7464 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7468 bool isFP = Op1.getValueType().isFloatingPoint();
7469 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7470 if (X86CC == X86::COND_INVALID)
7473 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7474 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7475 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7478 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7480 SDValue Op0 = Op.getOperand(0);
7481 SDValue Op1 = Op.getOperand(1);
7482 SDValue CC = Op.getOperand(2);
7483 EVT VT = Op.getValueType();
7484 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7485 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7486 DebugLoc dl = Op.getDebugLoc();
7490 EVT VT0 = Op0.getValueType();
7491 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7492 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7495 switch (SetCCOpcode) {
7498 case ISD::SETEQ: SSECC = 0; break;
7500 case ISD::SETGT: Swap = true; // Fallthrough
7502 case ISD::SETOLT: SSECC = 1; break;
7504 case ISD::SETGE: Swap = true; // Fallthrough
7506 case ISD::SETOLE: SSECC = 2; break;
7507 case ISD::SETUO: SSECC = 3; break;
7509 case ISD::SETNE: SSECC = 4; break;
7510 case ISD::SETULE: Swap = true;
7511 case ISD::SETUGE: SSECC = 5; break;
7512 case ISD::SETULT: Swap = true;
7513 case ISD::SETUGT: SSECC = 6; break;
7514 case ISD::SETO: SSECC = 7; break;
7517 std::swap(Op0, Op1);
7519 // In the two special cases we can't handle, emit two comparisons.
7521 if (SetCCOpcode == ISD::SETUEQ) {
7523 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7524 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7525 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7527 else if (SetCCOpcode == ISD::SETONE) {
7529 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7530 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7531 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7533 llvm_unreachable("Illegal FP comparison");
7535 // Handle all other FP comparisons here.
7536 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7539 // We are handling one of the integer comparisons here. Since SSE only has
7540 // GT and EQ comparisons for integer, swapping operands and multiple
7541 // operations may be required for some comparisons.
7542 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7543 bool Swap = false, Invert = false, FlipSigns = false;
7545 switch (VT.getSimpleVT().SimpleTy) {
7547 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7548 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7549 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7550 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7553 switch (SetCCOpcode) {
7555 case ISD::SETNE: Invert = true;
7556 case ISD::SETEQ: Opc = EQOpc; break;
7557 case ISD::SETLT: Swap = true;
7558 case ISD::SETGT: Opc = GTOpc; break;
7559 case ISD::SETGE: Swap = true;
7560 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7561 case ISD::SETULT: Swap = true;
7562 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7563 case ISD::SETUGE: Swap = true;
7564 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7567 std::swap(Op0, Op1);
7569 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7570 // bits of the inputs before performing those operations.
7572 EVT EltVT = VT.getVectorElementType();
7573 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7575 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7576 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7578 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7579 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7582 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7584 // If the logical-not of the result is required, perform that now.
7586 Result = DAG.getNOT(dl, Result, VT);
7591 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7592 static bool isX86LogicalCmp(SDValue Op) {
7593 unsigned Opc = Op.getNode()->getOpcode();
7594 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7596 if (Op.getResNo() == 1 &&
7597 (Opc == X86ISD::ADD ||
7598 Opc == X86ISD::SUB ||
7599 Opc == X86ISD::ADC ||
7600 Opc == X86ISD::SBB ||
7601 Opc == X86ISD::SMUL ||
7602 Opc == X86ISD::UMUL ||
7603 Opc == X86ISD::INC ||
7604 Opc == X86ISD::DEC ||
7605 Opc == X86ISD::OR ||
7606 Opc == X86ISD::XOR ||
7607 Opc == X86ISD::AND))
7610 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7616 static bool isZero(SDValue V) {
7617 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7618 return C && C->isNullValue();
7621 static bool isAllOnes(SDValue V) {
7622 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7623 return C && C->isAllOnesValue();
7626 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7627 bool addTest = true;
7628 SDValue Cond = Op.getOperand(0);
7629 SDValue Op1 = Op.getOperand(1);
7630 SDValue Op2 = Op.getOperand(2);
7631 DebugLoc DL = Op.getDebugLoc();
7634 if (Cond.getOpcode() == ISD::SETCC) {
7635 SDValue NewCond = LowerSETCC(Cond, DAG);
7636 if (NewCond.getNode())
7640 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7641 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7642 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7643 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7644 if (Cond.getOpcode() == X86ISD::SETCC &&
7645 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7646 isZero(Cond.getOperand(1).getOperand(1))) {
7647 SDValue Cmp = Cond.getOperand(1);
7649 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7651 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7652 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7653 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7655 SDValue CmpOp0 = Cmp.getOperand(0);
7656 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7657 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7659 SDValue Res = // Res = 0 or -1.
7660 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7661 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7663 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7664 Res = DAG.getNOT(DL, Res, Res.getValueType());
7666 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7667 if (N2C == 0 || !N2C->isNullValue())
7668 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7673 // Look past (and (setcc_carry (cmp ...)), 1).
7674 if (Cond.getOpcode() == ISD::AND &&
7675 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7677 if (C && C->getAPIntValue() == 1)
7678 Cond = Cond.getOperand(0);
7681 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7682 // setting operand in place of the X86ISD::SETCC.
7683 if (Cond.getOpcode() == X86ISD::SETCC ||
7684 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7685 CC = Cond.getOperand(0);
7687 SDValue Cmp = Cond.getOperand(1);
7688 unsigned Opc = Cmp.getOpcode();
7689 EVT VT = Op.getValueType();
7691 bool IllegalFPCMov = false;
7692 if (VT.isFloatingPoint() && !VT.isVector() &&
7693 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7694 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7696 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7697 Opc == X86ISD::BT) { // FIXME
7704 // Look pass the truncate.
7705 if (Cond.getOpcode() == ISD::TRUNCATE)
7706 Cond = Cond.getOperand(0);
7708 // We know the result of AND is compared against zero. Try to match
7710 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7711 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7712 if (NewSetCC.getNode()) {
7713 CC = NewSetCC.getOperand(0);
7714 Cond = NewSetCC.getOperand(1);
7721 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7722 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7725 // a < b ? -1 : 0 -> RES = ~setcc_carry
7726 // a < b ? 0 : -1 -> RES = setcc_carry
7727 // a >= b ? -1 : 0 -> RES = setcc_carry
7728 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7729 if (Cond.getOpcode() == X86ISD::CMP) {
7730 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7732 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7733 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7734 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7735 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7736 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7737 return DAG.getNOT(DL, Res, Res.getValueType());
7742 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7743 // condition is true.
7744 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7745 SDValue Ops[] = { Op2, Op1, CC, Cond };
7746 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7749 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7750 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7751 // from the AND / OR.
7752 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7753 Opc = Op.getOpcode();
7754 if (Opc != ISD::OR && Opc != ISD::AND)
7756 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7757 Op.getOperand(0).hasOneUse() &&
7758 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7759 Op.getOperand(1).hasOneUse());
7762 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7763 // 1 and that the SETCC node has a single use.
7764 static bool isXor1OfSetCC(SDValue Op) {
7765 if (Op.getOpcode() != ISD::XOR)
7767 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7768 if (N1C && N1C->getAPIntValue() == 1) {
7769 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7770 Op.getOperand(0).hasOneUse();
7775 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7776 bool addTest = true;
7777 SDValue Chain = Op.getOperand(0);
7778 SDValue Cond = Op.getOperand(1);
7779 SDValue Dest = Op.getOperand(2);
7780 DebugLoc dl = Op.getDebugLoc();
7783 if (Cond.getOpcode() == ISD::SETCC) {
7784 SDValue NewCond = LowerSETCC(Cond, DAG);
7785 if (NewCond.getNode())
7789 // FIXME: LowerXALUO doesn't handle these!!
7790 else if (Cond.getOpcode() == X86ISD::ADD ||
7791 Cond.getOpcode() == X86ISD::SUB ||
7792 Cond.getOpcode() == X86ISD::SMUL ||
7793 Cond.getOpcode() == X86ISD::UMUL)
7794 Cond = LowerXALUO(Cond, DAG);
7797 // Look pass (and (setcc_carry (cmp ...)), 1).
7798 if (Cond.getOpcode() == ISD::AND &&
7799 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7800 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7801 if (C && C->getAPIntValue() == 1)
7802 Cond = Cond.getOperand(0);
7805 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7806 // setting operand in place of the X86ISD::SETCC.
7807 if (Cond.getOpcode() == X86ISD::SETCC ||
7808 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7809 CC = Cond.getOperand(0);
7811 SDValue Cmp = Cond.getOperand(1);
7812 unsigned Opc = Cmp.getOpcode();
7813 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7814 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7818 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7822 // These can only come from an arithmetic instruction with overflow,
7823 // e.g. SADDO, UADDO.
7824 Cond = Cond.getNode()->getOperand(1);
7831 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7832 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7833 if (CondOpc == ISD::OR) {
7834 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7835 // two branches instead of an explicit OR instruction with a
7837 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7838 isX86LogicalCmp(Cmp)) {
7839 CC = Cond.getOperand(0).getOperand(0);
7840 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7841 Chain, Dest, CC, Cmp);
7842 CC = Cond.getOperand(1).getOperand(0);
7846 } else { // ISD::AND
7847 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7848 // two branches instead of an explicit AND instruction with a
7849 // separate test. However, we only do this if this block doesn't
7850 // have a fall-through edge, because this requires an explicit
7851 // jmp when the condition is false.
7852 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7853 isX86LogicalCmp(Cmp) &&
7854 Op.getNode()->hasOneUse()) {
7855 X86::CondCode CCode =
7856 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7857 CCode = X86::GetOppositeBranchCondition(CCode);
7858 CC = DAG.getConstant(CCode, MVT::i8);
7859 SDNode *User = *Op.getNode()->use_begin();
7860 // Look for an unconditional branch following this conditional branch.
7861 // We need this because we need to reverse the successors in order
7862 // to implement FCMP_OEQ.
7863 if (User->getOpcode() == ISD::BR) {
7864 SDValue FalseBB = User->getOperand(1);
7866 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7867 assert(NewBR == User);
7871 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7872 Chain, Dest, CC, Cmp);
7873 X86::CondCode CCode =
7874 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7875 CCode = X86::GetOppositeBranchCondition(CCode);
7876 CC = DAG.getConstant(CCode, MVT::i8);
7882 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7883 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7884 // It should be transformed during dag combiner except when the condition
7885 // is set by a arithmetics with overflow node.
7886 X86::CondCode CCode =
7887 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7888 CCode = X86::GetOppositeBranchCondition(CCode);
7889 CC = DAG.getConstant(CCode, MVT::i8);
7890 Cond = Cond.getOperand(0).getOperand(1);
7896 // Look pass the truncate.
7897 if (Cond.getOpcode() == ISD::TRUNCATE)
7898 Cond = Cond.getOperand(0);
7900 // We know the result of AND is compared against zero. Try to match
7902 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7903 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7904 if (NewSetCC.getNode()) {
7905 CC = NewSetCC.getOperand(0);
7906 Cond = NewSetCC.getOperand(1);
7913 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7914 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7916 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7917 Chain, Dest, CC, Cond);
7921 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7922 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7923 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7924 // that the guard pages used by the OS virtual memory manager are allocated in
7925 // correct sequence.
7927 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7928 SelectionDAG &DAG) const {
7929 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7930 "This should be used only on Windows targets");
7931 assert(!Subtarget->isTargetEnvMacho());
7932 DebugLoc dl = Op.getDebugLoc();
7935 SDValue Chain = Op.getOperand(0);
7936 SDValue Size = Op.getOperand(1);
7937 // FIXME: Ensure alignment here
7941 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7942 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7944 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7945 Flag = Chain.getValue(1);
7947 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7949 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7950 Flag = Chain.getValue(1);
7952 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7954 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7955 return DAG.getMergeValues(Ops1, 2, dl);
7958 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7959 MachineFunction &MF = DAG.getMachineFunction();
7960 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7962 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7963 DebugLoc DL = Op.getDebugLoc();
7965 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7966 // vastart just stores the address of the VarArgsFrameIndex slot into the
7967 // memory location argument.
7968 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7970 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7971 MachinePointerInfo(SV), false, false, 0);
7975 // gp_offset (0 - 6 * 8)
7976 // fp_offset (48 - 48 + 8 * 16)
7977 // overflow_arg_area (point to parameters coming in memory).
7979 SmallVector<SDValue, 8> MemOps;
7980 SDValue FIN = Op.getOperand(1);
7982 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7983 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7985 FIN, MachinePointerInfo(SV), false, false, 0);
7986 MemOps.push_back(Store);
7989 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7990 FIN, DAG.getIntPtrConstant(4));
7991 Store = DAG.getStore(Op.getOperand(0), DL,
7992 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7994 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7995 MemOps.push_back(Store);
7997 // Store ptr to overflow_arg_area
7998 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7999 FIN, DAG.getIntPtrConstant(4));
8000 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8002 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8003 MachinePointerInfo(SV, 8),
8005 MemOps.push_back(Store);
8007 // Store ptr to reg_save_area.
8008 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8009 FIN, DAG.getIntPtrConstant(8));
8010 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8012 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8013 MachinePointerInfo(SV, 16), false, false, 0);
8014 MemOps.push_back(Store);
8015 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8016 &MemOps[0], MemOps.size());
8019 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8020 assert(Subtarget->is64Bit() &&
8021 "LowerVAARG only handles 64-bit va_arg!");
8022 assert((Subtarget->isTargetLinux() ||
8023 Subtarget->isTargetDarwin()) &&
8024 "Unhandled target in LowerVAARG");
8025 assert(Op.getNode()->getNumOperands() == 4);
8026 SDValue Chain = Op.getOperand(0);
8027 SDValue SrcPtr = Op.getOperand(1);
8028 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8029 unsigned Align = Op.getConstantOperandVal(3);
8030 DebugLoc dl = Op.getDebugLoc();
8032 EVT ArgVT = Op.getNode()->getValueType(0);
8033 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8034 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8037 // Decide which area this value should be read from.
8038 // TODO: Implement the AMD64 ABI in its entirety. This simple
8039 // selection mechanism works only for the basic types.
8040 if (ArgVT == MVT::f80) {
8041 llvm_unreachable("va_arg for f80 not yet implemented");
8042 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8043 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8044 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8045 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8047 llvm_unreachable("Unhandled argument type in LowerVAARG");
8051 // Sanity Check: Make sure using fp_offset makes sense.
8052 assert(!UseSoftFloat &&
8053 !(DAG.getMachineFunction()
8054 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8055 Subtarget->hasXMM());
8058 // Insert VAARG_64 node into the DAG
8059 // VAARG_64 returns two values: Variable Argument Address, Chain
8060 SmallVector<SDValue, 11> InstOps;
8061 InstOps.push_back(Chain);
8062 InstOps.push_back(SrcPtr);
8063 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8064 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8065 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8066 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8067 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8068 VTs, &InstOps[0], InstOps.size(),
8070 MachinePointerInfo(SV),
8075 Chain = VAARG.getValue(1);
8077 // Load the next argument and return it
8078 return DAG.getLoad(ArgVT, dl,
8081 MachinePointerInfo(),
8085 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8086 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8087 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8088 SDValue Chain = Op.getOperand(0);
8089 SDValue DstPtr = Op.getOperand(1);
8090 SDValue SrcPtr = Op.getOperand(2);
8091 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8092 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8093 DebugLoc DL = Op.getDebugLoc();
8095 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8096 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8098 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8102 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8103 DebugLoc dl = Op.getDebugLoc();
8104 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8106 default: return SDValue(); // Don't custom lower most intrinsics.
8107 // Comparison intrinsics.
8108 case Intrinsic::x86_sse_comieq_ss:
8109 case Intrinsic::x86_sse_comilt_ss:
8110 case Intrinsic::x86_sse_comile_ss:
8111 case Intrinsic::x86_sse_comigt_ss:
8112 case Intrinsic::x86_sse_comige_ss:
8113 case Intrinsic::x86_sse_comineq_ss:
8114 case Intrinsic::x86_sse_ucomieq_ss:
8115 case Intrinsic::x86_sse_ucomilt_ss:
8116 case Intrinsic::x86_sse_ucomile_ss:
8117 case Intrinsic::x86_sse_ucomigt_ss:
8118 case Intrinsic::x86_sse_ucomige_ss:
8119 case Intrinsic::x86_sse_ucomineq_ss:
8120 case Intrinsic::x86_sse2_comieq_sd:
8121 case Intrinsic::x86_sse2_comilt_sd:
8122 case Intrinsic::x86_sse2_comile_sd:
8123 case Intrinsic::x86_sse2_comigt_sd:
8124 case Intrinsic::x86_sse2_comige_sd:
8125 case Intrinsic::x86_sse2_comineq_sd:
8126 case Intrinsic::x86_sse2_ucomieq_sd:
8127 case Intrinsic::x86_sse2_ucomilt_sd:
8128 case Intrinsic::x86_sse2_ucomile_sd:
8129 case Intrinsic::x86_sse2_ucomigt_sd:
8130 case Intrinsic::x86_sse2_ucomige_sd:
8131 case Intrinsic::x86_sse2_ucomineq_sd: {
8133 ISD::CondCode CC = ISD::SETCC_INVALID;
8136 case Intrinsic::x86_sse_comieq_ss:
8137 case Intrinsic::x86_sse2_comieq_sd:
8141 case Intrinsic::x86_sse_comilt_ss:
8142 case Intrinsic::x86_sse2_comilt_sd:
8146 case Intrinsic::x86_sse_comile_ss:
8147 case Intrinsic::x86_sse2_comile_sd:
8151 case Intrinsic::x86_sse_comigt_ss:
8152 case Intrinsic::x86_sse2_comigt_sd:
8156 case Intrinsic::x86_sse_comige_ss:
8157 case Intrinsic::x86_sse2_comige_sd:
8161 case Intrinsic::x86_sse_comineq_ss:
8162 case Intrinsic::x86_sse2_comineq_sd:
8166 case Intrinsic::x86_sse_ucomieq_ss:
8167 case Intrinsic::x86_sse2_ucomieq_sd:
8168 Opc = X86ISD::UCOMI;
8171 case Intrinsic::x86_sse_ucomilt_ss:
8172 case Intrinsic::x86_sse2_ucomilt_sd:
8173 Opc = X86ISD::UCOMI;
8176 case Intrinsic::x86_sse_ucomile_ss:
8177 case Intrinsic::x86_sse2_ucomile_sd:
8178 Opc = X86ISD::UCOMI;
8181 case Intrinsic::x86_sse_ucomigt_ss:
8182 case Intrinsic::x86_sse2_ucomigt_sd:
8183 Opc = X86ISD::UCOMI;
8186 case Intrinsic::x86_sse_ucomige_ss:
8187 case Intrinsic::x86_sse2_ucomige_sd:
8188 Opc = X86ISD::UCOMI;
8191 case Intrinsic::x86_sse_ucomineq_ss:
8192 case Intrinsic::x86_sse2_ucomineq_sd:
8193 Opc = X86ISD::UCOMI;
8198 SDValue LHS = Op.getOperand(1);
8199 SDValue RHS = Op.getOperand(2);
8200 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8201 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8202 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8203 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8204 DAG.getConstant(X86CC, MVT::i8), Cond);
8205 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8207 // ptest and testp intrinsics. The intrinsic these come from are designed to
8208 // return an integer value, not just an instruction so lower it to the ptest
8209 // or testp pattern and a setcc for the result.
8210 case Intrinsic::x86_sse41_ptestz:
8211 case Intrinsic::x86_sse41_ptestc:
8212 case Intrinsic::x86_sse41_ptestnzc:
8213 case Intrinsic::x86_avx_ptestz_256:
8214 case Intrinsic::x86_avx_ptestc_256:
8215 case Intrinsic::x86_avx_ptestnzc_256:
8216 case Intrinsic::x86_avx_vtestz_ps:
8217 case Intrinsic::x86_avx_vtestc_ps:
8218 case Intrinsic::x86_avx_vtestnzc_ps:
8219 case Intrinsic::x86_avx_vtestz_pd:
8220 case Intrinsic::x86_avx_vtestc_pd:
8221 case Intrinsic::x86_avx_vtestnzc_pd:
8222 case Intrinsic::x86_avx_vtestz_ps_256:
8223 case Intrinsic::x86_avx_vtestc_ps_256:
8224 case Intrinsic::x86_avx_vtestnzc_ps_256:
8225 case Intrinsic::x86_avx_vtestz_pd_256:
8226 case Intrinsic::x86_avx_vtestc_pd_256:
8227 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8228 bool IsTestPacked = false;
8231 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8232 case Intrinsic::x86_avx_vtestz_ps:
8233 case Intrinsic::x86_avx_vtestz_pd:
8234 case Intrinsic::x86_avx_vtestz_ps_256:
8235 case Intrinsic::x86_avx_vtestz_pd_256:
8236 IsTestPacked = true; // Fallthrough
8237 case Intrinsic::x86_sse41_ptestz:
8238 case Intrinsic::x86_avx_ptestz_256:
8240 X86CC = X86::COND_E;
8242 case Intrinsic::x86_avx_vtestc_ps:
8243 case Intrinsic::x86_avx_vtestc_pd:
8244 case Intrinsic::x86_avx_vtestc_ps_256:
8245 case Intrinsic::x86_avx_vtestc_pd_256:
8246 IsTestPacked = true; // Fallthrough
8247 case Intrinsic::x86_sse41_ptestc:
8248 case Intrinsic::x86_avx_ptestc_256:
8250 X86CC = X86::COND_B;
8252 case Intrinsic::x86_avx_vtestnzc_ps:
8253 case Intrinsic::x86_avx_vtestnzc_pd:
8254 case Intrinsic::x86_avx_vtestnzc_ps_256:
8255 case Intrinsic::x86_avx_vtestnzc_pd_256:
8256 IsTestPacked = true; // Fallthrough
8257 case Intrinsic::x86_sse41_ptestnzc:
8258 case Intrinsic::x86_avx_ptestnzc_256:
8260 X86CC = X86::COND_A;
8264 SDValue LHS = Op.getOperand(1);
8265 SDValue RHS = Op.getOperand(2);
8266 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8267 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8268 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8269 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8270 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8273 // Fix vector shift instructions where the last operand is a non-immediate
8275 case Intrinsic::x86_sse2_pslli_w:
8276 case Intrinsic::x86_sse2_pslli_d:
8277 case Intrinsic::x86_sse2_pslli_q:
8278 case Intrinsic::x86_sse2_psrli_w:
8279 case Intrinsic::x86_sse2_psrli_d:
8280 case Intrinsic::x86_sse2_psrli_q:
8281 case Intrinsic::x86_sse2_psrai_w:
8282 case Intrinsic::x86_sse2_psrai_d:
8283 case Intrinsic::x86_mmx_pslli_w:
8284 case Intrinsic::x86_mmx_pslli_d:
8285 case Intrinsic::x86_mmx_pslli_q:
8286 case Intrinsic::x86_mmx_psrli_w:
8287 case Intrinsic::x86_mmx_psrli_d:
8288 case Intrinsic::x86_mmx_psrli_q:
8289 case Intrinsic::x86_mmx_psrai_w:
8290 case Intrinsic::x86_mmx_psrai_d: {
8291 SDValue ShAmt = Op.getOperand(2);
8292 if (isa<ConstantSDNode>(ShAmt))
8295 unsigned NewIntNo = 0;
8296 EVT ShAmtVT = MVT::v4i32;
8298 case Intrinsic::x86_sse2_pslli_w:
8299 NewIntNo = Intrinsic::x86_sse2_psll_w;
8301 case Intrinsic::x86_sse2_pslli_d:
8302 NewIntNo = Intrinsic::x86_sse2_psll_d;
8304 case Intrinsic::x86_sse2_pslli_q:
8305 NewIntNo = Intrinsic::x86_sse2_psll_q;
8307 case Intrinsic::x86_sse2_psrli_w:
8308 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8310 case Intrinsic::x86_sse2_psrli_d:
8311 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8313 case Intrinsic::x86_sse2_psrli_q:
8314 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8316 case Intrinsic::x86_sse2_psrai_w:
8317 NewIntNo = Intrinsic::x86_sse2_psra_w;
8319 case Intrinsic::x86_sse2_psrai_d:
8320 NewIntNo = Intrinsic::x86_sse2_psra_d;
8323 ShAmtVT = MVT::v2i32;
8325 case Intrinsic::x86_mmx_pslli_w:
8326 NewIntNo = Intrinsic::x86_mmx_psll_w;
8328 case Intrinsic::x86_mmx_pslli_d:
8329 NewIntNo = Intrinsic::x86_mmx_psll_d;
8331 case Intrinsic::x86_mmx_pslli_q:
8332 NewIntNo = Intrinsic::x86_mmx_psll_q;
8334 case Intrinsic::x86_mmx_psrli_w:
8335 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8337 case Intrinsic::x86_mmx_psrli_d:
8338 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8340 case Intrinsic::x86_mmx_psrli_q:
8341 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8343 case Intrinsic::x86_mmx_psrai_w:
8344 NewIntNo = Intrinsic::x86_mmx_psra_w;
8346 case Intrinsic::x86_mmx_psrai_d:
8347 NewIntNo = Intrinsic::x86_mmx_psra_d;
8349 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8355 // The vector shift intrinsics with scalars uses 32b shift amounts but
8356 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8360 ShOps[1] = DAG.getConstant(0, MVT::i32);
8361 if (ShAmtVT == MVT::v4i32) {
8362 ShOps[2] = DAG.getUNDEF(MVT::i32);
8363 ShOps[3] = DAG.getUNDEF(MVT::i32);
8364 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8366 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8367 // FIXME this must be lowered to get rid of the invalid type.
8370 EVT VT = Op.getValueType();
8371 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8372 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8373 DAG.getConstant(NewIntNo, MVT::i32),
8374 Op.getOperand(1), ShAmt);
8379 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8380 SelectionDAG &DAG) const {
8381 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8382 MFI->setReturnAddressIsTaken(true);
8384 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8385 DebugLoc dl = Op.getDebugLoc();
8388 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8390 DAG.getConstant(TD->getPointerSize(),
8391 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8392 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8393 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8395 MachinePointerInfo(), false, false, 0);
8398 // Just load the return address.
8399 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8400 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8401 RetAddrFI, MachinePointerInfo(), false, false, 0);
8404 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8405 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8406 MFI->setFrameAddressIsTaken(true);
8408 EVT VT = Op.getValueType();
8409 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8410 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8411 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8412 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8414 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8415 MachinePointerInfo(),
8420 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8421 SelectionDAG &DAG) const {
8422 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8425 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8426 MachineFunction &MF = DAG.getMachineFunction();
8427 SDValue Chain = Op.getOperand(0);
8428 SDValue Offset = Op.getOperand(1);
8429 SDValue Handler = Op.getOperand(2);
8430 DebugLoc dl = Op.getDebugLoc();
8432 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8433 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8435 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8437 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8438 DAG.getIntPtrConstant(TD->getPointerSize()));
8439 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8440 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8442 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8443 MF.getRegInfo().addLiveOut(StoreAddrReg);
8445 return DAG.getNode(X86ISD::EH_RETURN, dl,
8447 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8450 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8451 SelectionDAG &DAG) const {
8452 SDValue Root = Op.getOperand(0);
8453 SDValue Trmp = Op.getOperand(1); // trampoline
8454 SDValue FPtr = Op.getOperand(2); // nested function
8455 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8456 DebugLoc dl = Op.getDebugLoc();
8458 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8460 if (Subtarget->is64Bit()) {
8461 SDValue OutChains[6];
8463 // Large code-model.
8464 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8465 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8467 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8468 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8470 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8472 // Load the pointer to the nested function into R11.
8473 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8474 SDValue Addr = Trmp;
8475 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8476 Addr, MachinePointerInfo(TrmpAddr),
8479 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8480 DAG.getConstant(2, MVT::i64));
8481 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8482 MachinePointerInfo(TrmpAddr, 2),
8485 // Load the 'nest' parameter value into R10.
8486 // R10 is specified in X86CallingConv.td
8487 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8488 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8489 DAG.getConstant(10, MVT::i64));
8490 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8491 Addr, MachinePointerInfo(TrmpAddr, 10),
8494 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8495 DAG.getConstant(12, MVT::i64));
8496 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8497 MachinePointerInfo(TrmpAddr, 12),
8500 // Jump to the nested function.
8501 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8502 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8503 DAG.getConstant(20, MVT::i64));
8504 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8505 Addr, MachinePointerInfo(TrmpAddr, 20),
8508 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8509 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8510 DAG.getConstant(22, MVT::i64));
8511 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8512 MachinePointerInfo(TrmpAddr, 22),
8516 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8517 return DAG.getMergeValues(Ops, 2, dl);
8519 const Function *Func =
8520 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8521 CallingConv::ID CC = Func->getCallingConv();
8526 llvm_unreachable("Unsupported calling convention");
8527 case CallingConv::C:
8528 case CallingConv::X86_StdCall: {
8529 // Pass 'nest' parameter in ECX.
8530 // Must be kept in sync with X86CallingConv.td
8533 // Check that ECX wasn't needed by an 'inreg' parameter.
8534 const FunctionType *FTy = Func->getFunctionType();
8535 const AttrListPtr &Attrs = Func->getAttributes();
8537 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8538 unsigned InRegCount = 0;
8541 for (FunctionType::param_iterator I = FTy->param_begin(),
8542 E = FTy->param_end(); I != E; ++I, ++Idx)
8543 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8544 // FIXME: should only count parameters that are lowered to integers.
8545 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8547 if (InRegCount > 2) {
8548 report_fatal_error("Nest register in use - reduce number of inreg"
8554 case CallingConv::X86_FastCall:
8555 case CallingConv::X86_ThisCall:
8556 case CallingConv::Fast:
8557 // Pass 'nest' parameter in EAX.
8558 // Must be kept in sync with X86CallingConv.td
8563 SDValue OutChains[4];
8566 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8567 DAG.getConstant(10, MVT::i32));
8568 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8570 // This is storing the opcode for MOV32ri.
8571 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8572 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8573 OutChains[0] = DAG.getStore(Root, dl,
8574 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8575 Trmp, MachinePointerInfo(TrmpAddr),
8578 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8579 DAG.getConstant(1, MVT::i32));
8580 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8581 MachinePointerInfo(TrmpAddr, 1),
8584 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8585 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8586 DAG.getConstant(5, MVT::i32));
8587 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8588 MachinePointerInfo(TrmpAddr, 5),
8591 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8592 DAG.getConstant(6, MVT::i32));
8593 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8594 MachinePointerInfo(TrmpAddr, 6),
8598 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8599 return DAG.getMergeValues(Ops, 2, dl);
8603 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8604 SelectionDAG &DAG) const {
8606 The rounding mode is in bits 11:10 of FPSR, and has the following
8613 FLT_ROUNDS, on the other hand, expects the following:
8620 To perform the conversion, we do:
8621 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8624 MachineFunction &MF = DAG.getMachineFunction();
8625 const TargetMachine &TM = MF.getTarget();
8626 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8627 unsigned StackAlignment = TFI.getStackAlignment();
8628 EVT VT = Op.getValueType();
8629 DebugLoc DL = Op.getDebugLoc();
8631 // Save FP Control Word to stack slot
8632 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8633 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8636 MachineMemOperand *MMO =
8637 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8638 MachineMemOperand::MOStore, 2, 2);
8640 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8641 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8642 DAG.getVTList(MVT::Other),
8643 Ops, 2, MVT::i16, MMO);
8645 // Load FP Control Word from stack slot
8646 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8647 MachinePointerInfo(), false, false, 0);
8649 // Transform as necessary
8651 DAG.getNode(ISD::SRL, DL, MVT::i16,
8652 DAG.getNode(ISD::AND, DL, MVT::i16,
8653 CWD, DAG.getConstant(0x800, MVT::i16)),
8654 DAG.getConstant(11, MVT::i8));
8656 DAG.getNode(ISD::SRL, DL, MVT::i16,
8657 DAG.getNode(ISD::AND, DL, MVT::i16,
8658 CWD, DAG.getConstant(0x400, MVT::i16)),
8659 DAG.getConstant(9, MVT::i8));
8662 DAG.getNode(ISD::AND, DL, MVT::i16,
8663 DAG.getNode(ISD::ADD, DL, MVT::i16,
8664 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8665 DAG.getConstant(1, MVT::i16)),
8666 DAG.getConstant(3, MVT::i16));
8669 return DAG.getNode((VT.getSizeInBits() < 16 ?
8670 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8673 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8674 EVT VT = Op.getValueType();
8676 unsigned NumBits = VT.getSizeInBits();
8677 DebugLoc dl = Op.getDebugLoc();
8679 Op = Op.getOperand(0);
8680 if (VT == MVT::i8) {
8681 // Zero extend to i32 since there is not an i8 bsr.
8683 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8686 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8687 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8688 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8690 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8693 DAG.getConstant(NumBits+NumBits-1, OpVT),
8694 DAG.getConstant(X86::COND_E, MVT::i8),
8697 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8699 // Finally xor with NumBits-1.
8700 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8703 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8707 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8708 EVT VT = Op.getValueType();
8710 unsigned NumBits = VT.getSizeInBits();
8711 DebugLoc dl = Op.getDebugLoc();
8713 Op = Op.getOperand(0);
8714 if (VT == MVT::i8) {
8716 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8719 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8720 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8721 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8723 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8726 DAG.getConstant(NumBits, OpVT),
8727 DAG.getConstant(X86::COND_E, MVT::i8),
8730 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8733 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8737 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8738 EVT VT = Op.getValueType();
8739 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8740 DebugLoc dl = Op.getDebugLoc();
8742 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8743 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8744 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8745 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8746 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8748 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8749 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8750 // return AloBlo + AloBhi + AhiBlo;
8752 SDValue A = Op.getOperand(0);
8753 SDValue B = Op.getOperand(1);
8755 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8756 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8757 A, DAG.getConstant(32, MVT::i32));
8758 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8759 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8760 B, DAG.getConstant(32, MVT::i32));
8761 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8762 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8764 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8765 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8767 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8768 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8770 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8771 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8772 AloBhi, DAG.getConstant(32, MVT::i32));
8773 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8774 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8775 AhiBlo, DAG.getConstant(32, MVT::i32));
8776 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8777 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8781 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8782 EVT VT = Op.getValueType();
8783 DebugLoc dl = Op.getDebugLoc();
8784 SDValue R = Op.getOperand(0);
8786 LLVMContext *Context = DAG.getContext();
8788 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8790 if (VT == MVT::v4i32) {
8791 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8792 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8793 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8795 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8797 std::vector<Constant*> CV(4, CI);
8798 Constant *C = ConstantVector::get(CV);
8799 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8800 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8801 MachinePointerInfo::getConstantPool(),
8804 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8805 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8806 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8807 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8809 if (VT == MVT::v16i8) {
8811 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8812 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8813 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8815 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8816 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8818 std::vector<Constant*> CVM1(16, CM1);
8819 std::vector<Constant*> CVM2(16, CM2);
8820 Constant *C = ConstantVector::get(CVM1);
8821 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8822 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8823 MachinePointerInfo::getConstantPool(),
8826 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8827 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8828 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8830 DAG.getConstant(4, MVT::i32));
8831 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8833 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8835 C = ConstantVector::get(CVM2);
8836 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8837 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8838 MachinePointerInfo::getConstantPool(),
8841 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8842 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8843 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8844 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8845 DAG.getConstant(2, MVT::i32));
8846 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8848 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8850 // return pblendv(r, r+r, a);
8851 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8852 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8858 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8859 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8860 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8861 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8862 // has only one use.
8863 SDNode *N = Op.getNode();
8864 SDValue LHS = N->getOperand(0);
8865 SDValue RHS = N->getOperand(1);
8866 unsigned BaseOp = 0;
8868 DebugLoc DL = Op.getDebugLoc();
8869 switch (Op.getOpcode()) {
8870 default: llvm_unreachable("Unknown ovf instruction!");
8872 // A subtract of one will be selected as a INC. Note that INC doesn't
8873 // set CF, so we can't do this for UADDO.
8874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8876 BaseOp = X86ISD::INC;
8880 BaseOp = X86ISD::ADD;
8884 BaseOp = X86ISD::ADD;
8888 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8889 // set CF, so we can't do this for USUBO.
8890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8892 BaseOp = X86ISD::DEC;
8896 BaseOp = X86ISD::SUB;
8900 BaseOp = X86ISD::SUB;
8904 BaseOp = X86ISD::SMUL;
8907 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8908 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8910 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8913 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8914 DAG.getConstant(X86::COND_O, MVT::i32),
8915 SDValue(Sum.getNode(), 2));
8917 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8922 // Also sets EFLAGS.
8923 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8924 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8927 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8928 DAG.getConstant(Cond, MVT::i32),
8929 SDValue(Sum.getNode(), 1));
8931 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8935 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8936 DebugLoc dl = Op.getDebugLoc();
8938 if (!Subtarget->hasSSE2()) {
8939 SDValue Chain = Op.getOperand(0);
8940 SDValue Zero = DAG.getConstant(0,
8941 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8943 DAG.getRegister(X86::ESP, MVT::i32), // Base
8944 DAG.getTargetConstant(1, MVT::i8), // Scale
8945 DAG.getRegister(0, MVT::i32), // Index
8946 DAG.getTargetConstant(0, MVT::i32), // Disp
8947 DAG.getRegister(0, MVT::i32), // Segment.
8952 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8953 array_lengthof(Ops));
8954 return SDValue(Res, 0);
8957 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8959 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8961 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8962 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8963 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8964 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8966 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8967 if (!Op1 && !Op2 && !Op3 && Op4)
8968 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8970 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8971 if (Op1 && !Op2 && !Op3 && !Op4)
8972 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8974 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8976 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8979 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8980 EVT T = Op.getValueType();
8981 DebugLoc DL = Op.getDebugLoc();
8984 switch(T.getSimpleVT().SimpleTy) {
8986 assert(false && "Invalid value type!");
8987 case MVT::i8: Reg = X86::AL; size = 1; break;
8988 case MVT::i16: Reg = X86::AX; size = 2; break;
8989 case MVT::i32: Reg = X86::EAX; size = 4; break;
8991 assert(Subtarget->is64Bit() && "Node not type legal!");
8992 Reg = X86::RAX; size = 8;
8995 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8996 Op.getOperand(2), SDValue());
8997 SDValue Ops[] = { cpIn.getValue(0),
9000 DAG.getTargetConstant(size, MVT::i8),
9002 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9003 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9004 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9007 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9011 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9012 SelectionDAG &DAG) const {
9013 assert(Subtarget->is64Bit() && "Result not type legalized?");
9014 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9015 SDValue TheChain = Op.getOperand(0);
9016 DebugLoc dl = Op.getDebugLoc();
9017 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9018 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9019 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9021 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9022 DAG.getConstant(32, MVT::i8));
9024 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9027 return DAG.getMergeValues(Ops, 2, dl);
9030 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9031 SelectionDAG &DAG) const {
9032 EVT SrcVT = Op.getOperand(0).getValueType();
9033 EVT DstVT = Op.getValueType();
9034 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9035 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9036 assert((DstVT == MVT::i64 ||
9037 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9038 "Unexpected custom BITCAST");
9039 // i64 <=> MMX conversions are Legal.
9040 if (SrcVT==MVT::i64 && DstVT.isVector())
9042 if (DstVT==MVT::i64 && SrcVT.isVector())
9044 // MMX <=> MMX conversions are Legal.
9045 if (SrcVT.isVector() && DstVT.isVector())
9047 // All other conversions need to be expanded.
9051 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9052 SDNode *Node = Op.getNode();
9053 DebugLoc dl = Node->getDebugLoc();
9054 EVT T = Node->getValueType(0);
9055 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9056 DAG.getConstant(0, T), Node->getOperand(2));
9057 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9058 cast<AtomicSDNode>(Node)->getMemoryVT(),
9059 Node->getOperand(0),
9060 Node->getOperand(1), negOp,
9061 cast<AtomicSDNode>(Node)->getSrcValue(),
9062 cast<AtomicSDNode>(Node)->getAlignment());
9065 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9066 EVT VT = Op.getNode()->getValueType(0);
9068 // Let legalize expand this if it isn't a legal type yet.
9069 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9072 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9075 bool ExtraOp = false;
9076 switch (Op.getOpcode()) {
9077 default: assert(0 && "Invalid code");
9078 case ISD::ADDC: Opc = X86ISD::ADD; break;
9079 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9080 case ISD::SUBC: Opc = X86ISD::SUB; break;
9081 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9085 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9087 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9088 Op.getOperand(1), Op.getOperand(2));
9091 /// LowerOperation - Provide custom lowering hooks for some operations.
9093 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9094 switch (Op.getOpcode()) {
9095 default: llvm_unreachable("Should not custom lower this!");
9096 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9097 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9098 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9099 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9100 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9101 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9102 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9103 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9104 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9105 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9106 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9107 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9108 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9109 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9110 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9111 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9112 case ISD::SHL_PARTS:
9113 case ISD::SRA_PARTS:
9114 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
9115 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9116 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9117 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9118 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9119 case ISD::FABS: return LowerFABS(Op, DAG);
9120 case ISD::FNEG: return LowerFNEG(Op, DAG);
9121 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9122 case ISD::SETCC: return LowerSETCC(Op, DAG);
9123 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9124 case ISD::SELECT: return LowerSELECT(Op, DAG);
9125 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9126 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9127 case ISD::VASTART: return LowerVASTART(Op, DAG);
9128 case ISD::VAARG: return LowerVAARG(Op, DAG);
9129 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9130 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9131 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9132 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9133 case ISD::FRAME_TO_ARGS_OFFSET:
9134 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9135 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9136 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9137 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9138 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9139 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9140 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9141 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9142 case ISD::SHL: return LowerSHL(Op, DAG);
9148 case ISD::UMULO: return LowerXALUO(Op, DAG);
9149 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9150 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9154 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9158 void X86TargetLowering::
9159 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9160 SelectionDAG &DAG, unsigned NewOp) const {
9161 EVT T = Node->getValueType(0);
9162 DebugLoc dl = Node->getDebugLoc();
9163 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9165 SDValue Chain = Node->getOperand(0);
9166 SDValue In1 = Node->getOperand(1);
9167 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9168 Node->getOperand(2), DAG.getIntPtrConstant(0));
9169 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9170 Node->getOperand(2), DAG.getIntPtrConstant(1));
9171 SDValue Ops[] = { Chain, In1, In2L, In2H };
9172 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9174 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9175 cast<MemSDNode>(Node)->getMemOperand());
9176 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9177 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9178 Results.push_back(Result.getValue(2));
9181 /// ReplaceNodeResults - Replace a node with an illegal result type
9182 /// with a new node built out of custom code.
9183 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9184 SmallVectorImpl<SDValue>&Results,
9185 SelectionDAG &DAG) const {
9186 DebugLoc dl = N->getDebugLoc();
9187 switch (N->getOpcode()) {
9189 assert(false && "Do not know how to custom type legalize this operation!");
9195 // We don't want to expand or promote these.
9197 case ISD::FP_TO_SINT: {
9198 std::pair<SDValue,SDValue> Vals =
9199 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9200 SDValue FIST = Vals.first, StackSlot = Vals.second;
9201 if (FIST.getNode() != 0) {
9202 EVT VT = N->getValueType(0);
9203 // Return a load from the stack slot.
9204 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9205 MachinePointerInfo(), false, false, 0));
9209 case ISD::READCYCLECOUNTER: {
9210 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9211 SDValue TheChain = N->getOperand(0);
9212 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9213 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9215 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9217 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9218 SDValue Ops[] = { eax, edx };
9219 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9220 Results.push_back(edx.getValue(1));
9223 case ISD::ATOMIC_CMP_SWAP: {
9224 EVT T = N->getValueType(0);
9225 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9226 SDValue cpInL, cpInH;
9227 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9228 DAG.getConstant(0, MVT::i32));
9229 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9230 DAG.getConstant(1, MVT::i32));
9231 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9232 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9234 SDValue swapInL, swapInH;
9235 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9236 DAG.getConstant(0, MVT::i32));
9237 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9238 DAG.getConstant(1, MVT::i32));
9239 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9241 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9242 swapInL.getValue(1));
9243 SDValue Ops[] = { swapInH.getValue(0),
9245 swapInH.getValue(1) };
9246 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9247 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9248 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9250 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9251 MVT::i32, Result.getValue(1));
9252 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9253 MVT::i32, cpOutL.getValue(2));
9254 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9255 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9256 Results.push_back(cpOutH.getValue(1));
9259 case ISD::ATOMIC_LOAD_ADD:
9260 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9262 case ISD::ATOMIC_LOAD_AND:
9263 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9265 case ISD::ATOMIC_LOAD_NAND:
9266 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9268 case ISD::ATOMIC_LOAD_OR:
9269 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9271 case ISD::ATOMIC_LOAD_SUB:
9272 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9274 case ISD::ATOMIC_LOAD_XOR:
9275 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9277 case ISD::ATOMIC_SWAP:
9278 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9283 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9285 default: return NULL;
9286 case X86ISD::BSF: return "X86ISD::BSF";
9287 case X86ISD::BSR: return "X86ISD::BSR";
9288 case X86ISD::SHLD: return "X86ISD::SHLD";
9289 case X86ISD::SHRD: return "X86ISD::SHRD";
9290 case X86ISD::FAND: return "X86ISD::FAND";
9291 case X86ISD::FOR: return "X86ISD::FOR";
9292 case X86ISD::FXOR: return "X86ISD::FXOR";
9293 case X86ISD::FSRL: return "X86ISD::FSRL";
9294 case X86ISD::FILD: return "X86ISD::FILD";
9295 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9296 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9297 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9298 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9299 case X86ISD::FLD: return "X86ISD::FLD";
9300 case X86ISD::FST: return "X86ISD::FST";
9301 case X86ISD::CALL: return "X86ISD::CALL";
9302 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9303 case X86ISD::BT: return "X86ISD::BT";
9304 case X86ISD::CMP: return "X86ISD::CMP";
9305 case X86ISD::COMI: return "X86ISD::COMI";
9306 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9307 case X86ISD::SETCC: return "X86ISD::SETCC";
9308 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9309 case X86ISD::CMOV: return "X86ISD::CMOV";
9310 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9311 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9312 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9313 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9314 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9315 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9316 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9317 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9318 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9319 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9320 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9321 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9322 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9323 case X86ISD::PANDN: return "X86ISD::PANDN";
9324 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9325 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9326 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9327 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9328 case X86ISD::FMAX: return "X86ISD::FMAX";
9329 case X86ISD::FMIN: return "X86ISD::FMIN";
9330 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9331 case X86ISD::FRCP: return "X86ISD::FRCP";
9332 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9333 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9334 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9335 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9336 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9337 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9338 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9339 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9340 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9341 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9342 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9343 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9344 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9345 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9346 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9347 case X86ISD::VSHL: return "X86ISD::VSHL";
9348 case X86ISD::VSRL: return "X86ISD::VSRL";
9349 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9350 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9351 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9352 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9353 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9354 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9355 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9356 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9357 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9358 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9359 case X86ISD::ADD: return "X86ISD::ADD";
9360 case X86ISD::SUB: return "X86ISD::SUB";
9361 case X86ISD::ADC: return "X86ISD::ADC";
9362 case X86ISD::SBB: return "X86ISD::SBB";
9363 case X86ISD::SMUL: return "X86ISD::SMUL";
9364 case X86ISD::UMUL: return "X86ISD::UMUL";
9365 case X86ISD::INC: return "X86ISD::INC";
9366 case X86ISD::DEC: return "X86ISD::DEC";
9367 case X86ISD::OR: return "X86ISD::OR";
9368 case X86ISD::XOR: return "X86ISD::XOR";
9369 case X86ISD::AND: return "X86ISD::AND";
9370 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9371 case X86ISD::PTEST: return "X86ISD::PTEST";
9372 case X86ISD::TESTP: return "X86ISD::TESTP";
9373 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9374 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9375 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9376 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9377 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9378 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9379 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9380 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9381 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9382 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9383 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9384 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9385 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9386 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9387 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9388 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9389 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9390 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9391 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9392 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9393 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9394 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9395 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9396 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9397 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9398 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9399 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9400 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9401 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9402 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9403 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9404 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9405 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9406 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9407 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9408 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9409 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9410 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9411 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9412 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9416 // isLegalAddressingMode - Return true if the addressing mode represented
9417 // by AM is legal for this target, for a load/store of the specified type.
9418 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9419 const Type *Ty) const {
9420 // X86 supports extremely general addressing modes.
9421 CodeModel::Model M = getTargetMachine().getCodeModel();
9422 Reloc::Model R = getTargetMachine().getRelocationModel();
9424 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9425 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9430 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9432 // If a reference to this global requires an extra load, we can't fold it.
9433 if (isGlobalStubReference(GVFlags))
9436 // If BaseGV requires a register for the PIC base, we cannot also have a
9437 // BaseReg specified.
9438 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9441 // If lower 4G is not available, then we must use rip-relative addressing.
9442 if ((M != CodeModel::Small || R != Reloc::Static) &&
9443 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9453 // These scales always work.
9458 // These scales are formed with basereg+scalereg. Only accept if there is
9463 default: // Other stuff never works.
9471 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9472 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9474 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9475 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9476 if (NumBits1 <= NumBits2)
9481 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9482 if (!VT1.isInteger() || !VT2.isInteger())
9484 unsigned NumBits1 = VT1.getSizeInBits();
9485 unsigned NumBits2 = VT2.getSizeInBits();
9486 if (NumBits1 <= NumBits2)
9491 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9492 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9493 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9496 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9497 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9498 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9501 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9502 // i16 instructions are longer (0x66 prefix) and potentially slower.
9503 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9506 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9507 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9508 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9509 /// are assumed to be legal.
9511 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9513 // Very little shuffling can be done for 64-bit vectors right now.
9514 if (VT.getSizeInBits() == 64)
9515 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9517 // FIXME: pshufb, blends, shifts.
9518 return (VT.getVectorNumElements() == 2 ||
9519 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9520 isMOVLMask(M, VT) ||
9521 isSHUFPMask(M, VT) ||
9522 isPSHUFDMask(M, VT) ||
9523 isPSHUFHWMask(M, VT) ||
9524 isPSHUFLWMask(M, VT) ||
9525 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9526 isUNPCKLMask(M, VT) ||
9527 isUNPCKHMask(M, VT) ||
9528 isUNPCKL_v_undef_Mask(M, VT) ||
9529 isUNPCKH_v_undef_Mask(M, VT));
9533 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9535 unsigned NumElts = VT.getVectorNumElements();
9536 // FIXME: This collection of masks seems suspect.
9539 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9540 return (isMOVLMask(Mask, VT) ||
9541 isCommutedMOVLMask(Mask, VT, true) ||
9542 isSHUFPMask(Mask, VT) ||
9543 isCommutedSHUFPMask(Mask, VT));
9548 //===----------------------------------------------------------------------===//
9549 // X86 Scheduler Hooks
9550 //===----------------------------------------------------------------------===//
9552 // private utility function
9554 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9555 MachineBasicBlock *MBB,
9562 TargetRegisterClass *RC,
9563 bool invSrc) const {
9564 // For the atomic bitwise operator, we generate
9567 // ld t1 = [bitinstr.addr]
9568 // op t2 = t1, [bitinstr.val]
9570 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9572 // fallthrough -->nextMBB
9573 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9574 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9575 MachineFunction::iterator MBBIter = MBB;
9578 /// First build the CFG
9579 MachineFunction *F = MBB->getParent();
9580 MachineBasicBlock *thisMBB = MBB;
9581 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9582 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9583 F->insert(MBBIter, newMBB);
9584 F->insert(MBBIter, nextMBB);
9586 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9587 nextMBB->splice(nextMBB->begin(), thisMBB,
9588 llvm::next(MachineBasicBlock::iterator(bInstr)),
9590 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9592 // Update thisMBB to fall through to newMBB
9593 thisMBB->addSuccessor(newMBB);
9595 // newMBB jumps to itself and fall through to nextMBB
9596 newMBB->addSuccessor(nextMBB);
9597 newMBB->addSuccessor(newMBB);
9599 // Insert instructions into newMBB based on incoming instruction
9600 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9601 "unexpected number of operands");
9602 DebugLoc dl = bInstr->getDebugLoc();
9603 MachineOperand& destOper = bInstr->getOperand(0);
9604 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9605 int numArgs = bInstr->getNumOperands() - 1;
9606 for (int i=0; i < numArgs; ++i)
9607 argOpers[i] = &bInstr->getOperand(i+1);
9609 // x86 address has 4 operands: base, index, scale, and displacement
9610 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9611 int valArgIndx = lastAddrIndx + 1;
9613 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9614 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9615 for (int i=0; i <= lastAddrIndx; ++i)
9616 (*MIB).addOperand(*argOpers[i]);
9618 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9620 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9625 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9626 assert((argOpers[valArgIndx]->isReg() ||
9627 argOpers[valArgIndx]->isImm()) &&
9629 if (argOpers[valArgIndx]->isReg())
9630 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9632 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9634 (*MIB).addOperand(*argOpers[valArgIndx]);
9636 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9639 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9640 for (int i=0; i <= lastAddrIndx; ++i)
9641 (*MIB).addOperand(*argOpers[i]);
9643 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9644 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9645 bInstr->memoperands_end());
9647 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9651 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9653 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9657 // private utility function: 64 bit atomics on 32 bit host.
9659 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9660 MachineBasicBlock *MBB,
9665 bool invSrc) const {
9666 // For the atomic bitwise operator, we generate
9667 // thisMBB (instructions are in pairs, except cmpxchg8b)
9668 // ld t1,t2 = [bitinstr.addr]
9670 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9671 // op t5, t6 <- out1, out2, [bitinstr.val]
9672 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9673 // mov ECX, EBX <- t5, t6
9674 // mov EAX, EDX <- t1, t2
9675 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9676 // mov t3, t4 <- EAX, EDX
9678 // result in out1, out2
9679 // fallthrough -->nextMBB
9681 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9682 const unsigned LoadOpc = X86::MOV32rm;
9683 const unsigned NotOpc = X86::NOT32r;
9684 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9685 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9686 MachineFunction::iterator MBBIter = MBB;
9689 /// First build the CFG
9690 MachineFunction *F = MBB->getParent();
9691 MachineBasicBlock *thisMBB = MBB;
9692 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9693 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9694 F->insert(MBBIter, newMBB);
9695 F->insert(MBBIter, nextMBB);
9697 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9698 nextMBB->splice(nextMBB->begin(), thisMBB,
9699 llvm::next(MachineBasicBlock::iterator(bInstr)),
9701 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9703 // Update thisMBB to fall through to newMBB
9704 thisMBB->addSuccessor(newMBB);
9706 // newMBB jumps to itself and fall through to nextMBB
9707 newMBB->addSuccessor(nextMBB);
9708 newMBB->addSuccessor(newMBB);
9710 DebugLoc dl = bInstr->getDebugLoc();
9711 // Insert instructions into newMBB based on incoming instruction
9712 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9713 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9714 "unexpected number of operands");
9715 MachineOperand& dest1Oper = bInstr->getOperand(0);
9716 MachineOperand& dest2Oper = bInstr->getOperand(1);
9717 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9718 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9719 argOpers[i] = &bInstr->getOperand(i+2);
9721 // We use some of the operands multiple times, so conservatively just
9722 // clear any kill flags that might be present.
9723 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9724 argOpers[i]->setIsKill(false);
9727 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9728 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9730 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9731 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9732 for (int i=0; i <= lastAddrIndx; ++i)
9733 (*MIB).addOperand(*argOpers[i]);
9734 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9735 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9736 // add 4 to displacement.
9737 for (int i=0; i <= lastAddrIndx-2; ++i)
9738 (*MIB).addOperand(*argOpers[i]);
9739 MachineOperand newOp3 = *(argOpers[3]);
9741 newOp3.setImm(newOp3.getImm()+4);
9743 newOp3.setOffset(newOp3.getOffset()+4);
9744 (*MIB).addOperand(newOp3);
9745 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9747 // t3/4 are defined later, at the bottom of the loop
9748 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9749 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9750 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9751 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9752 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9753 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9755 // The subsequent operations should be using the destination registers of
9756 //the PHI instructions.
9758 t1 = F->getRegInfo().createVirtualRegister(RC);
9759 t2 = F->getRegInfo().createVirtualRegister(RC);
9760 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9761 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9763 t1 = dest1Oper.getReg();
9764 t2 = dest2Oper.getReg();
9767 int valArgIndx = lastAddrIndx + 1;
9768 assert((argOpers[valArgIndx]->isReg() ||
9769 argOpers[valArgIndx]->isImm()) &&
9771 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9772 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9773 if (argOpers[valArgIndx]->isReg())
9774 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9776 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9777 if (regOpcL != X86::MOV32rr)
9779 (*MIB).addOperand(*argOpers[valArgIndx]);
9780 assert(argOpers[valArgIndx + 1]->isReg() ==
9781 argOpers[valArgIndx]->isReg());
9782 assert(argOpers[valArgIndx + 1]->isImm() ==
9783 argOpers[valArgIndx]->isImm());
9784 if (argOpers[valArgIndx + 1]->isReg())
9785 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9787 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9788 if (regOpcH != X86::MOV32rr)
9790 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9792 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9794 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9797 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9799 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9802 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9803 for (int i=0; i <= lastAddrIndx; ++i)
9804 (*MIB).addOperand(*argOpers[i]);
9806 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9807 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9808 bInstr->memoperands_end());
9810 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9811 MIB.addReg(X86::EAX);
9812 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9813 MIB.addReg(X86::EDX);
9816 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9818 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9822 // private utility function
9824 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9825 MachineBasicBlock *MBB,
9826 unsigned cmovOpc) const {
9827 // For the atomic min/max operator, we generate
9830 // ld t1 = [min/max.addr]
9831 // mov t2 = [min/max.val]
9833 // cmov[cond] t2 = t1
9835 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9837 // fallthrough -->nextMBB
9839 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9840 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9841 MachineFunction::iterator MBBIter = MBB;
9844 /// First build the CFG
9845 MachineFunction *F = MBB->getParent();
9846 MachineBasicBlock *thisMBB = MBB;
9847 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9848 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9849 F->insert(MBBIter, newMBB);
9850 F->insert(MBBIter, nextMBB);
9852 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9853 nextMBB->splice(nextMBB->begin(), thisMBB,
9854 llvm::next(MachineBasicBlock::iterator(mInstr)),
9856 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9858 // Update thisMBB to fall through to newMBB
9859 thisMBB->addSuccessor(newMBB);
9861 // newMBB jumps to newMBB and fall through to nextMBB
9862 newMBB->addSuccessor(nextMBB);
9863 newMBB->addSuccessor(newMBB);
9865 DebugLoc dl = mInstr->getDebugLoc();
9866 // Insert instructions into newMBB based on incoming instruction
9867 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9868 "unexpected number of operands");
9869 MachineOperand& destOper = mInstr->getOperand(0);
9870 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9871 int numArgs = mInstr->getNumOperands() - 1;
9872 for (int i=0; i < numArgs; ++i)
9873 argOpers[i] = &mInstr->getOperand(i+1);
9875 // x86 address has 4 operands: base, index, scale, and displacement
9876 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9877 int valArgIndx = lastAddrIndx + 1;
9879 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9880 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9881 for (int i=0; i <= lastAddrIndx; ++i)
9882 (*MIB).addOperand(*argOpers[i]);
9884 // We only support register and immediate values
9885 assert((argOpers[valArgIndx]->isReg() ||
9886 argOpers[valArgIndx]->isImm()) &&
9889 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9890 if (argOpers[valArgIndx]->isReg())
9891 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9893 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9894 (*MIB).addOperand(*argOpers[valArgIndx]);
9896 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9899 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9904 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9905 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9909 // Cmp and exchange if none has modified the memory location
9910 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9911 for (int i=0; i <= lastAddrIndx; ++i)
9912 (*MIB).addOperand(*argOpers[i]);
9914 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9915 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9916 mInstr->memoperands_end());
9918 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9919 MIB.addReg(X86::EAX);
9922 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9924 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9928 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9929 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9932 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9933 unsigned numArgs, bool memArg) const {
9934 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9935 "Target must have SSE4.2 or AVX features enabled");
9937 DebugLoc dl = MI->getDebugLoc();
9938 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9940 if (!Subtarget->hasAVX()) {
9942 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9944 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9947 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9949 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9952 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9953 for (unsigned i = 0; i < numArgs; ++i) {
9954 MachineOperand &Op = MI->getOperand(i+1);
9955 if (!(Op.isReg() && Op.isImplicit()))
9958 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9961 MI->eraseFromParent();
9966 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9967 DebugLoc dl = MI->getDebugLoc();
9968 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9970 // Address into RAX/EAX, other two args into ECX, EDX.
9971 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9972 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9973 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9974 for (int i = 0; i < X86::AddrNumOperands; ++i)
9975 MIB.addOperand(MI->getOperand(i));
9977 unsigned ValOps = X86::AddrNumOperands;
9978 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9979 .addReg(MI->getOperand(ValOps).getReg());
9980 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9981 .addReg(MI->getOperand(ValOps+1).getReg());
9983 // The instruction doesn't actually take any operands though.
9984 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9986 MI->eraseFromParent(); // The pseudo is gone now.
9991 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9992 DebugLoc dl = MI->getDebugLoc();
9993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9995 // First arg in ECX, the second in EAX.
9996 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9997 .addReg(MI->getOperand(0).getReg());
9998 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9999 .addReg(MI->getOperand(1).getReg());
10001 // The instruction doesn't actually take any operands though.
10002 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10004 MI->eraseFromParent(); // The pseudo is gone now.
10008 MachineBasicBlock *
10009 X86TargetLowering::EmitVAARG64WithCustomInserter(
10011 MachineBasicBlock *MBB) const {
10012 // Emit va_arg instruction on X86-64.
10014 // Operands to this pseudo-instruction:
10015 // 0 ) Output : destination address (reg)
10016 // 1-5) Input : va_list address (addr, i64mem)
10017 // 6 ) ArgSize : Size (in bytes) of vararg type
10018 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10019 // 8 ) Align : Alignment of type
10020 // 9 ) EFLAGS (implicit-def)
10022 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10023 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10025 unsigned DestReg = MI->getOperand(0).getReg();
10026 MachineOperand &Base = MI->getOperand(1);
10027 MachineOperand &Scale = MI->getOperand(2);
10028 MachineOperand &Index = MI->getOperand(3);
10029 MachineOperand &Disp = MI->getOperand(4);
10030 MachineOperand &Segment = MI->getOperand(5);
10031 unsigned ArgSize = MI->getOperand(6).getImm();
10032 unsigned ArgMode = MI->getOperand(7).getImm();
10033 unsigned Align = MI->getOperand(8).getImm();
10035 // Memory Reference
10036 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10037 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10038 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10040 // Machine Information
10041 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10042 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10043 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10044 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10045 DebugLoc DL = MI->getDebugLoc();
10047 // struct va_list {
10050 // i64 overflow_area (address)
10051 // i64 reg_save_area (address)
10053 // sizeof(va_list) = 24
10054 // alignment(va_list) = 8
10056 unsigned TotalNumIntRegs = 6;
10057 unsigned TotalNumXMMRegs = 8;
10058 bool UseGPOffset = (ArgMode == 1);
10059 bool UseFPOffset = (ArgMode == 2);
10060 unsigned MaxOffset = TotalNumIntRegs * 8 +
10061 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10063 /* Align ArgSize to a multiple of 8 */
10064 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10065 bool NeedsAlign = (Align > 8);
10067 MachineBasicBlock *thisMBB = MBB;
10068 MachineBasicBlock *overflowMBB;
10069 MachineBasicBlock *offsetMBB;
10070 MachineBasicBlock *endMBB;
10072 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10073 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10074 unsigned OffsetReg = 0;
10076 if (!UseGPOffset && !UseFPOffset) {
10077 // If we only pull from the overflow region, we don't create a branch.
10078 // We don't need to alter control flow.
10079 OffsetDestReg = 0; // unused
10080 OverflowDestReg = DestReg;
10083 overflowMBB = thisMBB;
10086 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10087 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10088 // If not, pull from overflow_area. (branch to overflowMBB)
10093 // offsetMBB overflowMBB
10098 // Registers for the PHI in endMBB
10099 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10100 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10102 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10103 MachineFunction *MF = MBB->getParent();
10104 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10105 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10106 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10108 MachineFunction::iterator MBBIter = MBB;
10111 // Insert the new basic blocks
10112 MF->insert(MBBIter, offsetMBB);
10113 MF->insert(MBBIter, overflowMBB);
10114 MF->insert(MBBIter, endMBB);
10116 // Transfer the remainder of MBB and its successor edges to endMBB.
10117 endMBB->splice(endMBB->begin(), thisMBB,
10118 llvm::next(MachineBasicBlock::iterator(MI)),
10120 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10122 // Make offsetMBB and overflowMBB successors of thisMBB
10123 thisMBB->addSuccessor(offsetMBB);
10124 thisMBB->addSuccessor(overflowMBB);
10126 // endMBB is a successor of both offsetMBB and overflowMBB
10127 offsetMBB->addSuccessor(endMBB);
10128 overflowMBB->addSuccessor(endMBB);
10130 // Load the offset value into a register
10131 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10132 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10136 .addDisp(Disp, UseFPOffset ? 4 : 0)
10137 .addOperand(Segment)
10138 .setMemRefs(MMOBegin, MMOEnd);
10140 // Check if there is enough room left to pull this argument.
10141 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10143 .addImm(MaxOffset + 8 - ArgSizeA8);
10145 // Branch to "overflowMBB" if offset >= max
10146 // Fall through to "offsetMBB" otherwise
10147 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10148 .addMBB(overflowMBB);
10151 // In offsetMBB, emit code to use the reg_save_area.
10153 assert(OffsetReg != 0);
10155 // Read the reg_save_area address.
10156 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10157 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10162 .addOperand(Segment)
10163 .setMemRefs(MMOBegin, MMOEnd);
10165 // Zero-extend the offset
10166 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10167 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10170 .addImm(X86::sub_32bit);
10172 // Add the offset to the reg_save_area to get the final address.
10173 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10174 .addReg(OffsetReg64)
10175 .addReg(RegSaveReg);
10177 // Compute the offset for the next argument
10178 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10179 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10181 .addImm(UseFPOffset ? 16 : 8);
10183 // Store it back into the va_list.
10184 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10188 .addDisp(Disp, UseFPOffset ? 4 : 0)
10189 .addOperand(Segment)
10190 .addReg(NextOffsetReg)
10191 .setMemRefs(MMOBegin, MMOEnd);
10194 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10199 // Emit code to use overflow area
10202 // Load the overflow_area address into a register.
10203 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10204 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10209 .addOperand(Segment)
10210 .setMemRefs(MMOBegin, MMOEnd);
10212 // If we need to align it, do so. Otherwise, just copy the address
10213 // to OverflowDestReg.
10215 // Align the overflow address
10216 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10217 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10219 // aligned_addr = (addr + (align-1)) & ~(align-1)
10220 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10221 .addReg(OverflowAddrReg)
10224 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10226 .addImm(~(uint64_t)(Align-1));
10228 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10229 .addReg(OverflowAddrReg);
10232 // Compute the next overflow address after this argument.
10233 // (the overflow address should be kept 8-byte aligned)
10234 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10235 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10236 .addReg(OverflowDestReg)
10237 .addImm(ArgSizeA8);
10239 // Store the new overflow address.
10240 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10245 .addOperand(Segment)
10246 .addReg(NextAddrReg)
10247 .setMemRefs(MMOBegin, MMOEnd);
10249 // If we branched, emit the PHI to the front of endMBB.
10251 BuildMI(*endMBB, endMBB->begin(), DL,
10252 TII->get(X86::PHI), DestReg)
10253 .addReg(OffsetDestReg).addMBB(offsetMBB)
10254 .addReg(OverflowDestReg).addMBB(overflowMBB);
10257 // Erase the pseudo instruction
10258 MI->eraseFromParent();
10263 MachineBasicBlock *
10264 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10266 MachineBasicBlock *MBB) const {
10267 // Emit code to save XMM registers to the stack. The ABI says that the
10268 // number of registers to save is given in %al, so it's theoretically
10269 // possible to do an indirect jump trick to avoid saving all of them,
10270 // however this code takes a simpler approach and just executes all
10271 // of the stores if %al is non-zero. It's less code, and it's probably
10272 // easier on the hardware branch predictor, and stores aren't all that
10273 // expensive anyway.
10275 // Create the new basic blocks. One block contains all the XMM stores,
10276 // and one block is the final destination regardless of whether any
10277 // stores were performed.
10278 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10279 MachineFunction *F = MBB->getParent();
10280 MachineFunction::iterator MBBIter = MBB;
10282 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10283 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10284 F->insert(MBBIter, XMMSaveMBB);
10285 F->insert(MBBIter, EndMBB);
10287 // Transfer the remainder of MBB and its successor edges to EndMBB.
10288 EndMBB->splice(EndMBB->begin(), MBB,
10289 llvm::next(MachineBasicBlock::iterator(MI)),
10291 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10293 // The original block will now fall through to the XMM save block.
10294 MBB->addSuccessor(XMMSaveMBB);
10295 // The XMMSaveMBB will fall through to the end block.
10296 XMMSaveMBB->addSuccessor(EndMBB);
10298 // Now add the instructions.
10299 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10300 DebugLoc DL = MI->getDebugLoc();
10302 unsigned CountReg = MI->getOperand(0).getReg();
10303 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10304 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10306 if (!Subtarget->isTargetWin64()) {
10307 // If %al is 0, branch around the XMM save block.
10308 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10309 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10310 MBB->addSuccessor(EndMBB);
10313 // In the XMM save block, save all the XMM argument registers.
10314 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10315 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10316 MachineMemOperand *MMO =
10317 F->getMachineMemOperand(
10318 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10319 MachineMemOperand::MOStore,
10320 /*Size=*/16, /*Align=*/16);
10321 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10322 .addFrameIndex(RegSaveFrameIndex)
10323 .addImm(/*Scale=*/1)
10324 .addReg(/*IndexReg=*/0)
10325 .addImm(/*Disp=*/Offset)
10326 .addReg(/*Segment=*/0)
10327 .addReg(MI->getOperand(i).getReg())
10328 .addMemOperand(MMO);
10331 MI->eraseFromParent(); // The pseudo instruction is gone now.
10336 MachineBasicBlock *
10337 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10338 MachineBasicBlock *BB) const {
10339 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10340 DebugLoc DL = MI->getDebugLoc();
10342 // To "insert" a SELECT_CC instruction, we actually have to insert the
10343 // diamond control-flow pattern. The incoming instruction knows the
10344 // destination vreg to set, the condition code register to branch on, the
10345 // true/false values to select between, and a branch opcode to use.
10346 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10347 MachineFunction::iterator It = BB;
10353 // cmpTY ccX, r1, r2
10355 // fallthrough --> copy0MBB
10356 MachineBasicBlock *thisMBB = BB;
10357 MachineFunction *F = BB->getParent();
10358 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10359 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10360 F->insert(It, copy0MBB);
10361 F->insert(It, sinkMBB);
10363 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10364 // live into the sink and copy blocks.
10365 const MachineFunction *MF = BB->getParent();
10366 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10367 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10369 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10370 const MachineOperand &MO = MI->getOperand(I);
10371 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10372 unsigned Reg = MO.getReg();
10373 if (Reg != X86::EFLAGS) continue;
10374 copy0MBB->addLiveIn(Reg);
10375 sinkMBB->addLiveIn(Reg);
10378 // Transfer the remainder of BB and its successor edges to sinkMBB.
10379 sinkMBB->splice(sinkMBB->begin(), BB,
10380 llvm::next(MachineBasicBlock::iterator(MI)),
10382 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10384 // Add the true and fallthrough blocks as its successors.
10385 BB->addSuccessor(copy0MBB);
10386 BB->addSuccessor(sinkMBB);
10388 // Create the conditional branch instruction.
10390 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10391 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10394 // %FalseValue = ...
10395 // # fallthrough to sinkMBB
10396 copy0MBB->addSuccessor(sinkMBB);
10399 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10401 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10402 TII->get(X86::PHI), MI->getOperand(0).getReg())
10403 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10404 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10406 MI->eraseFromParent(); // The pseudo instruction is gone now.
10410 MachineBasicBlock *
10411 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10412 MachineBasicBlock *BB) const {
10413 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10414 DebugLoc DL = MI->getDebugLoc();
10416 assert(!Subtarget->isTargetEnvMacho());
10418 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10419 // non-trivial part is impdef of ESP.
10421 if (Subtarget->isTargetWin64()) {
10422 if (Subtarget->isTargetCygMing()) {
10423 // ___chkstk(Mingw64):
10424 // Clobbers R10, R11, RAX and EFLAGS.
10426 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10427 .addExternalSymbol("___chkstk")
10428 .addReg(X86::RAX, RegState::Implicit)
10429 .addReg(X86::RSP, RegState::Implicit)
10430 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10431 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10432 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10434 // __chkstk(MSVCRT): does not update stack pointer.
10435 // Clobbers R10, R11 and EFLAGS.
10436 // FIXME: RAX(allocated size) might be reused and not killed.
10437 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10438 .addExternalSymbol("__chkstk")
10439 .addReg(X86::RAX, RegState::Implicit)
10440 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10441 // RAX has the offset to subtracted from RSP.
10442 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10447 const char *StackProbeSymbol =
10448 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10450 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10451 .addExternalSymbol(StackProbeSymbol)
10452 .addReg(X86::EAX, RegState::Implicit)
10453 .addReg(X86::ESP, RegState::Implicit)
10454 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10455 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10456 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10459 MI->eraseFromParent(); // The pseudo instruction is gone now.
10463 MachineBasicBlock *
10464 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10465 MachineBasicBlock *BB) const {
10466 // This is pretty easy. We're taking the value that we received from
10467 // our load from the relocation, sticking it in either RDI (x86-64)
10468 // or EAX and doing an indirect call. The return value will then
10469 // be in the normal return register.
10470 const X86InstrInfo *TII
10471 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10472 DebugLoc DL = MI->getDebugLoc();
10473 MachineFunction *F = BB->getParent();
10475 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10476 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10478 if (Subtarget->is64Bit()) {
10479 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10480 TII->get(X86::MOV64rm), X86::RDI)
10482 .addImm(0).addReg(0)
10483 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10484 MI->getOperand(3).getTargetFlags())
10486 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10487 addDirectMem(MIB, X86::RDI);
10488 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10489 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10490 TII->get(X86::MOV32rm), X86::EAX)
10492 .addImm(0).addReg(0)
10493 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10494 MI->getOperand(3).getTargetFlags())
10496 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10497 addDirectMem(MIB, X86::EAX);
10499 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10500 TII->get(X86::MOV32rm), X86::EAX)
10501 .addReg(TII->getGlobalBaseReg(F))
10502 .addImm(0).addReg(0)
10503 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10504 MI->getOperand(3).getTargetFlags())
10506 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10507 addDirectMem(MIB, X86::EAX);
10510 MI->eraseFromParent(); // The pseudo instruction is gone now.
10514 MachineBasicBlock *
10515 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10516 MachineBasicBlock *BB) const {
10517 switch (MI->getOpcode()) {
10518 default: assert(false && "Unexpected instr type to insert");
10519 case X86::TAILJMPd64:
10520 case X86::TAILJMPr64:
10521 case X86::TAILJMPm64:
10522 assert(!"TAILJMP64 would not be touched here.");
10523 case X86::TCRETURNdi64:
10524 case X86::TCRETURNri64:
10525 case X86::TCRETURNmi64:
10526 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10527 // On AMD64, additional defs should be added before register allocation.
10528 if (!Subtarget->isTargetWin64()) {
10529 MI->addRegisterDefined(X86::RSI);
10530 MI->addRegisterDefined(X86::RDI);
10531 MI->addRegisterDefined(X86::XMM6);
10532 MI->addRegisterDefined(X86::XMM7);
10533 MI->addRegisterDefined(X86::XMM8);
10534 MI->addRegisterDefined(X86::XMM9);
10535 MI->addRegisterDefined(X86::XMM10);
10536 MI->addRegisterDefined(X86::XMM11);
10537 MI->addRegisterDefined(X86::XMM12);
10538 MI->addRegisterDefined(X86::XMM13);
10539 MI->addRegisterDefined(X86::XMM14);
10540 MI->addRegisterDefined(X86::XMM15);
10543 case X86::WIN_ALLOCA:
10544 return EmitLoweredWinAlloca(MI, BB);
10545 case X86::TLSCall_32:
10546 case X86::TLSCall_64:
10547 return EmitLoweredTLSCall(MI, BB);
10548 case X86::CMOV_GR8:
10549 case X86::CMOV_FR32:
10550 case X86::CMOV_FR64:
10551 case X86::CMOV_V4F32:
10552 case X86::CMOV_V2F64:
10553 case X86::CMOV_V2I64:
10554 case X86::CMOV_GR16:
10555 case X86::CMOV_GR32:
10556 case X86::CMOV_RFP32:
10557 case X86::CMOV_RFP64:
10558 case X86::CMOV_RFP80:
10559 return EmitLoweredSelect(MI, BB);
10561 case X86::FP32_TO_INT16_IN_MEM:
10562 case X86::FP32_TO_INT32_IN_MEM:
10563 case X86::FP32_TO_INT64_IN_MEM:
10564 case X86::FP64_TO_INT16_IN_MEM:
10565 case X86::FP64_TO_INT32_IN_MEM:
10566 case X86::FP64_TO_INT64_IN_MEM:
10567 case X86::FP80_TO_INT16_IN_MEM:
10568 case X86::FP80_TO_INT32_IN_MEM:
10569 case X86::FP80_TO_INT64_IN_MEM: {
10570 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10571 DebugLoc DL = MI->getDebugLoc();
10573 // Change the floating point control register to use "round towards zero"
10574 // mode when truncating to an integer value.
10575 MachineFunction *F = BB->getParent();
10576 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10577 addFrameReference(BuildMI(*BB, MI, DL,
10578 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10580 // Load the old value of the high byte of the control word...
10582 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10583 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10586 // Set the high part to be round to zero...
10587 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10590 // Reload the modified control word now...
10591 addFrameReference(BuildMI(*BB, MI, DL,
10592 TII->get(X86::FLDCW16m)), CWFrameIdx);
10594 // Restore the memory image of control word to original value
10595 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10598 // Get the X86 opcode to use.
10600 switch (MI->getOpcode()) {
10601 default: llvm_unreachable("illegal opcode!");
10602 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10603 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10604 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10605 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10606 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10607 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10608 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10609 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10610 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10614 MachineOperand &Op = MI->getOperand(0);
10616 AM.BaseType = X86AddressMode::RegBase;
10617 AM.Base.Reg = Op.getReg();
10619 AM.BaseType = X86AddressMode::FrameIndexBase;
10620 AM.Base.FrameIndex = Op.getIndex();
10622 Op = MI->getOperand(1);
10624 AM.Scale = Op.getImm();
10625 Op = MI->getOperand(2);
10627 AM.IndexReg = Op.getImm();
10628 Op = MI->getOperand(3);
10629 if (Op.isGlobal()) {
10630 AM.GV = Op.getGlobal();
10632 AM.Disp = Op.getImm();
10634 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10635 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10637 // Reload the original control word now.
10638 addFrameReference(BuildMI(*BB, MI, DL,
10639 TII->get(X86::FLDCW16m)), CWFrameIdx);
10641 MI->eraseFromParent(); // The pseudo instruction is gone now.
10644 // String/text processing lowering.
10645 case X86::PCMPISTRM128REG:
10646 case X86::VPCMPISTRM128REG:
10647 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10648 case X86::PCMPISTRM128MEM:
10649 case X86::VPCMPISTRM128MEM:
10650 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10651 case X86::PCMPESTRM128REG:
10652 case X86::VPCMPESTRM128REG:
10653 return EmitPCMP(MI, BB, 5, false /* in mem */);
10654 case X86::PCMPESTRM128MEM:
10655 case X86::VPCMPESTRM128MEM:
10656 return EmitPCMP(MI, BB, 5, true /* in mem */);
10658 // Thread synchronization.
10660 return EmitMonitor(MI, BB);
10662 return EmitMwait(MI, BB);
10664 // Atomic Lowering.
10665 case X86::ATOMAND32:
10666 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10667 X86::AND32ri, X86::MOV32rm,
10669 X86::NOT32r, X86::EAX,
10670 X86::GR32RegisterClass);
10671 case X86::ATOMOR32:
10672 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10673 X86::OR32ri, X86::MOV32rm,
10675 X86::NOT32r, X86::EAX,
10676 X86::GR32RegisterClass);
10677 case X86::ATOMXOR32:
10678 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10679 X86::XOR32ri, X86::MOV32rm,
10681 X86::NOT32r, X86::EAX,
10682 X86::GR32RegisterClass);
10683 case X86::ATOMNAND32:
10684 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10685 X86::AND32ri, X86::MOV32rm,
10687 X86::NOT32r, X86::EAX,
10688 X86::GR32RegisterClass, true);
10689 case X86::ATOMMIN32:
10690 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10691 case X86::ATOMMAX32:
10692 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10693 case X86::ATOMUMIN32:
10694 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10695 case X86::ATOMUMAX32:
10696 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10698 case X86::ATOMAND16:
10699 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10700 X86::AND16ri, X86::MOV16rm,
10702 X86::NOT16r, X86::AX,
10703 X86::GR16RegisterClass);
10704 case X86::ATOMOR16:
10705 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10706 X86::OR16ri, X86::MOV16rm,
10708 X86::NOT16r, X86::AX,
10709 X86::GR16RegisterClass);
10710 case X86::ATOMXOR16:
10711 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10712 X86::XOR16ri, X86::MOV16rm,
10714 X86::NOT16r, X86::AX,
10715 X86::GR16RegisterClass);
10716 case X86::ATOMNAND16:
10717 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10718 X86::AND16ri, X86::MOV16rm,
10720 X86::NOT16r, X86::AX,
10721 X86::GR16RegisterClass, true);
10722 case X86::ATOMMIN16:
10723 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10724 case X86::ATOMMAX16:
10725 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10726 case X86::ATOMUMIN16:
10727 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10728 case X86::ATOMUMAX16:
10729 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10731 case X86::ATOMAND8:
10732 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10733 X86::AND8ri, X86::MOV8rm,
10735 X86::NOT8r, X86::AL,
10736 X86::GR8RegisterClass);
10738 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10739 X86::OR8ri, X86::MOV8rm,
10741 X86::NOT8r, X86::AL,
10742 X86::GR8RegisterClass);
10743 case X86::ATOMXOR8:
10744 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10745 X86::XOR8ri, X86::MOV8rm,
10747 X86::NOT8r, X86::AL,
10748 X86::GR8RegisterClass);
10749 case X86::ATOMNAND8:
10750 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10751 X86::AND8ri, X86::MOV8rm,
10753 X86::NOT8r, X86::AL,
10754 X86::GR8RegisterClass, true);
10755 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10756 // This group is for 64-bit host.
10757 case X86::ATOMAND64:
10758 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10759 X86::AND64ri32, X86::MOV64rm,
10761 X86::NOT64r, X86::RAX,
10762 X86::GR64RegisterClass);
10763 case X86::ATOMOR64:
10764 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10765 X86::OR64ri32, X86::MOV64rm,
10767 X86::NOT64r, X86::RAX,
10768 X86::GR64RegisterClass);
10769 case X86::ATOMXOR64:
10770 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10771 X86::XOR64ri32, X86::MOV64rm,
10773 X86::NOT64r, X86::RAX,
10774 X86::GR64RegisterClass);
10775 case X86::ATOMNAND64:
10776 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10777 X86::AND64ri32, X86::MOV64rm,
10779 X86::NOT64r, X86::RAX,
10780 X86::GR64RegisterClass, true);
10781 case X86::ATOMMIN64:
10782 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10783 case X86::ATOMMAX64:
10784 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10785 case X86::ATOMUMIN64:
10786 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10787 case X86::ATOMUMAX64:
10788 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10790 // This group does 64-bit operations on a 32-bit host.
10791 case X86::ATOMAND6432:
10792 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10793 X86::AND32rr, X86::AND32rr,
10794 X86::AND32ri, X86::AND32ri,
10796 case X86::ATOMOR6432:
10797 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10798 X86::OR32rr, X86::OR32rr,
10799 X86::OR32ri, X86::OR32ri,
10801 case X86::ATOMXOR6432:
10802 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10803 X86::XOR32rr, X86::XOR32rr,
10804 X86::XOR32ri, X86::XOR32ri,
10806 case X86::ATOMNAND6432:
10807 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10808 X86::AND32rr, X86::AND32rr,
10809 X86::AND32ri, X86::AND32ri,
10811 case X86::ATOMADD6432:
10812 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10813 X86::ADD32rr, X86::ADC32rr,
10814 X86::ADD32ri, X86::ADC32ri,
10816 case X86::ATOMSUB6432:
10817 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10818 X86::SUB32rr, X86::SBB32rr,
10819 X86::SUB32ri, X86::SBB32ri,
10821 case X86::ATOMSWAP6432:
10822 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10823 X86::MOV32rr, X86::MOV32rr,
10824 X86::MOV32ri, X86::MOV32ri,
10826 case X86::VASTART_SAVE_XMM_REGS:
10827 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10829 case X86::VAARG_64:
10830 return EmitVAARG64WithCustomInserter(MI, BB);
10834 //===----------------------------------------------------------------------===//
10835 // X86 Optimization Hooks
10836 //===----------------------------------------------------------------------===//
10838 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10842 const SelectionDAG &DAG,
10843 unsigned Depth) const {
10844 unsigned Opc = Op.getOpcode();
10845 assert((Opc >= ISD::BUILTIN_OP_END ||
10846 Opc == ISD::INTRINSIC_WO_CHAIN ||
10847 Opc == ISD::INTRINSIC_W_CHAIN ||
10848 Opc == ISD::INTRINSIC_VOID) &&
10849 "Should use MaskedValueIsZero if you don't know whether Op"
10850 " is a target node!");
10852 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10866 // These nodes' second result is a boolean.
10867 if (Op.getResNo() == 0)
10870 case X86ISD::SETCC:
10871 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10872 Mask.getBitWidth() - 1);
10877 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10878 unsigned Depth) const {
10879 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10880 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10881 return Op.getValueType().getScalarType().getSizeInBits();
10887 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10888 /// node is a GlobalAddress + offset.
10889 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10890 const GlobalValue* &GA,
10891 int64_t &Offset) const {
10892 if (N->getOpcode() == X86ISD::Wrapper) {
10893 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10894 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10895 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10899 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10902 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10903 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10904 /// if the load addresses are consecutive, non-overlapping, and in the right
10906 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10907 TargetLowering::DAGCombinerInfo &DCI) {
10908 DebugLoc dl = N->getDebugLoc();
10909 EVT VT = N->getValueType(0);
10911 if (VT.getSizeInBits() != 128)
10914 // Don't create instructions with illegal types after legalize types has run.
10915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10916 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10919 SmallVector<SDValue, 16> Elts;
10920 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10921 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10923 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10926 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10927 /// generation and convert it from being a bunch of shuffles and extracts
10928 /// to a simple store and scalar loads to extract the elements.
10929 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10930 const TargetLowering &TLI) {
10931 SDValue InputVector = N->getOperand(0);
10933 // Only operate on vectors of 4 elements, where the alternative shuffling
10934 // gets to be more expensive.
10935 if (InputVector.getValueType() != MVT::v4i32)
10938 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10939 // single use which is a sign-extend or zero-extend, and all elements are
10941 SmallVector<SDNode *, 4> Uses;
10942 unsigned ExtractedElements = 0;
10943 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10944 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10945 if (UI.getUse().getResNo() != InputVector.getResNo())
10948 SDNode *Extract = *UI;
10949 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10952 if (Extract->getValueType(0) != MVT::i32)
10954 if (!Extract->hasOneUse())
10956 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10957 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10959 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10962 // Record which element was extracted.
10963 ExtractedElements |=
10964 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10966 Uses.push_back(Extract);
10969 // If not all the elements were used, this may not be worthwhile.
10970 if (ExtractedElements != 15)
10973 // Ok, we've now decided to do the transformation.
10974 DebugLoc dl = InputVector.getDebugLoc();
10976 // Store the value to a temporary stack slot.
10977 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10978 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10979 MachinePointerInfo(), false, false, 0);
10981 // Replace each use (extract) with a load of the appropriate element.
10982 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10983 UE = Uses.end(); UI != UE; ++UI) {
10984 SDNode *Extract = *UI;
10986 // Compute the element's address.
10987 SDValue Idx = Extract->getOperand(1);
10989 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10990 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10991 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10993 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10994 StackPtr, OffsetVal);
10996 // Load the scalar.
10997 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10998 ScalarAddr, MachinePointerInfo(),
11001 // Replace the exact with the load.
11002 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11005 // The replacement was made in place; don't return anything.
11009 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11010 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11011 const X86Subtarget *Subtarget) {
11012 DebugLoc DL = N->getDebugLoc();
11013 SDValue Cond = N->getOperand(0);
11014 // Get the LHS/RHS of the select.
11015 SDValue LHS = N->getOperand(1);
11016 SDValue RHS = N->getOperand(2);
11018 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11019 // instructions match the semantics of the common C idiom x<y?x:y but not
11020 // x<=y?x:y, because of how they handle negative zero (which can be
11021 // ignored in unsafe-math mode).
11022 if (Subtarget->hasSSE2() &&
11023 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11024 Cond.getOpcode() == ISD::SETCC) {
11025 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11027 unsigned Opcode = 0;
11028 // Check for x CC y ? x : y.
11029 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11030 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11034 // Converting this to a min would handle NaNs incorrectly, and swapping
11035 // the operands would cause it to handle comparisons between positive
11036 // and negative zero incorrectly.
11037 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11038 if (!UnsafeFPMath &&
11039 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11041 std::swap(LHS, RHS);
11043 Opcode = X86ISD::FMIN;
11046 // Converting this to a min would handle comparisons between positive
11047 // and negative zero incorrectly.
11048 if (!UnsafeFPMath &&
11049 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11051 Opcode = X86ISD::FMIN;
11054 // Converting this to a min would handle both negative zeros and NaNs
11055 // incorrectly, but we can swap the operands to fix both.
11056 std::swap(LHS, RHS);
11060 Opcode = X86ISD::FMIN;
11064 // Converting this to a max would handle comparisons between positive
11065 // and negative zero incorrectly.
11066 if (!UnsafeFPMath &&
11067 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11069 Opcode = X86ISD::FMAX;
11072 // Converting this to a max would handle NaNs incorrectly, and swapping
11073 // the operands would cause it to handle comparisons between positive
11074 // and negative zero incorrectly.
11075 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11076 if (!UnsafeFPMath &&
11077 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11079 std::swap(LHS, RHS);
11081 Opcode = X86ISD::FMAX;
11084 // Converting this to a max would handle both negative zeros and NaNs
11085 // incorrectly, but we can swap the operands to fix both.
11086 std::swap(LHS, RHS);
11090 Opcode = X86ISD::FMAX;
11093 // Check for x CC y ? y : x -- a min/max with reversed arms.
11094 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11095 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11099 // Converting this to a min would handle comparisons between positive
11100 // and negative zero incorrectly, and swapping the operands would
11101 // cause it to handle NaNs incorrectly.
11102 if (!UnsafeFPMath &&
11103 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11106 std::swap(LHS, RHS);
11108 Opcode = X86ISD::FMIN;
11111 // Converting this to a min would handle NaNs incorrectly.
11112 if (!UnsafeFPMath &&
11113 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11115 Opcode = X86ISD::FMIN;
11118 // Converting this to a min would handle both negative zeros and NaNs
11119 // incorrectly, but we can swap the operands to fix both.
11120 std::swap(LHS, RHS);
11124 Opcode = X86ISD::FMIN;
11128 // Converting this to a max would handle NaNs incorrectly.
11129 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11131 Opcode = X86ISD::FMAX;
11134 // Converting this to a max would handle comparisons between positive
11135 // and negative zero incorrectly, and swapping the operands would
11136 // cause it to handle NaNs incorrectly.
11137 if (!UnsafeFPMath &&
11138 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11139 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11141 std::swap(LHS, RHS);
11143 Opcode = X86ISD::FMAX;
11146 // Converting this to a max would handle both negative zeros and NaNs
11147 // incorrectly, but we can swap the operands to fix both.
11148 std::swap(LHS, RHS);
11152 Opcode = X86ISD::FMAX;
11158 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11161 // If this is a select between two integer constants, try to do some
11163 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11164 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11165 // Don't do this for crazy integer types.
11166 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11167 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11168 // so that TrueC (the true value) is larger than FalseC.
11169 bool NeedsCondInvert = false;
11171 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11172 // Efficiently invertible.
11173 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11174 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11175 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11176 NeedsCondInvert = true;
11177 std::swap(TrueC, FalseC);
11180 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11181 if (FalseC->getAPIntValue() == 0 &&
11182 TrueC->getAPIntValue().isPowerOf2()) {
11183 if (NeedsCondInvert) // Invert the condition if needed.
11184 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11185 DAG.getConstant(1, Cond.getValueType()));
11187 // Zero extend the condition if needed.
11188 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11190 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11191 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11192 DAG.getConstant(ShAmt, MVT::i8));
11195 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11196 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11197 if (NeedsCondInvert) // Invert the condition if needed.
11198 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11199 DAG.getConstant(1, Cond.getValueType()));
11201 // Zero extend the condition if needed.
11202 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11203 FalseC->getValueType(0), Cond);
11204 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11205 SDValue(FalseC, 0));
11208 // Optimize cases that will turn into an LEA instruction. This requires
11209 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11210 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11211 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11212 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11214 bool isFastMultiplier = false;
11216 switch ((unsigned char)Diff) {
11218 case 1: // result = add base, cond
11219 case 2: // result = lea base( , cond*2)
11220 case 3: // result = lea base(cond, cond*2)
11221 case 4: // result = lea base( , cond*4)
11222 case 5: // result = lea base(cond, cond*4)
11223 case 8: // result = lea base( , cond*8)
11224 case 9: // result = lea base(cond, cond*8)
11225 isFastMultiplier = true;
11230 if (isFastMultiplier) {
11231 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11232 if (NeedsCondInvert) // Invert the condition if needed.
11233 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11234 DAG.getConstant(1, Cond.getValueType()));
11236 // Zero extend the condition if needed.
11237 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11239 // Scale the condition by the difference.
11241 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11242 DAG.getConstant(Diff, Cond.getValueType()));
11244 // Add the base if non-zero.
11245 if (FalseC->getAPIntValue() != 0)
11246 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11247 SDValue(FalseC, 0));
11257 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11258 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11259 TargetLowering::DAGCombinerInfo &DCI) {
11260 DebugLoc DL = N->getDebugLoc();
11262 // If the flag operand isn't dead, don't touch this CMOV.
11263 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11266 // If this is a select between two integer constants, try to do some
11267 // optimizations. Note that the operands are ordered the opposite of SELECT
11269 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11270 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11271 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11272 // larger than FalseC (the false value).
11273 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11275 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11276 CC = X86::GetOppositeBranchCondition(CC);
11277 std::swap(TrueC, FalseC);
11280 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11281 // This is efficient for any integer data type (including i8/i16) and
11283 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11284 SDValue Cond = N->getOperand(3);
11285 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11286 DAG.getConstant(CC, MVT::i8), Cond);
11288 // Zero extend the condition if needed.
11289 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11291 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11292 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11293 DAG.getConstant(ShAmt, MVT::i8));
11294 if (N->getNumValues() == 2) // Dead flag value?
11295 return DCI.CombineTo(N, Cond, SDValue());
11299 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11300 // for any integer data type, including i8/i16.
11301 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11302 SDValue Cond = N->getOperand(3);
11303 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11304 DAG.getConstant(CC, MVT::i8), Cond);
11306 // Zero extend the condition if needed.
11307 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11308 FalseC->getValueType(0), Cond);
11309 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11310 SDValue(FalseC, 0));
11312 if (N->getNumValues() == 2) // Dead flag value?
11313 return DCI.CombineTo(N, Cond, SDValue());
11317 // Optimize cases that will turn into an LEA instruction. This requires
11318 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11319 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11320 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11321 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11323 bool isFastMultiplier = false;
11325 switch ((unsigned char)Diff) {
11327 case 1: // result = add base, cond
11328 case 2: // result = lea base( , cond*2)
11329 case 3: // result = lea base(cond, cond*2)
11330 case 4: // result = lea base( , cond*4)
11331 case 5: // result = lea base(cond, cond*4)
11332 case 8: // result = lea base( , cond*8)
11333 case 9: // result = lea base(cond, cond*8)
11334 isFastMultiplier = true;
11339 if (isFastMultiplier) {
11340 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11341 SDValue Cond = N->getOperand(3);
11342 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11343 DAG.getConstant(CC, MVT::i8), Cond);
11344 // Zero extend the condition if needed.
11345 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11347 // Scale the condition by the difference.
11349 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11350 DAG.getConstant(Diff, Cond.getValueType()));
11352 // Add the base if non-zero.
11353 if (FalseC->getAPIntValue() != 0)
11354 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11355 SDValue(FalseC, 0));
11356 if (N->getNumValues() == 2) // Dead flag value?
11357 return DCI.CombineTo(N, Cond, SDValue());
11367 /// PerformMulCombine - Optimize a single multiply with constant into two
11368 /// in order to implement it with two cheaper instructions, e.g.
11369 /// LEA + SHL, LEA + LEA.
11370 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11371 TargetLowering::DAGCombinerInfo &DCI) {
11372 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11375 EVT VT = N->getValueType(0);
11376 if (VT != MVT::i64)
11379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11382 uint64_t MulAmt = C->getZExtValue();
11383 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11386 uint64_t MulAmt1 = 0;
11387 uint64_t MulAmt2 = 0;
11388 if ((MulAmt % 9) == 0) {
11390 MulAmt2 = MulAmt / 9;
11391 } else if ((MulAmt % 5) == 0) {
11393 MulAmt2 = MulAmt / 5;
11394 } else if ((MulAmt % 3) == 0) {
11396 MulAmt2 = MulAmt / 3;
11399 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11400 DebugLoc DL = N->getDebugLoc();
11402 if (isPowerOf2_64(MulAmt2) &&
11403 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11404 // If second multiplifer is pow2, issue it first. We want the multiply by
11405 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11407 std::swap(MulAmt1, MulAmt2);
11410 if (isPowerOf2_64(MulAmt1))
11411 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11412 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11414 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11415 DAG.getConstant(MulAmt1, VT));
11417 if (isPowerOf2_64(MulAmt2))
11418 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11419 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11421 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11422 DAG.getConstant(MulAmt2, VT));
11424 // Do not add new nodes to DAG combiner worklist.
11425 DCI.CombineTo(N, NewMul, false);
11430 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11431 SDValue N0 = N->getOperand(0);
11432 SDValue N1 = N->getOperand(1);
11433 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11434 EVT VT = N0.getValueType();
11436 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11437 // since the result of setcc_c is all zero's or all ones.
11438 if (N1C && N0.getOpcode() == ISD::AND &&
11439 N0.getOperand(1).getOpcode() == ISD::Constant) {
11440 SDValue N00 = N0.getOperand(0);
11441 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11442 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11443 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11444 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11445 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11446 APInt ShAmt = N1C->getAPIntValue();
11447 Mask = Mask.shl(ShAmt);
11449 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11450 N00, DAG.getConstant(Mask, VT));
11457 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11459 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11460 const X86Subtarget *Subtarget) {
11461 EVT VT = N->getValueType(0);
11462 if (!VT.isVector() && VT.isInteger() &&
11463 N->getOpcode() == ISD::SHL)
11464 return PerformSHLCombine(N, DAG);
11466 // On X86 with SSE2 support, we can transform this to a vector shift if
11467 // all elements are shifted by the same amount. We can't do this in legalize
11468 // because the a constant vector is typically transformed to a constant pool
11469 // so we have no knowledge of the shift amount.
11470 if (!Subtarget->hasSSE2())
11473 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11476 SDValue ShAmtOp = N->getOperand(1);
11477 EVT EltVT = VT.getVectorElementType();
11478 DebugLoc DL = N->getDebugLoc();
11479 SDValue BaseShAmt = SDValue();
11480 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11481 unsigned NumElts = VT.getVectorNumElements();
11483 for (; i != NumElts; ++i) {
11484 SDValue Arg = ShAmtOp.getOperand(i);
11485 if (Arg.getOpcode() == ISD::UNDEF) continue;
11489 for (; i != NumElts; ++i) {
11490 SDValue Arg = ShAmtOp.getOperand(i);
11491 if (Arg.getOpcode() == ISD::UNDEF) continue;
11492 if (Arg != BaseShAmt) {
11496 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11497 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11498 SDValue InVec = ShAmtOp.getOperand(0);
11499 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11500 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11502 for (; i != NumElts; ++i) {
11503 SDValue Arg = InVec.getOperand(i);
11504 if (Arg.getOpcode() == ISD::UNDEF) continue;
11508 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11510 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11511 if (C->getZExtValue() == SplatIdx)
11512 BaseShAmt = InVec.getOperand(1);
11515 if (BaseShAmt.getNode() == 0)
11516 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11517 DAG.getIntPtrConstant(0));
11521 // The shift amount is an i32.
11522 if (EltVT.bitsGT(MVT::i32))
11523 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11524 else if (EltVT.bitsLT(MVT::i32))
11525 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11527 // The shift amount is identical so we can do a vector shift.
11528 SDValue ValOp = N->getOperand(0);
11529 switch (N->getOpcode()) {
11531 llvm_unreachable("Unknown shift opcode!");
11534 if (VT == MVT::v2i64)
11535 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11536 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11538 if (VT == MVT::v4i32)
11539 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11540 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11542 if (VT == MVT::v8i16)
11543 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11544 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11548 if (VT == MVT::v4i32)
11549 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11550 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11552 if (VT == MVT::v8i16)
11553 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11554 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11558 if (VT == MVT::v2i64)
11559 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11560 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11562 if (VT == MVT::v4i32)
11563 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11564 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11566 if (VT == MVT::v8i16)
11567 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11568 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11576 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11577 TargetLowering::DAGCombinerInfo &DCI,
11578 const X86Subtarget *Subtarget) {
11579 if (DCI.isBeforeLegalizeOps())
11582 // Want to form PANDN nodes, in the hopes of then easily combining them with
11583 // OR and AND nodes to form PBLEND/PSIGN.
11584 EVT VT = N->getValueType(0);
11585 if (VT != MVT::v2i64)
11588 SDValue N0 = N->getOperand(0);
11589 SDValue N1 = N->getOperand(1);
11590 DebugLoc DL = N->getDebugLoc();
11592 // Check LHS for vnot
11593 if (N0.getOpcode() == ISD::XOR &&
11594 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11595 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11597 // Check RHS for vnot
11598 if (N1.getOpcode() == ISD::XOR &&
11599 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11600 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11605 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11606 TargetLowering::DAGCombinerInfo &DCI,
11607 const X86Subtarget *Subtarget) {
11608 if (DCI.isBeforeLegalizeOps())
11611 EVT VT = N->getValueType(0);
11612 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11615 SDValue N0 = N->getOperand(0);
11616 SDValue N1 = N->getOperand(1);
11618 // look for psign/blend
11619 if (Subtarget->hasSSSE3()) {
11620 if (VT == MVT::v2i64) {
11621 // Canonicalize pandn to RHS
11622 if (N0.getOpcode() == X86ISD::PANDN)
11624 // or (and (m, x), (pandn m, y))
11625 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11626 SDValue Mask = N1.getOperand(0);
11627 SDValue X = N1.getOperand(1);
11629 if (N0.getOperand(0) == Mask)
11630 Y = N0.getOperand(1);
11631 if (N0.getOperand(1) == Mask)
11632 Y = N0.getOperand(0);
11634 // Check to see if the mask appeared in both the AND and PANDN and
11638 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11639 if (Mask.getOpcode() != ISD::BITCAST ||
11640 X.getOpcode() != ISD::BITCAST ||
11641 Y.getOpcode() != ISD::BITCAST)
11644 // Look through mask bitcast.
11645 Mask = Mask.getOperand(0);
11646 EVT MaskVT = Mask.getValueType();
11648 // Validate that the Mask operand is a vector sra node. The sra node
11649 // will be an intrinsic.
11650 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11653 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11654 // there is no psrai.b
11655 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11656 case Intrinsic::x86_sse2_psrai_w:
11657 case Intrinsic::x86_sse2_psrai_d:
11659 default: return SDValue();
11662 // Check that the SRA is all signbits.
11663 SDValue SraC = Mask.getOperand(2);
11664 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11665 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11666 if ((SraAmt + 1) != EltBits)
11669 DebugLoc DL = N->getDebugLoc();
11671 // Now we know we at least have a plendvb with the mask val. See if
11672 // we can form a psignb/w/d.
11673 // psign = x.type == y.type == mask.type && y = sub(0, x);
11674 X = X.getOperand(0);
11675 Y = Y.getOperand(0);
11676 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11677 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11678 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11681 case 8: Opc = X86ISD::PSIGNB; break;
11682 case 16: Opc = X86ISD::PSIGNW; break;
11683 case 32: Opc = X86ISD::PSIGND; break;
11687 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11688 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11691 // PBLENDVB only available on SSE 4.1
11692 if (!Subtarget->hasSSE41())
11695 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11696 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11697 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11698 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11699 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11704 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11705 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11707 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11709 if (!N0.hasOneUse() || !N1.hasOneUse())
11712 SDValue ShAmt0 = N0.getOperand(1);
11713 if (ShAmt0.getValueType() != MVT::i8)
11715 SDValue ShAmt1 = N1.getOperand(1);
11716 if (ShAmt1.getValueType() != MVT::i8)
11718 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11719 ShAmt0 = ShAmt0.getOperand(0);
11720 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11721 ShAmt1 = ShAmt1.getOperand(0);
11723 DebugLoc DL = N->getDebugLoc();
11724 unsigned Opc = X86ISD::SHLD;
11725 SDValue Op0 = N0.getOperand(0);
11726 SDValue Op1 = N1.getOperand(0);
11727 if (ShAmt0.getOpcode() == ISD::SUB) {
11728 Opc = X86ISD::SHRD;
11729 std::swap(Op0, Op1);
11730 std::swap(ShAmt0, ShAmt1);
11733 unsigned Bits = VT.getSizeInBits();
11734 if (ShAmt1.getOpcode() == ISD::SUB) {
11735 SDValue Sum = ShAmt1.getOperand(0);
11736 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11737 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11738 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11739 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11740 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11741 return DAG.getNode(Opc, DL, VT,
11743 DAG.getNode(ISD::TRUNCATE, DL,
11746 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11747 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11749 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11750 return DAG.getNode(Opc, DL, VT,
11751 N0.getOperand(0), N1.getOperand(0),
11752 DAG.getNode(ISD::TRUNCATE, DL,
11759 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11760 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11761 const X86Subtarget *Subtarget) {
11762 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11763 // the FP state in cases where an emms may be missing.
11764 // A preferable solution to the general problem is to figure out the right
11765 // places to insert EMMS. This qualifies as a quick hack.
11767 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11768 StoreSDNode *St = cast<StoreSDNode>(N);
11769 EVT VT = St->getValue().getValueType();
11770 if (VT.getSizeInBits() != 64)
11773 const Function *F = DAG.getMachineFunction().getFunction();
11774 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11775 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11776 && Subtarget->hasSSE2();
11777 if ((VT.isVector() ||
11778 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11779 isa<LoadSDNode>(St->getValue()) &&
11780 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11781 St->getChain().hasOneUse() && !St->isVolatile()) {
11782 SDNode* LdVal = St->getValue().getNode();
11783 LoadSDNode *Ld = 0;
11784 int TokenFactorIndex = -1;
11785 SmallVector<SDValue, 8> Ops;
11786 SDNode* ChainVal = St->getChain().getNode();
11787 // Must be a store of a load. We currently handle two cases: the load
11788 // is a direct child, and it's under an intervening TokenFactor. It is
11789 // possible to dig deeper under nested TokenFactors.
11790 if (ChainVal == LdVal)
11791 Ld = cast<LoadSDNode>(St->getChain());
11792 else if (St->getValue().hasOneUse() &&
11793 ChainVal->getOpcode() == ISD::TokenFactor) {
11794 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11795 if (ChainVal->getOperand(i).getNode() == LdVal) {
11796 TokenFactorIndex = i;
11797 Ld = cast<LoadSDNode>(St->getValue());
11799 Ops.push_back(ChainVal->getOperand(i));
11803 if (!Ld || !ISD::isNormalLoad(Ld))
11806 // If this is not the MMX case, i.e. we are just turning i64 load/store
11807 // into f64 load/store, avoid the transformation if there are multiple
11808 // uses of the loaded value.
11809 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11812 DebugLoc LdDL = Ld->getDebugLoc();
11813 DebugLoc StDL = N->getDebugLoc();
11814 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11815 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11817 if (Subtarget->is64Bit() || F64IsLegal) {
11818 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11819 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11820 Ld->getPointerInfo(), Ld->isVolatile(),
11821 Ld->isNonTemporal(), Ld->getAlignment());
11822 SDValue NewChain = NewLd.getValue(1);
11823 if (TokenFactorIndex != -1) {
11824 Ops.push_back(NewChain);
11825 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11828 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11829 St->getPointerInfo(),
11830 St->isVolatile(), St->isNonTemporal(),
11831 St->getAlignment());
11834 // Otherwise, lower to two pairs of 32-bit loads / stores.
11835 SDValue LoAddr = Ld->getBasePtr();
11836 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11837 DAG.getConstant(4, MVT::i32));
11839 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11840 Ld->getPointerInfo(),
11841 Ld->isVolatile(), Ld->isNonTemporal(),
11842 Ld->getAlignment());
11843 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11844 Ld->getPointerInfo().getWithOffset(4),
11845 Ld->isVolatile(), Ld->isNonTemporal(),
11846 MinAlign(Ld->getAlignment(), 4));
11848 SDValue NewChain = LoLd.getValue(1);
11849 if (TokenFactorIndex != -1) {
11850 Ops.push_back(LoLd);
11851 Ops.push_back(HiLd);
11852 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11856 LoAddr = St->getBasePtr();
11857 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11858 DAG.getConstant(4, MVT::i32));
11860 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11861 St->getPointerInfo(),
11862 St->isVolatile(), St->isNonTemporal(),
11863 St->getAlignment());
11864 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11865 St->getPointerInfo().getWithOffset(4),
11867 St->isNonTemporal(),
11868 MinAlign(St->getAlignment(), 4));
11869 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11874 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11875 /// X86ISD::FXOR nodes.
11876 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11877 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11878 // F[X]OR(0.0, x) -> x
11879 // F[X]OR(x, 0.0) -> x
11880 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11881 if (C->getValueAPF().isPosZero())
11882 return N->getOperand(1);
11883 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11884 if (C->getValueAPF().isPosZero())
11885 return N->getOperand(0);
11889 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11890 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11891 // FAND(0.0, x) -> 0.0
11892 // FAND(x, 0.0) -> 0.0
11893 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11894 if (C->getValueAPF().isPosZero())
11895 return N->getOperand(0);
11896 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11897 if (C->getValueAPF().isPosZero())
11898 return N->getOperand(1);
11902 static SDValue PerformBTCombine(SDNode *N,
11904 TargetLowering::DAGCombinerInfo &DCI) {
11905 // BT ignores high bits in the bit index operand.
11906 SDValue Op1 = N->getOperand(1);
11907 if (Op1.hasOneUse()) {
11908 unsigned BitWidth = Op1.getValueSizeInBits();
11909 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11910 APInt KnownZero, KnownOne;
11911 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11912 !DCI.isBeforeLegalizeOps());
11913 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11914 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11915 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11916 DCI.CommitTargetLoweringOpt(TLO);
11921 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11922 SDValue Op = N->getOperand(0);
11923 if (Op.getOpcode() == ISD::BITCAST)
11924 Op = Op.getOperand(0);
11925 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11926 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11927 VT.getVectorElementType().getSizeInBits() ==
11928 OpVT.getVectorElementType().getSizeInBits()) {
11929 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11934 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11935 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11936 // (and (i32 x86isd::setcc_carry), 1)
11937 // This eliminates the zext. This transformation is necessary because
11938 // ISD::SETCC is always legalized to i8.
11939 DebugLoc dl = N->getDebugLoc();
11940 SDValue N0 = N->getOperand(0);
11941 EVT VT = N->getValueType(0);
11942 if (N0.getOpcode() == ISD::AND &&
11944 N0.getOperand(0).hasOneUse()) {
11945 SDValue N00 = N0.getOperand(0);
11946 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11948 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11949 if (!C || C->getZExtValue() != 1)
11951 return DAG.getNode(ISD::AND, dl, VT,
11952 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11953 N00.getOperand(0), N00.getOperand(1)),
11954 DAG.getConstant(1, VT));
11960 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11961 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11962 unsigned X86CC = N->getConstantOperandVal(0);
11963 SDValue EFLAG = N->getOperand(1);
11964 DebugLoc DL = N->getDebugLoc();
11966 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11967 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11969 if (X86CC == X86::COND_B)
11970 return DAG.getNode(ISD::AND, DL, MVT::i8,
11971 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11972 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11973 DAG.getConstant(1, MVT::i8));
11978 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11979 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11980 X86TargetLowering::DAGCombinerInfo &DCI) {
11981 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11982 // the result is either zero or one (depending on the input carry bit).
11983 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11984 if (X86::isZeroNode(N->getOperand(0)) &&
11985 X86::isZeroNode(N->getOperand(1)) &&
11986 // We don't have a good way to replace an EFLAGS use, so only do this when
11988 SDValue(N, 1).use_empty()) {
11989 DebugLoc DL = N->getDebugLoc();
11990 EVT VT = N->getValueType(0);
11991 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11992 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11993 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11994 DAG.getConstant(X86::COND_B,MVT::i8),
11996 DAG.getConstant(1, VT));
11997 return DCI.CombineTo(N, Res1, CarryOut);
12003 // fold (add Y, (sete X, 0)) -> adc 0, Y
12004 // (add Y, (setne X, 0)) -> sbb -1, Y
12005 // (sub (sete X, 0), Y) -> sbb 0, Y
12006 // (sub (setne X, 0), Y) -> adc -1, Y
12007 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12008 DebugLoc DL = N->getDebugLoc();
12010 // Look through ZExts.
12011 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12012 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12015 SDValue SetCC = Ext.getOperand(0);
12016 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12019 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12020 if (CC != X86::COND_E && CC != X86::COND_NE)
12023 SDValue Cmp = SetCC.getOperand(1);
12024 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12025 !X86::isZeroNode(Cmp.getOperand(1)) ||
12026 !Cmp.getOperand(0).getValueType().isInteger())
12029 SDValue CmpOp0 = Cmp.getOperand(0);
12030 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12031 DAG.getConstant(1, CmpOp0.getValueType()));
12033 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12034 if (CC == X86::COND_NE)
12035 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12036 DL, OtherVal.getValueType(), OtherVal,
12037 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12038 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12039 DL, OtherVal.getValueType(), OtherVal,
12040 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12043 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12044 DAGCombinerInfo &DCI) const {
12045 SelectionDAG &DAG = DCI.DAG;
12046 switch (N->getOpcode()) {
12048 case ISD::EXTRACT_VECTOR_ELT:
12049 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12050 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12051 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12053 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12054 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12055 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12058 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12059 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12060 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12061 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12063 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12064 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12065 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12066 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12067 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12068 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12069 case X86ISD::SHUFPS: // Handle all target specific shuffles
12070 case X86ISD::SHUFPD:
12071 case X86ISD::PALIGN:
12072 case X86ISD::PUNPCKHBW:
12073 case X86ISD::PUNPCKHWD:
12074 case X86ISD::PUNPCKHDQ:
12075 case X86ISD::PUNPCKHQDQ:
12076 case X86ISD::UNPCKHPS:
12077 case X86ISD::UNPCKHPD:
12078 case X86ISD::PUNPCKLBW:
12079 case X86ISD::PUNPCKLWD:
12080 case X86ISD::PUNPCKLDQ:
12081 case X86ISD::PUNPCKLQDQ:
12082 case X86ISD::UNPCKLPS:
12083 case X86ISD::UNPCKLPD:
12084 case X86ISD::VUNPCKLPS:
12085 case X86ISD::VUNPCKLPD:
12086 case X86ISD::VUNPCKLPSY:
12087 case X86ISD::VUNPCKLPDY:
12088 case X86ISD::MOVHLPS:
12089 case X86ISD::MOVLHPS:
12090 case X86ISD::PSHUFD:
12091 case X86ISD::PSHUFHW:
12092 case X86ISD::PSHUFLW:
12093 case X86ISD::MOVSS:
12094 case X86ISD::MOVSD:
12095 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12101 /// isTypeDesirableForOp - Return true if the target has native support for
12102 /// the specified value type and it is 'desirable' to use the type for the
12103 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12104 /// instruction encodings are longer and some i16 instructions are slow.
12105 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12106 if (!isTypeLegal(VT))
12108 if (VT != MVT::i16)
12115 case ISD::SIGN_EXTEND:
12116 case ISD::ZERO_EXTEND:
12117 case ISD::ANY_EXTEND:
12130 /// IsDesirableToPromoteOp - This method query the target whether it is
12131 /// beneficial for dag combiner to promote the specified node. If true, it
12132 /// should return the desired promotion type by reference.
12133 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12134 EVT VT = Op.getValueType();
12135 if (VT != MVT::i16)
12138 bool Promote = false;
12139 bool Commute = false;
12140 switch (Op.getOpcode()) {
12143 LoadSDNode *LD = cast<LoadSDNode>(Op);
12144 // If the non-extending load has a single use and it's not live out, then it
12145 // might be folded.
12146 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12147 Op.hasOneUse()*/) {
12148 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12149 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12150 // The only case where we'd want to promote LOAD (rather then it being
12151 // promoted as an operand is when it's only use is liveout.
12152 if (UI->getOpcode() != ISD::CopyToReg)
12159 case ISD::SIGN_EXTEND:
12160 case ISD::ZERO_EXTEND:
12161 case ISD::ANY_EXTEND:
12166 SDValue N0 = Op.getOperand(0);
12167 // Look out for (store (shl (load), x)).
12168 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12181 SDValue N0 = Op.getOperand(0);
12182 SDValue N1 = Op.getOperand(1);
12183 if (!Commute && MayFoldLoad(N1))
12185 // Avoid disabling potential load folding opportunities.
12186 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12188 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12198 //===----------------------------------------------------------------------===//
12199 // X86 Inline Assembly Support
12200 //===----------------------------------------------------------------------===//
12202 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12203 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12205 std::string AsmStr = IA->getAsmString();
12207 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12208 SmallVector<StringRef, 4> AsmPieces;
12209 SplitString(AsmStr, AsmPieces, ";\n");
12211 switch (AsmPieces.size()) {
12212 default: return false;
12214 AsmStr = AsmPieces[0];
12216 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12218 // FIXME: this should verify that we are targetting a 486 or better. If not,
12219 // we will turn this bswap into something that will be lowered to logical ops
12220 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12221 // so don't worry about this.
12223 if (AsmPieces.size() == 2 &&
12224 (AsmPieces[0] == "bswap" ||
12225 AsmPieces[0] == "bswapq" ||
12226 AsmPieces[0] == "bswapl") &&
12227 (AsmPieces[1] == "$0" ||
12228 AsmPieces[1] == "${0:q}")) {
12229 // No need to check constraints, nothing other than the equivalent of
12230 // "=r,0" would be valid here.
12231 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12232 if (!Ty || Ty->getBitWidth() % 16 != 0)
12234 return IntrinsicLowering::LowerToByteSwap(CI);
12236 // rorw $$8, ${0:w} --> llvm.bswap.i16
12237 if (CI->getType()->isIntegerTy(16) &&
12238 AsmPieces.size() == 3 &&
12239 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12240 AsmPieces[1] == "$$8," &&
12241 AsmPieces[2] == "${0:w}" &&
12242 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12244 const std::string &ConstraintsStr = IA->getConstraintString();
12245 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12246 std::sort(AsmPieces.begin(), AsmPieces.end());
12247 if (AsmPieces.size() == 4 &&
12248 AsmPieces[0] == "~{cc}" &&
12249 AsmPieces[1] == "~{dirflag}" &&
12250 AsmPieces[2] == "~{flags}" &&
12251 AsmPieces[3] == "~{fpsr}") {
12252 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12253 if (!Ty || Ty->getBitWidth() % 16 != 0)
12255 return IntrinsicLowering::LowerToByteSwap(CI);
12260 if (CI->getType()->isIntegerTy(32) &&
12261 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12262 SmallVector<StringRef, 4> Words;
12263 SplitString(AsmPieces[0], Words, " \t,");
12264 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12265 Words[2] == "${0:w}") {
12267 SplitString(AsmPieces[1], Words, " \t,");
12268 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12269 Words[2] == "$0") {
12271 SplitString(AsmPieces[2], Words, " \t,");
12272 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12273 Words[2] == "${0:w}") {
12275 const std::string &ConstraintsStr = IA->getConstraintString();
12276 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12277 std::sort(AsmPieces.begin(), AsmPieces.end());
12278 if (AsmPieces.size() == 4 &&
12279 AsmPieces[0] == "~{cc}" &&
12280 AsmPieces[1] == "~{dirflag}" &&
12281 AsmPieces[2] == "~{flags}" &&
12282 AsmPieces[3] == "~{fpsr}") {
12283 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12284 if (!Ty || Ty->getBitWidth() % 16 != 0)
12286 return IntrinsicLowering::LowerToByteSwap(CI);
12293 if (CI->getType()->isIntegerTy(64)) {
12294 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12295 if (Constraints.size() >= 2 &&
12296 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12297 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12298 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12299 SmallVector<StringRef, 4> Words;
12300 SplitString(AsmPieces[0], Words, " \t");
12301 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12303 SplitString(AsmPieces[1], Words, " \t");
12304 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12306 SplitString(AsmPieces[2], Words, " \t,");
12307 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12308 Words[2] == "%edx") {
12309 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12310 if (!Ty || Ty->getBitWidth() % 16 != 0)
12312 return IntrinsicLowering::LowerToByteSwap(CI);
12325 /// getConstraintType - Given a constraint letter, return the type of
12326 /// constraint it is for this target.
12327 X86TargetLowering::ConstraintType
12328 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12329 if (Constraint.size() == 1) {
12330 switch (Constraint[0]) {
12340 return C_RegisterClass;
12364 return TargetLowering::getConstraintType(Constraint);
12367 /// Examine constraint type and operand type and determine a weight value.
12368 /// This object must already have been set up with the operand type
12369 /// and the current alternative constraint selected.
12370 TargetLowering::ConstraintWeight
12371 X86TargetLowering::getSingleConstraintMatchWeight(
12372 AsmOperandInfo &info, const char *constraint) const {
12373 ConstraintWeight weight = CW_Invalid;
12374 Value *CallOperandVal = info.CallOperandVal;
12375 // If we don't have a value, we can't do a match,
12376 // but allow it at the lowest weight.
12377 if (CallOperandVal == NULL)
12379 const Type *type = CallOperandVal->getType();
12380 // Look at the constraint type.
12381 switch (*constraint) {
12383 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12394 if (CallOperandVal->getType()->isIntegerTy())
12395 weight = CW_SpecificReg;
12400 if (type->isFloatingPointTy())
12401 weight = CW_SpecificReg;
12404 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12405 weight = CW_SpecificReg;
12409 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12410 weight = CW_Register;
12413 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12414 if (C->getZExtValue() <= 31)
12415 weight = CW_Constant;
12419 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12420 if (C->getZExtValue() <= 63)
12421 weight = CW_Constant;
12425 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12426 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12427 weight = CW_Constant;
12431 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12432 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12433 weight = CW_Constant;
12437 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12438 if (C->getZExtValue() <= 3)
12439 weight = CW_Constant;
12443 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12444 if (C->getZExtValue() <= 0xff)
12445 weight = CW_Constant;
12450 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12451 weight = CW_Constant;
12455 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12456 if ((C->getSExtValue() >= -0x80000000LL) &&
12457 (C->getSExtValue() <= 0x7fffffffLL))
12458 weight = CW_Constant;
12462 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12463 if (C->getZExtValue() <= 0xffffffff)
12464 weight = CW_Constant;
12471 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12472 /// with another that has more specific requirements based on the type of the
12473 /// corresponding operand.
12474 const char *X86TargetLowering::
12475 LowerXConstraint(EVT ConstraintVT) const {
12476 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12477 // 'f' like normal targets.
12478 if (ConstraintVT.isFloatingPoint()) {
12479 if (Subtarget->hasXMMInt())
12481 if (Subtarget->hasXMM())
12485 return TargetLowering::LowerXConstraint(ConstraintVT);
12488 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12489 /// vector. If it is invalid, don't add anything to Ops.
12490 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12492 std::vector<SDValue>&Ops,
12493 SelectionDAG &DAG) const {
12494 SDValue Result(0, 0);
12496 switch (Constraint) {
12499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12500 if (C->getZExtValue() <= 31) {
12501 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12507 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12508 if (C->getZExtValue() <= 63) {
12509 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12516 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12517 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12524 if (C->getZExtValue() <= 255) {
12525 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12531 // 32-bit signed value
12532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12533 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12534 C->getSExtValue())) {
12535 // Widen to 64 bits here to get it sign extended.
12536 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12539 // FIXME gcc accepts some relocatable values here too, but only in certain
12540 // memory models; it's complicated.
12545 // 32-bit unsigned value
12546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12547 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12548 C->getZExtValue())) {
12549 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12553 // FIXME gcc accepts some relocatable values here too, but only in certain
12554 // memory models; it's complicated.
12558 // Literal immediates are always ok.
12559 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12560 // Widen to 64 bits here to get it sign extended.
12561 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12565 // In any sort of PIC mode addresses need to be computed at runtime by
12566 // adding in a register or some sort of table lookup. These can't
12567 // be used as immediates.
12568 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12571 // If we are in non-pic codegen mode, we allow the address of a global (with
12572 // an optional displacement) to be used with 'i'.
12573 GlobalAddressSDNode *GA = 0;
12574 int64_t Offset = 0;
12576 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12578 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12579 Offset += GA->getOffset();
12581 } else if (Op.getOpcode() == ISD::ADD) {
12582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12583 Offset += C->getZExtValue();
12584 Op = Op.getOperand(0);
12587 } else if (Op.getOpcode() == ISD::SUB) {
12588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12589 Offset += -C->getZExtValue();
12590 Op = Op.getOperand(0);
12595 // Otherwise, this isn't something we can handle, reject it.
12599 const GlobalValue *GV = GA->getGlobal();
12600 // If we require an extra load to get this address, as in PIC mode, we
12601 // can't accept it.
12602 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12603 getTargetMachine())))
12606 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12607 GA->getValueType(0), Offset);
12612 if (Result.getNode()) {
12613 Ops.push_back(Result);
12616 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12619 std::vector<unsigned> X86TargetLowering::
12620 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12622 if (Constraint.size() == 1) {
12623 // FIXME: not handling fp-stack yet!
12624 switch (Constraint[0]) { // GCC X86 Constraint Letters
12625 default: break; // Unknown constraint letter
12626 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12627 if (Subtarget->is64Bit()) {
12628 if (VT == MVT::i32)
12629 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12630 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12631 X86::R10D,X86::R11D,X86::R12D,
12632 X86::R13D,X86::R14D,X86::R15D,
12633 X86::EBP, X86::ESP, 0);
12634 else if (VT == MVT::i16)
12635 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12636 X86::SI, X86::DI, X86::R8W,X86::R9W,
12637 X86::R10W,X86::R11W,X86::R12W,
12638 X86::R13W,X86::R14W,X86::R15W,
12639 X86::BP, X86::SP, 0);
12640 else if (VT == MVT::i8)
12641 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12642 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12643 X86::R10B,X86::R11B,X86::R12B,
12644 X86::R13B,X86::R14B,X86::R15B,
12645 X86::BPL, X86::SPL, 0);
12647 else if (VT == MVT::i64)
12648 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12649 X86::RSI, X86::RDI, X86::R8, X86::R9,
12650 X86::R10, X86::R11, X86::R12,
12651 X86::R13, X86::R14, X86::R15,
12652 X86::RBP, X86::RSP, 0);
12656 // 32-bit fallthrough
12657 case 'Q': // Q_REGS
12658 if (VT == MVT::i32)
12659 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12660 else if (VT == MVT::i16)
12661 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12662 else if (VT == MVT::i8)
12663 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12664 else if (VT == MVT::i64)
12665 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12670 return std::vector<unsigned>();
12673 std::pair<unsigned, const TargetRegisterClass*>
12674 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12676 // First, see if this is a constraint that directly corresponds to an LLVM
12678 if (Constraint.size() == 1) {
12679 // GCC Constraint Letters
12680 switch (Constraint[0]) {
12682 case 'r': // GENERAL_REGS
12683 case 'l': // INDEX_REGS
12685 return std::make_pair(0U, X86::GR8RegisterClass);
12686 if (VT == MVT::i16)
12687 return std::make_pair(0U, X86::GR16RegisterClass);
12688 if (VT == MVT::i32 || !Subtarget->is64Bit())
12689 return std::make_pair(0U, X86::GR32RegisterClass);
12690 return std::make_pair(0U, X86::GR64RegisterClass);
12691 case 'R': // LEGACY_REGS
12693 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12694 if (VT == MVT::i16)
12695 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12696 if (VT == MVT::i32 || !Subtarget->is64Bit())
12697 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12698 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12699 case 'f': // FP Stack registers.
12700 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12701 // value to the correct fpstack register class.
12702 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12703 return std::make_pair(0U, X86::RFP32RegisterClass);
12704 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12705 return std::make_pair(0U, X86::RFP64RegisterClass);
12706 return std::make_pair(0U, X86::RFP80RegisterClass);
12707 case 'y': // MMX_REGS if MMX allowed.
12708 if (!Subtarget->hasMMX()) break;
12709 return std::make_pair(0U, X86::VR64RegisterClass);
12710 case 'Y': // SSE_REGS if SSE2 allowed
12711 if (!Subtarget->hasXMMInt()) break;
12713 case 'x': // SSE_REGS if SSE1 allowed
12714 if (!Subtarget->hasXMM()) break;
12716 switch (VT.getSimpleVT().SimpleTy) {
12718 // Scalar SSE types.
12721 return std::make_pair(0U, X86::FR32RegisterClass);
12724 return std::make_pair(0U, X86::FR64RegisterClass);
12732 return std::make_pair(0U, X86::VR128RegisterClass);
12738 // Use the default implementation in TargetLowering to convert the register
12739 // constraint into a member of a register class.
12740 std::pair<unsigned, const TargetRegisterClass*> Res;
12741 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12743 // Not found as a standard register?
12744 if (Res.second == 0) {
12745 // Map st(0) -> st(7) -> ST0
12746 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12747 tolower(Constraint[1]) == 's' &&
12748 tolower(Constraint[2]) == 't' &&
12749 Constraint[3] == '(' &&
12750 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12751 Constraint[5] == ')' &&
12752 Constraint[6] == '}') {
12754 Res.first = X86::ST0+Constraint[4]-'0';
12755 Res.second = X86::RFP80RegisterClass;
12759 // GCC allows "st(0)" to be called just plain "st".
12760 if (StringRef("{st}").equals_lower(Constraint)) {
12761 Res.first = X86::ST0;
12762 Res.second = X86::RFP80RegisterClass;
12767 if (StringRef("{flags}").equals_lower(Constraint)) {
12768 Res.first = X86::EFLAGS;
12769 Res.second = X86::CCRRegisterClass;
12773 // 'A' means EAX + EDX.
12774 if (Constraint == "A") {
12775 Res.first = X86::EAX;
12776 Res.second = X86::GR32_ADRegisterClass;
12782 // Otherwise, check to see if this is a register class of the wrong value
12783 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12784 // turn into {ax},{dx}.
12785 if (Res.second->hasType(VT))
12786 return Res; // Correct type already, nothing to do.
12788 // All of the single-register GCC register classes map their values onto
12789 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12790 // really want an 8-bit or 32-bit register, map to the appropriate register
12791 // class and return the appropriate register.
12792 if (Res.second == X86::GR16RegisterClass) {
12793 if (VT == MVT::i8) {
12794 unsigned DestReg = 0;
12795 switch (Res.first) {
12797 case X86::AX: DestReg = X86::AL; break;
12798 case X86::DX: DestReg = X86::DL; break;
12799 case X86::CX: DestReg = X86::CL; break;
12800 case X86::BX: DestReg = X86::BL; break;
12803 Res.first = DestReg;
12804 Res.second = X86::GR8RegisterClass;
12806 } else if (VT == MVT::i32) {
12807 unsigned DestReg = 0;
12808 switch (Res.first) {
12810 case X86::AX: DestReg = X86::EAX; break;
12811 case X86::DX: DestReg = X86::EDX; break;
12812 case X86::CX: DestReg = X86::ECX; break;
12813 case X86::BX: DestReg = X86::EBX; break;
12814 case X86::SI: DestReg = X86::ESI; break;
12815 case X86::DI: DestReg = X86::EDI; break;
12816 case X86::BP: DestReg = X86::EBP; break;
12817 case X86::SP: DestReg = X86::ESP; break;
12820 Res.first = DestReg;
12821 Res.second = X86::GR32RegisterClass;
12823 } else if (VT == MVT::i64) {
12824 unsigned DestReg = 0;
12825 switch (Res.first) {
12827 case X86::AX: DestReg = X86::RAX; break;
12828 case X86::DX: DestReg = X86::RDX; break;
12829 case X86::CX: DestReg = X86::RCX; break;
12830 case X86::BX: DestReg = X86::RBX; break;
12831 case X86::SI: DestReg = X86::RSI; break;
12832 case X86::DI: DestReg = X86::RDI; break;
12833 case X86::BP: DestReg = X86::RBP; break;
12834 case X86::SP: DestReg = X86::RSP; break;
12837 Res.first = DestReg;
12838 Res.second = X86::GR64RegisterClass;
12841 } else if (Res.second == X86::FR32RegisterClass ||
12842 Res.second == X86::FR64RegisterClass ||
12843 Res.second == X86::VR128RegisterClass) {
12844 // Handle references to XMM physical registers that got mapped into the
12845 // wrong class. This can happen with constraints like {xmm0} where the
12846 // target independent register mapper will just pick the first match it can
12847 // find, ignoring the required type.
12848 if (VT == MVT::f32)
12849 Res.second = X86::FR32RegisterClass;
12850 else if (VT == MVT::f64)
12851 Res.second = X86::FR64RegisterClass;
12852 else if (X86::VR128RegisterClass->hasType(VT))
12853 Res.second = X86::VR128RegisterClass;