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/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static SDValue Insert128BitVector(SDValue Result,
68 static SDValue Extract128BitVector(SDValue Vec,
73 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
76 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
77 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
78 /// simple subregister reference. Idx is an index in the 128 bits we
79 /// want. It need not be aligned to a 128-bit bounday. That makes
80 /// lowering EXTRACT_VECTOR_ELT operations easier.
81 static SDValue Extract128BitVector(SDValue Vec,
85 EVT VT = Vec.getValueType();
86 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88 EVT ElVT = VT.getVectorElementType();
90 int Factor = VT.getSizeInBits() / 128;
92 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94 VT.getVectorNumElements() / Factor);
96 // Extract from UNDEF is UNDEF.
97 if (Vec.getOpcode() == ISD::UNDEF)
98 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100 if (isa<ConstantSDNode>(Idx)) {
101 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
104 // we can match to VEXTRACTF128.
105 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107 // This is the index of the first element of the 128-bit chunk
109 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
112 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
123 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
124 /// sets things up to match to an AVX VINSERTF128 instruction or a
125 /// simple superregister reference. Idx is an index in the 128 bits
126 /// we want. It need not be aligned to a 128-bit bounday. That makes
127 /// lowering INSERT_VECTOR_ELT operations easier.
128 static SDValue Insert128BitVector(SDValue Result,
133 if (isa<ConstantSDNode>(Idx)) {
134 EVT VT = Vec.getValueType();
135 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137 EVT ElVT = VT.getVectorElementType();
139 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141 EVT ResultVT = Result.getValueType();
143 // Insert the relevant 128 bits.
144 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146 // This is the index of the first element of the 128-bit chunk
148 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
151 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
161 /// Given two vectors, concat them.
162 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
163 DebugLoc dl = Lower.getDebugLoc();
165 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167 EVT VT = EVT::getVectorVT(*DAG.getContext(),
168 Lower.getValueType().getVectorElementType(),
169 Lower.getValueType().getVectorNumElements() * 2);
171 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
172 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174 // Insert the upper subvector.
175 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177 // This is half the length of the result
178 // vector. Start inserting the upper 128
180 Lower.getValueType().getVectorNumElements(),
184 // Insert the lower subvector.
185 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
189 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
190 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
191 bool is64Bit = Subtarget->is64Bit();
193 if (Subtarget->isTargetEnvMacho()) {
195 return new X8664_MachoTargetObjectFile();
196 return new TargetLoweringObjectFileMachO();
199 if (Subtarget->isTargetELF()) {
201 return new X8664_ELFTargetObjectFile(TM);
202 return new X8632_ELFTargetObjectFile(TM);
204 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
205 return new TargetLoweringObjectFileCOFF();
206 llvm_unreachable("unknown subtarget type");
209 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
210 : TargetLowering(TM, createTLOF(TM)) {
211 Subtarget = &TM.getSubtarget<X86Subtarget>();
212 X86ScalarSSEf64 = Subtarget->hasXMMInt();
213 X86ScalarSSEf32 = Subtarget->hasXMM();
214 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216 RegInfo = TM.getRegisterInfo();
217 TD = getTargetData();
219 // Set up the TargetLowering object.
220 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222 // X86 is weird, it always uses i8 for shift amounts and setcc results.
223 setBooleanContents(ZeroOrOneBooleanContent);
225 // For 64-bit since we have so many registers use the ILP scheduler, for
226 // 32-bit code use the register pressure specific scheduling.
227 if (Subtarget->is64Bit())
228 setSchedulingPreference(Sched::ILP);
230 setSchedulingPreference(Sched::RegPressure);
231 setStackPointerRegisterToSaveRestore(X86StackPtr);
233 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
234 // Setup Windows compiler runtime calls.
235 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
236 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
237 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
238 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
239 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
240 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
241 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
242 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
245 if (Subtarget->isTargetDarwin()) {
246 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
247 setUseUnderscoreSetJmp(false);
248 setUseUnderscoreLongJmp(false);
249 } else if (Subtarget->isTargetMingw()) {
250 // MS runtime is weird: it exports _setjmp, but longjmp!
251 setUseUnderscoreSetJmp(true);
252 setUseUnderscoreLongJmp(false);
254 setUseUnderscoreSetJmp(true);
255 setUseUnderscoreLongJmp(true);
258 // Set up the register classes.
259 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
260 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
261 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
262 if (Subtarget->is64Bit())
263 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267 // We don't accept any truncstore of integer registers.
268 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
269 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
270 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
271 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
272 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
273 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
275 // SETOEQ and SETUNE require checking two conditions.
276 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
277 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
278 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
279 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
280 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
281 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
286 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
291 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
292 } else if (!UseSoftFloat) {
293 // We have an algorithm for SSE2->double, and we turn this into a
294 // 64-bit FILD followed by conditional FADD for other targets.
295 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
296 // We have an algorithm for SSE2, and we turn this into a 64-bit
297 // FILD for other targets.
298 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
301 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
304 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
307 // SSE has no i16 to fp conversion, only i32
308 if (X86ScalarSSEf32) {
309 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
310 // f32 and f64 cases are Legal, f80 case is not
311 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
313 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
317 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
321 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
322 // are Legal, f80 is custom lowered.
323 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
326 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
329 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
331 if (X86ScalarSSEf32) {
332 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
333 // f32 and f64 cases are Legal, f80 case is not
334 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
336 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
337 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
340 // Handle FP_TO_UINT by promoting the destination to a larger signed
342 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
343 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
346 if (Subtarget->is64Bit()) {
347 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
348 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
349 } else if (!UseSoftFloat) {
350 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
351 // Expand FP_TO_UINT into a select.
352 // FIXME: We would like to use a Custom expander here eventually to do
353 // the optimal thing for SSE vs. the default expansion in the legalizer.
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
356 // With SSE3 we can use fisttpll to convert to a signed i64; without
357 // SSE, we're stuck with a fistpll.
358 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
361 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
362 if (!X86ScalarSSEf64) {
363 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
364 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
365 if (Subtarget->is64Bit()) {
366 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
367 // Without SSE, i64->f64 goes through memory.
368 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
372 // Scalar integer divide and remainder are lowered to use operations that
373 // produce two results, to match the available instructions. This exposes
374 // the two-result form to trivial CSE, which is able to combine x/y and x%y
375 // into a single instruction.
377 // Scalar integer multiply-high is also lowered to use two-result
378 // operations, to match the available instructions. However, plain multiply
379 // (low) operations are left as Legal, as there are single-result
380 // instructions for this in x86. Using the two-result multiply instructions
381 // when both high and low results are needed must be arranged by dagcombine.
382 for (unsigned i = 0, e = 4; i != e; ++i) {
384 setOperationAction(ISD::MULHS, VT, Expand);
385 setOperationAction(ISD::MULHU, VT, Expand);
386 setOperationAction(ISD::SDIV, VT, Expand);
387 setOperationAction(ISD::UDIV, VT, Expand);
388 setOperationAction(ISD::SREM, VT, Expand);
389 setOperationAction(ISD::UREM, VT, Expand);
391 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
392 setOperationAction(ISD::ADDC, VT, Custom);
393 setOperationAction(ISD::ADDE, VT, Custom);
394 setOperationAction(ISD::SUBC, VT, Custom);
395 setOperationAction(ISD::SUBE, VT, Custom);
398 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
399 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
400 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
401 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
407 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
408 setOperationAction(ISD::FREM , MVT::f32 , Expand);
409 setOperationAction(ISD::FREM , MVT::f64 , Expand);
410 setOperationAction(ISD::FREM , MVT::f80 , Expand);
411 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
413 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
424 if (Subtarget->hasPOPCNT()) {
425 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
427 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
428 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
430 if (Subtarget->is64Bit())
431 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
434 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
435 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
437 // These should be promoted to a larger select which is supported.
438 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
439 // X86 wants to expand cmov itself.
440 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
441 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i64 , 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::i128 , 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 if (Subtarget->is64Bit())
554 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
555 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
556 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
558 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
560 if (!UseSoftFloat && X86ScalarSSEf64) {
561 // f32 and f64 use SSE.
562 // Set up the FP register classes.
563 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
564 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
566 // Use ANDPD to simulate FABS.
567 setOperationAction(ISD::FABS , MVT::f64, Custom);
568 setOperationAction(ISD::FABS , MVT::f32, Custom);
570 // Use XORP to simulate FNEG.
571 setOperationAction(ISD::FNEG , MVT::f64, Custom);
572 setOperationAction(ISD::FNEG , MVT::f32, Custom);
574 // Use ANDPD and ORPD to simulate FCOPYSIGN.
575 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
576 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
578 // We don't support sin/cos/fmod
579 setOperationAction(ISD::FSIN , MVT::f64, Expand);
580 setOperationAction(ISD::FCOS , MVT::f64, Expand);
581 setOperationAction(ISD::FSIN , MVT::f32, Expand);
582 setOperationAction(ISD::FCOS , MVT::f32, Expand);
584 // Expand FP immediates into loads from the stack, except for the special
586 addLegalFPImmediate(APFloat(+0.0)); // xorpd
587 addLegalFPImmediate(APFloat(+0.0f)); // xorps
588 } else if (!UseSoftFloat && X86ScalarSSEf32) {
589 // Use SSE for f32, x87 for f64.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
592 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
594 // Use ANDPS to simulate FABS.
595 setOperationAction(ISD::FABS , MVT::f32, Custom);
597 // Use XORP to simulate FNEG.
598 setOperationAction(ISD::FNEG , MVT::f32, Custom);
600 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
602 // Use ANDPS and ORPS to simulate FCOPYSIGN.
603 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
606 // We don't support sin/cos/fmod
607 setOperationAction(ISD::FSIN , MVT::f32, Expand);
608 setOperationAction(ISD::FCOS , MVT::f32, Expand);
610 // Special cases we handle for FP constants.
611 addLegalFPImmediate(APFloat(+0.0f)); // xorps
612 addLegalFPImmediate(APFloat(+0.0)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
619 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
621 } else if (!UseSoftFloat) {
622 // f32 and f64 in x87.
623 // Set up the FP register classes.
624 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
625 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
627 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
628 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
630 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
633 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
634 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
636 addLegalFPImmediate(APFloat(+0.0)); // FLD0
637 addLegalFPImmediate(APFloat(+1.0)); // FLD1
638 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
639 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
640 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
641 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
642 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
643 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
646 // Long double always uses X87.
648 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
649 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
650 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
652 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
653 addLegalFPImmediate(TmpFlt); // FLD0
655 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
658 APFloat TmpFlt2(+1.0);
659 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
661 addLegalFPImmediate(TmpFlt2); // FLD1
662 TmpFlt2.changeSign();
663 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
667 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
668 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
672 // Always use a library call for pow.
673 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
674 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
675 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
677 setOperationAction(ISD::FLOG, MVT::f80, Expand);
678 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
679 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
680 setOperationAction(ISD::FEXP, MVT::f80, Expand);
681 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
683 // First set operation action for all vector types to either promote
684 // (for widening) or expand (for scalarization). Then we will selectively
685 // turn on ones that can be effectively codegen'd.
686 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
687 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
688 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
706 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
738 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
742 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
743 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
744 setTruncStoreAction((MVT::SimpleValueType)VT,
745 (MVT::SimpleValueType)InnerVT, Expand);
746 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
748 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
751 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752 // with -msoft-float, disable use of MMX as well.
753 if (!UseSoftFloat && Subtarget->hasMMX()) {
754 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
755 // No operations on x86mmx supported, everything uses intrinsics.
758 // MMX-sized vectors (other than x86mmx) are expected to be expanded
759 // into smaller operations.
760 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
761 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
762 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
763 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
764 setOperationAction(ISD::AND, MVT::v8i8, Expand);
765 setOperationAction(ISD::AND, MVT::v4i16, Expand);
766 setOperationAction(ISD::AND, MVT::v2i32, Expand);
767 setOperationAction(ISD::AND, MVT::v1i64, Expand);
768 setOperationAction(ISD::OR, MVT::v8i8, Expand);
769 setOperationAction(ISD::OR, MVT::v4i16, Expand);
770 setOperationAction(ISD::OR, MVT::v2i32, Expand);
771 setOperationAction(ISD::OR, MVT::v1i64, Expand);
772 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
773 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
774 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
775 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
779 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
780 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
781 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
782 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
783 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
784 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
788 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
790 if (!UseSoftFloat && Subtarget->hasXMM()) {
791 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
793 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
794 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
795 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
796 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
798 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
799 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
800 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
801 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
802 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
803 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
804 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
807 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
808 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
810 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
811 // registers cannot be used even for integer operations.
812 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
815 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
817 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
818 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
819 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
820 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
821 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
822 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
823 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
824 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
825 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
826 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
827 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
828 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
829 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
830 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
831 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
832 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
834 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
835 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
836 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
837 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
840 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
849 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
851 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
852 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
853 EVT VT = (MVT::SimpleValueType)i;
854 // Do not attempt to custom lower non-power-of-2 vectors
855 if (!isPowerOf2_32(VT.getVectorNumElements()))
857 // Do not attempt to custom lower non-128-bit vectors
858 if (!VT.is128BitVector())
860 setOperationAction(ISD::BUILD_VECTOR,
861 VT.getSimpleVT().SimpleTy, Custom);
862 setOperationAction(ISD::VECTOR_SHUFFLE,
863 VT.getSimpleVT().SimpleTy, Custom);
864 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
865 VT.getSimpleVT().SimpleTy, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
869 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
871 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
872 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
873 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
875 if (Subtarget->is64Bit()) {
876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
877 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
880 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
881 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
882 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
885 // Do not attempt to promote non-128-bit vectors
886 if (!VT.is128BitVector())
889 setOperationAction(ISD::AND, SVT, Promote);
890 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
891 setOperationAction(ISD::OR, SVT, Promote);
892 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
893 setOperationAction(ISD::XOR, SVT, Promote);
894 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
895 setOperationAction(ISD::LOAD, SVT, Promote);
896 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
897 setOperationAction(ISD::SELECT, SVT, Promote);
898 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
901 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
903 // Custom lower v2i64 and v2f64 selects.
904 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
905 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
906 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
907 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
909 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
910 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
913 if (Subtarget->hasSSE41()) {
914 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
915 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
916 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
917 setOperationAction(ISD::FRINT, MVT::f32, Legal);
918 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
919 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
920 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
921 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
922 setOperationAction(ISD::FRINT, MVT::f64, Legal);
923 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
925 // FIXME: Do we need to handle scalar-to-vector here?
926 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
928 // Can turn SHL into an integer multiply.
929 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
930 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
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 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1599 /// a tailcall target by changing its ABI.
1600 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1601 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1605 X86TargetLowering::LowerMemArgument(SDValue Chain,
1606 CallingConv::ID CallConv,
1607 const SmallVectorImpl<ISD::InputArg> &Ins,
1608 DebugLoc dl, SelectionDAG &DAG,
1609 const CCValAssign &VA,
1610 MachineFrameInfo *MFI,
1612 // Create the nodes corresponding to a load from this parameter slot.
1613 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1614 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1615 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1618 // If value is passed by pointer we have address passed instead of the value
1620 if (VA.getLocInfo() == CCValAssign::Indirect)
1621 ValVT = VA.getLocVT();
1623 ValVT = VA.getValVT();
1625 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1626 // changed with more analysis.
1627 // In case of tail call optimization mark all arguments mutable. Since they
1628 // could be overwritten by lowering of arguments in case of a tail call.
1629 if (Flags.isByVal()) {
1630 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1631 VA.getLocMemOffset(), isImmutable);
1632 return DAG.getFrameIndex(FI, getPointerTy());
1634 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1635 VA.getLocMemOffset(), isImmutable);
1636 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1637 return DAG.getLoad(ValVT, dl, Chain, FIN,
1638 MachinePointerInfo::getFixedStack(FI),
1644 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1645 CallingConv::ID CallConv,
1647 const SmallVectorImpl<ISD::InputArg> &Ins,
1650 SmallVectorImpl<SDValue> &InVals)
1652 MachineFunction &MF = DAG.getMachineFunction();
1653 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1655 const Function* Fn = MF.getFunction();
1656 if (Fn->hasExternalLinkage() &&
1657 Subtarget->isTargetCygMing() &&
1658 Fn->getName() == "main")
1659 FuncInfo->setForceFramePointer(true);
1661 MachineFrameInfo *MFI = MF.getFrameInfo();
1662 bool Is64Bit = Subtarget->is64Bit();
1663 bool IsWin64 = Subtarget->isTargetWin64();
1665 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1666 "Var args not supported with calling convention fastcc or ghc");
1668 // Assign locations to all of the incoming arguments.
1669 SmallVector<CCValAssign, 16> ArgLocs;
1670 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1671 ArgLocs, *DAG.getContext());
1673 // Allocate shadow area for Win64
1675 CCInfo.AllocateStack(32, 8);
1678 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1680 unsigned LastVal = ~0U;
1682 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1683 CCValAssign &VA = ArgLocs[i];
1684 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1686 assert(VA.getValNo() != LastVal &&
1687 "Don't support value assigned to multiple locs yet");
1688 LastVal = VA.getValNo();
1690 if (VA.isRegLoc()) {
1691 EVT RegVT = VA.getLocVT();
1692 TargetRegisterClass *RC = NULL;
1693 if (RegVT == MVT::i32)
1694 RC = X86::GR32RegisterClass;
1695 else if (Is64Bit && RegVT == MVT::i64)
1696 RC = X86::GR64RegisterClass;
1697 else if (RegVT == MVT::f32)
1698 RC = X86::FR32RegisterClass;
1699 else if (RegVT == MVT::f64)
1700 RC = X86::FR64RegisterClass;
1701 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1702 RC = X86::VR256RegisterClass;
1703 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1704 RC = X86::VR128RegisterClass;
1705 else if (RegVT == MVT::x86mmx)
1706 RC = X86::VR64RegisterClass;
1708 llvm_unreachable("Unknown argument type!");
1710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1711 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1713 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1714 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1716 if (VA.getLocInfo() == CCValAssign::SExt)
1717 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1718 DAG.getValueType(VA.getValVT()));
1719 else if (VA.getLocInfo() == CCValAssign::ZExt)
1720 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1721 DAG.getValueType(VA.getValVT()));
1722 else if (VA.getLocInfo() == CCValAssign::BCvt)
1723 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1725 if (VA.isExtInLoc()) {
1726 // Handle MMX values passed in XMM regs.
1727 if (RegVT.isVector()) {
1728 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1731 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1734 assert(VA.isMemLoc());
1735 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1738 // If value is passed via pointer - do a load.
1739 if (VA.getLocInfo() == CCValAssign::Indirect)
1740 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1741 MachinePointerInfo(), false, false, 0);
1743 InVals.push_back(ArgValue);
1746 // The x86-64 ABI for returning structs by value requires that we copy
1747 // the sret argument into %rax for the return. Save the argument into
1748 // a virtual register so that we can access it from the return points.
1749 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1750 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1751 unsigned Reg = FuncInfo->getSRetReturnReg();
1753 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1754 FuncInfo->setSRetReturnReg(Reg);
1756 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1760 unsigned StackSize = CCInfo.getNextStackOffset();
1761 // Align stack specially for tail calls.
1762 if (FuncIsMadeTailCallSafe(CallConv))
1763 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1765 // If the function takes variable number of arguments, make a frame index for
1766 // the start of the first vararg value... for expansion of llvm.va_start.
1768 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1769 CallConv != CallingConv::X86_ThisCall)) {
1770 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1773 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1775 // FIXME: We should really autogenerate these arrays
1776 static const unsigned GPR64ArgRegsWin64[] = {
1777 X86::RCX, X86::RDX, X86::R8, X86::R9
1779 static const unsigned GPR64ArgRegs64Bit[] = {
1780 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1782 static const unsigned XMMArgRegs64Bit[] = {
1783 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1784 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1786 const unsigned *GPR64ArgRegs;
1787 unsigned NumXMMRegs = 0;
1790 // The XMM registers which might contain var arg parameters are shadowed
1791 // in their paired GPR. So we only need to save the GPR to their home
1793 TotalNumIntRegs = 4;
1794 GPR64ArgRegs = GPR64ArgRegsWin64;
1796 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1797 GPR64ArgRegs = GPR64ArgRegs64Bit;
1799 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1801 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1804 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1805 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1806 "SSE register cannot be used when SSE is disabled!");
1807 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1808 "SSE register cannot be used when SSE is disabled!");
1809 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1810 // Kernel mode asks for SSE to be disabled, so don't push them
1812 TotalNumXMMRegs = 0;
1815 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1816 // Get to the caller-allocated home save location. Add 8 to account
1817 // for the return address.
1818 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1819 FuncInfo->setRegSaveFrameIndex(
1820 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1821 // Fixup to set vararg frame on shadow area (4 x i64).
1823 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1825 // For X86-64, if there are vararg parameters that are passed via
1826 // registers, then we must store them to their spots on the stack so they
1827 // may be loaded by deferencing the result of va_next.
1828 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1829 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1830 FuncInfo->setRegSaveFrameIndex(
1831 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1835 // Store the integer parameter registers.
1836 SmallVector<SDValue, 8> MemOps;
1837 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1839 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1840 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1841 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1842 DAG.getIntPtrConstant(Offset));
1843 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1844 X86::GR64RegisterClass);
1845 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1847 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1848 MachinePointerInfo::getFixedStack(
1849 FuncInfo->getRegSaveFrameIndex(), Offset),
1851 MemOps.push_back(Store);
1855 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1856 // Now store the XMM (fp + vector) parameter registers.
1857 SmallVector<SDValue, 11> SaveXMMOps;
1858 SaveXMMOps.push_back(Chain);
1860 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1861 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1862 SaveXMMOps.push_back(ALVal);
1864 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1865 FuncInfo->getRegSaveFrameIndex()));
1866 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1867 FuncInfo->getVarArgsFPOffset()));
1869 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1870 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1871 X86::VR128RegisterClass);
1872 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1873 SaveXMMOps.push_back(Val);
1875 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1877 &SaveXMMOps[0], SaveXMMOps.size()));
1880 if (!MemOps.empty())
1881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1882 &MemOps[0], MemOps.size());
1886 // Some CCs need callee pop.
1887 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1888 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1890 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1891 // If this is an sret function, the return should pop the hidden pointer.
1892 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1893 FuncInfo->setBytesToPopOnReturn(4);
1897 // RegSaveFrameIndex is X86-64 only.
1898 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1899 if (CallConv == CallingConv::X86_FastCall ||
1900 CallConv == CallingConv::X86_ThisCall)
1901 // fastcc functions can't have varargs.
1902 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1909 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1910 SDValue StackPtr, SDValue Arg,
1911 DebugLoc dl, SelectionDAG &DAG,
1912 const CCValAssign &VA,
1913 ISD::ArgFlagsTy Flags) const {
1914 unsigned LocMemOffset = VA.getLocMemOffset();
1915 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1916 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1917 if (Flags.isByVal())
1918 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1920 return DAG.getStore(Chain, dl, Arg, PtrOff,
1921 MachinePointerInfo::getStack(LocMemOffset),
1925 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1926 /// optimization is performed and it is required.
1928 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1929 SDValue &OutRetAddr, SDValue Chain,
1930 bool IsTailCall, bool Is64Bit,
1931 int FPDiff, DebugLoc dl) const {
1932 // Adjust the Return address stack slot.
1933 EVT VT = getPointerTy();
1934 OutRetAddr = getReturnAddressFrameIndex(DAG);
1936 // Load the "old" Return address.
1937 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1939 return SDValue(OutRetAddr.getNode(), 1);
1942 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1943 /// optimization is performed and it is required (FPDiff!=0).
1945 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1946 SDValue Chain, SDValue RetAddrFrIdx,
1947 bool Is64Bit, int FPDiff, DebugLoc dl) {
1948 // Store the return address to the appropriate stack slot.
1949 if (!FPDiff) return Chain;
1950 // Calculate the new stack slot for the return address.
1951 int SlotSize = Is64Bit ? 8 : 4;
1952 int NewReturnAddrFI =
1953 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1954 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1955 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1956 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1957 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1963 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1964 CallingConv::ID CallConv, bool isVarArg,
1966 const SmallVectorImpl<ISD::OutputArg> &Outs,
1967 const SmallVectorImpl<SDValue> &OutVals,
1968 const SmallVectorImpl<ISD::InputArg> &Ins,
1969 DebugLoc dl, SelectionDAG &DAG,
1970 SmallVectorImpl<SDValue> &InVals) const {
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 bool Is64Bit = Subtarget->is64Bit();
1973 bool IsWin64 = Subtarget->isTargetWin64();
1974 bool IsStructRet = CallIsStructReturn(Outs);
1975 bool IsSibcall = false;
1978 // Check if it's really possible to do a tail call.
1979 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1980 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1981 Outs, OutVals, Ins, DAG);
1983 // Sibcalls are automatically detected tailcalls which do not require
1985 if (!GuaranteedTailCallOpt && isTailCall)
1992 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1993 "Var args not supported with calling convention fastcc or ghc");
1995 // Analyze operands of the call, assigning locations to each operand.
1996 SmallVector<CCValAssign, 16> ArgLocs;
1997 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1998 ArgLocs, *DAG.getContext());
2000 // Allocate shadow area for Win64
2002 CCInfo.AllocateStack(32, 8);
2005 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2007 // Get a count of how many bytes are to be pushed on the stack.
2008 unsigned NumBytes = CCInfo.getNextStackOffset();
2010 // This is a sibcall. The memory operands are available in caller's
2011 // own caller's stack.
2013 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2014 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2017 if (isTailCall && !IsSibcall) {
2018 // Lower arguments at fp - stackoffset + fpdiff.
2019 unsigned NumBytesCallerPushed =
2020 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2021 FPDiff = NumBytesCallerPushed - NumBytes;
2023 // Set the delta of movement of the returnaddr stackslot.
2024 // But only set if delta is greater than previous delta.
2025 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2026 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2030 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2032 SDValue RetAddrFrIdx;
2033 // Load return adress for tail calls.
2034 if (isTailCall && FPDiff)
2035 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2036 Is64Bit, FPDiff, dl);
2038 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2039 SmallVector<SDValue, 8> MemOpChains;
2042 // Walk the register/memloc assignments, inserting copies/loads. In the case
2043 // of tail call optimization arguments are handle later.
2044 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2045 CCValAssign &VA = ArgLocs[i];
2046 EVT RegVT = VA.getLocVT();
2047 SDValue Arg = OutVals[i];
2048 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2049 bool isByVal = Flags.isByVal();
2051 // Promote the value if needed.
2052 switch (VA.getLocInfo()) {
2053 default: llvm_unreachable("Unknown loc info!");
2054 case CCValAssign::Full: break;
2055 case CCValAssign::SExt:
2056 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2058 case CCValAssign::ZExt:
2059 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2061 case CCValAssign::AExt:
2062 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2063 // Special case: passing MMX values in XMM registers.
2064 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2065 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2066 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2068 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2070 case CCValAssign::BCvt:
2071 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2073 case CCValAssign::Indirect: {
2074 // Store the argument.
2075 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2076 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2077 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2078 MachinePointerInfo::getFixedStack(FI),
2085 if (VA.isRegLoc()) {
2086 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2087 if (isVarArg && IsWin64) {
2088 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2089 // shadow reg if callee is a varargs function.
2090 unsigned ShadowReg = 0;
2091 switch (VA.getLocReg()) {
2092 case X86::XMM0: ShadowReg = X86::RCX; break;
2093 case X86::XMM1: ShadowReg = X86::RDX; break;
2094 case X86::XMM2: ShadowReg = X86::R8; break;
2095 case X86::XMM3: ShadowReg = X86::R9; break;
2098 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2100 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2101 assert(VA.isMemLoc());
2102 if (StackPtr.getNode() == 0)
2103 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2104 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2105 dl, DAG, VA, Flags));
2109 if (!MemOpChains.empty())
2110 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2111 &MemOpChains[0], MemOpChains.size());
2113 // Build a sequence of copy-to-reg nodes chained together with token chain
2114 // and flag operands which copy the outgoing args into registers.
2116 // Tail call byval lowering might overwrite argument registers so in case of
2117 // tail call optimization the copies to registers are lowered later.
2119 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2120 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2121 RegsToPass[i].second, InFlag);
2122 InFlag = Chain.getValue(1);
2125 if (Subtarget->isPICStyleGOT()) {
2126 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2129 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2130 DAG.getNode(X86ISD::GlobalBaseReg,
2131 DebugLoc(), getPointerTy()),
2133 InFlag = Chain.getValue(1);
2135 // If we are tail calling and generating PIC/GOT style code load the
2136 // address of the callee into ECX. The value in ecx is used as target of
2137 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2138 // for tail calls on PIC/GOT architectures. Normally we would just put the
2139 // address of GOT into ebx and then call target@PLT. But for tail calls
2140 // ebx would be restored (since ebx is callee saved) before jumping to the
2143 // Note: The actual moving to ECX is done further down.
2144 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2145 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2146 !G->getGlobal()->hasProtectedVisibility())
2147 Callee = LowerGlobalAddress(Callee, DAG);
2148 else if (isa<ExternalSymbolSDNode>(Callee))
2149 Callee = LowerExternalSymbol(Callee, DAG);
2153 if (Is64Bit && isVarArg && !IsWin64) {
2154 // From AMD64 ABI document:
2155 // For calls that may call functions that use varargs or stdargs
2156 // (prototype-less calls or calls to functions containing ellipsis (...) in
2157 // the declaration) %al is used as hidden argument to specify the number
2158 // of SSE registers used. The contents of %al do not need to match exactly
2159 // the number of registers, but must be an ubound on the number of SSE
2160 // registers used and is in the range 0 - 8 inclusive.
2162 // Count the number of XMM registers allocated.
2163 static const unsigned XMMArgRegs[] = {
2164 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2165 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2167 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2168 assert((Subtarget->hasXMM() || !NumXMMRegs)
2169 && "SSE registers cannot be used when SSE is disabled");
2171 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2172 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2173 InFlag = Chain.getValue(1);
2177 // For tail calls lower the arguments to the 'real' stack slot.
2179 // Force all the incoming stack arguments to be loaded from the stack
2180 // before any new outgoing arguments are stored to the stack, because the
2181 // outgoing stack slots may alias the incoming argument stack slots, and
2182 // the alias isn't otherwise explicit. This is slightly more conservative
2183 // than necessary, because it means that each store effectively depends
2184 // on every argument instead of just those arguments it would clobber.
2185 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2187 SmallVector<SDValue, 8> MemOpChains2;
2190 // Do not flag preceeding copytoreg stuff together with the following stuff.
2192 if (GuaranteedTailCallOpt) {
2193 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2194 CCValAssign &VA = ArgLocs[i];
2197 assert(VA.isMemLoc());
2198 SDValue Arg = OutVals[i];
2199 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2200 // Create frame index.
2201 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2202 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2203 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2204 FIN = DAG.getFrameIndex(FI, getPointerTy());
2206 if (Flags.isByVal()) {
2207 // Copy relative to framepointer.
2208 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2209 if (StackPtr.getNode() == 0)
2210 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2212 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2214 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2218 // Store relative to framepointer.
2219 MemOpChains2.push_back(
2220 DAG.getStore(ArgChain, dl, Arg, FIN,
2221 MachinePointerInfo::getFixedStack(FI),
2227 if (!MemOpChains2.empty())
2228 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2229 &MemOpChains2[0], MemOpChains2.size());
2231 // Copy arguments to their registers.
2232 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2233 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2234 RegsToPass[i].second, InFlag);
2235 InFlag = Chain.getValue(1);
2239 // Store the return address to the appropriate stack slot.
2240 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2244 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2245 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2246 // In the 64-bit large code model, we have to make all calls
2247 // through a register, since the call instruction's 32-bit
2248 // pc-relative offset may not be large enough to hold the whole
2250 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2251 // If the callee is a GlobalAddress node (quite common, every direct call
2252 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2255 // We should use extra load for direct calls to dllimported functions in
2257 const GlobalValue *GV = G->getGlobal();
2258 if (!GV->hasDLLImportLinkage()) {
2259 unsigned char OpFlags = 0;
2261 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2262 // external symbols most go through the PLT in PIC mode. If the symbol
2263 // has hidden or protected visibility, or if it is static or local, then
2264 // we don't need to use the PLT - we can directly call it.
2265 if (Subtarget->isTargetELF() &&
2266 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2267 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2268 OpFlags = X86II::MO_PLT;
2269 } else if (Subtarget->isPICStyleStubAny() &&
2270 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2271 Subtarget->getDarwinVers() < 9) {
2272 // PC-relative references to external symbols should go through $stub,
2273 // unless we're building with the leopard linker or later, which
2274 // automatically synthesizes these stubs.
2275 OpFlags = X86II::MO_DARWIN_STUB;
2278 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2279 G->getOffset(), OpFlags);
2281 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2282 unsigned char OpFlags = 0;
2284 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2285 // external symbols should go through the PLT.
2286 if (Subtarget->isTargetELF() &&
2287 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2288 OpFlags = X86II::MO_PLT;
2289 } else if (Subtarget->isPICStyleStubAny() &&
2290 Subtarget->getDarwinVers() < 9) {
2291 // PC-relative references to external symbols should go through $stub,
2292 // unless we're building with the leopard linker or later, which
2293 // automatically synthesizes these stubs.
2294 OpFlags = X86II::MO_DARWIN_STUB;
2297 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2301 // Returns a chain & a flag for retval copy to use.
2302 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2303 SmallVector<SDValue, 8> Ops;
2305 if (!IsSibcall && isTailCall) {
2306 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2307 DAG.getIntPtrConstant(0, true), InFlag);
2308 InFlag = Chain.getValue(1);
2311 Ops.push_back(Chain);
2312 Ops.push_back(Callee);
2315 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2317 // Add argument registers to the end of the list so that they are known live
2319 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2320 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2321 RegsToPass[i].second.getValueType()));
2323 // Add an implicit use GOT pointer in EBX.
2324 if (!isTailCall && Subtarget->isPICStyleGOT())
2325 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2327 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2328 if (Is64Bit && isVarArg && !IsWin64)
2329 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2331 if (InFlag.getNode())
2332 Ops.push_back(InFlag);
2336 //// If this is the first return lowered for this function, add the regs
2337 //// to the liveout set for the function.
2338 // This isn't right, although it's probably harmless on x86; liveouts
2339 // should be computed from returns not tail calls. Consider a void
2340 // function making a tail call to a function returning int.
2341 return DAG.getNode(X86ISD::TC_RETURN, dl,
2342 NodeTys, &Ops[0], Ops.size());
2345 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2346 InFlag = Chain.getValue(1);
2348 // Create the CALLSEQ_END node.
2349 unsigned NumBytesForCalleeToPush;
2350 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2351 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2352 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2353 // If this is a call to a struct-return function, the callee
2354 // pops the hidden struct pointer, so we have to push it back.
2355 // This is common for Darwin/X86, Linux & Mingw32 targets.
2356 NumBytesForCalleeToPush = 4;
2358 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2360 // Returns a flag for retval copy to use.
2362 Chain = DAG.getCALLSEQ_END(Chain,
2363 DAG.getIntPtrConstant(NumBytes, true),
2364 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2367 InFlag = Chain.getValue(1);
2370 // Handle result values, copying them out of physregs into vregs that we
2372 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2373 Ins, dl, DAG, InVals);
2377 //===----------------------------------------------------------------------===//
2378 // Fast Calling Convention (tail call) implementation
2379 //===----------------------------------------------------------------------===//
2381 // Like std call, callee cleans arguments, convention except that ECX is
2382 // reserved for storing the tail called function address. Only 2 registers are
2383 // free for argument passing (inreg). Tail call optimization is performed
2385 // * tailcallopt is enabled
2386 // * caller/callee are fastcc
2387 // On X86_64 architecture with GOT-style position independent code only local
2388 // (within module) calls are supported at the moment.
2389 // To keep the stack aligned according to platform abi the function
2390 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2391 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2392 // If a tail called function callee has more arguments than the caller the
2393 // caller needs to make sure that there is room to move the RETADDR to. This is
2394 // achieved by reserving an area the size of the argument delta right after the
2395 // original REtADDR, but before the saved framepointer or the spilled registers
2396 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2408 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2409 /// for a 16 byte align requirement.
2411 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2412 SelectionDAG& DAG) const {
2413 MachineFunction &MF = DAG.getMachineFunction();
2414 const TargetMachine &TM = MF.getTarget();
2415 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2416 unsigned StackAlignment = TFI.getStackAlignment();
2417 uint64_t AlignMask = StackAlignment - 1;
2418 int64_t Offset = StackSize;
2419 uint64_t SlotSize = TD->getPointerSize();
2420 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2421 // Number smaller than 12 so just add the difference.
2422 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2424 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2425 Offset = ((~AlignMask) & Offset) + StackAlignment +
2426 (StackAlignment-SlotSize);
2431 /// MatchingStackOffset - Return true if the given stack call argument is
2432 /// already available in the same position (relatively) of the caller's
2433 /// incoming argument stack.
2435 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2436 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2437 const X86InstrInfo *TII) {
2438 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2440 if (Arg.getOpcode() == ISD::CopyFromReg) {
2441 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2442 if (!TargetRegisterInfo::isVirtualRegister(VR))
2444 MachineInstr *Def = MRI->getVRegDef(VR);
2447 if (!Flags.isByVal()) {
2448 if (!TII->isLoadFromStackSlot(Def, FI))
2451 unsigned Opcode = Def->getOpcode();
2452 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2453 Def->getOperand(1).isFI()) {
2454 FI = Def->getOperand(1).getIndex();
2455 Bytes = Flags.getByValSize();
2459 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2460 if (Flags.isByVal())
2461 // ByVal argument is passed in as a pointer but it's now being
2462 // dereferenced. e.g.
2463 // define @foo(%struct.X* %A) {
2464 // tail call @bar(%struct.X* byval %A)
2467 SDValue Ptr = Ld->getBasePtr();
2468 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2471 FI = FINode->getIndex();
2475 assert(FI != INT_MAX);
2476 if (!MFI->isFixedObjectIndex(FI))
2478 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2481 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2482 /// for tail call optimization. Targets which want to do tail call
2483 /// optimization should implement this function.
2485 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2486 CallingConv::ID CalleeCC,
2488 bool isCalleeStructRet,
2489 bool isCallerStructRet,
2490 const SmallVectorImpl<ISD::OutputArg> &Outs,
2491 const SmallVectorImpl<SDValue> &OutVals,
2492 const SmallVectorImpl<ISD::InputArg> &Ins,
2493 SelectionDAG& DAG) const {
2494 if (!IsTailCallConvention(CalleeCC) &&
2495 CalleeCC != CallingConv::C)
2498 // If -tailcallopt is specified, make fastcc functions tail-callable.
2499 const MachineFunction &MF = DAG.getMachineFunction();
2500 const Function *CallerF = DAG.getMachineFunction().getFunction();
2501 CallingConv::ID CallerCC = CallerF->getCallingConv();
2502 bool CCMatch = CallerCC == CalleeCC;
2504 if (GuaranteedTailCallOpt) {
2505 if (IsTailCallConvention(CalleeCC) && CCMatch)
2510 // Look for obvious safe cases to perform tail call optimization that do not
2511 // require ABI changes. This is what gcc calls sibcall.
2513 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2514 // emit a special epilogue.
2515 if (RegInfo->needsStackRealignment(MF))
2518 // Do not sibcall optimize vararg calls unless the call site is not passing
2520 if (isVarArg && !Outs.empty())
2523 // Also avoid sibcall optimization if either caller or callee uses struct
2524 // return semantics.
2525 if (isCalleeStructRet || isCallerStructRet)
2528 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2529 // Therefore if it's not used by the call it is not safe to optimize this into
2531 bool Unused = false;
2532 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2539 SmallVector<CCValAssign, 16> RVLocs;
2540 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2541 RVLocs, *DAG.getContext());
2542 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2543 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2544 CCValAssign &VA = RVLocs[i];
2545 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2550 // If the calling conventions do not match, then we'd better make sure the
2551 // results are returned in the same way as what the caller expects.
2553 SmallVector<CCValAssign, 16> RVLocs1;
2554 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2555 RVLocs1, *DAG.getContext());
2556 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2558 SmallVector<CCValAssign, 16> RVLocs2;
2559 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2560 RVLocs2, *DAG.getContext());
2561 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2563 if (RVLocs1.size() != RVLocs2.size())
2565 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2566 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2568 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2570 if (RVLocs1[i].isRegLoc()) {
2571 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2574 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2580 // If the callee takes no arguments then go on to check the results of the
2582 if (!Outs.empty()) {
2583 // Check if stack adjustment is needed. For now, do not do this if any
2584 // argument is passed on the stack.
2585 SmallVector<CCValAssign, 16> ArgLocs;
2586 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2587 ArgLocs, *DAG.getContext());
2589 // Allocate shadow area for Win64
2590 if (Subtarget->isTargetWin64()) {
2591 CCInfo.AllocateStack(32, 8);
2594 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2595 if (CCInfo.getNextStackOffset()) {
2596 MachineFunction &MF = DAG.getMachineFunction();
2597 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2600 // Check if the arguments are already laid out in the right way as
2601 // the caller's fixed stack objects.
2602 MachineFrameInfo *MFI = MF.getFrameInfo();
2603 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2604 const X86InstrInfo *TII =
2605 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607 CCValAssign &VA = ArgLocs[i];
2608 SDValue Arg = OutVals[i];
2609 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2610 if (VA.getLocInfo() == CCValAssign::Indirect)
2612 if (!VA.isRegLoc()) {
2613 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2620 // If the tailcall address may be in a register, then make sure it's
2621 // possible to register allocate for it. In 32-bit, the call address can
2622 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2623 // callee-saved registers are restored. These happen to be the same
2624 // registers used to pass 'inreg' arguments so watch out for those.
2625 if (!Subtarget->is64Bit() &&
2626 !isa<GlobalAddressSDNode>(Callee) &&
2627 !isa<ExternalSymbolSDNode>(Callee)) {
2628 unsigned NumInRegs = 0;
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630 CCValAssign &VA = ArgLocs[i];
2633 unsigned Reg = VA.getLocReg();
2636 case X86::EAX: case X86::EDX: case X86::ECX:
2637 if (++NumInRegs == 3)
2645 // An stdcall caller is expected to clean up its arguments; the callee
2646 // isn't going to do that.
2647 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2654 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2655 return X86::createFastISel(funcInfo);
2659 //===----------------------------------------------------------------------===//
2660 // Other Lowering Hooks
2661 //===----------------------------------------------------------------------===//
2663 static bool MayFoldLoad(SDValue Op) {
2664 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2667 static bool MayFoldIntoStore(SDValue Op) {
2668 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2671 static bool isTargetShuffle(unsigned Opcode) {
2673 default: return false;
2674 case X86ISD::PSHUFD:
2675 case X86ISD::PSHUFHW:
2676 case X86ISD::PSHUFLW:
2677 case X86ISD::SHUFPD:
2678 case X86ISD::PALIGN:
2679 case X86ISD::SHUFPS:
2680 case X86ISD::MOVLHPS:
2681 case X86ISD::MOVLHPD:
2682 case X86ISD::MOVHLPS:
2683 case X86ISD::MOVLPS:
2684 case X86ISD::MOVLPD:
2685 case X86ISD::MOVSHDUP:
2686 case X86ISD::MOVSLDUP:
2687 case X86ISD::MOVDDUP:
2690 case X86ISD::UNPCKLPS:
2691 case X86ISD::UNPCKLPD:
2692 case X86ISD::VUNPCKLPS:
2693 case X86ISD::VUNPCKLPD:
2694 case X86ISD::VUNPCKLPSY:
2695 case X86ISD::VUNPCKLPDY:
2696 case X86ISD::PUNPCKLWD:
2697 case X86ISD::PUNPCKLBW:
2698 case X86ISD::PUNPCKLDQ:
2699 case X86ISD::PUNPCKLQDQ:
2700 case X86ISD::UNPCKHPS:
2701 case X86ISD::UNPCKHPD:
2702 case X86ISD::PUNPCKHWD:
2703 case X86ISD::PUNPCKHBW:
2704 case X86ISD::PUNPCKHDQ:
2705 case X86ISD::PUNPCKHQDQ:
2711 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2712 SDValue V1, SelectionDAG &DAG) {
2714 default: llvm_unreachable("Unknown x86 shuffle node");
2715 case X86ISD::MOVSHDUP:
2716 case X86ISD::MOVSLDUP:
2717 case X86ISD::MOVDDUP:
2718 return DAG.getNode(Opc, dl, VT, V1);
2724 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2725 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2727 default: llvm_unreachable("Unknown x86 shuffle node");
2728 case X86ISD::PSHUFD:
2729 case X86ISD::PSHUFHW:
2730 case X86ISD::PSHUFLW:
2731 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2737 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2738 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2740 default: llvm_unreachable("Unknown x86 shuffle node");
2741 case X86ISD::PALIGN:
2742 case X86ISD::SHUFPD:
2743 case X86ISD::SHUFPS:
2744 return DAG.getNode(Opc, dl, VT, V1, V2,
2745 DAG.getConstant(TargetMask, MVT::i8));
2750 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2751 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2753 default: llvm_unreachable("Unknown x86 shuffle node");
2754 case X86ISD::MOVLHPS:
2755 case X86ISD::MOVLHPD:
2756 case X86ISD::MOVHLPS:
2757 case X86ISD::MOVLPS:
2758 case X86ISD::MOVLPD:
2761 case X86ISD::UNPCKLPS:
2762 case X86ISD::UNPCKLPD:
2763 case X86ISD::VUNPCKLPS:
2764 case X86ISD::VUNPCKLPD:
2765 case X86ISD::VUNPCKLPSY:
2766 case X86ISD::VUNPCKLPDY:
2767 case X86ISD::PUNPCKLWD:
2768 case X86ISD::PUNPCKLBW:
2769 case X86ISD::PUNPCKLDQ:
2770 case X86ISD::PUNPCKLQDQ:
2771 case X86ISD::UNPCKHPS:
2772 case X86ISD::UNPCKHPD:
2773 case X86ISD::PUNPCKHWD:
2774 case X86ISD::PUNPCKHBW:
2775 case X86ISD::PUNPCKHDQ:
2776 case X86ISD::PUNPCKHQDQ:
2777 return DAG.getNode(Opc, dl, VT, V1, V2);
2782 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2783 MachineFunction &MF = DAG.getMachineFunction();
2784 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2785 int ReturnAddrIndex = FuncInfo->getRAIndex();
2787 if (ReturnAddrIndex == 0) {
2788 // Set up a frame object for the return address.
2789 uint64_t SlotSize = TD->getPointerSize();
2790 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2792 FuncInfo->setRAIndex(ReturnAddrIndex);
2795 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2799 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2800 bool hasSymbolicDisplacement) {
2801 // Offset should fit into 32 bit immediate field.
2802 if (!isInt<32>(Offset))
2805 // If we don't have a symbolic displacement - we don't have any extra
2807 if (!hasSymbolicDisplacement)
2810 // FIXME: Some tweaks might be needed for medium code model.
2811 if (M != CodeModel::Small && M != CodeModel::Kernel)
2814 // For small code model we assume that latest object is 16MB before end of 31
2815 // bits boundary. We may also accept pretty large negative constants knowing
2816 // that all objects are in the positive half of address space.
2817 if (M == CodeModel::Small && Offset < 16*1024*1024)
2820 // For kernel code model we know that all object resist in the negative half
2821 // of 32bits address space. We may not accept negative offsets, since they may
2822 // be just off and we may accept pretty large positive ones.
2823 if (M == CodeModel::Kernel && Offset > 0)
2829 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2830 /// specific condition code, returning the condition code and the LHS/RHS of the
2831 /// comparison to make.
2832 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2833 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2835 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2836 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2837 // X > -1 -> X == 0, jump !sign.
2838 RHS = DAG.getConstant(0, RHS.getValueType());
2839 return X86::COND_NS;
2840 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2841 // X < 0 -> X == 0, jump on sign.
2843 } else if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
2845 RHS = DAG.getConstant(0, RHS.getValueType());
2846 return X86::COND_LE;
2850 switch (SetCCOpcode) {
2851 default: llvm_unreachable("Invalid integer condition!");
2852 case ISD::SETEQ: return X86::COND_E;
2853 case ISD::SETGT: return X86::COND_G;
2854 case ISD::SETGE: return X86::COND_GE;
2855 case ISD::SETLT: return X86::COND_L;
2856 case ISD::SETLE: return X86::COND_LE;
2857 case ISD::SETNE: return X86::COND_NE;
2858 case ISD::SETULT: return X86::COND_B;
2859 case ISD::SETUGT: return X86::COND_A;
2860 case ISD::SETULE: return X86::COND_BE;
2861 case ISD::SETUGE: return X86::COND_AE;
2865 // First determine if it is required or is profitable to flip the operands.
2867 // If LHS is a foldable load, but RHS is not, flip the condition.
2868 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2869 !ISD::isNON_EXTLoad(RHS.getNode())) {
2870 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2871 std::swap(LHS, RHS);
2874 switch (SetCCOpcode) {
2880 std::swap(LHS, RHS);
2884 // On a floating point condition, the flags are set as follows:
2886 // 0 | 0 | 0 | X > Y
2887 // 0 | 0 | 1 | X < Y
2888 // 1 | 0 | 0 | X == Y
2889 // 1 | 1 | 1 | unordered
2890 switch (SetCCOpcode) {
2891 default: llvm_unreachable("Condcode should be pre-legalized away");
2893 case ISD::SETEQ: return X86::COND_E;
2894 case ISD::SETOLT: // flipped
2896 case ISD::SETGT: return X86::COND_A;
2897 case ISD::SETOLE: // flipped
2899 case ISD::SETGE: return X86::COND_AE;
2900 case ISD::SETUGT: // flipped
2902 case ISD::SETLT: return X86::COND_B;
2903 case ISD::SETUGE: // flipped
2905 case ISD::SETLE: return X86::COND_BE;
2907 case ISD::SETNE: return X86::COND_NE;
2908 case ISD::SETUO: return X86::COND_P;
2909 case ISD::SETO: return X86::COND_NP;
2911 case ISD::SETUNE: return X86::COND_INVALID;
2915 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2916 /// code. Current x86 isa includes the following FP cmov instructions:
2917 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2918 static bool hasFPCMov(unsigned X86CC) {
2934 /// isFPImmLegal - Returns true if the target can instruction select the
2935 /// specified FP immediate natively. If false, the legalizer will
2936 /// materialize the FP immediate as a load from a constant pool.
2937 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2938 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2939 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2945 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2946 /// the specified range (L, H].
2947 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2948 return (Val < 0) || (Val >= Low && Val < Hi);
2951 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2952 /// specified value.
2953 static bool isUndefOrEqual(int Val, int CmpVal) {
2954 if (Val < 0 || Val == CmpVal)
2959 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2960 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2961 /// the second operand.
2962 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2963 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2964 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2965 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2966 return (Mask[0] < 2 && Mask[1] < 2);
2970 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2971 SmallVector<int, 8> M;
2973 return ::isPSHUFDMask(M, N->getValueType(0));
2976 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2977 /// is suitable for input to PSHUFHW.
2978 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2979 if (VT != MVT::v8i16)
2982 // Lower quadword copied in order or undef.
2983 for (int i = 0; i != 4; ++i)
2984 if (Mask[i] >= 0 && Mask[i] != i)
2987 // Upper quadword shuffled.
2988 for (int i = 4; i != 8; ++i)
2989 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2995 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2996 SmallVector<int, 8> M;
2998 return ::isPSHUFHWMask(M, N->getValueType(0));
3001 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3002 /// is suitable for input to PSHUFLW.
3003 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3004 if (VT != MVT::v8i16)
3007 // Upper quadword copied in order.
3008 for (int i = 4; i != 8; ++i)
3009 if (Mask[i] >= 0 && Mask[i] != i)
3012 // Lower quadword shuffled.
3013 for (int i = 0; i != 4; ++i)
3020 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3021 SmallVector<int, 8> M;
3023 return ::isPSHUFLWMask(M, N->getValueType(0));
3026 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3027 /// is suitable for input to PALIGNR.
3028 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3030 int i, e = VT.getVectorNumElements();
3032 // Do not handle v2i64 / v2f64 shuffles with palignr.
3033 if (e < 4 || !hasSSSE3)
3036 for (i = 0; i != e; ++i)
3040 // All undef, not a palignr.
3044 // Determine if it's ok to perform a palignr with only the LHS, since we
3045 // don't have access to the actual shuffle elements to see if RHS is undef.
3046 bool Unary = Mask[i] < (int)e;
3047 bool NeedsUnary = false;
3049 int s = Mask[i] - i;
3051 // Check the rest of the elements to see if they are consecutive.
3052 for (++i; i != e; ++i) {
3057 Unary = Unary && (m < (int)e);
3058 NeedsUnary = NeedsUnary || (m < s);
3060 if (NeedsUnary && !Unary)
3062 if (Unary && m != ((s+i) & (e-1)))
3064 if (!Unary && m != (s+i))
3070 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3071 SmallVector<int, 8> M;
3073 return ::isPALIGNRMask(M, N->getValueType(0), true);
3076 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3077 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3078 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3079 int NumElems = VT.getVectorNumElements();
3080 if (NumElems != 2 && NumElems != 4)
3083 int Half = NumElems / 2;
3084 for (int i = 0; i < Half; ++i)
3085 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3087 for (int i = Half; i < NumElems; ++i)
3088 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3094 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3095 SmallVector<int, 8> M;
3097 return ::isSHUFPMask(M, N->getValueType(0));
3100 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3101 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3102 /// half elements to come from vector 1 (which would equal the dest.) and
3103 /// the upper half to come from vector 2.
3104 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3105 int NumElems = VT.getVectorNumElements();
3107 if (NumElems != 2 && NumElems != 4)
3110 int Half = NumElems / 2;
3111 for (int i = 0; i < Half; ++i)
3112 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3114 for (int i = Half; i < NumElems; ++i)
3115 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3120 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3121 SmallVector<int, 8> M;
3123 return isCommutedSHUFPMask(M, N->getValueType(0));
3126 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3127 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3128 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3129 if (N->getValueType(0).getVectorNumElements() != 4)
3132 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3133 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3134 isUndefOrEqual(N->getMaskElt(1), 7) &&
3135 isUndefOrEqual(N->getMaskElt(2), 2) &&
3136 isUndefOrEqual(N->getMaskElt(3), 3);
3139 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3140 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3142 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3143 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3148 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3149 isUndefOrEqual(N->getMaskElt(1), 3) &&
3150 isUndefOrEqual(N->getMaskElt(2), 2) &&
3151 isUndefOrEqual(N->getMaskElt(3), 3);
3154 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3155 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3156 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3157 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3159 if (NumElems != 2 && NumElems != 4)
3162 for (unsigned i = 0; i < NumElems/2; ++i)
3163 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3166 for (unsigned i = NumElems/2; i < NumElems; ++i)
3167 if (!isUndefOrEqual(N->getMaskElt(i), i))
3173 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3174 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3175 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3176 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3178 if ((NumElems != 2 && NumElems != 4)
3179 || N->getValueType(0).getSizeInBits() > 128)
3182 for (unsigned i = 0; i < NumElems/2; ++i)
3183 if (!isUndefOrEqual(N->getMaskElt(i), i))
3186 for (unsigned i = 0; i < NumElems/2; ++i)
3187 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3193 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3194 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3195 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3196 bool V2IsSplat = false) {
3197 int NumElts = VT.getVectorNumElements();
3198 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3201 // Handle vector lengths > 128 bits. Define a "section" as a set of
3202 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3204 unsigned NumSections = VT.getSizeInBits() / 128;
3205 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3206 unsigned NumSectionElts = NumElts / NumSections;
3209 unsigned End = NumSectionElts;
3210 for (unsigned s = 0; s < NumSections; ++s) {
3211 for (unsigned i = Start, j = s * NumSectionElts;
3215 int BitI1 = Mask[i+1];
3216 if (!isUndefOrEqual(BitI, j))
3219 if (!isUndefOrEqual(BitI1, NumElts))
3222 if (!isUndefOrEqual(BitI1, j + NumElts))
3226 // Process the next 128 bits.
3227 Start += NumSectionElts;
3228 End += NumSectionElts;
3234 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3235 SmallVector<int, 8> M;
3237 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3240 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3241 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3242 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3243 bool V2IsSplat = false) {
3244 int NumElts = VT.getVectorNumElements();
3245 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3248 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3250 int BitI1 = Mask[i+1];
3251 if (!isUndefOrEqual(BitI, j + NumElts/2))
3254 if (isUndefOrEqual(BitI1, NumElts))
3257 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3264 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3265 SmallVector<int, 8> M;
3267 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3270 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3271 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3273 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3274 int NumElems = VT.getVectorNumElements();
3275 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3278 // Handle vector lengths > 128 bits. Define a "section" as a set of
3279 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3281 unsigned NumSections = VT.getSizeInBits() / 128;
3282 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3283 unsigned NumSectionElts = NumElems / NumSections;
3285 for (unsigned s = 0; s < NumSections; ++s) {
3286 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3287 i != NumSectionElts * (s + 1);
3290 int BitI1 = Mask[i+1];
3292 if (!isUndefOrEqual(BitI, j))
3294 if (!isUndefOrEqual(BitI1, j))
3302 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3303 SmallVector<int, 8> M;
3305 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3308 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3309 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3311 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3312 int NumElems = VT.getVectorNumElements();
3313 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3316 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3318 int BitI1 = Mask[i+1];
3319 if (!isUndefOrEqual(BitI, j))
3321 if (!isUndefOrEqual(BitI1, j))
3327 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3328 SmallVector<int, 8> M;
3330 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3333 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3334 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3335 /// MOVSD, and MOVD, i.e. setting the lowest element.
3336 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3337 if (VT.getVectorElementType().getSizeInBits() < 32)
3340 int NumElts = VT.getVectorNumElements();
3342 if (!isUndefOrEqual(Mask[0], NumElts))
3345 for (int i = 1; i < NumElts; ++i)
3346 if (!isUndefOrEqual(Mask[i], i))
3352 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3353 SmallVector<int, 8> M;
3355 return ::isMOVLMask(M, N->getValueType(0));
3358 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3359 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3360 /// element of vector 2 and the other elements to come from vector 1 in order.
3361 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3362 bool V2IsSplat = false, bool V2IsUndef = false) {
3363 int NumOps = VT.getVectorNumElements();
3364 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3367 if (!isUndefOrEqual(Mask[0], 0))
3370 for (int i = 1; i < NumOps; ++i)
3371 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3372 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3373 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3379 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3380 bool V2IsUndef = false) {
3381 SmallVector<int, 8> M;
3383 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3386 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3387 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3388 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3389 if (N->getValueType(0).getVectorNumElements() != 4)
3392 // Expect 1, 1, 3, 3
3393 for (unsigned i = 0; i < 2; ++i) {
3394 int Elt = N->getMaskElt(i);
3395 if (Elt >= 0 && Elt != 1)
3400 for (unsigned i = 2; i < 4; ++i) {
3401 int Elt = N->getMaskElt(i);
3402 if (Elt >= 0 && Elt != 3)
3407 // Don't use movshdup if it can be done with a shufps.
3408 // FIXME: verify that matching u, u, 3, 3 is what we want.
3412 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3413 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3414 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3415 if (N->getValueType(0).getVectorNumElements() != 4)
3418 // Expect 0, 0, 2, 2
3419 for (unsigned i = 0; i < 2; ++i)
3420 if (N->getMaskElt(i) > 0)
3424 for (unsigned i = 2; i < 4; ++i) {
3425 int Elt = N->getMaskElt(i);
3426 if (Elt >= 0 && Elt != 2)
3431 // Don't use movsldup if it can be done with a shufps.
3435 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3436 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3437 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3438 int e = N->getValueType(0).getVectorNumElements() / 2;
3440 for (int i = 0; i < e; ++i)
3441 if (!isUndefOrEqual(N->getMaskElt(i), i))
3443 for (int i = 0; i < e; ++i)
3444 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3449 /// isVEXTRACTF128Index - Return true if the specified
3450 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3451 /// suitable for input to VEXTRACTF128.
3452 bool X86::isVEXTRACTF128Index(SDNode *N) {
3453 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3456 // The index should be aligned on a 128-bit boundary.
3458 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3460 unsigned VL = N->getValueType(0).getVectorNumElements();
3461 unsigned VBits = N->getValueType(0).getSizeInBits();
3462 unsigned ElSize = VBits / VL;
3463 bool Result = (Index * ElSize) % 128 == 0;
3468 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3469 /// operand specifies a subvector insert that is suitable for input to
3471 bool X86::isVINSERTF128Index(SDNode *N) {
3472 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3475 // The index should be aligned on a 128-bit boundary.
3477 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3479 unsigned VL = N->getValueType(0).getVectorNumElements();
3480 unsigned VBits = N->getValueType(0).getSizeInBits();
3481 unsigned ElSize = VBits / VL;
3482 bool Result = (Index * ElSize) % 128 == 0;
3487 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3488 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3489 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3490 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3491 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3493 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3495 for (int i = 0; i < NumOperands; ++i) {
3496 int Val = SVOp->getMaskElt(NumOperands-i-1);
3497 if (Val < 0) Val = 0;
3498 if (Val >= NumOperands) Val -= NumOperands;
3500 if (i != NumOperands - 1)
3506 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3507 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3508 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3509 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3511 // 8 nodes, but we only care about the last 4.
3512 for (unsigned i = 7; i >= 4; --i) {
3513 int Val = SVOp->getMaskElt(i);
3522 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3523 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3524 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3525 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3527 // 8 nodes, but we only care about the first 4.
3528 for (int i = 3; i >= 0; --i) {
3529 int Val = SVOp->getMaskElt(i);
3538 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3539 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3540 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3541 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3542 EVT VVT = N->getValueType(0);
3543 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3547 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3548 Val = SVOp->getMaskElt(i);
3552 return (Val - i) * EltSize;
3555 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3556 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3558 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3559 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3560 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3563 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3565 EVT VecVT = N->getOperand(0).getValueType();
3566 EVT ElVT = VecVT.getVectorElementType();
3568 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3570 return Index / NumElemsPerChunk;
3573 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3574 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3576 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3577 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3578 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3581 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3583 EVT VecVT = N->getValueType(0);
3584 EVT ElVT = VecVT.getVectorElementType();
3586 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3588 return Index / NumElemsPerChunk;
3591 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3593 bool X86::isZeroNode(SDValue Elt) {
3594 return ((isa<ConstantSDNode>(Elt) &&
3595 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3596 (isa<ConstantFPSDNode>(Elt) &&
3597 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3600 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3601 /// their permute mask.
3602 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3603 SelectionDAG &DAG) {
3604 EVT VT = SVOp->getValueType(0);
3605 unsigned NumElems = VT.getVectorNumElements();
3606 SmallVector<int, 8> MaskVec;
3608 for (unsigned i = 0; i != NumElems; ++i) {
3609 int idx = SVOp->getMaskElt(i);
3611 MaskVec.push_back(idx);
3612 else if (idx < (int)NumElems)
3613 MaskVec.push_back(idx + NumElems);
3615 MaskVec.push_back(idx - NumElems);
3617 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3618 SVOp->getOperand(0), &MaskVec[0]);
3621 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3622 /// the two vector operands have swapped position.
3623 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3624 unsigned NumElems = VT.getVectorNumElements();
3625 for (unsigned i = 0; i != NumElems; ++i) {
3629 else if (idx < (int)NumElems)
3630 Mask[i] = idx + NumElems;
3632 Mask[i] = idx - NumElems;
3636 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3637 /// match movhlps. The lower half elements should come from upper half of
3638 /// V1 (and in order), and the upper half elements should come from the upper
3639 /// half of V2 (and in order).
3640 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3641 if (Op->getValueType(0).getVectorNumElements() != 4)
3643 for (unsigned i = 0, e = 2; i != e; ++i)
3644 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3646 for (unsigned i = 2; i != 4; ++i)
3647 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3652 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3653 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3655 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3656 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3658 N = N->getOperand(0).getNode();
3659 if (!ISD::isNON_EXTLoad(N))
3662 *LD = cast<LoadSDNode>(N);
3666 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3667 /// match movlp{s|d}. The lower half elements should come from lower half of
3668 /// V1 (and in order), and the upper half elements should come from the upper
3669 /// half of V2 (and in order). And since V1 will become the source of the
3670 /// MOVLP, it must be either a vector load or a scalar load to vector.
3671 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3672 ShuffleVectorSDNode *Op) {
3673 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3675 // Is V2 is a vector load, don't do this transformation. We will try to use
3676 // load folding shufps op.
3677 if (ISD::isNON_EXTLoad(V2))
3680 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3682 if (NumElems != 2 && NumElems != 4)
3684 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3685 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3687 for (unsigned i = NumElems/2; i != NumElems; ++i)
3688 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3693 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3695 static bool isSplatVector(SDNode *N) {
3696 if (N->getOpcode() != ISD::BUILD_VECTOR)
3699 SDValue SplatValue = N->getOperand(0);
3700 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3701 if (N->getOperand(i) != SplatValue)
3706 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3707 /// to an zero vector.
3708 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3709 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3710 SDValue V1 = N->getOperand(0);
3711 SDValue V2 = N->getOperand(1);
3712 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3713 for (unsigned i = 0; i != NumElems; ++i) {
3714 int Idx = N->getMaskElt(i);
3715 if (Idx >= (int)NumElems) {
3716 unsigned Opc = V2.getOpcode();
3717 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3719 if (Opc != ISD::BUILD_VECTOR ||
3720 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3722 } else if (Idx >= 0) {
3723 unsigned Opc = V1.getOpcode();
3724 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3726 if (Opc != ISD::BUILD_VECTOR ||
3727 !X86::isZeroNode(V1.getOperand(Idx)))
3734 /// getZeroVector - Returns a vector of specified type with all zero elements.
3736 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3738 assert(VT.isVector() && "Expected a vector type");
3740 // Always build SSE zero vectors as <4 x i32> bitcasted
3741 // to their dest type. This ensures they get CSE'd.
3743 if (VT.getSizeInBits() == 128) { // SSE
3744 if (HasSSE2) { // SSE2
3745 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3746 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3748 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3749 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3751 } else if (VT.getSizeInBits() == 256) { // AVX
3752 // 256-bit logic and arithmetic instructions in AVX are
3753 // all floating-point, no support for integer ops. Default
3754 // to emitting fp zeroed vectors then.
3755 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3756 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3757 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3759 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3762 /// getOnesVector - Returns a vector of specified type with all bits set.
3764 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3765 assert(VT.isVector() && "Expected a vector type");
3767 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3768 // type. This ensures they get CSE'd.
3769 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3771 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3772 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3776 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3777 /// that point to V2 points to its first element.
3778 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3779 EVT VT = SVOp->getValueType(0);
3780 unsigned NumElems = VT.getVectorNumElements();
3782 bool Changed = false;
3783 SmallVector<int, 8> MaskVec;
3784 SVOp->getMask(MaskVec);
3786 for (unsigned i = 0; i != NumElems; ++i) {
3787 if (MaskVec[i] > (int)NumElems) {
3788 MaskVec[i] = NumElems;
3793 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3794 SVOp->getOperand(1), &MaskVec[0]);
3795 return SDValue(SVOp, 0);
3798 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3799 /// operation of specified width.
3800 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3802 unsigned NumElems = VT.getVectorNumElements();
3803 SmallVector<int, 8> Mask;
3804 Mask.push_back(NumElems);
3805 for (unsigned i = 1; i != NumElems; ++i)
3807 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3810 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3811 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3813 unsigned NumElems = VT.getVectorNumElements();
3814 SmallVector<int, 8> Mask;
3815 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3817 Mask.push_back(i + NumElems);
3819 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3822 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3823 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3825 unsigned NumElems = VT.getVectorNumElements();
3826 unsigned Half = NumElems/2;
3827 SmallVector<int, 8> Mask;
3828 for (unsigned i = 0; i != Half; ++i) {
3829 Mask.push_back(i + Half);
3830 Mask.push_back(i + NumElems + Half);
3832 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3835 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3836 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3837 EVT PVT = MVT::v4f32;
3838 EVT VT = SV->getValueType(0);
3839 DebugLoc dl = SV->getDebugLoc();
3840 SDValue V1 = SV->getOperand(0);
3841 int NumElems = VT.getVectorNumElements();
3842 int EltNo = SV->getSplatIndex();
3844 // unpack elements to the correct location
3845 while (NumElems > 4) {
3846 if (EltNo < NumElems/2) {
3847 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3849 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3850 EltNo -= NumElems/2;
3855 // Perform the splat.
3856 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3857 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3858 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3859 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3862 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3863 /// vector of zero or undef vector. This produces a shuffle where the low
3864 /// element of V2 is swizzled into the zero/undef vector, landing at element
3865 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3866 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3867 bool isZero, bool HasSSE2,
3868 SelectionDAG &DAG) {
3869 EVT VT = V2.getValueType();
3871 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3872 unsigned NumElems = VT.getVectorNumElements();
3873 SmallVector<int, 16> MaskVec;
3874 for (unsigned i = 0; i != NumElems; ++i)
3875 // If this is the insertion idx, put the low elt of V2 here.
3876 MaskVec.push_back(i == Idx ? NumElems : i);
3877 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3880 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3881 /// element of the result of the vector shuffle.
3882 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3885 return SDValue(); // Limit search depth.
3887 SDValue V = SDValue(N, 0);
3888 EVT VT = V.getValueType();
3889 unsigned Opcode = V.getOpcode();
3891 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3892 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3893 Index = SV->getMaskElt(Index);
3896 return DAG.getUNDEF(VT.getVectorElementType());
3898 int NumElems = VT.getVectorNumElements();
3899 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3900 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3903 // Recurse into target specific vector shuffles to find scalars.
3904 if (isTargetShuffle(Opcode)) {
3905 int NumElems = VT.getVectorNumElements();
3906 SmallVector<unsigned, 16> ShuffleMask;
3910 case X86ISD::SHUFPS:
3911 case X86ISD::SHUFPD:
3912 ImmN = N->getOperand(N->getNumOperands()-1);
3913 DecodeSHUFPSMask(NumElems,
3914 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3917 case X86ISD::PUNPCKHBW:
3918 case X86ISD::PUNPCKHWD:
3919 case X86ISD::PUNPCKHDQ:
3920 case X86ISD::PUNPCKHQDQ:
3921 DecodePUNPCKHMask(NumElems, ShuffleMask);
3923 case X86ISD::UNPCKHPS:
3924 case X86ISD::UNPCKHPD:
3925 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3927 case X86ISD::PUNPCKLBW:
3928 case X86ISD::PUNPCKLWD:
3929 case X86ISD::PUNPCKLDQ:
3930 case X86ISD::PUNPCKLQDQ:
3931 DecodePUNPCKLMask(VT, ShuffleMask);
3933 case X86ISD::UNPCKLPS:
3934 case X86ISD::UNPCKLPD:
3935 case X86ISD::VUNPCKLPS:
3936 case X86ISD::VUNPCKLPD:
3937 case X86ISD::VUNPCKLPSY:
3938 case X86ISD::VUNPCKLPDY:
3939 DecodeUNPCKLPMask(VT, ShuffleMask);
3941 case X86ISD::MOVHLPS:
3942 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3944 case X86ISD::MOVLHPS:
3945 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3947 case X86ISD::PSHUFD:
3948 ImmN = N->getOperand(N->getNumOperands()-1);
3949 DecodePSHUFMask(NumElems,
3950 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3953 case X86ISD::PSHUFHW:
3954 ImmN = N->getOperand(N->getNumOperands()-1);
3955 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3958 case X86ISD::PSHUFLW:
3959 ImmN = N->getOperand(N->getNumOperands()-1);
3960 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3964 case X86ISD::MOVSD: {
3965 // The index 0 always comes from the first element of the second source,
3966 // this is why MOVSS and MOVSD are used in the first place. The other
3967 // elements come from the other positions of the first source vector.
3968 unsigned OpNum = (Index == 0) ? 1 : 0;
3969 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3973 assert("not implemented for target shuffle node");
3977 Index = ShuffleMask[Index];
3979 return DAG.getUNDEF(VT.getVectorElementType());
3981 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3982 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3986 // Actual nodes that may contain scalar elements
3987 if (Opcode == ISD::BITCAST) {
3988 V = V.getOperand(0);
3989 EVT SrcVT = V.getValueType();
3990 unsigned NumElems = VT.getVectorNumElements();
3992 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3996 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3997 return (Index == 0) ? V.getOperand(0)
3998 : DAG.getUNDEF(VT.getVectorElementType());
4000 if (V.getOpcode() == ISD::BUILD_VECTOR)
4001 return V.getOperand(Index);
4006 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4007 /// shuffle operation which come from a consecutively from a zero. The
4008 /// search can start in two diferent directions, from left or right.
4010 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4011 bool ZerosFromLeft, SelectionDAG &DAG) {
4014 while (i < NumElems) {
4015 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4016 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4017 if (!(Elt.getNode() &&
4018 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4026 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4027 /// MaskE correspond consecutively to elements from one of the vector operands,
4028 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4030 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4031 int OpIdx, int NumElems, unsigned &OpNum) {
4032 bool SeenV1 = false;
4033 bool SeenV2 = false;
4035 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4036 int Idx = SVOp->getMaskElt(i);
4037 // Ignore undef indicies
4046 // Only accept consecutive elements from the same vector
4047 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4051 OpNum = SeenV1 ? 0 : 1;
4055 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4056 /// logical left shift of a vector.
4057 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4058 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4059 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4060 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4061 false /* check zeros from right */, DAG);
4067 // Considering the elements in the mask that are not consecutive zeros,
4068 // check if they consecutively come from only one of the source vectors.
4070 // V1 = {X, A, B, C} 0
4072 // vector_shuffle V1, V2 <1, 2, 3, X>
4074 if (!isShuffleMaskConsecutive(SVOp,
4075 0, // Mask Start Index
4076 NumElems-NumZeros-1, // Mask End Index
4077 NumZeros, // Where to start looking in the src vector
4078 NumElems, // Number of elements in vector
4079 OpSrc)) // Which source operand ?
4084 ShVal = SVOp->getOperand(OpSrc);
4088 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4089 /// logical left shift of a vector.
4090 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4091 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4092 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4093 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4094 true /* check zeros from left */, DAG);
4100 // Considering the elements in the mask that are not consecutive zeros,
4101 // check if they consecutively come from only one of the source vectors.
4103 // 0 { A, B, X, X } = V2
4105 // vector_shuffle V1, V2 <X, X, 4, 5>
4107 if (!isShuffleMaskConsecutive(SVOp,
4108 NumZeros, // Mask Start Index
4109 NumElems-1, // Mask End Index
4110 0, // Where to start looking in the src vector
4111 NumElems, // Number of elements in vector
4112 OpSrc)) // Which source operand ?
4117 ShVal = SVOp->getOperand(OpSrc);
4121 /// isVectorShift - Returns true if the shuffle can be implemented as a
4122 /// logical left or right shift of a vector.
4123 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4124 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4125 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4126 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4132 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4134 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4135 unsigned NumNonZero, unsigned NumZero,
4137 const TargetLowering &TLI) {
4141 DebugLoc dl = Op.getDebugLoc();
4144 for (unsigned i = 0; i < 16; ++i) {
4145 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4146 if (ThisIsNonZero && First) {
4148 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4150 V = DAG.getUNDEF(MVT::v8i16);
4155 SDValue ThisElt(0, 0), LastElt(0, 0);
4156 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4157 if (LastIsNonZero) {
4158 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4159 MVT::i16, Op.getOperand(i-1));
4161 if (ThisIsNonZero) {
4162 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4163 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4164 ThisElt, DAG.getConstant(8, MVT::i8));
4166 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4170 if (ThisElt.getNode())
4171 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4172 DAG.getIntPtrConstant(i/2));
4176 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4179 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4181 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4182 unsigned NumNonZero, unsigned NumZero,
4184 const TargetLowering &TLI) {
4188 DebugLoc dl = Op.getDebugLoc();
4191 for (unsigned i = 0; i < 8; ++i) {
4192 bool isNonZero = (NonZeros & (1 << i)) != 0;
4196 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4198 V = DAG.getUNDEF(MVT::v8i16);
4201 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4202 MVT::v8i16, V, Op.getOperand(i),
4203 DAG.getIntPtrConstant(i));
4210 /// getVShift - Return a vector logical shift node.
4212 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4213 unsigned NumBits, SelectionDAG &DAG,
4214 const TargetLowering &TLI, DebugLoc dl) {
4215 EVT ShVT = MVT::v2i64;
4216 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4217 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4218 return DAG.getNode(ISD::BITCAST, dl, VT,
4219 DAG.getNode(Opc, dl, ShVT, SrcOp,
4220 DAG.getConstant(NumBits,
4221 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4225 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4226 SelectionDAG &DAG) const {
4228 // Check if the scalar load can be widened into a vector load. And if
4229 // the address is "base + cst" see if the cst can be "absorbed" into
4230 // the shuffle mask.
4231 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4232 SDValue Ptr = LD->getBasePtr();
4233 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4235 EVT PVT = LD->getValueType(0);
4236 if (PVT != MVT::i32 && PVT != MVT::f32)
4241 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4242 FI = FINode->getIndex();
4244 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4245 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4246 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4247 Offset = Ptr.getConstantOperandVal(1);
4248 Ptr = Ptr.getOperand(0);
4253 SDValue Chain = LD->getChain();
4254 // Make sure the stack object alignment is at least 16.
4255 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4256 if (DAG.InferPtrAlignment(Ptr) < 16) {
4257 if (MFI->isFixedObjectIndex(FI)) {
4258 // Can't change the alignment. FIXME: It's possible to compute
4259 // the exact stack offset and reference FI + adjust offset instead.
4260 // If someone *really* cares about this. That's the way to implement it.
4263 MFI->setObjectAlignment(FI, 16);
4267 // (Offset % 16) must be multiple of 4. Then address is then
4268 // Ptr + (Offset & ~15).
4271 if ((Offset % 16) & 3)
4273 int64_t StartOffset = Offset & ~15;
4275 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4276 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4278 int EltNo = (Offset - StartOffset) >> 2;
4279 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4280 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4281 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4282 LD->getPointerInfo().getWithOffset(StartOffset),
4284 // Canonicalize it to a v4i32 shuffle.
4285 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4286 return DAG.getNode(ISD::BITCAST, dl, VT,
4287 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4288 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4294 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4295 /// vector of type 'VT', see if the elements can be replaced by a single large
4296 /// load which has the same value as a build_vector whose operands are 'elts'.
4298 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4300 /// FIXME: we'd also like to handle the case where the last elements are zero
4301 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4302 /// There's even a handy isZeroNode for that purpose.
4303 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4304 DebugLoc &DL, SelectionDAG &DAG) {
4305 EVT EltVT = VT.getVectorElementType();
4306 unsigned NumElems = Elts.size();
4308 LoadSDNode *LDBase = NULL;
4309 unsigned LastLoadedElt = -1U;
4311 // For each element in the initializer, see if we've found a load or an undef.
4312 // If we don't find an initial load element, or later load elements are
4313 // non-consecutive, bail out.
4314 for (unsigned i = 0; i < NumElems; ++i) {
4315 SDValue Elt = Elts[i];
4317 if (!Elt.getNode() ||
4318 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4321 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4323 LDBase = cast<LoadSDNode>(Elt.getNode());
4327 if (Elt.getOpcode() == ISD::UNDEF)
4330 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4331 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4336 // If we have found an entire vector of loads and undefs, then return a large
4337 // load of the entire vector width starting at the base pointer. If we found
4338 // consecutive loads for the low half, generate a vzext_load node.
4339 if (LastLoadedElt == NumElems - 1) {
4340 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4341 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4342 LDBase->getPointerInfo(),
4343 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4344 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4345 LDBase->getPointerInfo(),
4346 LDBase->isVolatile(), LDBase->isNonTemporal(),
4347 LDBase->getAlignment());
4348 } else if (NumElems == 4 && LastLoadedElt == 1) {
4349 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4350 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4351 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4353 LDBase->getMemOperand());
4354 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4360 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4361 DebugLoc dl = Op.getDebugLoc();
4363 EVT VT = Op.getValueType();
4364 EVT ExtVT = VT.getVectorElementType();
4366 unsigned NumElems = Op.getNumOperands();
4368 // For AVX-length vectors, build the individual 128-bit pieces and
4369 // use shuffles to put them in place.
4370 if (VT.getSizeInBits() > 256 &&
4371 Subtarget->hasAVX() &&
4372 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4373 SmallVector<SDValue, 8> V;
4375 for (unsigned i = 0; i < NumElems; ++i) {
4376 V[i] = Op.getOperand(i);
4379 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4381 // Build the lower subvector.
4382 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4383 // Build the upper subvector.
4384 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4387 return ConcatVectors(Lower, Upper, DAG);
4390 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4391 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4392 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4393 // is present, so AllOnes is ignored.
4394 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4395 (Op.getValueType().getSizeInBits() != 256 &&
4396 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4397 // Canonicalize this to <4 x i32> (SSE) to
4398 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4399 // eliminated on x86-32 hosts.
4400 if (Op.getValueType() == MVT::v4i32)
4403 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4404 return getOnesVector(Op.getValueType(), DAG, dl);
4405 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4408 unsigned EVTBits = ExtVT.getSizeInBits();
4410 unsigned NumZero = 0;
4411 unsigned NumNonZero = 0;
4412 unsigned NonZeros = 0;
4413 bool IsAllConstants = true;
4414 SmallSet<SDValue, 8> Values;
4415 for (unsigned i = 0; i < NumElems; ++i) {
4416 SDValue Elt = Op.getOperand(i);
4417 if (Elt.getOpcode() == ISD::UNDEF)
4420 if (Elt.getOpcode() != ISD::Constant &&
4421 Elt.getOpcode() != ISD::ConstantFP)
4422 IsAllConstants = false;
4423 if (X86::isZeroNode(Elt))
4426 NonZeros |= (1 << i);
4431 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4432 if (NumNonZero == 0)
4433 return DAG.getUNDEF(VT);
4435 // Special case for single non-zero, non-undef, element.
4436 if (NumNonZero == 1) {
4437 unsigned Idx = CountTrailingZeros_32(NonZeros);
4438 SDValue Item = Op.getOperand(Idx);
4440 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4441 // the value are obviously zero, truncate the value to i32 and do the
4442 // insertion that way. Only do this if the value is non-constant or if the
4443 // value is a constant being inserted into element 0. It is cheaper to do
4444 // a constant pool load than it is to do a movd + shuffle.
4445 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4446 (!IsAllConstants || Idx == 0)) {
4447 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4449 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4450 EVT VecVT = MVT::v4i32;
4451 unsigned VecElts = 4;
4453 // Truncate the value (which may itself be a constant) to i32, and
4454 // convert it to a vector with movd (S2V+shuffle to zero extend).
4455 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4456 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4457 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4458 Subtarget->hasSSE2(), DAG);
4460 // Now we have our 32-bit value zero extended in the low element of
4461 // a vector. If Idx != 0, swizzle it into place.
4463 SmallVector<int, 4> Mask;
4464 Mask.push_back(Idx);
4465 for (unsigned i = 1; i != VecElts; ++i)
4467 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4468 DAG.getUNDEF(Item.getValueType()),
4471 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4475 // If we have a constant or non-constant insertion into the low element of
4476 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4477 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4478 // depending on what the source datatype is.
4481 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4482 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4483 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4484 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4485 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4486 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4488 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4489 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4490 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4491 EVT MiddleVT = MVT::v4i32;
4492 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4493 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4494 Subtarget->hasSSE2(), DAG);
4495 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4499 // Is it a vector logical left shift?
4500 if (NumElems == 2 && Idx == 1 &&
4501 X86::isZeroNode(Op.getOperand(0)) &&
4502 !X86::isZeroNode(Op.getOperand(1))) {
4503 unsigned NumBits = VT.getSizeInBits();
4504 return getVShift(true, VT,
4505 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4506 VT, Op.getOperand(1)),
4507 NumBits/2, DAG, *this, dl);
4510 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4513 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4514 // is a non-constant being inserted into an element other than the low one,
4515 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4516 // movd/movss) to move this into the low element, then shuffle it into
4518 if (EVTBits == 32) {
4519 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4521 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4522 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4523 Subtarget->hasSSE2(), DAG);
4524 SmallVector<int, 8> MaskVec;
4525 for (unsigned i = 0; i < NumElems; i++)
4526 MaskVec.push_back(i == Idx ? 0 : 1);
4527 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4531 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4532 if (Values.size() == 1) {
4533 if (EVTBits == 32) {
4534 // Instead of a shuffle like this:
4535 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4536 // Check if it's possible to issue this instead.
4537 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4538 unsigned Idx = CountTrailingZeros_32(NonZeros);
4539 SDValue Item = Op.getOperand(Idx);
4540 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4541 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4546 // A vector full of immediates; various special cases are already
4547 // handled, so this is best done with a single constant-pool load.
4551 // Let legalizer expand 2-wide build_vectors.
4552 if (EVTBits == 64) {
4553 if (NumNonZero == 1) {
4554 // One half is zero or undef.
4555 unsigned Idx = CountTrailingZeros_32(NonZeros);
4556 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4557 Op.getOperand(Idx));
4558 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4559 Subtarget->hasSSE2(), DAG);
4564 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4565 if (EVTBits == 8 && NumElems == 16) {
4566 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4568 if (V.getNode()) return V;
4571 if (EVTBits == 16 && NumElems == 8) {
4572 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4574 if (V.getNode()) return V;
4577 // If element VT is == 32 bits, turn it into a number of shuffles.
4578 SmallVector<SDValue, 8> V;
4580 if (NumElems == 4 && NumZero > 0) {
4581 for (unsigned i = 0; i < 4; ++i) {
4582 bool isZero = !(NonZeros & (1 << i));
4584 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4586 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4589 for (unsigned i = 0; i < 2; ++i) {
4590 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4593 V[i] = V[i*2]; // Must be a zero vector.
4596 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4599 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4602 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4607 SmallVector<int, 8> MaskVec;
4608 bool Reverse = (NonZeros & 0x3) == 2;
4609 for (unsigned i = 0; i < 2; ++i)
4610 MaskVec.push_back(Reverse ? 1-i : i);
4611 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4612 for (unsigned i = 0; i < 2; ++i)
4613 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4614 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4617 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4618 // Check for a build vector of consecutive loads.
4619 for (unsigned i = 0; i < NumElems; ++i)
4620 V[i] = Op.getOperand(i);
4622 // Check for elements which are consecutive loads.
4623 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4627 // For SSE 4.1, use insertps to put the high elements into the low element.
4628 if (getSubtarget()->hasSSE41()) {
4630 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4631 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4633 Result = DAG.getUNDEF(VT);
4635 for (unsigned i = 1; i < NumElems; ++i) {
4636 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4637 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4638 Op.getOperand(i), DAG.getIntPtrConstant(i));
4643 // Otherwise, expand into a number of unpckl*, start by extending each of
4644 // our (non-undef) elements to the full vector width with the element in the
4645 // bottom slot of the vector (which generates no code for SSE).
4646 for (unsigned i = 0; i < NumElems; ++i) {
4647 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4648 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4650 V[i] = DAG.getUNDEF(VT);
4653 // Next, we iteratively mix elements, e.g. for v4f32:
4654 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4655 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4656 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4657 unsigned EltStride = NumElems >> 1;
4658 while (EltStride != 0) {
4659 for (unsigned i = 0; i < EltStride; ++i) {
4660 // If V[i+EltStride] is undef and this is the first round of mixing,
4661 // then it is safe to just drop this shuffle: V[i] is already in the
4662 // right place, the one element (since it's the first round) being
4663 // inserted as undef can be dropped. This isn't safe for successive
4664 // rounds because they will permute elements within both vectors.
4665 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4666 EltStride == NumElems/2)
4669 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4679 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4680 // We support concatenate two MMX registers and place them in a MMX
4681 // register. This is better than doing a stack convert.
4682 DebugLoc dl = Op.getDebugLoc();
4683 EVT ResVT = Op.getValueType();
4684 assert(Op.getNumOperands() == 2);
4685 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4686 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4688 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4689 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4690 InVec = Op.getOperand(1);
4691 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4692 unsigned NumElts = ResVT.getVectorNumElements();
4693 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4694 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4695 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4697 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4698 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4699 Mask[0] = 0; Mask[1] = 2;
4700 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4702 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4705 // v8i16 shuffles - Prefer shuffles in the following order:
4706 // 1. [all] pshuflw, pshufhw, optional move
4707 // 2. [ssse3] 1 x pshufb
4708 // 3. [ssse3] 2 x pshufb + 1 x por
4709 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4711 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4712 SelectionDAG &DAG) const {
4713 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4714 SDValue V1 = SVOp->getOperand(0);
4715 SDValue V2 = SVOp->getOperand(1);
4716 DebugLoc dl = SVOp->getDebugLoc();
4717 SmallVector<int, 8> MaskVals;
4719 // Determine if more than 1 of the words in each of the low and high quadwords
4720 // of the result come from the same quadword of one of the two inputs. Undef
4721 // mask values count as coming from any quadword, for better codegen.
4722 SmallVector<unsigned, 4> LoQuad(4);
4723 SmallVector<unsigned, 4> HiQuad(4);
4724 BitVector InputQuads(4);
4725 for (unsigned i = 0; i < 8; ++i) {
4726 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4727 int EltIdx = SVOp->getMaskElt(i);
4728 MaskVals.push_back(EltIdx);
4737 InputQuads.set(EltIdx / 4);
4740 int BestLoQuad = -1;
4741 unsigned MaxQuad = 1;
4742 for (unsigned i = 0; i < 4; ++i) {
4743 if (LoQuad[i] > MaxQuad) {
4745 MaxQuad = LoQuad[i];
4749 int BestHiQuad = -1;
4751 for (unsigned i = 0; i < 4; ++i) {
4752 if (HiQuad[i] > MaxQuad) {
4754 MaxQuad = HiQuad[i];
4758 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4759 // of the two input vectors, shuffle them into one input vector so only a
4760 // single pshufb instruction is necessary. If There are more than 2 input
4761 // quads, disable the next transformation since it does not help SSSE3.
4762 bool V1Used = InputQuads[0] || InputQuads[1];
4763 bool V2Used = InputQuads[2] || InputQuads[3];
4764 if (Subtarget->hasSSSE3()) {
4765 if (InputQuads.count() == 2 && V1Used && V2Used) {
4766 BestLoQuad = InputQuads.find_first();
4767 BestHiQuad = InputQuads.find_next(BestLoQuad);
4769 if (InputQuads.count() > 2) {
4775 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4776 // the shuffle mask. If a quad is scored as -1, that means that it contains
4777 // words from all 4 input quadwords.
4779 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4780 SmallVector<int, 8> MaskV;
4781 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4782 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4783 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4784 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4785 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4786 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4788 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4789 // source words for the shuffle, to aid later transformations.
4790 bool AllWordsInNewV = true;
4791 bool InOrder[2] = { true, true };
4792 for (unsigned i = 0; i != 8; ++i) {
4793 int idx = MaskVals[i];
4795 InOrder[i/4] = false;
4796 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4798 AllWordsInNewV = false;
4802 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4803 if (AllWordsInNewV) {
4804 for (int i = 0; i != 8; ++i) {
4805 int idx = MaskVals[i];
4808 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4809 if ((idx != i) && idx < 4)
4811 if ((idx != i) && idx > 3)
4820 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4821 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4822 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4823 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4824 unsigned TargetMask = 0;
4825 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4826 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4827 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4828 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4829 V1 = NewV.getOperand(0);
4830 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4834 // If we have SSSE3, and all words of the result are from 1 input vector,
4835 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4836 // is present, fall back to case 4.
4837 if (Subtarget->hasSSSE3()) {
4838 SmallVector<SDValue,16> pshufbMask;
4840 // If we have elements from both input vectors, set the high bit of the
4841 // shuffle mask element to zero out elements that come from V2 in the V1
4842 // mask, and elements that come from V1 in the V2 mask, so that the two
4843 // results can be OR'd together.
4844 bool TwoInputs = V1Used && V2Used;
4845 for (unsigned i = 0; i != 8; ++i) {
4846 int EltIdx = MaskVals[i] * 2;
4847 if (TwoInputs && (EltIdx >= 16)) {
4848 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4849 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4852 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4853 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4855 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4856 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4857 DAG.getNode(ISD::BUILD_VECTOR, dl,
4858 MVT::v16i8, &pshufbMask[0], 16));
4860 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4862 // Calculate the shuffle mask for the second input, shuffle it, and
4863 // OR it with the first shuffled input.
4865 for (unsigned i = 0; i != 8; ++i) {
4866 int EltIdx = MaskVals[i] * 2;
4868 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4869 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4872 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4873 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4875 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4876 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4877 DAG.getNode(ISD::BUILD_VECTOR, dl,
4878 MVT::v16i8, &pshufbMask[0], 16));
4879 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4880 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4883 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4884 // and update MaskVals with new element order.
4885 BitVector InOrder(8);
4886 if (BestLoQuad >= 0) {
4887 SmallVector<int, 8> MaskV;
4888 for (int i = 0; i != 4; ++i) {
4889 int idx = MaskVals[i];
4891 MaskV.push_back(-1);
4893 } else if ((idx / 4) == BestLoQuad) {
4894 MaskV.push_back(idx & 3);
4897 MaskV.push_back(-1);
4900 for (unsigned i = 4; i != 8; ++i)
4902 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4905 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4906 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4908 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4912 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4913 // and update MaskVals with the new element order.
4914 if (BestHiQuad >= 0) {
4915 SmallVector<int, 8> MaskV;
4916 for (unsigned i = 0; i != 4; ++i)
4918 for (unsigned i = 4; i != 8; ++i) {
4919 int idx = MaskVals[i];
4921 MaskV.push_back(-1);
4923 } else if ((idx / 4) == BestHiQuad) {
4924 MaskV.push_back((idx & 3) + 4);
4927 MaskV.push_back(-1);
4930 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4933 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4934 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4936 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4940 // In case BestHi & BestLo were both -1, which means each quadword has a word
4941 // from each of the four input quadwords, calculate the InOrder bitvector now
4942 // before falling through to the insert/extract cleanup.
4943 if (BestLoQuad == -1 && BestHiQuad == -1) {
4945 for (int i = 0; i != 8; ++i)
4946 if (MaskVals[i] < 0 || MaskVals[i] == i)
4950 // The other elements are put in the right place using pextrw and pinsrw.
4951 for (unsigned i = 0; i != 8; ++i) {
4954 int EltIdx = MaskVals[i];
4957 SDValue ExtOp = (EltIdx < 8)
4958 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4959 DAG.getIntPtrConstant(EltIdx))
4960 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4961 DAG.getIntPtrConstant(EltIdx - 8));
4962 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4963 DAG.getIntPtrConstant(i));
4968 // v16i8 shuffles - Prefer shuffles in the following order:
4969 // 1. [ssse3] 1 x pshufb
4970 // 2. [ssse3] 2 x pshufb + 1 x por
4971 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4973 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4975 const X86TargetLowering &TLI) {
4976 SDValue V1 = SVOp->getOperand(0);
4977 SDValue V2 = SVOp->getOperand(1);
4978 DebugLoc dl = SVOp->getDebugLoc();
4979 SmallVector<int, 16> MaskVals;
4980 SVOp->getMask(MaskVals);
4982 // If we have SSSE3, case 1 is generated when all result bytes come from
4983 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4984 // present, fall back to case 3.
4985 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4988 for (unsigned i = 0; i < 16; ++i) {
4989 int EltIdx = MaskVals[i];
4998 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4999 if (TLI.getSubtarget()->hasSSSE3()) {
5000 SmallVector<SDValue,16> pshufbMask;
5002 // If all result elements are from one input vector, then only translate
5003 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5005 // Otherwise, we have elements from both input vectors, and must zero out
5006 // elements that come from V2 in the first mask, and V1 in the second mask
5007 // so that we can OR them together.
5008 bool TwoInputs = !(V1Only || V2Only);
5009 for (unsigned i = 0; i != 16; ++i) {
5010 int EltIdx = MaskVals[i];
5011 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5012 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5015 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5017 // If all the elements are from V2, assign it to V1 and return after
5018 // building the first pshufb.
5021 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5022 DAG.getNode(ISD::BUILD_VECTOR, dl,
5023 MVT::v16i8, &pshufbMask[0], 16));
5027 // Calculate the shuffle mask for the second input, shuffle it, and
5028 // OR it with the first shuffled input.
5030 for (unsigned i = 0; i != 16; ++i) {
5031 int EltIdx = MaskVals[i];
5033 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5036 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5038 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5039 DAG.getNode(ISD::BUILD_VECTOR, dl,
5040 MVT::v16i8, &pshufbMask[0], 16));
5041 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5044 // No SSSE3 - Calculate in place words and then fix all out of place words
5045 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5046 // the 16 different words that comprise the two doublequadword input vectors.
5047 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5048 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5049 SDValue NewV = V2Only ? V2 : V1;
5050 for (int i = 0; i != 8; ++i) {
5051 int Elt0 = MaskVals[i*2];
5052 int Elt1 = MaskVals[i*2+1];
5054 // This word of the result is all undef, skip it.
5055 if (Elt0 < 0 && Elt1 < 0)
5058 // This word of the result is already in the correct place, skip it.
5059 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5061 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5064 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5065 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5068 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5069 // using a single extract together, load it and store it.
5070 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5071 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5072 DAG.getIntPtrConstant(Elt1 / 2));
5073 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5074 DAG.getIntPtrConstant(i));
5078 // If Elt1 is defined, extract it from the appropriate source. If the
5079 // source byte is not also odd, shift the extracted word left 8 bits
5080 // otherwise clear the bottom 8 bits if we need to do an or.
5082 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5083 DAG.getIntPtrConstant(Elt1 / 2));
5084 if ((Elt1 & 1) == 0)
5085 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5087 TLI.getShiftAmountTy(InsElt.getValueType())));
5089 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5090 DAG.getConstant(0xFF00, MVT::i16));
5092 // If Elt0 is defined, extract it from the appropriate source. If the
5093 // source byte is not also even, shift the extracted word right 8 bits. If
5094 // Elt1 was also defined, OR the extracted values together before
5095 // inserting them in the result.
5097 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5098 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5099 if ((Elt0 & 1) != 0)
5100 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5102 TLI.getShiftAmountTy(InsElt0.getValueType())));
5104 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5105 DAG.getConstant(0x00FF, MVT::i16));
5106 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5109 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5110 DAG.getIntPtrConstant(i));
5112 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5115 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5116 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5117 /// done when every pair / quad of shuffle mask elements point to elements in
5118 /// the right sequence. e.g.
5119 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5121 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5122 SelectionDAG &DAG, DebugLoc dl) {
5123 EVT VT = SVOp->getValueType(0);
5124 SDValue V1 = SVOp->getOperand(0);
5125 SDValue V2 = SVOp->getOperand(1);
5126 unsigned NumElems = VT.getVectorNumElements();
5127 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5129 switch (VT.getSimpleVT().SimpleTy) {
5130 default: assert(false && "Unexpected!");
5131 case MVT::v4f32: NewVT = MVT::v2f64; break;
5132 case MVT::v4i32: NewVT = MVT::v2i64; break;
5133 case MVT::v8i16: NewVT = MVT::v4i32; break;
5134 case MVT::v16i8: NewVT = MVT::v4i32; break;
5137 int Scale = NumElems / NewWidth;
5138 SmallVector<int, 8> MaskVec;
5139 for (unsigned i = 0; i < NumElems; i += Scale) {
5141 for (int j = 0; j < Scale; ++j) {
5142 int EltIdx = SVOp->getMaskElt(i+j);
5146 StartIdx = EltIdx - (EltIdx % Scale);
5147 if (EltIdx != StartIdx + j)
5151 MaskVec.push_back(-1);
5153 MaskVec.push_back(StartIdx / Scale);
5156 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5157 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5158 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5161 /// getVZextMovL - Return a zero-extending vector move low node.
5163 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5164 SDValue SrcOp, SelectionDAG &DAG,
5165 const X86Subtarget *Subtarget, DebugLoc dl) {
5166 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5167 LoadSDNode *LD = NULL;
5168 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5169 LD = dyn_cast<LoadSDNode>(SrcOp);
5171 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5173 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5174 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5175 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5176 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5177 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5179 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5180 return DAG.getNode(ISD::BITCAST, dl, VT,
5181 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5182 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5190 return DAG.getNode(ISD::BITCAST, dl, VT,
5191 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5192 DAG.getNode(ISD::BITCAST, dl,
5196 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5199 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5200 SDValue V1 = SVOp->getOperand(0);
5201 SDValue V2 = SVOp->getOperand(1);
5202 DebugLoc dl = SVOp->getDebugLoc();
5203 EVT VT = SVOp->getValueType(0);
5205 SmallVector<std::pair<int, int>, 8> Locs;
5207 SmallVector<int, 8> Mask1(4U, -1);
5208 SmallVector<int, 8> PermMask;
5209 SVOp->getMask(PermMask);
5213 for (unsigned i = 0; i != 4; ++i) {
5214 int Idx = PermMask[i];
5216 Locs[i] = std::make_pair(-1, -1);
5218 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5220 Locs[i] = std::make_pair(0, NumLo);
5224 Locs[i] = std::make_pair(1, NumHi);
5226 Mask1[2+NumHi] = Idx;
5232 if (NumLo <= 2 && NumHi <= 2) {
5233 // If no more than two elements come from either vector. This can be
5234 // implemented with two shuffles. First shuffle gather the elements.
5235 // The second shuffle, which takes the first shuffle as both of its
5236 // vector operands, put the elements into the right order.
5237 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5239 SmallVector<int, 8> Mask2(4U, -1);
5241 for (unsigned i = 0; i != 4; ++i) {
5242 if (Locs[i].first == -1)
5245 unsigned Idx = (i < 2) ? 0 : 4;
5246 Idx += Locs[i].first * 2 + Locs[i].second;
5251 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5252 } else if (NumLo == 3 || NumHi == 3) {
5253 // Otherwise, we must have three elements from one vector, call it X, and
5254 // one element from the other, call it Y. First, use a shufps to build an
5255 // intermediate vector with the one element from Y and the element from X
5256 // that will be in the same half in the final destination (the indexes don't
5257 // matter). Then, use a shufps to build the final vector, taking the half
5258 // containing the element from Y from the intermediate, and the other half
5261 // Normalize it so the 3 elements come from V1.
5262 CommuteVectorShuffleMask(PermMask, VT);
5266 // Find the element from V2.
5268 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5269 int Val = PermMask[HiIndex];
5276 Mask1[0] = PermMask[HiIndex];
5278 Mask1[2] = PermMask[HiIndex^1];
5280 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5283 Mask1[0] = PermMask[0];
5284 Mask1[1] = PermMask[1];
5285 Mask1[2] = HiIndex & 1 ? 6 : 4;
5286 Mask1[3] = HiIndex & 1 ? 4 : 6;
5287 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5289 Mask1[0] = HiIndex & 1 ? 2 : 0;
5290 Mask1[1] = HiIndex & 1 ? 0 : 2;
5291 Mask1[2] = PermMask[2];
5292 Mask1[3] = PermMask[3];
5297 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5301 // Break it into (shuffle shuffle_hi, shuffle_lo).
5304 SmallVector<int,8> LoMask(4U, -1);
5305 SmallVector<int,8> HiMask(4U, -1);
5307 SmallVector<int,8> *MaskPtr = &LoMask;
5308 unsigned MaskIdx = 0;
5311 for (unsigned i = 0; i != 4; ++i) {
5318 int Idx = PermMask[i];
5320 Locs[i] = std::make_pair(-1, -1);
5321 } else if (Idx < 4) {
5322 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5323 (*MaskPtr)[LoIdx] = Idx;
5326 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5327 (*MaskPtr)[HiIdx] = Idx;
5332 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5333 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5334 SmallVector<int, 8> MaskOps;
5335 for (unsigned i = 0; i != 4; ++i) {
5336 if (Locs[i].first == -1) {
5337 MaskOps.push_back(-1);
5339 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5340 MaskOps.push_back(Idx);
5343 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5346 static bool MayFoldVectorLoad(SDValue V) {
5347 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5348 V = V.getOperand(0);
5349 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5350 V = V.getOperand(0);
5356 // FIXME: the version above should always be used. Since there's
5357 // a bug where several vector shuffles can't be folded because the
5358 // DAG is not updated during lowering and a node claims to have two
5359 // uses while it only has one, use this version, and let isel match
5360 // another instruction if the load really happens to have more than
5361 // one use. Remove this version after this bug get fixed.
5362 // rdar://8434668, PR8156
5363 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5364 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5365 V = V.getOperand(0);
5366 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5367 V = V.getOperand(0);
5368 if (ISD::isNormalLoad(V.getNode()))
5373 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5374 /// a vector extract, and if both can be later optimized into a single load.
5375 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5376 /// here because otherwise a target specific shuffle node is going to be
5377 /// emitted for this shuffle, and the optimization not done.
5378 /// FIXME: This is probably not the best approach, but fix the problem
5379 /// until the right path is decided.
5381 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5382 const TargetLowering &TLI) {
5383 EVT VT = V.getValueType();
5384 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5386 // Be sure that the vector shuffle is present in a pattern like this:
5387 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5391 SDNode *N = *V.getNode()->use_begin();
5392 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5395 SDValue EltNo = N->getOperand(1);
5396 if (!isa<ConstantSDNode>(EltNo))
5399 // If the bit convert changed the number of elements, it is unsafe
5400 // to examine the mask.
5401 bool HasShuffleIntoBitcast = false;
5402 if (V.getOpcode() == ISD::BITCAST) {
5403 EVT SrcVT = V.getOperand(0).getValueType();
5404 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5406 V = V.getOperand(0);
5407 HasShuffleIntoBitcast = true;
5410 // Select the input vector, guarding against out of range extract vector.
5411 unsigned NumElems = VT.getVectorNumElements();
5412 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5413 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5414 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5416 // Skip one more bit_convert if necessary
5417 if (V.getOpcode() == ISD::BITCAST)
5418 V = V.getOperand(0);
5420 if (ISD::isNormalLoad(V.getNode())) {
5421 // Is the original load suitable?
5422 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5424 // FIXME: avoid the multi-use bug that is preventing lots of
5425 // of foldings to be detected, this is still wrong of course, but
5426 // give the temporary desired behavior, and if it happens that
5427 // the load has real more uses, during isel it will not fold, and
5428 // will generate poor code.
5429 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5432 if (!HasShuffleIntoBitcast)
5435 // If there's a bitcast before the shuffle, check if the load type and
5436 // alignment is valid.
5437 unsigned Align = LN0->getAlignment();
5439 TLI.getTargetData()->getABITypeAlignment(
5440 VT.getTypeForEVT(*DAG.getContext()));
5442 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5450 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5451 EVT VT = Op.getValueType();
5453 // Canonizalize to v2f64.
5454 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5455 return DAG.getNode(ISD::BITCAST, dl, VT,
5456 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5461 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5463 SDValue V1 = Op.getOperand(0);
5464 SDValue V2 = Op.getOperand(1);
5465 EVT VT = Op.getValueType();
5467 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5469 if (HasSSE2 && VT == MVT::v2f64)
5470 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5473 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5477 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5478 SDValue V1 = Op.getOperand(0);
5479 SDValue V2 = Op.getOperand(1);
5480 EVT VT = Op.getValueType();
5482 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5483 "unsupported shuffle type");
5485 if (V2.getOpcode() == ISD::UNDEF)
5489 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5493 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5494 SDValue V1 = Op.getOperand(0);
5495 SDValue V2 = Op.getOperand(1);
5496 EVT VT = Op.getValueType();
5497 unsigned NumElems = VT.getVectorNumElements();
5499 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5500 // operand of these instructions is only memory, so check if there's a
5501 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5503 bool CanFoldLoad = false;
5505 // Trivial case, when V2 comes from a load.
5506 if (MayFoldVectorLoad(V2))
5509 // When V1 is a load, it can be folded later into a store in isel, example:
5510 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5512 // (MOVLPSmr addr:$src1, VR128:$src2)
5513 // So, recognize this potential and also use MOVLPS or MOVLPD
5514 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5517 // Both of them can't be memory operations though.
5518 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5519 CanFoldLoad = false;
5522 if (HasSSE2 && NumElems == 2)
5523 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5526 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5529 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5530 // movl and movlp will both match v2i64, but v2i64 is never matched by
5531 // movl earlier because we make it strict to avoid messing with the movlp load
5532 // folding logic (see the code above getMOVLP call). Match it here then,
5533 // this is horrible, but will stay like this until we move all shuffle
5534 // matching to x86 specific nodes. Note that for the 1st condition all
5535 // types are matched with movsd.
5536 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5537 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5539 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5542 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5544 // Invert the operand order and use SHUFPS to match it.
5545 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5546 X86::getShuffleSHUFImmediate(SVOp), DAG);
5549 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5550 switch(VT.getSimpleVT().SimpleTy) {
5551 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5552 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5554 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5556 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5557 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5558 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5559 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5560 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5562 llvm_unreachable("Unknown type for unpckl");
5567 static inline unsigned getUNPCKHOpcode(EVT VT) {
5568 switch(VT.getSimpleVT().SimpleTy) {
5569 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5570 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5571 case MVT::v4f32: return X86ISD::UNPCKHPS;
5572 case MVT::v2f64: return X86ISD::UNPCKHPD;
5573 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5574 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5576 llvm_unreachable("Unknown type for unpckh");
5582 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5583 const TargetLowering &TLI,
5584 const X86Subtarget *Subtarget) {
5585 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5586 EVT VT = Op.getValueType();
5587 DebugLoc dl = Op.getDebugLoc();
5588 SDValue V1 = Op.getOperand(0);
5589 SDValue V2 = Op.getOperand(1);
5591 if (isZeroShuffle(SVOp))
5592 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5594 // Handle splat operations
5595 if (SVOp->isSplat()) {
5596 // Special case, this is the only place now where it's
5597 // allowed to return a vector_shuffle operation without
5598 // using a target specific node, because *hopefully* it
5599 // will be optimized away by the dag combiner.
5600 if (VT.getVectorNumElements() <= 4 &&
5601 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5604 // Handle splats by matching through known masks
5605 if (VT.getVectorNumElements() <= 4)
5608 // Canonicalize all of the remaining to v4f32.
5609 return PromoteSplat(SVOp, DAG);
5612 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5614 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5615 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5616 if (NewOp.getNode())
5617 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5618 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5619 // FIXME: Figure out a cleaner way to do this.
5620 // Try to make use of movq to zero out the top part.
5621 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5622 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5623 if (NewOp.getNode()) {
5624 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5625 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5626 DAG, Subtarget, dl);
5628 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5629 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5630 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5631 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5632 DAG, Subtarget, dl);
5639 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5641 SDValue V1 = Op.getOperand(0);
5642 SDValue V2 = Op.getOperand(1);
5643 EVT VT = Op.getValueType();
5644 DebugLoc dl = Op.getDebugLoc();
5645 unsigned NumElems = VT.getVectorNumElements();
5646 bool isMMX = VT.getSizeInBits() == 64;
5647 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5648 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5649 bool V1IsSplat = false;
5650 bool V2IsSplat = false;
5651 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5652 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5653 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5654 MachineFunction &MF = DAG.getMachineFunction();
5655 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5657 // Shuffle operations on MMX not supported.
5661 // Vector shuffle lowering takes 3 steps:
5663 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5664 // narrowing and commutation of operands should be handled.
5665 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5667 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5668 // so the shuffle can be broken into other shuffles and the legalizer can
5669 // try the lowering again.
5671 // The general ideia is that no vector_shuffle operation should be left to
5672 // be matched during isel, all of them must be converted to a target specific
5675 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5676 // narrowing and commutation of operands should be handled. The actual code
5677 // doesn't include all of those, work in progress...
5678 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5679 if (NewOp.getNode())
5682 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5683 // unpckh_undef). Only use pshufd if speed is more important than size.
5684 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5685 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5686 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5687 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5688 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5689 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5691 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5692 RelaxedMayFoldVectorLoad(V1))
5693 return getMOVDDup(Op, dl, V1, DAG);
5695 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5696 return getMOVHighToLow(Op, dl, DAG);
5698 // Use to match splats
5699 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5700 (VT == MVT::v2f64 || VT == MVT::v2i64))
5701 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5703 if (X86::isPSHUFDMask(SVOp)) {
5704 // The actual implementation will match the mask in the if above and then
5705 // during isel it can match several different instructions, not only pshufd
5706 // as its name says, sad but true, emulate the behavior for now...
5707 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5708 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5710 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5712 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5713 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5715 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5716 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5719 if (VT == MVT::v4f32)
5720 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5724 // Check if this can be converted into a logical shift.
5725 bool isLeft = false;
5728 bool isShift = getSubtarget()->hasSSE2() &&
5729 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5730 if (isShift && ShVal.hasOneUse()) {
5731 // If the shifted value has multiple uses, it may be cheaper to use
5732 // v_set0 + movlhps or movhlps, etc.
5733 EVT EltVT = VT.getVectorElementType();
5734 ShAmt *= EltVT.getSizeInBits();
5735 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5738 if (X86::isMOVLMask(SVOp)) {
5741 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5742 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5743 if (!X86::isMOVLPMask(SVOp)) {
5744 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5745 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5747 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5748 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5752 // FIXME: fold these into legal mask.
5753 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5754 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5756 if (X86::isMOVHLPSMask(SVOp))
5757 return getMOVHighToLow(Op, dl, DAG);
5759 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5760 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5762 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5763 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5765 if (X86::isMOVLPMask(SVOp))
5766 return getMOVLP(Op, dl, DAG, HasSSE2);
5768 if (ShouldXformToMOVHLPS(SVOp) ||
5769 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5770 return CommuteVectorShuffle(SVOp, DAG);
5773 // No better options. Use a vshl / vsrl.
5774 EVT EltVT = VT.getVectorElementType();
5775 ShAmt *= EltVT.getSizeInBits();
5776 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5779 bool Commuted = false;
5780 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5781 // 1,1,1,1 -> v8i16 though.
5782 V1IsSplat = isSplatVector(V1.getNode());
5783 V2IsSplat = isSplatVector(V2.getNode());
5785 // Canonicalize the splat or undef, if present, to be on the RHS.
5786 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5787 Op = CommuteVectorShuffle(SVOp, DAG);
5788 SVOp = cast<ShuffleVectorSDNode>(Op);
5789 V1 = SVOp->getOperand(0);
5790 V2 = SVOp->getOperand(1);
5791 std::swap(V1IsSplat, V2IsSplat);
5792 std::swap(V1IsUndef, V2IsUndef);
5796 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5797 // Shuffling low element of v1 into undef, just return v1.
5800 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5801 // the instruction selector will not match, so get a canonical MOVL with
5802 // swapped operands to undo the commute.
5803 return getMOVL(DAG, dl, VT, V2, V1);
5806 if (X86::isUNPCKLMask(SVOp))
5807 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5808 dl, VT, V1, V2, DAG);
5810 if (X86::isUNPCKHMask(SVOp))
5811 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5814 // Normalize mask so all entries that point to V2 points to its first
5815 // element then try to match unpck{h|l} again. If match, return a
5816 // new vector_shuffle with the corrected mask.
5817 SDValue NewMask = NormalizeMask(SVOp, DAG);
5818 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5819 if (NSVOp != SVOp) {
5820 if (X86::isUNPCKLMask(NSVOp, true)) {
5822 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5829 // Commute is back and try unpck* again.
5830 // FIXME: this seems wrong.
5831 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5832 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5834 if (X86::isUNPCKLMask(NewSVOp))
5835 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5836 dl, VT, V2, V1, DAG);
5838 if (X86::isUNPCKHMask(NewSVOp))
5839 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5842 // Normalize the node to match x86 shuffle ops if needed
5843 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5844 return CommuteVectorShuffle(SVOp, DAG);
5846 // The checks below are all present in isShuffleMaskLegal, but they are
5847 // inlined here right now to enable us to directly emit target specific
5848 // nodes, and remove one by one until they don't return Op anymore.
5849 SmallVector<int, 16> M;
5852 if (isPALIGNRMask(M, VT, HasSSSE3))
5853 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5854 X86::getShufflePALIGNRImmediate(SVOp),
5857 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5858 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5859 if (VT == MVT::v2f64) {
5860 X86ISD::NodeType Opcode =
5861 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5862 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5864 if (VT == MVT::v2i64)
5865 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5868 if (isPSHUFHWMask(M, VT))
5869 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5870 X86::getShufflePSHUFHWImmediate(SVOp),
5873 if (isPSHUFLWMask(M, VT))
5874 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5875 X86::getShufflePSHUFLWImmediate(SVOp),
5878 if (isSHUFPMask(M, VT)) {
5879 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5880 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5881 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5883 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5884 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5888 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5889 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5890 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5891 dl, VT, V1, V1, DAG);
5892 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5893 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5894 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5896 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5897 if (VT == MVT::v8i16) {
5898 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5899 if (NewOp.getNode())
5903 if (VT == MVT::v16i8) {
5904 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5905 if (NewOp.getNode())
5909 // Handle all 4 wide cases with a number of shuffles.
5911 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5917 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5918 SelectionDAG &DAG) const {
5919 EVT VT = Op.getValueType();
5920 DebugLoc dl = Op.getDebugLoc();
5921 if (VT.getSizeInBits() == 8) {
5922 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5923 Op.getOperand(0), Op.getOperand(1));
5924 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5925 DAG.getValueType(VT));
5926 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5927 } else if (VT.getSizeInBits() == 16) {
5928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5929 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5931 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5932 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5933 DAG.getNode(ISD::BITCAST, dl,
5937 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5938 Op.getOperand(0), Op.getOperand(1));
5939 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5940 DAG.getValueType(VT));
5941 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5942 } else if (VT == MVT::f32) {
5943 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5944 // the result back to FR32 register. It's only worth matching if the
5945 // result has a single use which is a store or a bitcast to i32. And in
5946 // the case of a store, it's not worth it if the index is a constant 0,
5947 // because a MOVSSmr can be used instead, which is smaller and faster.
5948 if (!Op.hasOneUse())
5950 SDNode *User = *Op.getNode()->use_begin();
5951 if ((User->getOpcode() != ISD::STORE ||
5952 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5953 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5954 (User->getOpcode() != ISD::BITCAST ||
5955 User->getValueType(0) != MVT::i32))
5957 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5958 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5961 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5962 } else if (VT == MVT::i32) {
5963 // ExtractPS works with constant index.
5964 if (isa<ConstantSDNode>(Op.getOperand(1)))
5972 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5973 SelectionDAG &DAG) const {
5974 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5977 SDValue Vec = Op.getOperand(0);
5978 EVT VecVT = Vec.getValueType();
5980 // If this is a 256-bit vector result, first extract the 128-bit
5981 // vector and then extract from the 128-bit vector.
5982 if (VecVT.getSizeInBits() > 128) {
5983 DebugLoc dl = Op.getNode()->getDebugLoc();
5984 unsigned NumElems = VecVT.getVectorNumElements();
5985 SDValue Idx = Op.getOperand(1);
5987 if (!isa<ConstantSDNode>(Idx))
5990 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5991 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5993 // Get the 128-bit vector.
5994 bool Upper = IdxVal >= ExtractNumElems;
5995 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5998 SDValue ScaledIdx = Idx;
6000 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6001 DAG.getConstant(ExtractNumElems,
6002 Idx.getValueType()));
6003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6007 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6009 if (Subtarget->hasSSE41()) {
6010 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6015 EVT VT = Op.getValueType();
6016 DebugLoc dl = Op.getDebugLoc();
6017 // TODO: handle v16i8.
6018 if (VT.getSizeInBits() == 16) {
6019 SDValue Vec = Op.getOperand(0);
6020 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6022 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6023 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6024 DAG.getNode(ISD::BITCAST, dl,
6027 // Transform it so it match pextrw which produces a 32-bit result.
6028 EVT EltVT = MVT::i32;
6029 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6030 Op.getOperand(0), Op.getOperand(1));
6031 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6032 DAG.getValueType(VT));
6033 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6034 } else if (VT.getSizeInBits() == 32) {
6035 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6039 // SHUFPS the element to the lowest double word, then movss.
6040 int Mask[4] = { Idx, -1, -1, -1 };
6041 EVT VVT = Op.getOperand(0).getValueType();
6042 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6043 DAG.getUNDEF(VVT), Mask);
6044 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6045 DAG.getIntPtrConstant(0));
6046 } else if (VT.getSizeInBits() == 64) {
6047 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6048 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6049 // to match extract_elt for f64.
6050 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6054 // UNPCKHPD the element to the lowest double word, then movsd.
6055 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6056 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6057 int Mask[2] = { 1, -1 };
6058 EVT VVT = Op.getOperand(0).getValueType();
6059 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6060 DAG.getUNDEF(VVT), Mask);
6061 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6062 DAG.getIntPtrConstant(0));
6069 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6070 SelectionDAG &DAG) const {
6071 EVT VT = Op.getValueType();
6072 EVT EltVT = VT.getVectorElementType();
6073 DebugLoc dl = Op.getDebugLoc();
6075 SDValue N0 = Op.getOperand(0);
6076 SDValue N1 = Op.getOperand(1);
6077 SDValue N2 = Op.getOperand(2);
6079 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6080 isa<ConstantSDNode>(N2)) {
6082 if (VT == MVT::v8i16)
6083 Opc = X86ISD::PINSRW;
6084 else if (VT == MVT::v16i8)
6085 Opc = X86ISD::PINSRB;
6087 Opc = X86ISD::PINSRB;
6089 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6091 if (N1.getValueType() != MVT::i32)
6092 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6093 if (N2.getValueType() != MVT::i32)
6094 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6095 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6096 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6097 // Bits [7:6] of the constant are the source select. This will always be
6098 // zero here. The DAG Combiner may combine an extract_elt index into these
6099 // bits. For example (insert (extract, 3), 2) could be matched by putting
6100 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6101 // Bits [5:4] of the constant are the destination select. This is the
6102 // value of the incoming immediate.
6103 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6104 // combine either bitwise AND or insert of float 0.0 to set these bits.
6105 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6106 // Create this as a scalar to vector..
6107 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6108 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6109 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6110 // PINSR* works with constant index.
6117 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6118 EVT VT = Op.getValueType();
6119 EVT EltVT = VT.getVectorElementType();
6121 DebugLoc dl = Op.getDebugLoc();
6122 SDValue N0 = Op.getOperand(0);
6123 SDValue N1 = Op.getOperand(1);
6124 SDValue N2 = Op.getOperand(2);
6126 // If this is a 256-bit vector result, first insert into a 128-bit
6127 // vector and then insert into the 256-bit vector.
6128 if (VT.getSizeInBits() > 128) {
6129 if (!isa<ConstantSDNode>(N2))
6132 // Get the 128-bit vector.
6133 unsigned NumElems = VT.getVectorNumElements();
6134 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6135 bool Upper = IdxVal >= NumElems / 2;
6137 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6140 SDValue ScaledN2 = N2;
6142 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6143 DAG.getConstant(NumElems /
6144 (VT.getSizeInBits() / 128),
6145 N2.getValueType()));
6146 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6149 // Insert the 128-bit vector
6150 // FIXME: Why UNDEF?
6151 return Insert128BitVector(N0, Op, N2, DAG, dl);
6154 if (Subtarget->hasSSE41())
6155 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6157 if (EltVT == MVT::i8)
6160 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6161 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6162 // as its second argument.
6163 if (N1.getValueType() != MVT::i32)
6164 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6165 if (N2.getValueType() != MVT::i32)
6166 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6167 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6173 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6174 LLVMContext *Context = DAG.getContext();
6175 DebugLoc dl = Op.getDebugLoc();
6176 EVT OpVT = Op.getValueType();
6178 // If this is a 256-bit vector result, first insert into a 128-bit
6179 // vector and then insert into the 256-bit vector.
6180 if (OpVT.getSizeInBits() > 128) {
6181 // Insert into a 128-bit vector.
6182 EVT VT128 = EVT::getVectorVT(*Context,
6183 OpVT.getVectorElementType(),
6184 OpVT.getVectorNumElements() / 2);
6186 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6188 // Insert the 128-bit vector.
6189 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6190 DAG.getConstant(0, MVT::i32),
6194 if (Op.getValueType() == MVT::v1i64 &&
6195 Op.getOperand(0).getValueType() == MVT::i64)
6196 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6198 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6199 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6200 "Expected an SSE type!");
6201 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6202 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6205 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6206 // a simple subregister reference or explicit instructions to grab
6207 // upper bits of a vector.
6209 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6210 if (Subtarget->hasAVX()) {
6211 DebugLoc dl = Op.getNode()->getDebugLoc();
6212 SDValue Vec = Op.getNode()->getOperand(0);
6213 SDValue Idx = Op.getNode()->getOperand(1);
6215 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6216 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6217 return Extract128BitVector(Vec, Idx, DAG, dl);
6223 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6224 // simple superregister reference or explicit instructions to insert
6225 // the upper bits of a vector.
6227 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6228 if (Subtarget->hasAVX()) {
6229 DebugLoc dl = Op.getNode()->getDebugLoc();
6230 SDValue Vec = Op.getNode()->getOperand(0);
6231 SDValue SubVec = Op.getNode()->getOperand(1);
6232 SDValue Idx = Op.getNode()->getOperand(2);
6234 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6235 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6236 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6242 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6243 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6244 // one of the above mentioned nodes. It has to be wrapped because otherwise
6245 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6246 // be used to form addressing mode. These wrapped nodes will be selected
6249 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6250 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6252 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6254 unsigned char OpFlag = 0;
6255 unsigned WrapperKind = X86ISD::Wrapper;
6256 CodeModel::Model M = getTargetMachine().getCodeModel();
6258 if (Subtarget->isPICStyleRIPRel() &&
6259 (M == CodeModel::Small || M == CodeModel::Kernel))
6260 WrapperKind = X86ISD::WrapperRIP;
6261 else if (Subtarget->isPICStyleGOT())
6262 OpFlag = X86II::MO_GOTOFF;
6263 else if (Subtarget->isPICStyleStubPIC())
6264 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6266 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6268 CP->getOffset(), OpFlag);
6269 DebugLoc DL = CP->getDebugLoc();
6270 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6271 // With PIC, the address is actually $g + Offset.
6273 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6274 DAG.getNode(X86ISD::GlobalBaseReg,
6275 DebugLoc(), getPointerTy()),
6282 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6283 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6285 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6287 unsigned char OpFlag = 0;
6288 unsigned WrapperKind = X86ISD::Wrapper;
6289 CodeModel::Model M = getTargetMachine().getCodeModel();
6291 if (Subtarget->isPICStyleRIPRel() &&
6292 (M == CodeModel::Small || M == CodeModel::Kernel))
6293 WrapperKind = X86ISD::WrapperRIP;
6294 else if (Subtarget->isPICStyleGOT())
6295 OpFlag = X86II::MO_GOTOFF;
6296 else if (Subtarget->isPICStyleStubPIC())
6297 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6299 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6301 DebugLoc DL = JT->getDebugLoc();
6302 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6304 // With PIC, the address is actually $g + Offset.
6306 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6307 DAG.getNode(X86ISD::GlobalBaseReg,
6308 DebugLoc(), getPointerTy()),
6315 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6316 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6318 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6320 unsigned char OpFlag = 0;
6321 unsigned WrapperKind = X86ISD::Wrapper;
6322 CodeModel::Model M = getTargetMachine().getCodeModel();
6324 if (Subtarget->isPICStyleRIPRel() &&
6325 (M == CodeModel::Small || M == CodeModel::Kernel))
6326 WrapperKind = X86ISD::WrapperRIP;
6327 else if (Subtarget->isPICStyleGOT())
6328 OpFlag = X86II::MO_GOTOFF;
6329 else if (Subtarget->isPICStyleStubPIC())
6330 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6332 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6334 DebugLoc DL = Op.getDebugLoc();
6335 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6338 // With PIC, the address is actually $g + Offset.
6339 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6340 !Subtarget->is64Bit()) {
6341 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6342 DAG.getNode(X86ISD::GlobalBaseReg,
6343 DebugLoc(), getPointerTy()),
6351 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6352 // Create the TargetBlockAddressAddress node.
6353 unsigned char OpFlags =
6354 Subtarget->ClassifyBlockAddressReference();
6355 CodeModel::Model M = getTargetMachine().getCodeModel();
6356 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6357 DebugLoc dl = Op.getDebugLoc();
6358 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6359 /*isTarget=*/true, OpFlags);
6361 if (Subtarget->isPICStyleRIPRel() &&
6362 (M == CodeModel::Small || M == CodeModel::Kernel))
6363 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6365 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6367 // With PIC, the address is actually $g + Offset.
6368 if (isGlobalRelativeToPICBase(OpFlags)) {
6369 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6370 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6378 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6380 SelectionDAG &DAG) const {
6381 // Create the TargetGlobalAddress node, folding in the constant
6382 // offset if it is legal.
6383 unsigned char OpFlags =
6384 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6385 CodeModel::Model M = getTargetMachine().getCodeModel();
6387 if (OpFlags == X86II::MO_NO_FLAG &&
6388 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6389 // A direct static reference to a global.
6390 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6393 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6396 if (Subtarget->isPICStyleRIPRel() &&
6397 (M == CodeModel::Small || M == CodeModel::Kernel))
6398 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6400 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6402 // With PIC, the address is actually $g + Offset.
6403 if (isGlobalRelativeToPICBase(OpFlags)) {
6404 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6405 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6409 // For globals that require a load from a stub to get the address, emit the
6411 if (isGlobalStubReference(OpFlags))
6412 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6413 MachinePointerInfo::getGOT(), false, false, 0);
6415 // If there was a non-zero offset that we didn't fold, create an explicit
6418 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6419 DAG.getConstant(Offset, getPointerTy()));
6425 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6426 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6427 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6428 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6432 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6433 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6434 unsigned char OperandFlags) {
6435 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6436 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6437 DebugLoc dl = GA->getDebugLoc();
6438 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6439 GA->getValueType(0),
6443 SDValue Ops[] = { Chain, TGA, *InFlag };
6444 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6446 SDValue Ops[] = { Chain, TGA };
6447 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6450 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6451 MFI->setAdjustsStack(true);
6453 SDValue Flag = Chain.getValue(1);
6454 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6457 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6459 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6462 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6463 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6464 DAG.getNode(X86ISD::GlobalBaseReg,
6465 DebugLoc(), PtrVT), InFlag);
6466 InFlag = Chain.getValue(1);
6468 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6471 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6473 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6475 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6476 X86::RAX, X86II::MO_TLSGD);
6479 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6480 // "local exec" model.
6481 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6482 const EVT PtrVT, TLSModel::Model model,
6484 DebugLoc dl = GA->getDebugLoc();
6486 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6487 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6488 is64Bit ? 257 : 256));
6490 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6491 DAG.getIntPtrConstant(0),
6492 MachinePointerInfo(Ptr), false, false, 0);
6494 unsigned char OperandFlags = 0;
6495 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6497 unsigned WrapperKind = X86ISD::Wrapper;
6498 if (model == TLSModel::LocalExec) {
6499 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6500 } else if (is64Bit) {
6501 assert(model == TLSModel::InitialExec);
6502 OperandFlags = X86II::MO_GOTTPOFF;
6503 WrapperKind = X86ISD::WrapperRIP;
6505 assert(model == TLSModel::InitialExec);
6506 OperandFlags = X86II::MO_INDNTPOFF;
6509 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6511 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6512 GA->getValueType(0),
6513 GA->getOffset(), OperandFlags);
6514 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6516 if (model == TLSModel::InitialExec)
6517 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6518 MachinePointerInfo::getGOT(), false, false, 0);
6520 // The address of the thread local variable is the add of the thread
6521 // pointer with the offset of the variable.
6522 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6526 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6528 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6529 const GlobalValue *GV = GA->getGlobal();
6531 if (Subtarget->isTargetELF()) {
6532 // TODO: implement the "local dynamic" model
6533 // TODO: implement the "initial exec"model for pic executables
6535 // If GV is an alias then use the aliasee for determining
6536 // thread-localness.
6537 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6538 GV = GA->resolveAliasedGlobal(false);
6540 TLSModel::Model model
6541 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6544 case TLSModel::GeneralDynamic:
6545 case TLSModel::LocalDynamic: // not implemented
6546 if (Subtarget->is64Bit())
6547 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6548 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6550 case TLSModel::InitialExec:
6551 case TLSModel::LocalExec:
6552 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6553 Subtarget->is64Bit());
6555 } else if (Subtarget->isTargetDarwin()) {
6556 // Darwin only has one model of TLS. Lower to that.
6557 unsigned char OpFlag = 0;
6558 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6559 X86ISD::WrapperRIP : X86ISD::Wrapper;
6561 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6563 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6564 !Subtarget->is64Bit();
6566 OpFlag = X86II::MO_TLVP_PIC_BASE;
6568 OpFlag = X86II::MO_TLVP;
6569 DebugLoc DL = Op.getDebugLoc();
6570 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6571 GA->getValueType(0),
6572 GA->getOffset(), OpFlag);
6573 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6575 // With PIC32, the address is actually $g + Offset.
6577 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6578 DAG.getNode(X86ISD::GlobalBaseReg,
6579 DebugLoc(), getPointerTy()),
6582 // Lowering the machine isd will make sure everything is in the right
6584 SDValue Chain = DAG.getEntryNode();
6585 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6586 SDValue Args[] = { Chain, Offset };
6587 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6589 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6590 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6591 MFI->setAdjustsStack(true);
6593 // And our return value (tls address) is in the standard call return value
6595 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6596 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6600 "TLS not implemented for this target.");
6602 llvm_unreachable("Unreachable");
6607 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6608 /// take a 2 x i32 value to shift plus a shift amount.
6609 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6610 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6611 EVT VT = Op.getValueType();
6612 unsigned VTBits = VT.getSizeInBits();
6613 DebugLoc dl = Op.getDebugLoc();
6614 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6615 SDValue ShOpLo = Op.getOperand(0);
6616 SDValue ShOpHi = Op.getOperand(1);
6617 SDValue ShAmt = Op.getOperand(2);
6618 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6619 DAG.getConstant(VTBits - 1, MVT::i8))
6620 : DAG.getConstant(0, VT);
6623 if (Op.getOpcode() == ISD::SHL_PARTS) {
6624 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6625 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6627 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6628 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6631 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6632 DAG.getConstant(VTBits, MVT::i8));
6633 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6634 AndNode, DAG.getConstant(0, MVT::i8));
6637 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6638 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6639 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6641 if (Op.getOpcode() == ISD::SHL_PARTS) {
6642 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6643 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6645 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6646 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6649 SDValue Ops[2] = { Lo, Hi };
6650 return DAG.getMergeValues(Ops, 2, dl);
6653 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6654 SelectionDAG &DAG) const {
6655 EVT SrcVT = Op.getOperand(0).getValueType();
6657 if (SrcVT.isVector())
6660 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6661 "Unknown SINT_TO_FP to lower!");
6663 // These are really Legal; return the operand so the caller accepts it as
6665 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6667 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6668 Subtarget->is64Bit()) {
6672 DebugLoc dl = Op.getDebugLoc();
6673 unsigned Size = SrcVT.getSizeInBits()/8;
6674 MachineFunction &MF = DAG.getMachineFunction();
6675 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6676 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6677 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6679 MachinePointerInfo::getFixedStack(SSFI),
6681 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6684 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6686 SelectionDAG &DAG) const {
6688 DebugLoc DL = Op.getDebugLoc();
6690 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6692 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6694 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6696 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6698 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6699 MachineMemOperand *MMO =
6700 DAG.getMachineFunction()
6701 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6702 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6704 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6705 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6707 Tys, Ops, array_lengthof(Ops),
6711 Chain = Result.getValue(1);
6712 SDValue InFlag = Result.getValue(2);
6714 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6715 // shouldn't be necessary except that RFP cannot be live across
6716 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6717 MachineFunction &MF = DAG.getMachineFunction();
6718 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6719 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6720 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6721 Tys = DAG.getVTList(MVT::Other);
6723 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6725 MachineMemOperand *MMO =
6726 DAG.getMachineFunction()
6727 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6728 MachineMemOperand::MOStore, SSFISize, SSFISize);
6730 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6731 Ops, array_lengthof(Ops),
6732 Op.getValueType(), MMO);
6733 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6734 MachinePointerInfo::getFixedStack(SSFI),
6741 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6742 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6743 SelectionDAG &DAG) const {
6744 // This algorithm is not obvious. Here it is in C code, more or less:
6746 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6747 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6748 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6750 // Copy ints to xmm registers.
6751 __m128i xh = _mm_cvtsi32_si128( hi );
6752 __m128i xl = _mm_cvtsi32_si128( lo );
6754 // Combine into low half of a single xmm register.
6755 __m128i x = _mm_unpacklo_epi32( xh, xl );
6759 // Merge in appropriate exponents to give the integer bits the right
6761 x = _mm_unpacklo_epi32( x, exp );
6763 // Subtract away the biases to deal with the IEEE-754 double precision
6765 d = _mm_sub_pd( (__m128d) x, bias );
6767 // All conversions up to here are exact. The correctly rounded result is
6768 // calculated using the current rounding mode using the following
6770 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6771 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6772 // store doesn't really need to be here (except
6773 // maybe to zero the other double)
6778 DebugLoc dl = Op.getDebugLoc();
6779 LLVMContext *Context = DAG.getContext();
6781 // Build some magic constants.
6782 std::vector<Constant*> CV0;
6783 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6784 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6785 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6786 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6787 Constant *C0 = ConstantVector::get(CV0);
6788 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6790 std::vector<Constant*> CV1;
6792 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6794 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6795 Constant *C1 = ConstantVector::get(CV1);
6796 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6798 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6799 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6801 DAG.getIntPtrConstant(1)));
6802 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6803 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6805 DAG.getIntPtrConstant(0)));
6806 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6807 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6808 MachinePointerInfo::getConstantPool(),
6810 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6811 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6812 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6813 MachinePointerInfo::getConstantPool(),
6815 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6817 // Add the halves; easiest way is to swap them into another reg first.
6818 int ShufMask[2] = { 1, -1 };
6819 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6820 DAG.getUNDEF(MVT::v2f64), ShufMask);
6821 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6823 DAG.getIntPtrConstant(0));
6826 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6827 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6828 SelectionDAG &DAG) const {
6829 DebugLoc dl = Op.getDebugLoc();
6830 // FP constant to bias correct the final result.
6831 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6834 // Load the 32-bit value into an XMM register.
6835 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6836 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6838 DAG.getIntPtrConstant(0)));
6840 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6841 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6842 DAG.getIntPtrConstant(0));
6844 // Or the load with the bias.
6845 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6846 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6847 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6849 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6850 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6851 MVT::v2f64, Bias)));
6852 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6853 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6854 DAG.getIntPtrConstant(0));
6856 // Subtract the bias.
6857 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6859 // Handle final rounding.
6860 EVT DestVT = Op.getValueType();
6862 if (DestVT.bitsLT(MVT::f64)) {
6863 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6864 DAG.getIntPtrConstant(0));
6865 } else if (DestVT.bitsGT(MVT::f64)) {
6866 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6869 // Handle final rounding.
6873 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6874 SelectionDAG &DAG) const {
6875 SDValue N0 = Op.getOperand(0);
6876 DebugLoc dl = Op.getDebugLoc();
6878 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6879 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6880 // the optimization here.
6881 if (DAG.SignBitIsZero(N0))
6882 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6884 EVT SrcVT = N0.getValueType();
6885 EVT DstVT = Op.getValueType();
6886 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6887 return LowerUINT_TO_FP_i64(Op, DAG);
6888 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6889 return LowerUINT_TO_FP_i32(Op, DAG);
6891 // Make a 64-bit buffer, and use it to build an FILD.
6892 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6893 if (SrcVT == MVT::i32) {
6894 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6895 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6896 getPointerTy(), StackSlot, WordOff);
6897 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6898 StackSlot, MachinePointerInfo(),
6900 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6901 OffsetSlot, MachinePointerInfo(),
6903 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6907 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6908 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6909 StackSlot, MachinePointerInfo(),
6911 // For i64 source, we need to add the appropriate power of 2 if the input
6912 // was negative. This is the same as the optimization in
6913 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6914 // we must be careful to do the computation in x87 extended precision, not
6915 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6916 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6917 MachineMemOperand *MMO =
6918 DAG.getMachineFunction()
6919 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6920 MachineMemOperand::MOLoad, 8, 8);
6922 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6923 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6924 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6927 APInt FF(32, 0x5F800000ULL);
6929 // Check whether the sign bit is set.
6930 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6931 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6934 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6935 SDValue FudgePtr = DAG.getConstantPool(
6936 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6939 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6940 SDValue Zero = DAG.getIntPtrConstant(0);
6941 SDValue Four = DAG.getIntPtrConstant(4);
6942 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6944 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6946 // Load the value out, extending it from f32 to f80.
6947 // FIXME: Avoid the extend by constructing the right constant pool?
6948 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6949 FudgePtr, MachinePointerInfo::getConstantPool(),
6950 MVT::f32, false, false, 4);
6951 // Extend everything to 80 bits to force it to be done on x87.
6952 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6953 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6956 std::pair<SDValue,SDValue> X86TargetLowering::
6957 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6958 DebugLoc DL = Op.getDebugLoc();
6960 EVT DstTy = Op.getValueType();
6963 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6967 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6968 DstTy.getSimpleVT() >= MVT::i16 &&
6969 "Unknown FP_TO_SINT to lower!");
6971 // These are really Legal.
6972 if (DstTy == MVT::i32 &&
6973 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6974 return std::make_pair(SDValue(), SDValue());
6975 if (Subtarget->is64Bit() &&
6976 DstTy == MVT::i64 &&
6977 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6978 return std::make_pair(SDValue(), SDValue());
6980 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6982 MachineFunction &MF = DAG.getMachineFunction();
6983 unsigned MemSize = DstTy.getSizeInBits()/8;
6984 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6985 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6990 switch (DstTy.getSimpleVT().SimpleTy) {
6991 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6992 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6993 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6994 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6997 SDValue Chain = DAG.getEntryNode();
6998 SDValue Value = Op.getOperand(0);
6999 EVT TheVT = Op.getOperand(0).getValueType();
7000 if (isScalarFPTypeInSSEReg(TheVT)) {
7001 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7002 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7003 MachinePointerInfo::getFixedStack(SSFI),
7005 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7007 Chain, StackSlot, DAG.getValueType(TheVT)
7010 MachineMemOperand *MMO =
7011 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7012 MachineMemOperand::MOLoad, MemSize, MemSize);
7013 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7015 Chain = Value.getValue(1);
7016 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7017 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7020 MachineMemOperand *MMO =
7021 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7022 MachineMemOperand::MOStore, MemSize, MemSize);
7024 // Build the FP_TO_INT*_IN_MEM
7025 SDValue Ops[] = { Chain, Value, StackSlot };
7026 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7027 Ops, 3, DstTy, MMO);
7029 return std::make_pair(FIST, StackSlot);
7032 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7033 SelectionDAG &DAG) const {
7034 if (Op.getValueType().isVector())
7037 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7038 SDValue FIST = Vals.first, StackSlot = Vals.second;
7039 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7040 if (FIST.getNode() == 0) return Op;
7043 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7044 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7047 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7048 SelectionDAG &DAG) const {
7049 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7050 SDValue FIST = Vals.first, StackSlot = Vals.second;
7051 assert(FIST.getNode() && "Unexpected failure");
7054 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7055 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7058 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7059 SelectionDAG &DAG) const {
7060 LLVMContext *Context = DAG.getContext();
7061 DebugLoc dl = Op.getDebugLoc();
7062 EVT VT = Op.getValueType();
7065 EltVT = VT.getVectorElementType();
7066 std::vector<Constant*> CV;
7067 if (EltVT == MVT::f64) {
7068 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7072 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7078 Constant *C = ConstantVector::get(CV);
7079 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7080 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7081 MachinePointerInfo::getConstantPool(),
7083 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7086 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7087 LLVMContext *Context = DAG.getContext();
7088 DebugLoc dl = Op.getDebugLoc();
7089 EVT VT = Op.getValueType();
7092 EltVT = VT.getVectorElementType();
7093 std::vector<Constant*> CV;
7094 if (EltVT == MVT::f64) {
7095 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7099 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7105 Constant *C = ConstantVector::get(CV);
7106 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7107 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7108 MachinePointerInfo::getConstantPool(),
7110 if (VT.isVector()) {
7111 return DAG.getNode(ISD::BITCAST, dl, VT,
7112 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7113 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7115 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7117 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7121 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7122 LLVMContext *Context = DAG.getContext();
7123 SDValue Op0 = Op.getOperand(0);
7124 SDValue Op1 = Op.getOperand(1);
7125 DebugLoc dl = Op.getDebugLoc();
7126 EVT VT = Op.getValueType();
7127 EVT SrcVT = Op1.getValueType();
7129 // If second operand is smaller, extend it first.
7130 if (SrcVT.bitsLT(VT)) {
7131 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7134 // And if it is bigger, shrink it first.
7135 if (SrcVT.bitsGT(VT)) {
7136 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7140 // At this point the operands and the result should have the same
7141 // type, and that won't be f80 since that is not custom lowered.
7143 // First get the sign bit of second operand.
7144 std::vector<Constant*> CV;
7145 if (SrcVT == MVT::f64) {
7146 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7147 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7149 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7150 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7151 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7152 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7154 Constant *C = ConstantVector::get(CV);
7155 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7156 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7157 MachinePointerInfo::getConstantPool(),
7159 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7161 // Shift sign bit right or left if the two operands have different types.
7162 if (SrcVT.bitsGT(VT)) {
7163 // Op0 is MVT::f32, Op1 is MVT::f64.
7164 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7165 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7166 DAG.getConstant(32, MVT::i32));
7167 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7168 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7169 DAG.getIntPtrConstant(0));
7172 // Clear first operand sign bit.
7174 if (VT == MVT::f64) {
7175 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7176 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7178 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7179 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7180 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7181 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7183 C = ConstantVector::get(CV);
7184 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7185 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7186 MachinePointerInfo::getConstantPool(),
7188 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7190 // Or the value with the sign bit.
7191 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7194 /// Emit nodes that will be selected as "test Op0,Op0", or something
7196 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7197 SelectionDAG &DAG) const {
7198 DebugLoc dl = Op.getDebugLoc();
7200 // CF and OF aren't always set the way we want. Determine which
7201 // of these we need.
7202 bool NeedCF = false;
7203 bool NeedOF = false;
7206 case X86::COND_A: case X86::COND_AE:
7207 case X86::COND_B: case X86::COND_BE:
7210 case X86::COND_G: case X86::COND_GE:
7211 case X86::COND_L: case X86::COND_LE:
7212 case X86::COND_O: case X86::COND_NO:
7217 // See if we can use the EFLAGS value from the operand instead of
7218 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7219 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7220 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7221 // Emit a CMP with 0, which is the TEST pattern.
7222 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7223 DAG.getConstant(0, Op.getValueType()));
7225 unsigned Opcode = 0;
7226 unsigned NumOperands = 0;
7227 switch (Op.getNode()->getOpcode()) {
7229 // Due to an isel shortcoming, be conservative if this add is likely to be
7230 // selected as part of a load-modify-store instruction. When the root node
7231 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7232 // uses of other nodes in the match, such as the ADD in this case. This
7233 // leads to the ADD being left around and reselected, with the result being
7234 // two adds in the output. Alas, even if none our users are stores, that
7235 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7236 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7237 // climbing the DAG back to the root, and it doesn't seem to be worth the
7239 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7240 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7241 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7244 if (ConstantSDNode *C =
7245 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7246 // An add of one will be selected as an INC.
7247 if (C->getAPIntValue() == 1) {
7248 Opcode = X86ISD::INC;
7253 // An add of negative one (subtract of one) will be selected as a DEC.
7254 if (C->getAPIntValue().isAllOnesValue()) {
7255 Opcode = X86ISD::DEC;
7261 // Otherwise use a regular EFLAGS-setting add.
7262 Opcode = X86ISD::ADD;
7266 // If the primary and result isn't used, don't bother using X86ISD::AND,
7267 // because a TEST instruction will be better.
7268 bool NonFlagUse = false;
7269 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7270 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7272 unsigned UOpNo = UI.getOperandNo();
7273 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7274 // Look pass truncate.
7275 UOpNo = User->use_begin().getOperandNo();
7276 User = *User->use_begin();
7279 if (User->getOpcode() != ISD::BRCOND &&
7280 User->getOpcode() != ISD::SETCC &&
7281 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7294 // Due to the ISEL shortcoming noted above, be conservative if this op is
7295 // likely to be selected as part of a load-modify-store instruction.
7296 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7297 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7298 if (UI->getOpcode() == ISD::STORE)
7301 // Otherwise use a regular EFLAGS-setting instruction.
7302 switch (Op.getNode()->getOpcode()) {
7303 default: llvm_unreachable("unexpected operator!");
7304 case ISD::SUB: Opcode = X86ISD::SUB; break;
7305 case ISD::OR: Opcode = X86ISD::OR; break;
7306 case ISD::XOR: Opcode = X86ISD::XOR; break;
7307 case ISD::AND: Opcode = X86ISD::AND; break;
7319 return SDValue(Op.getNode(), 1);
7326 // Emit a CMP with 0, which is the TEST pattern.
7327 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7328 DAG.getConstant(0, Op.getValueType()));
7330 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7331 SmallVector<SDValue, 4> Ops;
7332 for (unsigned i = 0; i != NumOperands; ++i)
7333 Ops.push_back(Op.getOperand(i));
7335 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7336 DAG.ReplaceAllUsesWith(Op, New);
7337 return SDValue(New.getNode(), 1);
7340 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7342 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7343 SelectionDAG &DAG) const {
7344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7345 if (C->getAPIntValue() == 0)
7346 return EmitTest(Op0, X86CC, DAG);
7348 DebugLoc dl = Op0.getDebugLoc();
7349 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7352 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7353 /// if it's possible.
7354 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7355 DebugLoc dl, SelectionDAG &DAG) const {
7356 SDValue Op0 = And.getOperand(0);
7357 SDValue Op1 = And.getOperand(1);
7358 if (Op0.getOpcode() == ISD::TRUNCATE)
7359 Op0 = Op0.getOperand(0);
7360 if (Op1.getOpcode() == ISD::TRUNCATE)
7361 Op1 = Op1.getOperand(0);
7364 if (Op1.getOpcode() == ISD::SHL)
7365 std::swap(Op0, Op1);
7366 if (Op0.getOpcode() == ISD::SHL) {
7367 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7368 if (And00C->getZExtValue() == 1) {
7369 // If we looked past a truncate, check that it's only truncating away
7371 unsigned BitWidth = Op0.getValueSizeInBits();
7372 unsigned AndBitWidth = And.getValueSizeInBits();
7373 if (BitWidth > AndBitWidth) {
7374 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7375 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7376 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7380 RHS = Op0.getOperand(1);
7382 } else if (Op1.getOpcode() == ISD::Constant) {
7383 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7384 SDValue AndLHS = Op0;
7385 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7386 LHS = AndLHS.getOperand(0);
7387 RHS = AndLHS.getOperand(1);
7391 if (LHS.getNode()) {
7392 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7393 // instruction. Since the shift amount is in-range-or-undefined, we know
7394 // that doing a bittest on the i32 value is ok. We extend to i32 because
7395 // the encoding for the i16 version is larger than the i32 version.
7396 // Also promote i16 to i32 for performance / code size reason.
7397 if (LHS.getValueType() == MVT::i8 ||
7398 LHS.getValueType() == MVT::i16)
7399 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7401 // If the operand types disagree, extend the shift amount to match. Since
7402 // BT ignores high bits (like shifts) we can use anyextend.
7403 if (LHS.getValueType() != RHS.getValueType())
7404 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7406 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7407 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7408 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7409 DAG.getConstant(Cond, MVT::i8), BT);
7415 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7416 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7417 SDValue Op0 = Op.getOperand(0);
7418 SDValue Op1 = Op.getOperand(1);
7419 DebugLoc dl = Op.getDebugLoc();
7420 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7422 // Optimize to BT if possible.
7423 // Lower (X & (1 << N)) == 0 to BT(X, N).
7424 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7425 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7426 if (isTypeLegal(Op0.getValueType()) &&
7427 Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7428 Op1.getOpcode() == ISD::Constant &&
7429 cast<ConstantSDNode>(Op1)->isNullValue() &&
7430 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7431 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7432 if (NewSetCC.getNode())
7436 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7438 if (Op1.getOpcode() == ISD::Constant &&
7439 (cast<ConstantSDNode>(Op1)->isOne() ||
7440 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7441 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7443 // If the input is a setcc, then reuse the input setcc or use a new one with
7444 // the inverted condition.
7445 if (Op0.getOpcode() == X86ISD::SETCC) {
7446 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7447 bool Invert = (CC == ISD::SETNE) ^
7448 cast<ConstantSDNode>(Op1)->isNullValue();
7449 if (!Invert) return Op0;
7451 CCode = X86::GetOppositeBranchCondition(CCode);
7452 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7453 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7457 bool isFP = Op1.getValueType().isFloatingPoint();
7458 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7459 if (X86CC == X86::COND_INVALID)
7462 if ((!Subtarget->is64Bit() && Op0.getValueType() == MVT::i64) ||
7463 (Subtarget->is64Bit() && Op0.getValueType() == MVT::i128)) {
7469 // Just use the generic lowering, which works well on x86.
7475 // Use SBB-based lowering.
7478 // Use SBB-based lowering; commute so ZF isn't used.
7479 X86CC = X86::COND_B;
7480 std::swap(Op0, Op1);
7483 // Use SBB-based lowering; commute so ZF isn't used.
7484 X86CC = X86::COND_AE;
7485 std::swap(Op0, Op1);
7488 // Use SBB-based lowering; commute so ZF isn't used.
7489 X86CC = X86::COND_L;
7490 std::swap(Op0, Op1);
7493 // Use SBB-based lowering; commute so ZF isn't used.
7494 X86CC = X86::COND_GE;
7495 std::swap(Op0, Op1);
7498 assert(0 && "Unexpected X86CC.");
7501 MVT HalfType = getPointerTy();
7502 // FIXME: Refactor this code out to implement ISD::SADDO and friends.
7503 SDValue Op0Low = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfType,
7504 Op0, DAG.getIntPtrConstant(0));
7505 SDValue Op1Low = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfType,
7506 Op1, DAG.getIntPtrConstant(0));
7507 SDValue Op0High = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfType,
7508 Op0, DAG.getIntPtrConstant(1));
7509 SDValue Op1High = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfType,
7510 Op1, DAG.getIntPtrConstant(1));
7511 // Redirect some cases which will simplify to the generic expansion;
7512 // X86ISD::SUB and X86ISD::SBB are not optimized well at the moment.
7513 // FIXME: We really need to add DAGCombines for SUB/SBB/etc.
7514 if (Op1Low.getOpcode() == ISD::Constant &&
7515 cast<ConstantSDNode>(Op1Low)->isNullValue())
7517 if (Op0Low.getOpcode() == ISD::Constant &&
7518 cast<ConstantSDNode>(Op0Low)->isAllOnesValue())
7521 SDVTList VTList = DAG.getVTList(HalfType, MVT::i32);
7522 res1 = DAG.getNode(X86ISD::SUB, dl, VTList, Op0Low, Op1Low).getValue(1);
7523 res2 = DAG.getNode(X86ISD::SBB, dl, VTList, Op0High, Op1High,
7525 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7526 DAG.getConstant(X86CC, MVT::i8), res2);
7529 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7530 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7531 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7534 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7536 SDValue Op0 = Op.getOperand(0);
7537 SDValue Op1 = Op.getOperand(1);
7538 SDValue CC = Op.getOperand(2);
7539 EVT VT = Op.getValueType();
7540 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7541 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7542 DebugLoc dl = Op.getDebugLoc();
7546 EVT VT0 = Op0.getValueType();
7547 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7548 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7551 switch (SetCCOpcode) {
7554 case ISD::SETEQ: SSECC = 0; break;
7556 case ISD::SETGT: Swap = true; // Fallthrough
7558 case ISD::SETOLT: SSECC = 1; break;
7560 case ISD::SETGE: Swap = true; // Fallthrough
7562 case ISD::SETOLE: SSECC = 2; break;
7563 case ISD::SETUO: SSECC = 3; break;
7565 case ISD::SETNE: SSECC = 4; break;
7566 case ISD::SETULE: Swap = true;
7567 case ISD::SETUGE: SSECC = 5; break;
7568 case ISD::SETULT: Swap = true;
7569 case ISD::SETUGT: SSECC = 6; break;
7570 case ISD::SETO: SSECC = 7; break;
7573 std::swap(Op0, Op1);
7575 // In the two special cases we can't handle, emit two comparisons.
7577 if (SetCCOpcode == ISD::SETUEQ) {
7579 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7580 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7581 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7583 else if (SetCCOpcode == ISD::SETONE) {
7585 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7586 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7587 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7589 llvm_unreachable("Illegal FP comparison");
7591 // Handle all other FP comparisons here.
7592 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7595 // We are handling one of the integer comparisons here. Since SSE only has
7596 // GT and EQ comparisons for integer, swapping operands and multiple
7597 // operations may be required for some comparisons.
7598 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7599 bool Swap = false, Invert = false, FlipSigns = false;
7601 switch (VT.getSimpleVT().SimpleTy) {
7603 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7604 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7605 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7606 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7609 switch (SetCCOpcode) {
7611 case ISD::SETNE: Invert = true;
7612 case ISD::SETEQ: Opc = EQOpc; break;
7613 case ISD::SETLT: Swap = true;
7614 case ISD::SETGT: Opc = GTOpc; break;
7615 case ISD::SETGE: Swap = true;
7616 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7617 case ISD::SETULT: Swap = true;
7618 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7619 case ISD::SETUGE: Swap = true;
7620 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7623 std::swap(Op0, Op1);
7625 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7626 // bits of the inputs before performing those operations.
7628 EVT EltVT = VT.getVectorElementType();
7629 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7631 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7632 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7634 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7635 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7638 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7640 // If the logical-not of the result is required, perform that now.
7642 Result = DAG.getNOT(dl, Result, VT);
7647 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7648 static bool isX86LogicalCmp(SDValue Op) {
7649 unsigned Opc = Op.getNode()->getOpcode();
7650 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7652 if (Op.getResNo() == 1 &&
7653 (Opc == X86ISD::ADD ||
7654 Opc == X86ISD::SUB ||
7655 Opc == X86ISD::ADC ||
7656 Opc == X86ISD::SBB ||
7657 Opc == X86ISD::SMUL ||
7658 Opc == X86ISD::UMUL ||
7659 Opc == X86ISD::INC ||
7660 Opc == X86ISD::DEC ||
7661 Opc == X86ISD::OR ||
7662 Opc == X86ISD::XOR ||
7663 Opc == X86ISD::AND))
7666 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7672 static bool isZero(SDValue V) {
7673 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7674 return C && C->isNullValue();
7677 static bool isAllOnes(SDValue V) {
7678 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7679 return C && C->isAllOnesValue();
7682 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7683 bool addTest = true;
7684 SDValue Cond = Op.getOperand(0);
7685 SDValue Op1 = Op.getOperand(1);
7686 SDValue Op2 = Op.getOperand(2);
7687 DebugLoc DL = Op.getDebugLoc();
7690 if (Cond.getOpcode() == ISD::SETCC) {
7691 SDValue NewCond = LowerSETCC(Cond, DAG);
7692 if (NewCond.getNode())
7696 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7697 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7698 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7699 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7700 if (Cond.getOpcode() == X86ISD::SETCC &&
7701 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7702 isZero(Cond.getOperand(1).getOperand(1))) {
7703 SDValue Cmp = Cond.getOperand(1);
7705 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7707 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7708 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7709 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7711 SDValue CmpOp0 = Cmp.getOperand(0);
7712 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7713 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7715 SDValue Res = // Res = 0 or -1.
7716 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7717 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7719 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7720 Res = DAG.getNOT(DL, Res, Res.getValueType());
7722 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7723 if (N2C == 0 || !N2C->isNullValue())
7724 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7729 // Look past (and (setcc_carry (cmp ...)), 1).
7730 if (Cond.getOpcode() == ISD::AND &&
7731 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7733 if (C && C->getAPIntValue() == 1)
7734 Cond = Cond.getOperand(0);
7737 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7738 // setting operand in place of the X86ISD::SETCC.
7739 if (Cond.getOpcode() == X86ISD::SETCC ||
7740 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7741 CC = Cond.getOperand(0);
7743 SDValue Cmp = Cond.getOperand(1);
7744 unsigned Opc = Cmp.getOpcode();
7745 EVT VT = Op.getValueType();
7747 bool IllegalFPCMov = false;
7748 if (VT.isFloatingPoint() && !VT.isVector() &&
7749 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7750 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7752 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7753 Opc == X86ISD::BT) { // FIXME
7760 // Look pass the truncate.
7761 if (Cond.getOpcode() == ISD::TRUNCATE)
7762 Cond = Cond.getOperand(0);
7764 // We know the result of AND is compared against zero. Try to match
7766 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7767 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7768 if (NewSetCC.getNode()) {
7769 CC = NewSetCC.getOperand(0);
7770 Cond = NewSetCC.getOperand(1);
7777 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7778 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7781 // a < b ? -1 : 0 -> RES = ~setcc_carry
7782 // a < b ? 0 : -1 -> RES = setcc_carry
7783 // a >= b ? -1 : 0 -> RES = setcc_carry
7784 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7785 if (Cond.getOpcode() == X86ISD::CMP) {
7786 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7788 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7789 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7790 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7791 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7792 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7793 return DAG.getNOT(DL, Res, Res.getValueType());
7798 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7799 // condition is true.
7800 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7801 SDValue Ops[] = { Op2, Op1, CC, Cond };
7802 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7805 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7806 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7807 // from the AND / OR.
7808 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7809 Opc = Op.getOpcode();
7810 if (Opc != ISD::OR && Opc != ISD::AND)
7812 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7813 Op.getOperand(0).hasOneUse() &&
7814 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7815 Op.getOperand(1).hasOneUse());
7818 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7819 // 1 and that the SETCC node has a single use.
7820 static bool isXor1OfSetCC(SDValue Op) {
7821 if (Op.getOpcode() != ISD::XOR)
7823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7824 if (N1C && N1C->getAPIntValue() == 1) {
7825 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7826 Op.getOperand(0).hasOneUse();
7831 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7832 bool addTest = true;
7833 SDValue Chain = Op.getOperand(0);
7834 SDValue Cond = Op.getOperand(1);
7835 SDValue Dest = Op.getOperand(2);
7836 DebugLoc dl = Op.getDebugLoc();
7839 if (Cond.getOpcode() == ISD::SETCC) {
7840 SDValue NewCond = LowerSETCC(Cond, DAG);
7841 if (NewCond.getNode())
7845 // FIXME: LowerXALUO doesn't handle these!!
7846 else if (Cond.getOpcode() == X86ISD::ADD ||
7847 Cond.getOpcode() == X86ISD::SUB ||
7848 Cond.getOpcode() == X86ISD::SMUL ||
7849 Cond.getOpcode() == X86ISD::UMUL)
7850 Cond = LowerXALUO(Cond, DAG);
7853 // Look pass (and (setcc_carry (cmp ...)), 1).
7854 if (Cond.getOpcode() == ISD::AND &&
7855 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7856 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7857 if (C && C->getAPIntValue() == 1)
7858 Cond = Cond.getOperand(0);
7861 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7862 // setting operand in place of the X86ISD::SETCC.
7863 if (Cond.getOpcode() == X86ISD::SETCC ||
7864 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7865 CC = Cond.getOperand(0);
7867 SDValue Cmp = Cond.getOperand(1);
7868 unsigned Opc = Cmp.getOpcode();
7869 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7870 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7874 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7878 // These can only come from an arithmetic instruction with overflow,
7879 // e.g. SADDO, UADDO.
7880 Cond = Cond.getNode()->getOperand(1);
7887 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7888 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7889 if (CondOpc == ISD::OR) {
7890 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7891 // two branches instead of an explicit OR instruction with a
7893 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7894 isX86LogicalCmp(Cmp)) {
7895 CC = Cond.getOperand(0).getOperand(0);
7896 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7897 Chain, Dest, CC, Cmp);
7898 CC = Cond.getOperand(1).getOperand(0);
7902 } else { // ISD::AND
7903 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7904 // two branches instead of an explicit AND instruction with a
7905 // separate test. However, we only do this if this block doesn't
7906 // have a fall-through edge, because this requires an explicit
7907 // jmp when the condition is false.
7908 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7909 isX86LogicalCmp(Cmp) &&
7910 Op.getNode()->hasOneUse()) {
7911 X86::CondCode CCode =
7912 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7913 CCode = X86::GetOppositeBranchCondition(CCode);
7914 CC = DAG.getConstant(CCode, MVT::i8);
7915 SDNode *User = *Op.getNode()->use_begin();
7916 // Look for an unconditional branch following this conditional branch.
7917 // We need this because we need to reverse the successors in order
7918 // to implement FCMP_OEQ.
7919 if (User->getOpcode() == ISD::BR) {
7920 SDValue FalseBB = User->getOperand(1);
7922 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7923 assert(NewBR == User);
7927 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7928 Chain, Dest, CC, Cmp);
7929 X86::CondCode CCode =
7930 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7931 CCode = X86::GetOppositeBranchCondition(CCode);
7932 CC = DAG.getConstant(CCode, MVT::i8);
7938 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7939 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7940 // It should be transformed during dag combiner except when the condition
7941 // is set by a arithmetics with overflow node.
7942 X86::CondCode CCode =
7943 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7944 CCode = X86::GetOppositeBranchCondition(CCode);
7945 CC = DAG.getConstant(CCode, MVT::i8);
7946 Cond = Cond.getOperand(0).getOperand(1);
7952 // Look pass the truncate.
7953 if (Cond.getOpcode() == ISD::TRUNCATE)
7954 Cond = Cond.getOperand(0);
7956 // We know the result of AND is compared against zero. Try to match
7958 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7959 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7960 if (NewSetCC.getNode()) {
7961 CC = NewSetCC.getOperand(0);
7962 Cond = NewSetCC.getOperand(1);
7969 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7970 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7972 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7973 Chain, Dest, CC, Cond);
7977 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7978 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7979 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7980 // that the guard pages used by the OS virtual memory manager are allocated in
7981 // correct sequence.
7983 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7984 SelectionDAG &DAG) const {
7985 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7986 "This should be used only on Windows targets");
7987 DebugLoc dl = Op.getDebugLoc();
7990 SDValue Chain = Op.getOperand(0);
7991 SDValue Size = Op.getOperand(1);
7992 // FIXME: Ensure alignment here
7996 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7998 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7999 Flag = Chain.getValue(1);
8001 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8003 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8004 Flag = Chain.getValue(1);
8006 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8008 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8009 return DAG.getMergeValues(Ops1, 2, dl);
8012 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8013 MachineFunction &MF = DAG.getMachineFunction();
8014 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8016 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8017 DebugLoc DL = Op.getDebugLoc();
8019 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8020 // vastart just stores the address of the VarArgsFrameIndex slot into the
8021 // memory location argument.
8022 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8024 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8025 MachinePointerInfo(SV), false, false, 0);
8029 // gp_offset (0 - 6 * 8)
8030 // fp_offset (48 - 48 + 8 * 16)
8031 // overflow_arg_area (point to parameters coming in memory).
8033 SmallVector<SDValue, 8> MemOps;
8034 SDValue FIN = Op.getOperand(1);
8036 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8037 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8039 FIN, MachinePointerInfo(SV), false, false, 0);
8040 MemOps.push_back(Store);
8043 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8044 FIN, DAG.getIntPtrConstant(4));
8045 Store = DAG.getStore(Op.getOperand(0), DL,
8046 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8048 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8049 MemOps.push_back(Store);
8051 // Store ptr to overflow_arg_area
8052 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8053 FIN, DAG.getIntPtrConstant(4));
8054 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8056 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8057 MachinePointerInfo(SV, 8),
8059 MemOps.push_back(Store);
8061 // Store ptr to reg_save_area.
8062 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8063 FIN, DAG.getIntPtrConstant(8));
8064 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8066 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8067 MachinePointerInfo(SV, 16), false, false, 0);
8068 MemOps.push_back(Store);
8069 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8070 &MemOps[0], MemOps.size());
8073 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8074 assert(Subtarget->is64Bit() &&
8075 "LowerVAARG only handles 64-bit va_arg!");
8076 assert((Subtarget->isTargetLinux() ||
8077 Subtarget->isTargetDarwin()) &&
8078 "Unhandled target in LowerVAARG");
8079 assert(Op.getNode()->getNumOperands() == 4);
8080 SDValue Chain = Op.getOperand(0);
8081 SDValue SrcPtr = Op.getOperand(1);
8082 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8083 unsigned Align = Op.getConstantOperandVal(3);
8084 DebugLoc dl = Op.getDebugLoc();
8086 EVT ArgVT = Op.getNode()->getValueType(0);
8087 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8088 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8091 // Decide which area this value should be read from.
8092 // TODO: Implement the AMD64 ABI in its entirety. This simple
8093 // selection mechanism works only for the basic types.
8094 if (ArgVT == MVT::f80) {
8095 llvm_unreachable("va_arg for f80 not yet implemented");
8096 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8097 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8098 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8099 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8101 llvm_unreachable("Unhandled argument type in LowerVAARG");
8105 // Sanity Check: Make sure using fp_offset makes sense.
8106 assert(!UseSoftFloat &&
8107 !(DAG.getMachineFunction()
8108 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8109 Subtarget->hasXMM());
8112 // Insert VAARG_64 node into the DAG
8113 // VAARG_64 returns two values: Variable Argument Address, Chain
8114 SmallVector<SDValue, 11> InstOps;
8115 InstOps.push_back(Chain);
8116 InstOps.push_back(SrcPtr);
8117 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8118 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8119 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8120 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8121 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8122 VTs, &InstOps[0], InstOps.size(),
8124 MachinePointerInfo(SV),
8129 Chain = VAARG.getValue(1);
8131 // Load the next argument and return it
8132 return DAG.getLoad(ArgVT, dl,
8135 MachinePointerInfo(),
8139 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8140 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8141 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8142 SDValue Chain = Op.getOperand(0);
8143 SDValue DstPtr = Op.getOperand(1);
8144 SDValue SrcPtr = Op.getOperand(2);
8145 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8146 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8147 DebugLoc DL = Op.getDebugLoc();
8149 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8150 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8152 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8156 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8157 DebugLoc dl = Op.getDebugLoc();
8158 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8160 default: return SDValue(); // Don't custom lower most intrinsics.
8161 // Comparison intrinsics.
8162 case Intrinsic::x86_sse_comieq_ss:
8163 case Intrinsic::x86_sse_comilt_ss:
8164 case Intrinsic::x86_sse_comile_ss:
8165 case Intrinsic::x86_sse_comigt_ss:
8166 case Intrinsic::x86_sse_comige_ss:
8167 case Intrinsic::x86_sse_comineq_ss:
8168 case Intrinsic::x86_sse_ucomieq_ss:
8169 case Intrinsic::x86_sse_ucomilt_ss:
8170 case Intrinsic::x86_sse_ucomile_ss:
8171 case Intrinsic::x86_sse_ucomigt_ss:
8172 case Intrinsic::x86_sse_ucomige_ss:
8173 case Intrinsic::x86_sse_ucomineq_ss:
8174 case Intrinsic::x86_sse2_comieq_sd:
8175 case Intrinsic::x86_sse2_comilt_sd:
8176 case Intrinsic::x86_sse2_comile_sd:
8177 case Intrinsic::x86_sse2_comigt_sd:
8178 case Intrinsic::x86_sse2_comige_sd:
8179 case Intrinsic::x86_sse2_comineq_sd:
8180 case Intrinsic::x86_sse2_ucomieq_sd:
8181 case Intrinsic::x86_sse2_ucomilt_sd:
8182 case Intrinsic::x86_sse2_ucomile_sd:
8183 case Intrinsic::x86_sse2_ucomigt_sd:
8184 case Intrinsic::x86_sse2_ucomige_sd:
8185 case Intrinsic::x86_sse2_ucomineq_sd: {
8187 ISD::CondCode CC = ISD::SETCC_INVALID;
8190 case Intrinsic::x86_sse_comieq_ss:
8191 case Intrinsic::x86_sse2_comieq_sd:
8195 case Intrinsic::x86_sse_comilt_ss:
8196 case Intrinsic::x86_sse2_comilt_sd:
8200 case Intrinsic::x86_sse_comile_ss:
8201 case Intrinsic::x86_sse2_comile_sd:
8205 case Intrinsic::x86_sse_comigt_ss:
8206 case Intrinsic::x86_sse2_comigt_sd:
8210 case Intrinsic::x86_sse_comige_ss:
8211 case Intrinsic::x86_sse2_comige_sd:
8215 case Intrinsic::x86_sse_comineq_ss:
8216 case Intrinsic::x86_sse2_comineq_sd:
8220 case Intrinsic::x86_sse_ucomieq_ss:
8221 case Intrinsic::x86_sse2_ucomieq_sd:
8222 Opc = X86ISD::UCOMI;
8225 case Intrinsic::x86_sse_ucomilt_ss:
8226 case Intrinsic::x86_sse2_ucomilt_sd:
8227 Opc = X86ISD::UCOMI;
8230 case Intrinsic::x86_sse_ucomile_ss:
8231 case Intrinsic::x86_sse2_ucomile_sd:
8232 Opc = X86ISD::UCOMI;
8235 case Intrinsic::x86_sse_ucomigt_ss:
8236 case Intrinsic::x86_sse2_ucomigt_sd:
8237 Opc = X86ISD::UCOMI;
8240 case Intrinsic::x86_sse_ucomige_ss:
8241 case Intrinsic::x86_sse2_ucomige_sd:
8242 Opc = X86ISD::UCOMI;
8245 case Intrinsic::x86_sse_ucomineq_ss:
8246 case Intrinsic::x86_sse2_ucomineq_sd:
8247 Opc = X86ISD::UCOMI;
8252 SDValue LHS = Op.getOperand(1);
8253 SDValue RHS = Op.getOperand(2);
8254 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8255 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8256 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8257 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8258 DAG.getConstant(X86CC, MVT::i8), Cond);
8259 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8261 // ptest and testp intrinsics. The intrinsic these come from are designed to
8262 // return an integer value, not just an instruction so lower it to the ptest
8263 // or testp pattern and a setcc for the result.
8264 case Intrinsic::x86_sse41_ptestz:
8265 case Intrinsic::x86_sse41_ptestc:
8266 case Intrinsic::x86_sse41_ptestnzc:
8267 case Intrinsic::x86_avx_ptestz_256:
8268 case Intrinsic::x86_avx_ptestc_256:
8269 case Intrinsic::x86_avx_ptestnzc_256:
8270 case Intrinsic::x86_avx_vtestz_ps:
8271 case Intrinsic::x86_avx_vtestc_ps:
8272 case Intrinsic::x86_avx_vtestnzc_ps:
8273 case Intrinsic::x86_avx_vtestz_pd:
8274 case Intrinsic::x86_avx_vtestc_pd:
8275 case Intrinsic::x86_avx_vtestnzc_pd:
8276 case Intrinsic::x86_avx_vtestz_ps_256:
8277 case Intrinsic::x86_avx_vtestc_ps_256:
8278 case Intrinsic::x86_avx_vtestnzc_ps_256:
8279 case Intrinsic::x86_avx_vtestz_pd_256:
8280 case Intrinsic::x86_avx_vtestc_pd_256:
8281 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8282 bool IsTestPacked = false;
8285 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8286 case Intrinsic::x86_avx_vtestz_ps:
8287 case Intrinsic::x86_avx_vtestz_pd:
8288 case Intrinsic::x86_avx_vtestz_ps_256:
8289 case Intrinsic::x86_avx_vtestz_pd_256:
8290 IsTestPacked = true; // Fallthrough
8291 case Intrinsic::x86_sse41_ptestz:
8292 case Intrinsic::x86_avx_ptestz_256:
8294 X86CC = X86::COND_E;
8296 case Intrinsic::x86_avx_vtestc_ps:
8297 case Intrinsic::x86_avx_vtestc_pd:
8298 case Intrinsic::x86_avx_vtestc_ps_256:
8299 case Intrinsic::x86_avx_vtestc_pd_256:
8300 IsTestPacked = true; // Fallthrough
8301 case Intrinsic::x86_sse41_ptestc:
8302 case Intrinsic::x86_avx_ptestc_256:
8304 X86CC = X86::COND_B;
8306 case Intrinsic::x86_avx_vtestnzc_ps:
8307 case Intrinsic::x86_avx_vtestnzc_pd:
8308 case Intrinsic::x86_avx_vtestnzc_ps_256:
8309 case Intrinsic::x86_avx_vtestnzc_pd_256:
8310 IsTestPacked = true; // Fallthrough
8311 case Intrinsic::x86_sse41_ptestnzc:
8312 case Intrinsic::x86_avx_ptestnzc_256:
8314 X86CC = X86::COND_A;
8318 SDValue LHS = Op.getOperand(1);
8319 SDValue RHS = Op.getOperand(2);
8320 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8321 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8322 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8323 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8324 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8327 // Fix vector shift instructions where the last operand is a non-immediate
8329 case Intrinsic::x86_sse2_pslli_w:
8330 case Intrinsic::x86_sse2_pslli_d:
8331 case Intrinsic::x86_sse2_pslli_q:
8332 case Intrinsic::x86_sse2_psrli_w:
8333 case Intrinsic::x86_sse2_psrli_d:
8334 case Intrinsic::x86_sse2_psrli_q:
8335 case Intrinsic::x86_sse2_psrai_w:
8336 case Intrinsic::x86_sse2_psrai_d:
8337 case Intrinsic::x86_mmx_pslli_w:
8338 case Intrinsic::x86_mmx_pslli_d:
8339 case Intrinsic::x86_mmx_pslli_q:
8340 case Intrinsic::x86_mmx_psrli_w:
8341 case Intrinsic::x86_mmx_psrli_d:
8342 case Intrinsic::x86_mmx_psrli_q:
8343 case Intrinsic::x86_mmx_psrai_w:
8344 case Intrinsic::x86_mmx_psrai_d: {
8345 SDValue ShAmt = Op.getOperand(2);
8346 if (isa<ConstantSDNode>(ShAmt))
8349 unsigned NewIntNo = 0;
8350 EVT ShAmtVT = MVT::v4i32;
8352 case Intrinsic::x86_sse2_pslli_w:
8353 NewIntNo = Intrinsic::x86_sse2_psll_w;
8355 case Intrinsic::x86_sse2_pslli_d:
8356 NewIntNo = Intrinsic::x86_sse2_psll_d;
8358 case Intrinsic::x86_sse2_pslli_q:
8359 NewIntNo = Intrinsic::x86_sse2_psll_q;
8361 case Intrinsic::x86_sse2_psrli_w:
8362 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8364 case Intrinsic::x86_sse2_psrli_d:
8365 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8367 case Intrinsic::x86_sse2_psrli_q:
8368 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8370 case Intrinsic::x86_sse2_psrai_w:
8371 NewIntNo = Intrinsic::x86_sse2_psra_w;
8373 case Intrinsic::x86_sse2_psrai_d:
8374 NewIntNo = Intrinsic::x86_sse2_psra_d;
8377 ShAmtVT = MVT::v2i32;
8379 case Intrinsic::x86_mmx_pslli_w:
8380 NewIntNo = Intrinsic::x86_mmx_psll_w;
8382 case Intrinsic::x86_mmx_pslli_d:
8383 NewIntNo = Intrinsic::x86_mmx_psll_d;
8385 case Intrinsic::x86_mmx_pslli_q:
8386 NewIntNo = Intrinsic::x86_mmx_psll_q;
8388 case Intrinsic::x86_mmx_psrli_w:
8389 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8391 case Intrinsic::x86_mmx_psrli_d:
8392 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8394 case Intrinsic::x86_mmx_psrli_q:
8395 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8397 case Intrinsic::x86_mmx_psrai_w:
8398 NewIntNo = Intrinsic::x86_mmx_psra_w;
8400 case Intrinsic::x86_mmx_psrai_d:
8401 NewIntNo = Intrinsic::x86_mmx_psra_d;
8403 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8409 // The vector shift intrinsics with scalars uses 32b shift amounts but
8410 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8414 ShOps[1] = DAG.getConstant(0, MVT::i32);
8415 if (ShAmtVT == MVT::v4i32) {
8416 ShOps[2] = DAG.getUNDEF(MVT::i32);
8417 ShOps[3] = DAG.getUNDEF(MVT::i32);
8418 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8420 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8421 // FIXME this must be lowered to get rid of the invalid type.
8424 EVT VT = Op.getValueType();
8425 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8426 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8427 DAG.getConstant(NewIntNo, MVT::i32),
8428 Op.getOperand(1), ShAmt);
8433 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8434 SelectionDAG &DAG) const {
8435 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8436 MFI->setReturnAddressIsTaken(true);
8438 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8439 DebugLoc dl = Op.getDebugLoc();
8442 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8444 DAG.getConstant(TD->getPointerSize(),
8445 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8446 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8447 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8449 MachinePointerInfo(), false, false, 0);
8452 // Just load the return address.
8453 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8454 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8455 RetAddrFI, MachinePointerInfo(), false, false, 0);
8458 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8459 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8460 MFI->setFrameAddressIsTaken(true);
8462 EVT VT = Op.getValueType();
8463 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8464 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8465 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8466 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8468 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8469 MachinePointerInfo(),
8474 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8475 SelectionDAG &DAG) const {
8476 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8479 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8480 MachineFunction &MF = DAG.getMachineFunction();
8481 SDValue Chain = Op.getOperand(0);
8482 SDValue Offset = Op.getOperand(1);
8483 SDValue Handler = Op.getOperand(2);
8484 DebugLoc dl = Op.getDebugLoc();
8486 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8487 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8489 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8491 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8492 DAG.getIntPtrConstant(TD->getPointerSize()));
8493 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8494 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8496 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8497 MF.getRegInfo().addLiveOut(StoreAddrReg);
8499 return DAG.getNode(X86ISD::EH_RETURN, dl,
8501 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8504 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8505 SelectionDAG &DAG) const {
8506 SDValue Root = Op.getOperand(0);
8507 SDValue Trmp = Op.getOperand(1); // trampoline
8508 SDValue FPtr = Op.getOperand(2); // nested function
8509 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8510 DebugLoc dl = Op.getDebugLoc();
8512 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8514 if (Subtarget->is64Bit()) {
8515 SDValue OutChains[6];
8517 // Large code-model.
8518 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8519 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8521 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8522 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8524 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8526 // Load the pointer to the nested function into R11.
8527 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8528 SDValue Addr = Trmp;
8529 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8530 Addr, MachinePointerInfo(TrmpAddr),
8533 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8534 DAG.getConstant(2, MVT::i64));
8535 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8536 MachinePointerInfo(TrmpAddr, 2),
8539 // Load the 'nest' parameter value into R10.
8540 // R10 is specified in X86CallingConv.td
8541 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8542 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8543 DAG.getConstant(10, MVT::i64));
8544 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8545 Addr, MachinePointerInfo(TrmpAddr, 10),
8548 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8549 DAG.getConstant(12, MVT::i64));
8550 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8551 MachinePointerInfo(TrmpAddr, 12),
8554 // Jump to the nested function.
8555 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8557 DAG.getConstant(20, MVT::i64));
8558 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8559 Addr, MachinePointerInfo(TrmpAddr, 20),
8562 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8563 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8564 DAG.getConstant(22, MVT::i64));
8565 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8566 MachinePointerInfo(TrmpAddr, 22),
8570 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8571 return DAG.getMergeValues(Ops, 2, dl);
8573 const Function *Func =
8574 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8575 CallingConv::ID CC = Func->getCallingConv();
8580 llvm_unreachable("Unsupported calling convention");
8581 case CallingConv::C:
8582 case CallingConv::X86_StdCall: {
8583 // Pass 'nest' parameter in ECX.
8584 // Must be kept in sync with X86CallingConv.td
8587 // Check that ECX wasn't needed by an 'inreg' parameter.
8588 const FunctionType *FTy = Func->getFunctionType();
8589 const AttrListPtr &Attrs = Func->getAttributes();
8591 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8592 unsigned InRegCount = 0;
8595 for (FunctionType::param_iterator I = FTy->param_begin(),
8596 E = FTy->param_end(); I != E; ++I, ++Idx)
8597 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8598 // FIXME: should only count parameters that are lowered to integers.
8599 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8601 if (InRegCount > 2) {
8602 report_fatal_error("Nest register in use - reduce number of inreg"
8608 case CallingConv::X86_FastCall:
8609 case CallingConv::X86_ThisCall:
8610 case CallingConv::Fast:
8611 // Pass 'nest' parameter in EAX.
8612 // Must be kept in sync with X86CallingConv.td
8617 SDValue OutChains[4];
8620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8621 DAG.getConstant(10, MVT::i32));
8622 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8624 // This is storing the opcode for MOV32ri.
8625 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8626 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8627 OutChains[0] = DAG.getStore(Root, dl,
8628 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8629 Trmp, MachinePointerInfo(TrmpAddr),
8632 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8633 DAG.getConstant(1, MVT::i32));
8634 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8635 MachinePointerInfo(TrmpAddr, 1),
8638 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8639 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8640 DAG.getConstant(5, MVT::i32));
8641 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8642 MachinePointerInfo(TrmpAddr, 5),
8645 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8646 DAG.getConstant(6, MVT::i32));
8647 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8648 MachinePointerInfo(TrmpAddr, 6),
8652 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8653 return DAG.getMergeValues(Ops, 2, dl);
8657 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8658 SelectionDAG &DAG) const {
8660 The rounding mode is in bits 11:10 of FPSR, and has the following
8667 FLT_ROUNDS, on the other hand, expects the following:
8674 To perform the conversion, we do:
8675 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8678 MachineFunction &MF = DAG.getMachineFunction();
8679 const TargetMachine &TM = MF.getTarget();
8680 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8681 unsigned StackAlignment = TFI.getStackAlignment();
8682 EVT VT = Op.getValueType();
8683 DebugLoc DL = Op.getDebugLoc();
8685 // Save FP Control Word to stack slot
8686 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8687 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8690 MachineMemOperand *MMO =
8691 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8692 MachineMemOperand::MOStore, 2, 2);
8694 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8695 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8696 DAG.getVTList(MVT::Other),
8697 Ops, 2, MVT::i16, MMO);
8699 // Load FP Control Word from stack slot
8700 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8701 MachinePointerInfo(), false, false, 0);
8703 // Transform as necessary
8705 DAG.getNode(ISD::SRL, DL, MVT::i16,
8706 DAG.getNode(ISD::AND, DL, MVT::i16,
8707 CWD, DAG.getConstant(0x800, MVT::i16)),
8708 DAG.getConstant(11, MVT::i8));
8710 DAG.getNode(ISD::SRL, DL, MVT::i16,
8711 DAG.getNode(ISD::AND, DL, MVT::i16,
8712 CWD, DAG.getConstant(0x400, MVT::i16)),
8713 DAG.getConstant(9, MVT::i8));
8716 DAG.getNode(ISD::AND, DL, MVT::i16,
8717 DAG.getNode(ISD::ADD, DL, MVT::i16,
8718 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8719 DAG.getConstant(1, MVT::i16)),
8720 DAG.getConstant(3, MVT::i16));
8723 return DAG.getNode((VT.getSizeInBits() < 16 ?
8724 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8727 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8728 EVT VT = Op.getValueType();
8730 unsigned NumBits = VT.getSizeInBits();
8731 DebugLoc dl = Op.getDebugLoc();
8733 Op = Op.getOperand(0);
8734 if (VT == MVT::i8) {
8735 // Zero extend to i32 since there is not an i8 bsr.
8737 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8740 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8741 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8742 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8744 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8747 DAG.getConstant(NumBits+NumBits-1, OpVT),
8748 DAG.getConstant(X86::COND_E, MVT::i8),
8751 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8753 // Finally xor with NumBits-1.
8754 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8757 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8761 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8762 EVT VT = Op.getValueType();
8764 unsigned NumBits = VT.getSizeInBits();
8765 DebugLoc dl = Op.getDebugLoc();
8767 Op = Op.getOperand(0);
8768 if (VT == MVT::i8) {
8770 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8773 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8774 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8775 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8777 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8780 DAG.getConstant(NumBits, OpVT),
8781 DAG.getConstant(X86::COND_E, MVT::i8),
8784 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8787 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8791 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8792 EVT VT = Op.getValueType();
8793 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8794 DebugLoc dl = Op.getDebugLoc();
8796 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8797 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8798 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8799 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8800 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8802 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8803 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8804 // return AloBlo + AloBhi + AhiBlo;
8806 SDValue A = Op.getOperand(0);
8807 SDValue B = Op.getOperand(1);
8809 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8810 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8811 A, DAG.getConstant(32, MVT::i32));
8812 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8813 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8814 B, DAG.getConstant(32, MVT::i32));
8815 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8816 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8818 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8819 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8821 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8822 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8824 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8825 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8826 AloBhi, DAG.getConstant(32, MVT::i32));
8827 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8828 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8829 AhiBlo, DAG.getConstant(32, MVT::i32));
8830 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8831 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8835 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8836 EVT VT = Op.getValueType();
8837 DebugLoc dl = Op.getDebugLoc();
8838 SDValue R = Op.getOperand(0);
8840 LLVMContext *Context = DAG.getContext();
8842 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8844 if (VT == MVT::v4i32) {
8845 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8846 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8847 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8849 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8851 std::vector<Constant*> CV(4, CI);
8852 Constant *C = ConstantVector::get(CV);
8853 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8854 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8855 MachinePointerInfo::getConstantPool(),
8858 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8859 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8860 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8861 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8863 if (VT == MVT::v16i8) {
8865 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8866 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8867 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8869 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8870 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8872 std::vector<Constant*> CVM1(16, CM1);
8873 std::vector<Constant*> CVM2(16, CM2);
8874 Constant *C = ConstantVector::get(CVM1);
8875 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8876 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8877 MachinePointerInfo::getConstantPool(),
8880 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8881 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8882 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8883 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8884 DAG.getConstant(4, MVT::i32));
8885 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8887 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8889 C = ConstantVector::get(CVM2);
8890 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8891 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8892 MachinePointerInfo::getConstantPool(),
8895 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8896 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8897 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8898 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8899 DAG.getConstant(2, MVT::i32));
8900 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8902 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8904 // return pblendv(r, r+r, a);
8905 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8906 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8912 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8913 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8914 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8915 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8916 // has only one use.
8917 SDNode *N = Op.getNode();
8918 SDValue LHS = N->getOperand(0);
8919 SDValue RHS = N->getOperand(1);
8920 unsigned BaseOp = 0;
8922 DebugLoc DL = Op.getDebugLoc();
8923 switch (Op.getOpcode()) {
8924 default: llvm_unreachable("Unknown ovf instruction!");
8926 // A subtract of one will be selected as a INC. Note that INC doesn't
8927 // set CF, so we can't do this for UADDO.
8928 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8930 BaseOp = X86ISD::INC;
8934 BaseOp = X86ISD::ADD;
8938 BaseOp = X86ISD::ADD;
8942 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8943 // set CF, so we can't do this for USUBO.
8944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8946 BaseOp = X86ISD::DEC;
8950 BaseOp = X86ISD::SUB;
8954 BaseOp = X86ISD::SUB;
8958 BaseOp = X86ISD::SMUL;
8961 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8962 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8964 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8967 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8968 DAG.getConstant(X86::COND_O, MVT::i32),
8969 SDValue(Sum.getNode(), 2));
8971 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8976 // Also sets EFLAGS.
8977 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8978 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8981 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8982 DAG.getConstant(Cond, MVT::i32),
8983 SDValue(Sum.getNode(), 1));
8985 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8989 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8990 DebugLoc dl = Op.getDebugLoc();
8992 if (!Subtarget->hasSSE2()) {
8993 SDValue Chain = Op.getOperand(0);
8994 SDValue Zero = DAG.getConstant(0,
8995 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8997 DAG.getRegister(X86::ESP, MVT::i32), // Base
8998 DAG.getTargetConstant(1, MVT::i8), // Scale
8999 DAG.getRegister(0, MVT::i32), // Index
9000 DAG.getTargetConstant(0, MVT::i32), // Disp
9001 DAG.getRegister(0, MVT::i32), // Segment.
9006 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9007 array_lengthof(Ops));
9008 return SDValue(Res, 0);
9011 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9013 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9015 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9016 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9017 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9018 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9020 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9021 if (!Op1 && !Op2 && !Op3 && Op4)
9022 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9024 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9025 if (Op1 && !Op2 && !Op3 && !Op4)
9026 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9028 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9030 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9033 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9034 EVT T = Op.getValueType();
9035 DebugLoc DL = Op.getDebugLoc();
9038 switch(T.getSimpleVT().SimpleTy) {
9040 assert(false && "Invalid value type!");
9041 case MVT::i8: Reg = X86::AL; size = 1; break;
9042 case MVT::i16: Reg = X86::AX; size = 2; break;
9043 case MVT::i32: Reg = X86::EAX; size = 4; break;
9045 assert(Subtarget->is64Bit() && "Node not type legal!");
9046 Reg = X86::RAX; size = 8;
9049 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9050 Op.getOperand(2), SDValue());
9051 SDValue Ops[] = { cpIn.getValue(0),
9054 DAG.getTargetConstant(size, MVT::i8),
9056 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9057 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9058 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9061 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9065 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9066 SelectionDAG &DAG) const {
9067 assert(Subtarget->is64Bit() && "Result not type legalized?");
9068 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9069 SDValue TheChain = Op.getOperand(0);
9070 DebugLoc dl = Op.getDebugLoc();
9071 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9072 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9073 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9075 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9076 DAG.getConstant(32, MVT::i8));
9078 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9081 return DAG.getMergeValues(Ops, 2, dl);
9084 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9085 SelectionDAG &DAG) const {
9086 EVT SrcVT = Op.getOperand(0).getValueType();
9087 EVT DstVT = Op.getValueType();
9088 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9089 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9090 assert((DstVT == MVT::i64 ||
9091 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9092 "Unexpected custom BITCAST");
9093 // i64 <=> MMX conversions are Legal.
9094 if (SrcVT==MVT::i64 && DstVT.isVector())
9096 if (DstVT==MVT::i64 && SrcVT.isVector())
9098 // MMX <=> MMX conversions are Legal.
9099 if (SrcVT.isVector() && DstVT.isVector())
9101 // All other conversions need to be expanded.
9105 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9106 SDNode *Node = Op.getNode();
9107 DebugLoc dl = Node->getDebugLoc();
9108 EVT T = Node->getValueType(0);
9109 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9110 DAG.getConstant(0, T), Node->getOperand(2));
9111 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9112 cast<AtomicSDNode>(Node)->getMemoryVT(),
9113 Node->getOperand(0),
9114 Node->getOperand(1), negOp,
9115 cast<AtomicSDNode>(Node)->getSrcValue(),
9116 cast<AtomicSDNode>(Node)->getAlignment());
9119 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9120 EVT VT = Op.getNode()->getValueType(0);
9122 // Let legalize expand this if it isn't a legal type yet.
9123 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9126 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9129 bool ExtraOp = false;
9130 switch (Op.getOpcode()) {
9131 default: assert(0 && "Invalid code");
9132 case ISD::ADDC: Opc = X86ISD::ADD; break;
9133 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9134 case ISD::SUBC: Opc = X86ISD::SUB; break;
9135 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9139 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9141 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9142 Op.getOperand(1), Op.getOperand(2));
9145 /// LowerOperation - Provide custom lowering hooks for some operations.
9147 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9148 switch (Op.getOpcode()) {
9149 default: llvm_unreachable("Should not custom lower this!");
9150 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9151 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9152 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9153 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9154 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9155 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9156 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9157 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9158 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9159 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9160 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9161 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9162 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9163 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9164 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9165 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9166 case ISD::SHL_PARTS:
9167 case ISD::SRA_PARTS:
9168 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
9169 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9170 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9171 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9172 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9173 case ISD::FABS: return LowerFABS(Op, DAG);
9174 case ISD::FNEG: return LowerFNEG(Op, DAG);
9175 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9176 case ISD::SETCC: return LowerSETCC(Op, DAG);
9177 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9178 case ISD::SELECT: return LowerSELECT(Op, DAG);
9179 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9180 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9181 case ISD::VASTART: return LowerVASTART(Op, DAG);
9182 case ISD::VAARG: return LowerVAARG(Op, DAG);
9183 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9184 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9185 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9186 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9187 case ISD::FRAME_TO_ARGS_OFFSET:
9188 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9189 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9190 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9191 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9192 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9193 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9194 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9195 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9196 case ISD::SHL: return LowerSHL(Op, DAG);
9202 case ISD::UMULO: return LowerXALUO(Op, DAG);
9203 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9204 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9208 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9212 void X86TargetLowering::
9213 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9214 SelectionDAG &DAG, unsigned NewOp) const {
9215 EVT T = Node->getValueType(0);
9216 DebugLoc dl = Node->getDebugLoc();
9217 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9219 SDValue Chain = Node->getOperand(0);
9220 SDValue In1 = Node->getOperand(1);
9221 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9222 Node->getOperand(2), DAG.getIntPtrConstant(0));
9223 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9224 Node->getOperand(2), DAG.getIntPtrConstant(1));
9225 SDValue Ops[] = { Chain, In1, In2L, In2H };
9226 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9228 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9229 cast<MemSDNode>(Node)->getMemOperand());
9230 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9231 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9232 Results.push_back(Result.getValue(2));
9235 /// ReplaceNodeResults - Replace a node with an illegal result type
9236 /// with a new node built out of custom code.
9237 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9238 SmallVectorImpl<SDValue>&Results,
9239 SelectionDAG &DAG) const {
9240 DebugLoc dl = N->getDebugLoc();
9241 switch (N->getOpcode()) {
9243 assert(false && "Do not know how to custom type legalize this operation!");
9249 // We don't want to expand or promote these.
9251 case ISD::FP_TO_SINT: {
9252 std::pair<SDValue,SDValue> Vals =
9253 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9254 SDValue FIST = Vals.first, StackSlot = Vals.second;
9255 if (FIST.getNode() != 0) {
9256 EVT VT = N->getValueType(0);
9257 // Return a load from the stack slot.
9258 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9259 MachinePointerInfo(), false, false, 0));
9263 case ISD::READCYCLECOUNTER: {
9264 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9265 SDValue TheChain = N->getOperand(0);
9266 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9267 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9269 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9271 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9272 SDValue Ops[] = { eax, edx };
9273 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9274 Results.push_back(edx.getValue(1));
9277 case ISD::ATOMIC_CMP_SWAP: {
9278 EVT T = N->getValueType(0);
9279 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9280 SDValue cpInL, cpInH;
9281 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9282 DAG.getConstant(0, MVT::i32));
9283 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9284 DAG.getConstant(1, MVT::i32));
9285 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9286 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9288 SDValue swapInL, swapInH;
9289 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9290 DAG.getConstant(0, MVT::i32));
9291 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9292 DAG.getConstant(1, MVT::i32));
9293 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9295 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9296 swapInL.getValue(1));
9297 SDValue Ops[] = { swapInH.getValue(0),
9299 swapInH.getValue(1) };
9300 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9301 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9302 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9304 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9305 MVT::i32, Result.getValue(1));
9306 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9307 MVT::i32, cpOutL.getValue(2));
9308 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9309 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9310 Results.push_back(cpOutH.getValue(1));
9313 case ISD::ATOMIC_LOAD_ADD:
9314 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9316 case ISD::ATOMIC_LOAD_AND:
9317 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9319 case ISD::ATOMIC_LOAD_NAND:
9320 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9322 case ISD::ATOMIC_LOAD_OR:
9323 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9325 case ISD::ATOMIC_LOAD_SUB:
9326 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9328 case ISD::ATOMIC_LOAD_XOR:
9329 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9331 case ISD::ATOMIC_SWAP:
9332 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9337 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9339 default: return NULL;
9340 case X86ISD::BSF: return "X86ISD::BSF";
9341 case X86ISD::BSR: return "X86ISD::BSR";
9342 case X86ISD::SHLD: return "X86ISD::SHLD";
9343 case X86ISD::SHRD: return "X86ISD::SHRD";
9344 case X86ISD::FAND: return "X86ISD::FAND";
9345 case X86ISD::FOR: return "X86ISD::FOR";
9346 case X86ISD::FXOR: return "X86ISD::FXOR";
9347 case X86ISD::FSRL: return "X86ISD::FSRL";
9348 case X86ISD::FILD: return "X86ISD::FILD";
9349 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9350 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9351 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9352 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9353 case X86ISD::FLD: return "X86ISD::FLD";
9354 case X86ISD::FST: return "X86ISD::FST";
9355 case X86ISD::CALL: return "X86ISD::CALL";
9356 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9357 case X86ISD::BT: return "X86ISD::BT";
9358 case X86ISD::CMP: return "X86ISD::CMP";
9359 case X86ISD::COMI: return "X86ISD::COMI";
9360 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9361 case X86ISD::SETCC: return "X86ISD::SETCC";
9362 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9363 case X86ISD::CMOV: return "X86ISD::CMOV";
9364 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9365 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9366 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9367 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9368 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9369 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9370 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9371 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9372 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9373 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9374 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9375 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9376 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9377 case X86ISD::PANDN: return "X86ISD::PANDN";
9378 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9379 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9380 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9381 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9382 case X86ISD::FMAX: return "X86ISD::FMAX";
9383 case X86ISD::FMIN: return "X86ISD::FMIN";
9384 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9385 case X86ISD::FRCP: return "X86ISD::FRCP";
9386 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9387 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9388 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9389 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9390 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9391 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9392 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9393 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9394 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9395 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9396 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9397 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9398 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9399 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9400 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9401 case X86ISD::VSHL: return "X86ISD::VSHL";
9402 case X86ISD::VSRL: return "X86ISD::VSRL";
9403 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9404 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9405 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9406 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9407 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9408 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9409 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9410 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9411 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9412 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9413 case X86ISD::ADD: return "X86ISD::ADD";
9414 case X86ISD::SUB: return "X86ISD::SUB";
9415 case X86ISD::ADC: return "X86ISD::ADC";
9416 case X86ISD::SBB: return "X86ISD::SBB";
9417 case X86ISD::SMUL: return "X86ISD::SMUL";
9418 case X86ISD::UMUL: return "X86ISD::UMUL";
9419 case X86ISD::INC: return "X86ISD::INC";
9420 case X86ISD::DEC: return "X86ISD::DEC";
9421 case X86ISD::OR: return "X86ISD::OR";
9422 case X86ISD::XOR: return "X86ISD::XOR";
9423 case X86ISD::AND: return "X86ISD::AND";
9424 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9425 case X86ISD::PTEST: return "X86ISD::PTEST";
9426 case X86ISD::TESTP: return "X86ISD::TESTP";
9427 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9428 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9429 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9430 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9431 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9432 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9433 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9434 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9435 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9436 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9437 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9438 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9439 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9440 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9441 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9442 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9443 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9444 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9445 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9446 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9447 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9448 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9449 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9450 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9451 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9452 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9453 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9454 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9455 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9456 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9457 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9458 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9459 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9460 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9461 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9462 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9463 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9464 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9465 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9466 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9470 // isLegalAddressingMode - Return true if the addressing mode represented
9471 // by AM is legal for this target, for a load/store of the specified type.
9472 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9473 const Type *Ty) const {
9474 // X86 supports extremely general addressing modes.
9475 CodeModel::Model M = getTargetMachine().getCodeModel();
9476 Reloc::Model R = getTargetMachine().getRelocationModel();
9478 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9479 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9484 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9486 // If a reference to this global requires an extra load, we can't fold it.
9487 if (isGlobalStubReference(GVFlags))
9490 // If BaseGV requires a register for the PIC base, we cannot also have a
9491 // BaseReg specified.
9492 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9495 // If lower 4G is not available, then we must use rip-relative addressing.
9496 if ((M != CodeModel::Small || R != Reloc::Static) &&
9497 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9507 // These scales always work.
9512 // These scales are formed with basereg+scalereg. Only accept if there is
9517 default: // Other stuff never works.
9525 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9526 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9528 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9529 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9530 if (NumBits1 <= NumBits2)
9535 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9536 if (!VT1.isInteger() || !VT2.isInteger())
9538 unsigned NumBits1 = VT1.getSizeInBits();
9539 unsigned NumBits2 = VT2.getSizeInBits();
9540 if (NumBits1 <= NumBits2)
9545 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9546 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9547 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9550 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9551 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9552 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9555 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9556 // i16 instructions are longer (0x66 prefix) and potentially slower.
9557 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9560 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9561 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9562 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9563 /// are assumed to be legal.
9565 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9567 // Very little shuffling can be done for 64-bit vectors right now.
9568 if (VT.getSizeInBits() == 64)
9569 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9571 // FIXME: pshufb, blends, shifts.
9572 return (VT.getVectorNumElements() == 2 ||
9573 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9574 isMOVLMask(M, VT) ||
9575 isSHUFPMask(M, VT) ||
9576 isPSHUFDMask(M, VT) ||
9577 isPSHUFHWMask(M, VT) ||
9578 isPSHUFLWMask(M, VT) ||
9579 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9580 isUNPCKLMask(M, VT) ||
9581 isUNPCKHMask(M, VT) ||
9582 isUNPCKL_v_undef_Mask(M, VT) ||
9583 isUNPCKH_v_undef_Mask(M, VT));
9587 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9589 unsigned NumElts = VT.getVectorNumElements();
9590 // FIXME: This collection of masks seems suspect.
9593 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9594 return (isMOVLMask(Mask, VT) ||
9595 isCommutedMOVLMask(Mask, VT, true) ||
9596 isSHUFPMask(Mask, VT) ||
9597 isCommutedSHUFPMask(Mask, VT));
9602 //===----------------------------------------------------------------------===//
9603 // X86 Scheduler Hooks
9604 //===----------------------------------------------------------------------===//
9606 // private utility function
9608 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9609 MachineBasicBlock *MBB,
9616 TargetRegisterClass *RC,
9617 bool invSrc) const {
9618 // For the atomic bitwise operator, we generate
9621 // ld t1 = [bitinstr.addr]
9622 // op t2 = t1, [bitinstr.val]
9624 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9626 // fallthrough -->nextMBB
9627 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9628 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9629 MachineFunction::iterator MBBIter = MBB;
9632 /// First build the CFG
9633 MachineFunction *F = MBB->getParent();
9634 MachineBasicBlock *thisMBB = MBB;
9635 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9636 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9637 F->insert(MBBIter, newMBB);
9638 F->insert(MBBIter, nextMBB);
9640 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9641 nextMBB->splice(nextMBB->begin(), thisMBB,
9642 llvm::next(MachineBasicBlock::iterator(bInstr)),
9644 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9646 // Update thisMBB to fall through to newMBB
9647 thisMBB->addSuccessor(newMBB);
9649 // newMBB jumps to itself and fall through to nextMBB
9650 newMBB->addSuccessor(nextMBB);
9651 newMBB->addSuccessor(newMBB);
9653 // Insert instructions into newMBB based on incoming instruction
9654 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9655 "unexpected number of operands");
9656 DebugLoc dl = bInstr->getDebugLoc();
9657 MachineOperand& destOper = bInstr->getOperand(0);
9658 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9659 int numArgs = bInstr->getNumOperands() - 1;
9660 for (int i=0; i < numArgs; ++i)
9661 argOpers[i] = &bInstr->getOperand(i+1);
9663 // x86 address has 4 operands: base, index, scale, and displacement
9664 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9665 int valArgIndx = lastAddrIndx + 1;
9667 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9668 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9669 for (int i=0; i <= lastAddrIndx; ++i)
9670 (*MIB).addOperand(*argOpers[i]);
9672 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9674 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9679 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9680 assert((argOpers[valArgIndx]->isReg() ||
9681 argOpers[valArgIndx]->isImm()) &&
9683 if (argOpers[valArgIndx]->isReg())
9684 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9686 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9688 (*MIB).addOperand(*argOpers[valArgIndx]);
9690 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9693 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9694 for (int i=0; i <= lastAddrIndx; ++i)
9695 (*MIB).addOperand(*argOpers[i]);
9697 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9698 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9699 bInstr->memoperands_end());
9701 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9705 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9707 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9711 // private utility function: 64 bit atomics on 32 bit host.
9713 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9714 MachineBasicBlock *MBB,
9719 bool invSrc) const {
9720 // For the atomic bitwise operator, we generate
9721 // thisMBB (instructions are in pairs, except cmpxchg8b)
9722 // ld t1,t2 = [bitinstr.addr]
9724 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9725 // op t5, t6 <- out1, out2, [bitinstr.val]
9726 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9727 // mov ECX, EBX <- t5, t6
9728 // mov EAX, EDX <- t1, t2
9729 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9730 // mov t3, t4 <- EAX, EDX
9732 // result in out1, out2
9733 // fallthrough -->nextMBB
9735 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9736 const unsigned LoadOpc = X86::MOV32rm;
9737 const unsigned NotOpc = X86::NOT32r;
9738 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9739 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9740 MachineFunction::iterator MBBIter = MBB;
9743 /// First build the CFG
9744 MachineFunction *F = MBB->getParent();
9745 MachineBasicBlock *thisMBB = MBB;
9746 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9747 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9748 F->insert(MBBIter, newMBB);
9749 F->insert(MBBIter, nextMBB);
9751 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9752 nextMBB->splice(nextMBB->begin(), thisMBB,
9753 llvm::next(MachineBasicBlock::iterator(bInstr)),
9755 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9757 // Update thisMBB to fall through to newMBB
9758 thisMBB->addSuccessor(newMBB);
9760 // newMBB jumps to itself and fall through to nextMBB
9761 newMBB->addSuccessor(nextMBB);
9762 newMBB->addSuccessor(newMBB);
9764 DebugLoc dl = bInstr->getDebugLoc();
9765 // Insert instructions into newMBB based on incoming instruction
9766 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9767 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9768 "unexpected number of operands");
9769 MachineOperand& dest1Oper = bInstr->getOperand(0);
9770 MachineOperand& dest2Oper = bInstr->getOperand(1);
9771 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9772 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9773 argOpers[i] = &bInstr->getOperand(i+2);
9775 // We use some of the operands multiple times, so conservatively just
9776 // clear any kill flags that might be present.
9777 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9778 argOpers[i]->setIsKill(false);
9781 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9782 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9784 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9785 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9786 for (int i=0; i <= lastAddrIndx; ++i)
9787 (*MIB).addOperand(*argOpers[i]);
9788 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9789 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9790 // add 4 to displacement.
9791 for (int i=0; i <= lastAddrIndx-2; ++i)
9792 (*MIB).addOperand(*argOpers[i]);
9793 MachineOperand newOp3 = *(argOpers[3]);
9795 newOp3.setImm(newOp3.getImm()+4);
9797 newOp3.setOffset(newOp3.getOffset()+4);
9798 (*MIB).addOperand(newOp3);
9799 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9801 // t3/4 are defined later, at the bottom of the loop
9802 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9803 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9804 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9805 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9806 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9807 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9809 // The subsequent operations should be using the destination registers of
9810 //the PHI instructions.
9812 t1 = F->getRegInfo().createVirtualRegister(RC);
9813 t2 = F->getRegInfo().createVirtualRegister(RC);
9814 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9815 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9817 t1 = dest1Oper.getReg();
9818 t2 = dest2Oper.getReg();
9821 int valArgIndx = lastAddrIndx + 1;
9822 assert((argOpers[valArgIndx]->isReg() ||
9823 argOpers[valArgIndx]->isImm()) &&
9825 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9826 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9827 if (argOpers[valArgIndx]->isReg())
9828 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9830 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9831 if (regOpcL != X86::MOV32rr)
9833 (*MIB).addOperand(*argOpers[valArgIndx]);
9834 assert(argOpers[valArgIndx + 1]->isReg() ==
9835 argOpers[valArgIndx]->isReg());
9836 assert(argOpers[valArgIndx + 1]->isImm() ==
9837 argOpers[valArgIndx]->isImm());
9838 if (argOpers[valArgIndx + 1]->isReg())
9839 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9841 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9842 if (regOpcH != X86::MOV32rr)
9844 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9846 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9848 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9851 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9853 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9856 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9857 for (int i=0; i <= lastAddrIndx; ++i)
9858 (*MIB).addOperand(*argOpers[i]);
9860 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9861 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9862 bInstr->memoperands_end());
9864 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9865 MIB.addReg(X86::EAX);
9866 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9867 MIB.addReg(X86::EDX);
9870 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9872 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9876 // private utility function
9878 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9879 MachineBasicBlock *MBB,
9880 unsigned cmovOpc) const {
9881 // For the atomic min/max operator, we generate
9884 // ld t1 = [min/max.addr]
9885 // mov t2 = [min/max.val]
9887 // cmov[cond] t2 = t1
9889 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9891 // fallthrough -->nextMBB
9893 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9894 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9895 MachineFunction::iterator MBBIter = MBB;
9898 /// First build the CFG
9899 MachineFunction *F = MBB->getParent();
9900 MachineBasicBlock *thisMBB = MBB;
9901 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9902 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903 F->insert(MBBIter, newMBB);
9904 F->insert(MBBIter, nextMBB);
9906 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9907 nextMBB->splice(nextMBB->begin(), thisMBB,
9908 llvm::next(MachineBasicBlock::iterator(mInstr)),
9910 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9912 // Update thisMBB to fall through to newMBB
9913 thisMBB->addSuccessor(newMBB);
9915 // newMBB jumps to newMBB and fall through to nextMBB
9916 newMBB->addSuccessor(nextMBB);
9917 newMBB->addSuccessor(newMBB);
9919 DebugLoc dl = mInstr->getDebugLoc();
9920 // Insert instructions into newMBB based on incoming instruction
9921 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9922 "unexpected number of operands");
9923 MachineOperand& destOper = mInstr->getOperand(0);
9924 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9925 int numArgs = mInstr->getNumOperands() - 1;
9926 for (int i=0; i < numArgs; ++i)
9927 argOpers[i] = &mInstr->getOperand(i+1);
9929 // x86 address has 4 operands: base, index, scale, and displacement
9930 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9931 int valArgIndx = lastAddrIndx + 1;
9933 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9934 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9935 for (int i=0; i <= lastAddrIndx; ++i)
9936 (*MIB).addOperand(*argOpers[i]);
9938 // We only support register and immediate values
9939 assert((argOpers[valArgIndx]->isReg() ||
9940 argOpers[valArgIndx]->isImm()) &&
9943 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9944 if (argOpers[valArgIndx]->isReg())
9945 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9947 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9948 (*MIB).addOperand(*argOpers[valArgIndx]);
9950 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9953 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9958 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9959 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9963 // Cmp and exchange if none has modified the memory location
9964 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9965 for (int i=0; i <= lastAddrIndx; ++i)
9966 (*MIB).addOperand(*argOpers[i]);
9968 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9969 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9970 mInstr->memoperands_end());
9972 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9973 MIB.addReg(X86::EAX);
9976 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9978 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9982 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9983 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9986 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9987 unsigned numArgs, bool memArg) const {
9988 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9989 "Target must have SSE4.2 or AVX features enabled");
9991 DebugLoc dl = MI->getDebugLoc();
9992 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9994 if (!Subtarget->hasAVX()) {
9996 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9998 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10001 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10003 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10006 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10007 for (unsigned i = 0; i < numArgs; ++i) {
10008 MachineOperand &Op = MI->getOperand(i+1);
10009 if (!(Op.isReg() && Op.isImplicit()))
10010 MIB.addOperand(Op);
10012 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10013 .addReg(X86::XMM0);
10015 MI->eraseFromParent();
10019 MachineBasicBlock *
10020 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10021 DebugLoc dl = MI->getDebugLoc();
10022 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10024 // Address into RAX/EAX, other two args into ECX, EDX.
10025 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10026 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10027 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10028 for (int i = 0; i < X86::AddrNumOperands; ++i)
10029 MIB.addOperand(MI->getOperand(i));
10031 unsigned ValOps = X86::AddrNumOperands;
10032 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10033 .addReg(MI->getOperand(ValOps).getReg());
10034 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10035 .addReg(MI->getOperand(ValOps+1).getReg());
10037 // The instruction doesn't actually take any operands though.
10038 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10040 MI->eraseFromParent(); // The pseudo is gone now.
10044 MachineBasicBlock *
10045 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10046 DebugLoc dl = MI->getDebugLoc();
10047 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10049 // First arg in ECX, the second in EAX.
10050 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10051 .addReg(MI->getOperand(0).getReg());
10052 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10053 .addReg(MI->getOperand(1).getReg());
10055 // The instruction doesn't actually take any operands though.
10056 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10058 MI->eraseFromParent(); // The pseudo is gone now.
10062 MachineBasicBlock *
10063 X86TargetLowering::EmitVAARG64WithCustomInserter(
10065 MachineBasicBlock *MBB) const {
10066 // Emit va_arg instruction on X86-64.
10068 // Operands to this pseudo-instruction:
10069 // 0 ) Output : destination address (reg)
10070 // 1-5) Input : va_list address (addr, i64mem)
10071 // 6 ) ArgSize : Size (in bytes) of vararg type
10072 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10073 // 8 ) Align : Alignment of type
10074 // 9 ) EFLAGS (implicit-def)
10076 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10077 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10079 unsigned DestReg = MI->getOperand(0).getReg();
10080 MachineOperand &Base = MI->getOperand(1);
10081 MachineOperand &Scale = MI->getOperand(2);
10082 MachineOperand &Index = MI->getOperand(3);
10083 MachineOperand &Disp = MI->getOperand(4);
10084 MachineOperand &Segment = MI->getOperand(5);
10085 unsigned ArgSize = MI->getOperand(6).getImm();
10086 unsigned ArgMode = MI->getOperand(7).getImm();
10087 unsigned Align = MI->getOperand(8).getImm();
10089 // Memory Reference
10090 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10091 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10092 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10094 // Machine Information
10095 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10096 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10097 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10098 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10099 DebugLoc DL = MI->getDebugLoc();
10101 // struct va_list {
10104 // i64 overflow_area (address)
10105 // i64 reg_save_area (address)
10107 // sizeof(va_list) = 24
10108 // alignment(va_list) = 8
10110 unsigned TotalNumIntRegs = 6;
10111 unsigned TotalNumXMMRegs = 8;
10112 bool UseGPOffset = (ArgMode == 1);
10113 bool UseFPOffset = (ArgMode == 2);
10114 unsigned MaxOffset = TotalNumIntRegs * 8 +
10115 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10117 /* Align ArgSize to a multiple of 8 */
10118 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10119 bool NeedsAlign = (Align > 8);
10121 MachineBasicBlock *thisMBB = MBB;
10122 MachineBasicBlock *overflowMBB;
10123 MachineBasicBlock *offsetMBB;
10124 MachineBasicBlock *endMBB;
10126 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10127 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10128 unsigned OffsetReg = 0;
10130 if (!UseGPOffset && !UseFPOffset) {
10131 // If we only pull from the overflow region, we don't create a branch.
10132 // We don't need to alter control flow.
10133 OffsetDestReg = 0; // unused
10134 OverflowDestReg = DestReg;
10137 overflowMBB = thisMBB;
10140 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10141 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10142 // If not, pull from overflow_area. (branch to overflowMBB)
10147 // offsetMBB overflowMBB
10152 // Registers for the PHI in endMBB
10153 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10154 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10156 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10157 MachineFunction *MF = MBB->getParent();
10158 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10159 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10160 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10162 MachineFunction::iterator MBBIter = MBB;
10165 // Insert the new basic blocks
10166 MF->insert(MBBIter, offsetMBB);
10167 MF->insert(MBBIter, overflowMBB);
10168 MF->insert(MBBIter, endMBB);
10170 // Transfer the remainder of MBB and its successor edges to endMBB.
10171 endMBB->splice(endMBB->begin(), thisMBB,
10172 llvm::next(MachineBasicBlock::iterator(MI)),
10174 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10176 // Make offsetMBB and overflowMBB successors of thisMBB
10177 thisMBB->addSuccessor(offsetMBB);
10178 thisMBB->addSuccessor(overflowMBB);
10180 // endMBB is a successor of both offsetMBB and overflowMBB
10181 offsetMBB->addSuccessor(endMBB);
10182 overflowMBB->addSuccessor(endMBB);
10184 // Load the offset value into a register
10185 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10186 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10190 .addDisp(Disp, UseFPOffset ? 4 : 0)
10191 .addOperand(Segment)
10192 .setMemRefs(MMOBegin, MMOEnd);
10194 // Check if there is enough room left to pull this argument.
10195 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10197 .addImm(MaxOffset + 8 - ArgSizeA8);
10199 // Branch to "overflowMBB" if offset >= max
10200 // Fall through to "offsetMBB" otherwise
10201 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10202 .addMBB(overflowMBB);
10205 // In offsetMBB, emit code to use the reg_save_area.
10207 assert(OffsetReg != 0);
10209 // Read the reg_save_area address.
10210 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10211 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10216 .addOperand(Segment)
10217 .setMemRefs(MMOBegin, MMOEnd);
10219 // Zero-extend the offset
10220 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10221 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10224 .addImm(X86::sub_32bit);
10226 // Add the offset to the reg_save_area to get the final address.
10227 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10228 .addReg(OffsetReg64)
10229 .addReg(RegSaveReg);
10231 // Compute the offset for the next argument
10232 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10233 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10235 .addImm(UseFPOffset ? 16 : 8);
10237 // Store it back into the va_list.
10238 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10242 .addDisp(Disp, UseFPOffset ? 4 : 0)
10243 .addOperand(Segment)
10244 .addReg(NextOffsetReg)
10245 .setMemRefs(MMOBegin, MMOEnd);
10248 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10253 // Emit code to use overflow area
10256 // Load the overflow_area address into a register.
10257 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10258 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10263 .addOperand(Segment)
10264 .setMemRefs(MMOBegin, MMOEnd);
10266 // If we need to align it, do so. Otherwise, just copy the address
10267 // to OverflowDestReg.
10269 // Align the overflow address
10270 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10271 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10273 // aligned_addr = (addr + (align-1)) & ~(align-1)
10274 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10275 .addReg(OverflowAddrReg)
10278 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10280 .addImm(~(uint64_t)(Align-1));
10282 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10283 .addReg(OverflowAddrReg);
10286 // Compute the next overflow address after this argument.
10287 // (the overflow address should be kept 8-byte aligned)
10288 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10289 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10290 .addReg(OverflowDestReg)
10291 .addImm(ArgSizeA8);
10293 // Store the new overflow address.
10294 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10299 .addOperand(Segment)
10300 .addReg(NextAddrReg)
10301 .setMemRefs(MMOBegin, MMOEnd);
10303 // If we branched, emit the PHI to the front of endMBB.
10305 BuildMI(*endMBB, endMBB->begin(), DL,
10306 TII->get(X86::PHI), DestReg)
10307 .addReg(OffsetDestReg).addMBB(offsetMBB)
10308 .addReg(OverflowDestReg).addMBB(overflowMBB);
10311 // Erase the pseudo instruction
10312 MI->eraseFromParent();
10317 MachineBasicBlock *
10318 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10320 MachineBasicBlock *MBB) const {
10321 // Emit code to save XMM registers to the stack. The ABI says that the
10322 // number of registers to save is given in %al, so it's theoretically
10323 // possible to do an indirect jump trick to avoid saving all of them,
10324 // however this code takes a simpler approach and just executes all
10325 // of the stores if %al is non-zero. It's less code, and it's probably
10326 // easier on the hardware branch predictor, and stores aren't all that
10327 // expensive anyway.
10329 // Create the new basic blocks. One block contains all the XMM stores,
10330 // and one block is the final destination regardless of whether any
10331 // stores were performed.
10332 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10333 MachineFunction *F = MBB->getParent();
10334 MachineFunction::iterator MBBIter = MBB;
10336 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10337 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10338 F->insert(MBBIter, XMMSaveMBB);
10339 F->insert(MBBIter, EndMBB);
10341 // Transfer the remainder of MBB and its successor edges to EndMBB.
10342 EndMBB->splice(EndMBB->begin(), MBB,
10343 llvm::next(MachineBasicBlock::iterator(MI)),
10345 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10347 // The original block will now fall through to the XMM save block.
10348 MBB->addSuccessor(XMMSaveMBB);
10349 // The XMMSaveMBB will fall through to the end block.
10350 XMMSaveMBB->addSuccessor(EndMBB);
10352 // Now add the instructions.
10353 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10354 DebugLoc DL = MI->getDebugLoc();
10356 unsigned CountReg = MI->getOperand(0).getReg();
10357 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10358 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10360 if (!Subtarget->isTargetWin64()) {
10361 // If %al is 0, branch around the XMM save block.
10362 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10363 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10364 MBB->addSuccessor(EndMBB);
10367 // In the XMM save block, save all the XMM argument registers.
10368 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10369 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10370 MachineMemOperand *MMO =
10371 F->getMachineMemOperand(
10372 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10373 MachineMemOperand::MOStore,
10374 /*Size=*/16, /*Align=*/16);
10375 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10376 .addFrameIndex(RegSaveFrameIndex)
10377 .addImm(/*Scale=*/1)
10378 .addReg(/*IndexReg=*/0)
10379 .addImm(/*Disp=*/Offset)
10380 .addReg(/*Segment=*/0)
10381 .addReg(MI->getOperand(i).getReg())
10382 .addMemOperand(MMO);
10385 MI->eraseFromParent(); // The pseudo instruction is gone now.
10390 MachineBasicBlock *
10391 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10392 MachineBasicBlock *BB) const {
10393 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10394 DebugLoc DL = MI->getDebugLoc();
10396 // To "insert" a SELECT_CC instruction, we actually have to insert the
10397 // diamond control-flow pattern. The incoming instruction knows the
10398 // destination vreg to set, the condition code register to branch on, the
10399 // true/false values to select between, and a branch opcode to use.
10400 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10401 MachineFunction::iterator It = BB;
10407 // cmpTY ccX, r1, r2
10409 // fallthrough --> copy0MBB
10410 MachineBasicBlock *thisMBB = BB;
10411 MachineFunction *F = BB->getParent();
10412 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10413 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10414 F->insert(It, copy0MBB);
10415 F->insert(It, sinkMBB);
10417 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10418 // live into the sink and copy blocks.
10419 const MachineFunction *MF = BB->getParent();
10420 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10421 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10423 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10424 const MachineOperand &MO = MI->getOperand(I);
10425 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10426 unsigned Reg = MO.getReg();
10427 if (Reg != X86::EFLAGS) continue;
10428 copy0MBB->addLiveIn(Reg);
10429 sinkMBB->addLiveIn(Reg);
10432 // Transfer the remainder of BB and its successor edges to sinkMBB.
10433 sinkMBB->splice(sinkMBB->begin(), BB,
10434 llvm::next(MachineBasicBlock::iterator(MI)),
10436 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10438 // Add the true and fallthrough blocks as its successors.
10439 BB->addSuccessor(copy0MBB);
10440 BB->addSuccessor(sinkMBB);
10442 // Create the conditional branch instruction.
10444 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10445 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10448 // %FalseValue = ...
10449 // # fallthrough to sinkMBB
10450 copy0MBB->addSuccessor(sinkMBB);
10453 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10455 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10456 TII->get(X86::PHI), MI->getOperand(0).getReg())
10457 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10458 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10460 MI->eraseFromParent(); // The pseudo instruction is gone now.
10464 MachineBasicBlock *
10465 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10466 MachineBasicBlock *BB) const {
10467 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10468 DebugLoc DL = MI->getDebugLoc();
10470 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10471 // non-trivial part is impdef of ESP.
10472 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10475 const char *StackProbeSymbol =
10476 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10478 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10479 .addExternalSymbol(StackProbeSymbol)
10480 .addReg(X86::EAX, RegState::Implicit)
10481 .addReg(X86::ESP, RegState::Implicit)
10482 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10483 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10484 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10486 MI->eraseFromParent(); // The pseudo instruction is gone now.
10490 MachineBasicBlock *
10491 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10492 MachineBasicBlock *BB) const {
10493 // This is pretty easy. We're taking the value that we received from
10494 // our load from the relocation, sticking it in either RDI (x86-64)
10495 // or EAX and doing an indirect call. The return value will then
10496 // be in the normal return register.
10497 const X86InstrInfo *TII
10498 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10499 DebugLoc DL = MI->getDebugLoc();
10500 MachineFunction *F = BB->getParent();
10502 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10503 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10505 if (Subtarget->is64Bit()) {
10506 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10507 TII->get(X86::MOV64rm), X86::RDI)
10509 .addImm(0).addReg(0)
10510 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10511 MI->getOperand(3).getTargetFlags())
10513 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10514 addDirectMem(MIB, X86::RDI);
10515 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10516 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10517 TII->get(X86::MOV32rm), X86::EAX)
10519 .addImm(0).addReg(0)
10520 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10521 MI->getOperand(3).getTargetFlags())
10523 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10524 addDirectMem(MIB, X86::EAX);
10526 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10527 TII->get(X86::MOV32rm), X86::EAX)
10528 .addReg(TII->getGlobalBaseReg(F))
10529 .addImm(0).addReg(0)
10530 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10531 MI->getOperand(3).getTargetFlags())
10533 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10534 addDirectMem(MIB, X86::EAX);
10537 MI->eraseFromParent(); // The pseudo instruction is gone now.
10541 MachineBasicBlock *
10542 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10543 MachineBasicBlock *BB) const {
10544 switch (MI->getOpcode()) {
10545 default: assert(false && "Unexpected instr type to insert");
10546 case X86::TAILJMPd64:
10547 case X86::TAILJMPr64:
10548 case X86::TAILJMPm64:
10549 assert(!"TAILJMP64 would not be touched here.");
10550 case X86::TCRETURNdi64:
10551 case X86::TCRETURNri64:
10552 case X86::TCRETURNmi64:
10553 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10554 // On AMD64, additional defs should be added before register allocation.
10555 if (!Subtarget->isTargetWin64()) {
10556 MI->addRegisterDefined(X86::RSI);
10557 MI->addRegisterDefined(X86::RDI);
10558 MI->addRegisterDefined(X86::XMM6);
10559 MI->addRegisterDefined(X86::XMM7);
10560 MI->addRegisterDefined(X86::XMM8);
10561 MI->addRegisterDefined(X86::XMM9);
10562 MI->addRegisterDefined(X86::XMM10);
10563 MI->addRegisterDefined(X86::XMM11);
10564 MI->addRegisterDefined(X86::XMM12);
10565 MI->addRegisterDefined(X86::XMM13);
10566 MI->addRegisterDefined(X86::XMM14);
10567 MI->addRegisterDefined(X86::XMM15);
10570 case X86::WIN_ALLOCA:
10571 return EmitLoweredWinAlloca(MI, BB);
10572 case X86::TLSCall_32:
10573 case X86::TLSCall_64:
10574 return EmitLoweredTLSCall(MI, BB);
10575 case X86::CMOV_GR8:
10576 case X86::CMOV_FR32:
10577 case X86::CMOV_FR64:
10578 case X86::CMOV_V4F32:
10579 case X86::CMOV_V2F64:
10580 case X86::CMOV_V2I64:
10581 case X86::CMOV_GR16:
10582 case X86::CMOV_GR32:
10583 case X86::CMOV_RFP32:
10584 case X86::CMOV_RFP64:
10585 case X86::CMOV_RFP80:
10586 return EmitLoweredSelect(MI, BB);
10588 case X86::FP32_TO_INT16_IN_MEM:
10589 case X86::FP32_TO_INT32_IN_MEM:
10590 case X86::FP32_TO_INT64_IN_MEM:
10591 case X86::FP64_TO_INT16_IN_MEM:
10592 case X86::FP64_TO_INT32_IN_MEM:
10593 case X86::FP64_TO_INT64_IN_MEM:
10594 case X86::FP80_TO_INT16_IN_MEM:
10595 case X86::FP80_TO_INT32_IN_MEM:
10596 case X86::FP80_TO_INT64_IN_MEM: {
10597 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10598 DebugLoc DL = MI->getDebugLoc();
10600 // Change the floating point control register to use "round towards zero"
10601 // mode when truncating to an integer value.
10602 MachineFunction *F = BB->getParent();
10603 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10604 addFrameReference(BuildMI(*BB, MI, DL,
10605 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10607 // Load the old value of the high byte of the control word...
10609 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10610 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10613 // Set the high part to be round to zero...
10614 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10617 // Reload the modified control word now...
10618 addFrameReference(BuildMI(*BB, MI, DL,
10619 TII->get(X86::FLDCW16m)), CWFrameIdx);
10621 // Restore the memory image of control word to original value
10622 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10625 // Get the X86 opcode to use.
10627 switch (MI->getOpcode()) {
10628 default: llvm_unreachable("illegal opcode!");
10629 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10630 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10631 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10632 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10633 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10634 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10635 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10636 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10637 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10641 MachineOperand &Op = MI->getOperand(0);
10643 AM.BaseType = X86AddressMode::RegBase;
10644 AM.Base.Reg = Op.getReg();
10646 AM.BaseType = X86AddressMode::FrameIndexBase;
10647 AM.Base.FrameIndex = Op.getIndex();
10649 Op = MI->getOperand(1);
10651 AM.Scale = Op.getImm();
10652 Op = MI->getOperand(2);
10654 AM.IndexReg = Op.getImm();
10655 Op = MI->getOperand(3);
10656 if (Op.isGlobal()) {
10657 AM.GV = Op.getGlobal();
10659 AM.Disp = Op.getImm();
10661 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10662 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10664 // Reload the original control word now.
10665 addFrameReference(BuildMI(*BB, MI, DL,
10666 TII->get(X86::FLDCW16m)), CWFrameIdx);
10668 MI->eraseFromParent(); // The pseudo instruction is gone now.
10671 // String/text processing lowering.
10672 case X86::PCMPISTRM128REG:
10673 case X86::VPCMPISTRM128REG:
10674 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10675 case X86::PCMPISTRM128MEM:
10676 case X86::VPCMPISTRM128MEM:
10677 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10678 case X86::PCMPESTRM128REG:
10679 case X86::VPCMPESTRM128REG:
10680 return EmitPCMP(MI, BB, 5, false /* in mem */);
10681 case X86::PCMPESTRM128MEM:
10682 case X86::VPCMPESTRM128MEM:
10683 return EmitPCMP(MI, BB, 5, true /* in mem */);
10685 // Thread synchronization.
10687 return EmitMonitor(MI, BB);
10689 return EmitMwait(MI, BB);
10691 // Atomic Lowering.
10692 case X86::ATOMAND32:
10693 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10694 X86::AND32ri, X86::MOV32rm,
10696 X86::NOT32r, X86::EAX,
10697 X86::GR32RegisterClass);
10698 case X86::ATOMOR32:
10699 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10700 X86::OR32ri, X86::MOV32rm,
10702 X86::NOT32r, X86::EAX,
10703 X86::GR32RegisterClass);
10704 case X86::ATOMXOR32:
10705 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10706 X86::XOR32ri, X86::MOV32rm,
10708 X86::NOT32r, X86::EAX,
10709 X86::GR32RegisterClass);
10710 case X86::ATOMNAND32:
10711 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10712 X86::AND32ri, X86::MOV32rm,
10714 X86::NOT32r, X86::EAX,
10715 X86::GR32RegisterClass, true);
10716 case X86::ATOMMIN32:
10717 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10718 case X86::ATOMMAX32:
10719 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10720 case X86::ATOMUMIN32:
10721 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10722 case X86::ATOMUMAX32:
10723 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10725 case X86::ATOMAND16:
10726 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10727 X86::AND16ri, X86::MOV16rm,
10729 X86::NOT16r, X86::AX,
10730 X86::GR16RegisterClass);
10731 case X86::ATOMOR16:
10732 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10733 X86::OR16ri, X86::MOV16rm,
10735 X86::NOT16r, X86::AX,
10736 X86::GR16RegisterClass);
10737 case X86::ATOMXOR16:
10738 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10739 X86::XOR16ri, X86::MOV16rm,
10741 X86::NOT16r, X86::AX,
10742 X86::GR16RegisterClass);
10743 case X86::ATOMNAND16:
10744 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10745 X86::AND16ri, X86::MOV16rm,
10747 X86::NOT16r, X86::AX,
10748 X86::GR16RegisterClass, true);
10749 case X86::ATOMMIN16:
10750 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10751 case X86::ATOMMAX16:
10752 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10753 case X86::ATOMUMIN16:
10754 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10755 case X86::ATOMUMAX16:
10756 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10758 case X86::ATOMAND8:
10759 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10760 X86::AND8ri, X86::MOV8rm,
10762 X86::NOT8r, X86::AL,
10763 X86::GR8RegisterClass);
10765 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10766 X86::OR8ri, X86::MOV8rm,
10768 X86::NOT8r, X86::AL,
10769 X86::GR8RegisterClass);
10770 case X86::ATOMXOR8:
10771 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10772 X86::XOR8ri, X86::MOV8rm,
10774 X86::NOT8r, X86::AL,
10775 X86::GR8RegisterClass);
10776 case X86::ATOMNAND8:
10777 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10778 X86::AND8ri, X86::MOV8rm,
10780 X86::NOT8r, X86::AL,
10781 X86::GR8RegisterClass, true);
10782 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10783 // This group is for 64-bit host.
10784 case X86::ATOMAND64:
10785 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10786 X86::AND64ri32, X86::MOV64rm,
10788 X86::NOT64r, X86::RAX,
10789 X86::GR64RegisterClass);
10790 case X86::ATOMOR64:
10791 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10792 X86::OR64ri32, X86::MOV64rm,
10794 X86::NOT64r, X86::RAX,
10795 X86::GR64RegisterClass);
10796 case X86::ATOMXOR64:
10797 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10798 X86::XOR64ri32, X86::MOV64rm,
10800 X86::NOT64r, X86::RAX,
10801 X86::GR64RegisterClass);
10802 case X86::ATOMNAND64:
10803 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10804 X86::AND64ri32, X86::MOV64rm,
10806 X86::NOT64r, X86::RAX,
10807 X86::GR64RegisterClass, true);
10808 case X86::ATOMMIN64:
10809 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10810 case X86::ATOMMAX64:
10811 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10812 case X86::ATOMUMIN64:
10813 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10814 case X86::ATOMUMAX64:
10815 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10817 // This group does 64-bit operations on a 32-bit host.
10818 case X86::ATOMAND6432:
10819 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10820 X86::AND32rr, X86::AND32rr,
10821 X86::AND32ri, X86::AND32ri,
10823 case X86::ATOMOR6432:
10824 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10825 X86::OR32rr, X86::OR32rr,
10826 X86::OR32ri, X86::OR32ri,
10828 case X86::ATOMXOR6432:
10829 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10830 X86::XOR32rr, X86::XOR32rr,
10831 X86::XOR32ri, X86::XOR32ri,
10833 case X86::ATOMNAND6432:
10834 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10835 X86::AND32rr, X86::AND32rr,
10836 X86::AND32ri, X86::AND32ri,
10838 case X86::ATOMADD6432:
10839 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10840 X86::ADD32rr, X86::ADC32rr,
10841 X86::ADD32ri, X86::ADC32ri,
10843 case X86::ATOMSUB6432:
10844 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10845 X86::SUB32rr, X86::SBB32rr,
10846 X86::SUB32ri, X86::SBB32ri,
10848 case X86::ATOMSWAP6432:
10849 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10850 X86::MOV32rr, X86::MOV32rr,
10851 X86::MOV32ri, X86::MOV32ri,
10853 case X86::VASTART_SAVE_XMM_REGS:
10854 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10856 case X86::VAARG_64:
10857 return EmitVAARG64WithCustomInserter(MI, BB);
10861 //===----------------------------------------------------------------------===//
10862 // X86 Optimization Hooks
10863 //===----------------------------------------------------------------------===//
10865 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10869 const SelectionDAG &DAG,
10870 unsigned Depth) const {
10871 unsigned Opc = Op.getOpcode();
10872 assert((Opc >= ISD::BUILTIN_OP_END ||
10873 Opc == ISD::INTRINSIC_WO_CHAIN ||
10874 Opc == ISD::INTRINSIC_W_CHAIN ||
10875 Opc == ISD::INTRINSIC_VOID) &&
10876 "Should use MaskedValueIsZero if you don't know whether Op"
10877 " is a target node!");
10879 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10893 // These nodes' second result is a boolean.
10894 if (Op.getResNo() == 0)
10897 case X86ISD::SETCC:
10898 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10899 Mask.getBitWidth() - 1);
10904 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10905 unsigned Depth) const {
10906 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10907 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10908 return Op.getValueType().getScalarType().getSizeInBits();
10914 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10915 /// node is a GlobalAddress + offset.
10916 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10917 const GlobalValue* &GA,
10918 int64_t &Offset) const {
10919 if (N->getOpcode() == X86ISD::Wrapper) {
10920 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10921 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10922 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10926 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10929 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10930 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10931 /// if the load addresses are consecutive, non-overlapping, and in the right
10933 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10934 TargetLowering::DAGCombinerInfo &DCI) {
10935 DebugLoc dl = N->getDebugLoc();
10936 EVT VT = N->getValueType(0);
10938 if (VT.getSizeInBits() != 128)
10941 // Don't create instructions with illegal types after legalize types has run.
10942 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10943 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10946 SmallVector<SDValue, 16> Elts;
10947 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10948 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10950 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10953 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10954 /// generation and convert it from being a bunch of shuffles and extracts
10955 /// to a simple store and scalar loads to extract the elements.
10956 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10957 const TargetLowering &TLI) {
10958 SDValue InputVector = N->getOperand(0);
10960 // Only operate on vectors of 4 elements, where the alternative shuffling
10961 // gets to be more expensive.
10962 if (InputVector.getValueType() != MVT::v4i32)
10965 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10966 // single use which is a sign-extend or zero-extend, and all elements are
10968 SmallVector<SDNode *, 4> Uses;
10969 unsigned ExtractedElements = 0;
10970 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10971 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10972 if (UI.getUse().getResNo() != InputVector.getResNo())
10975 SDNode *Extract = *UI;
10976 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10979 if (Extract->getValueType(0) != MVT::i32)
10981 if (!Extract->hasOneUse())
10983 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10984 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10986 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10989 // Record which element was extracted.
10990 ExtractedElements |=
10991 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10993 Uses.push_back(Extract);
10996 // If not all the elements were used, this may not be worthwhile.
10997 if (ExtractedElements != 15)
11000 // Ok, we've now decided to do the transformation.
11001 DebugLoc dl = InputVector.getDebugLoc();
11003 // Store the value to a temporary stack slot.
11004 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11005 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11006 MachinePointerInfo(), false, false, 0);
11008 // Replace each use (extract) with a load of the appropriate element.
11009 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11010 UE = Uses.end(); UI != UE; ++UI) {
11011 SDNode *Extract = *UI;
11013 // Compute the element's address.
11014 SDValue Idx = Extract->getOperand(1);
11016 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11017 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11018 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11020 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
11021 StackPtr, OffsetVal);
11023 // Load the scalar.
11024 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11025 ScalarAddr, MachinePointerInfo(),
11028 // Replace the exact with the load.
11029 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11032 // The replacement was made in place; don't return anything.
11036 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11037 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11038 const X86Subtarget *Subtarget) {
11039 DebugLoc DL = N->getDebugLoc();
11040 SDValue Cond = N->getOperand(0);
11041 // Get the LHS/RHS of the select.
11042 SDValue LHS = N->getOperand(1);
11043 SDValue RHS = N->getOperand(2);
11045 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11046 // instructions match the semantics of the common C idiom x<y?x:y but not
11047 // x<=y?x:y, because of how they handle negative zero (which can be
11048 // ignored in unsafe-math mode).
11049 if (Subtarget->hasSSE2() &&
11050 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11051 Cond.getOpcode() == ISD::SETCC) {
11052 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11054 unsigned Opcode = 0;
11055 // Check for x CC y ? x : y.
11056 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11057 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11061 // Converting this to a min would handle NaNs incorrectly, and swapping
11062 // the operands would cause it to handle comparisons between positive
11063 // and negative zero incorrectly.
11064 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11065 if (!UnsafeFPMath &&
11066 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11068 std::swap(LHS, RHS);
11070 Opcode = X86ISD::FMIN;
11073 // Converting this to a min would handle comparisons between positive
11074 // and negative zero incorrectly.
11075 if (!UnsafeFPMath &&
11076 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11078 Opcode = X86ISD::FMIN;
11081 // Converting this to a min would handle both negative zeros and NaNs
11082 // incorrectly, but we can swap the operands to fix both.
11083 std::swap(LHS, RHS);
11087 Opcode = X86ISD::FMIN;
11091 // Converting this to a max would handle comparisons between positive
11092 // and negative zero incorrectly.
11093 if (!UnsafeFPMath &&
11094 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11096 Opcode = X86ISD::FMAX;
11099 // Converting this to a max would handle NaNs incorrectly, and swapping
11100 // the operands would cause it to handle comparisons between positive
11101 // and negative zero incorrectly.
11102 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11103 if (!UnsafeFPMath &&
11104 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11106 std::swap(LHS, RHS);
11108 Opcode = X86ISD::FMAX;
11111 // Converting this to a max would handle both negative zeros and NaNs
11112 // incorrectly, but we can swap the operands to fix both.
11113 std::swap(LHS, RHS);
11117 Opcode = X86ISD::FMAX;
11120 // Check for x CC y ? y : x -- a min/max with reversed arms.
11121 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11122 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11126 // Converting this to a min would handle comparisons between positive
11127 // and negative zero incorrectly, and swapping the operands would
11128 // cause it to handle NaNs incorrectly.
11129 if (!UnsafeFPMath &&
11130 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11131 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11133 std::swap(LHS, RHS);
11135 Opcode = X86ISD::FMIN;
11138 // Converting this to a min would handle NaNs incorrectly.
11139 if (!UnsafeFPMath &&
11140 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11142 Opcode = X86ISD::FMIN;
11145 // Converting this to a min would handle both negative zeros and NaNs
11146 // incorrectly, but we can swap the operands to fix both.
11147 std::swap(LHS, RHS);
11151 Opcode = X86ISD::FMIN;
11155 // Converting this to a max would handle NaNs incorrectly.
11156 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11158 Opcode = X86ISD::FMAX;
11161 // Converting this to a max would handle comparisons between positive
11162 // and negative zero incorrectly, and swapping the operands would
11163 // cause it to handle NaNs incorrectly.
11164 if (!UnsafeFPMath &&
11165 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11166 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11168 std::swap(LHS, RHS);
11170 Opcode = X86ISD::FMAX;
11173 // Converting this to a max would handle both negative zeros and NaNs
11174 // incorrectly, but we can swap the operands to fix both.
11175 std::swap(LHS, RHS);
11179 Opcode = X86ISD::FMAX;
11185 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11188 // If this is a select between two integer constants, try to do some
11190 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11191 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11192 // Don't do this for crazy integer types.
11193 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11194 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11195 // so that TrueC (the true value) is larger than FalseC.
11196 bool NeedsCondInvert = false;
11198 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11199 // Efficiently invertible.
11200 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11201 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11202 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11203 NeedsCondInvert = true;
11204 std::swap(TrueC, FalseC);
11207 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11208 if (FalseC->getAPIntValue() == 0 &&
11209 TrueC->getAPIntValue().isPowerOf2()) {
11210 if (NeedsCondInvert) // Invert the condition if needed.
11211 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11212 DAG.getConstant(1, Cond.getValueType()));
11214 // Zero extend the condition if needed.
11215 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11217 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11218 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11219 DAG.getConstant(ShAmt, MVT::i8));
11222 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11223 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11224 if (NeedsCondInvert) // Invert the condition if needed.
11225 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11226 DAG.getConstant(1, Cond.getValueType()));
11228 // Zero extend the condition if needed.
11229 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11230 FalseC->getValueType(0), Cond);
11231 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11232 SDValue(FalseC, 0));
11235 // Optimize cases that will turn into an LEA instruction. This requires
11236 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11237 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11238 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11239 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11241 bool isFastMultiplier = false;
11243 switch ((unsigned char)Diff) {
11245 case 1: // result = add base, cond
11246 case 2: // result = lea base( , cond*2)
11247 case 3: // result = lea base(cond, cond*2)
11248 case 4: // result = lea base( , cond*4)
11249 case 5: // result = lea base(cond, cond*4)
11250 case 8: // result = lea base( , cond*8)
11251 case 9: // result = lea base(cond, cond*8)
11252 isFastMultiplier = true;
11257 if (isFastMultiplier) {
11258 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11259 if (NeedsCondInvert) // Invert the condition if needed.
11260 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11261 DAG.getConstant(1, Cond.getValueType()));
11263 // Zero extend the condition if needed.
11264 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11266 // Scale the condition by the difference.
11268 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11269 DAG.getConstant(Diff, Cond.getValueType()));
11271 // Add the base if non-zero.
11272 if (FalseC->getAPIntValue() != 0)
11273 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11274 SDValue(FalseC, 0));
11284 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11285 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11286 TargetLowering::DAGCombinerInfo &DCI) {
11287 DebugLoc DL = N->getDebugLoc();
11289 // If the flag operand isn't dead, don't touch this CMOV.
11290 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11293 // If this is a select between two integer constants, try to do some
11294 // optimizations. Note that the operands are ordered the opposite of SELECT
11296 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11297 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11298 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11299 // larger than FalseC (the false value).
11300 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11302 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11303 CC = X86::GetOppositeBranchCondition(CC);
11304 std::swap(TrueC, FalseC);
11307 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11308 // This is efficient for any integer data type (including i8/i16) and
11310 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11311 SDValue Cond = N->getOperand(3);
11312 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11313 DAG.getConstant(CC, MVT::i8), Cond);
11315 // Zero extend the condition if needed.
11316 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11318 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11319 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11320 DAG.getConstant(ShAmt, MVT::i8));
11321 if (N->getNumValues() == 2) // Dead flag value?
11322 return DCI.CombineTo(N, Cond, SDValue());
11326 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11327 // for any integer data type, including i8/i16.
11328 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11329 SDValue Cond = N->getOperand(3);
11330 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11331 DAG.getConstant(CC, MVT::i8), Cond);
11333 // Zero extend the condition if needed.
11334 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11335 FalseC->getValueType(0), Cond);
11336 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11337 SDValue(FalseC, 0));
11339 if (N->getNumValues() == 2) // Dead flag value?
11340 return DCI.CombineTo(N, Cond, SDValue());
11344 // Optimize cases that will turn into an LEA instruction. This requires
11345 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11346 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11347 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11348 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11350 bool isFastMultiplier = false;
11352 switch ((unsigned char)Diff) {
11354 case 1: // result = add base, cond
11355 case 2: // result = lea base( , cond*2)
11356 case 3: // result = lea base(cond, cond*2)
11357 case 4: // result = lea base( , cond*4)
11358 case 5: // result = lea base(cond, cond*4)
11359 case 8: // result = lea base( , cond*8)
11360 case 9: // result = lea base(cond, cond*8)
11361 isFastMultiplier = true;
11366 if (isFastMultiplier) {
11367 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11368 SDValue Cond = N->getOperand(3);
11369 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11370 DAG.getConstant(CC, MVT::i8), Cond);
11371 // Zero extend the condition if needed.
11372 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11374 // Scale the condition by the difference.
11376 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11377 DAG.getConstant(Diff, Cond.getValueType()));
11379 // Add the base if non-zero.
11380 if (FalseC->getAPIntValue() != 0)
11381 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11382 SDValue(FalseC, 0));
11383 if (N->getNumValues() == 2) // Dead flag value?
11384 return DCI.CombineTo(N, Cond, SDValue());
11394 /// PerformMulCombine - Optimize a single multiply with constant into two
11395 /// in order to implement it with two cheaper instructions, e.g.
11396 /// LEA + SHL, LEA + LEA.
11397 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11398 TargetLowering::DAGCombinerInfo &DCI) {
11399 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11402 EVT VT = N->getValueType(0);
11403 if (VT != MVT::i64)
11406 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11409 uint64_t MulAmt = C->getZExtValue();
11410 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11413 uint64_t MulAmt1 = 0;
11414 uint64_t MulAmt2 = 0;
11415 if ((MulAmt % 9) == 0) {
11417 MulAmt2 = MulAmt / 9;
11418 } else if ((MulAmt % 5) == 0) {
11420 MulAmt2 = MulAmt / 5;
11421 } else if ((MulAmt % 3) == 0) {
11423 MulAmt2 = MulAmt / 3;
11426 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11427 DebugLoc DL = N->getDebugLoc();
11429 if (isPowerOf2_64(MulAmt2) &&
11430 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11431 // If second multiplifer is pow2, issue it first. We want the multiply by
11432 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11434 std::swap(MulAmt1, MulAmt2);
11437 if (isPowerOf2_64(MulAmt1))
11438 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11439 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11441 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11442 DAG.getConstant(MulAmt1, VT));
11444 if (isPowerOf2_64(MulAmt2))
11445 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11446 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11448 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11449 DAG.getConstant(MulAmt2, VT));
11451 // Do not add new nodes to DAG combiner worklist.
11452 DCI.CombineTo(N, NewMul, false);
11457 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11458 SDValue N0 = N->getOperand(0);
11459 SDValue N1 = N->getOperand(1);
11460 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11461 EVT VT = N0.getValueType();
11463 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11464 // since the result of setcc_c is all zero's or all ones.
11465 if (N1C && N0.getOpcode() == ISD::AND &&
11466 N0.getOperand(1).getOpcode() == ISD::Constant) {
11467 SDValue N00 = N0.getOperand(0);
11468 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11469 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11470 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11471 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11472 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11473 APInt ShAmt = N1C->getAPIntValue();
11474 Mask = Mask.shl(ShAmt);
11476 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11477 N00, DAG.getConstant(Mask, VT));
11484 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11486 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11487 const X86Subtarget *Subtarget) {
11488 EVT VT = N->getValueType(0);
11489 if (!VT.isVector() && VT.isInteger() &&
11490 N->getOpcode() == ISD::SHL)
11491 return PerformSHLCombine(N, DAG);
11493 // On X86 with SSE2 support, we can transform this to a vector shift if
11494 // all elements are shifted by the same amount. We can't do this in legalize
11495 // because the a constant vector is typically transformed to a constant pool
11496 // so we have no knowledge of the shift amount.
11497 if (!Subtarget->hasSSE2())
11500 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11503 SDValue ShAmtOp = N->getOperand(1);
11504 EVT EltVT = VT.getVectorElementType();
11505 DebugLoc DL = N->getDebugLoc();
11506 SDValue BaseShAmt = SDValue();
11507 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11508 unsigned NumElts = VT.getVectorNumElements();
11510 for (; i != NumElts; ++i) {
11511 SDValue Arg = ShAmtOp.getOperand(i);
11512 if (Arg.getOpcode() == ISD::UNDEF) continue;
11516 for (; i != NumElts; ++i) {
11517 SDValue Arg = ShAmtOp.getOperand(i);
11518 if (Arg.getOpcode() == ISD::UNDEF) continue;
11519 if (Arg != BaseShAmt) {
11523 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11524 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11525 SDValue InVec = ShAmtOp.getOperand(0);
11526 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11527 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11529 for (; i != NumElts; ++i) {
11530 SDValue Arg = InVec.getOperand(i);
11531 if (Arg.getOpcode() == ISD::UNDEF) continue;
11535 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11537 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11538 if (C->getZExtValue() == SplatIdx)
11539 BaseShAmt = InVec.getOperand(1);
11542 if (BaseShAmt.getNode() == 0)
11543 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11544 DAG.getIntPtrConstant(0));
11548 // The shift amount is an i32.
11549 if (EltVT.bitsGT(MVT::i32))
11550 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11551 else if (EltVT.bitsLT(MVT::i32))
11552 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11554 // The shift amount is identical so we can do a vector shift.
11555 SDValue ValOp = N->getOperand(0);
11556 switch (N->getOpcode()) {
11558 llvm_unreachable("Unknown shift opcode!");
11561 if (VT == MVT::v2i64)
11562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11563 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11565 if (VT == MVT::v4i32)
11566 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11567 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11569 if (VT == MVT::v8i16)
11570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11571 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11575 if (VT == MVT::v4i32)
11576 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11577 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11579 if (VT == MVT::v8i16)
11580 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11581 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11585 if (VT == MVT::v2i64)
11586 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11587 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11589 if (VT == MVT::v4i32)
11590 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11591 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11593 if (VT == MVT::v8i16)
11594 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11595 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11603 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11604 TargetLowering::DAGCombinerInfo &DCI,
11605 const X86Subtarget *Subtarget) {
11606 if (DCI.isBeforeLegalizeOps())
11609 // Want to form PANDN nodes, in the hopes of then easily combining them with
11610 // OR and AND nodes to form PBLEND/PSIGN.
11611 EVT VT = N->getValueType(0);
11612 if (VT != MVT::v2i64)
11615 SDValue N0 = N->getOperand(0);
11616 SDValue N1 = N->getOperand(1);
11617 DebugLoc DL = N->getDebugLoc();
11619 // Check LHS for vnot
11620 if (N0.getOpcode() == ISD::XOR &&
11621 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11622 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11624 // Check RHS for vnot
11625 if (N1.getOpcode() == ISD::XOR &&
11626 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11627 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11632 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11633 TargetLowering::DAGCombinerInfo &DCI,
11634 const X86Subtarget *Subtarget) {
11635 if (DCI.isBeforeLegalizeOps())
11638 EVT VT = N->getValueType(0);
11639 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11642 SDValue N0 = N->getOperand(0);
11643 SDValue N1 = N->getOperand(1);
11645 // look for psign/blend
11646 if (Subtarget->hasSSSE3()) {
11647 if (VT == MVT::v2i64) {
11648 // Canonicalize pandn to RHS
11649 if (N0.getOpcode() == X86ISD::PANDN)
11651 // or (and (m, x), (pandn m, y))
11652 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11653 SDValue Mask = N1.getOperand(0);
11654 SDValue X = N1.getOperand(1);
11656 if (N0.getOperand(0) == Mask)
11657 Y = N0.getOperand(1);
11658 if (N0.getOperand(1) == Mask)
11659 Y = N0.getOperand(0);
11661 // Check to see if the mask appeared in both the AND and PANDN and
11665 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11666 if (Mask.getOpcode() != ISD::BITCAST ||
11667 X.getOpcode() != ISD::BITCAST ||
11668 Y.getOpcode() != ISD::BITCAST)
11671 // Look through mask bitcast.
11672 Mask = Mask.getOperand(0);
11673 EVT MaskVT = Mask.getValueType();
11675 // Validate that the Mask operand is a vector sra node. The sra node
11676 // will be an intrinsic.
11677 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11680 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11681 // there is no psrai.b
11682 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11683 case Intrinsic::x86_sse2_psrai_w:
11684 case Intrinsic::x86_sse2_psrai_d:
11686 default: return SDValue();
11689 // Check that the SRA is all signbits.
11690 SDValue SraC = Mask.getOperand(2);
11691 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11692 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11693 if ((SraAmt + 1) != EltBits)
11696 DebugLoc DL = N->getDebugLoc();
11698 // Now we know we at least have a plendvb with the mask val. See if
11699 // we can form a psignb/w/d.
11700 // psign = x.type == y.type == mask.type && y = sub(0, x);
11701 X = X.getOperand(0);
11702 Y = Y.getOperand(0);
11703 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11704 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11705 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11708 case 8: Opc = X86ISD::PSIGNB; break;
11709 case 16: Opc = X86ISD::PSIGNW; break;
11710 case 32: Opc = X86ISD::PSIGND; break;
11714 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11715 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11718 // PBLENDVB only available on SSE 4.1
11719 if (!Subtarget->hasSSE41())
11722 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11723 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11724 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11725 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11726 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11731 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11732 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11734 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11736 if (!N0.hasOneUse() || !N1.hasOneUse())
11739 SDValue ShAmt0 = N0.getOperand(1);
11740 if (ShAmt0.getValueType() != MVT::i8)
11742 SDValue ShAmt1 = N1.getOperand(1);
11743 if (ShAmt1.getValueType() != MVT::i8)
11745 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11746 ShAmt0 = ShAmt0.getOperand(0);
11747 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11748 ShAmt1 = ShAmt1.getOperand(0);
11750 DebugLoc DL = N->getDebugLoc();
11751 unsigned Opc = X86ISD::SHLD;
11752 SDValue Op0 = N0.getOperand(0);
11753 SDValue Op1 = N1.getOperand(0);
11754 if (ShAmt0.getOpcode() == ISD::SUB) {
11755 Opc = X86ISD::SHRD;
11756 std::swap(Op0, Op1);
11757 std::swap(ShAmt0, ShAmt1);
11760 unsigned Bits = VT.getSizeInBits();
11761 if (ShAmt1.getOpcode() == ISD::SUB) {
11762 SDValue Sum = ShAmt1.getOperand(0);
11763 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11764 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11765 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11766 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11767 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11768 return DAG.getNode(Opc, DL, VT,
11770 DAG.getNode(ISD::TRUNCATE, DL,
11773 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11774 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11776 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11777 return DAG.getNode(Opc, DL, VT,
11778 N0.getOperand(0), N1.getOperand(0),
11779 DAG.getNode(ISD::TRUNCATE, DL,
11786 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11787 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11788 const X86Subtarget *Subtarget) {
11789 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11790 // the FP state in cases where an emms may be missing.
11791 // A preferable solution to the general problem is to figure out the right
11792 // places to insert EMMS. This qualifies as a quick hack.
11794 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11795 StoreSDNode *St = cast<StoreSDNode>(N);
11796 EVT VT = St->getValue().getValueType();
11797 if (VT.getSizeInBits() != 64)
11800 const Function *F = DAG.getMachineFunction().getFunction();
11801 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11802 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11803 && Subtarget->hasSSE2();
11804 if ((VT.isVector() ||
11805 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11806 isa<LoadSDNode>(St->getValue()) &&
11807 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11808 St->getChain().hasOneUse() && !St->isVolatile()) {
11809 SDNode* LdVal = St->getValue().getNode();
11810 LoadSDNode *Ld = 0;
11811 int TokenFactorIndex = -1;
11812 SmallVector<SDValue, 8> Ops;
11813 SDNode* ChainVal = St->getChain().getNode();
11814 // Must be a store of a load. We currently handle two cases: the load
11815 // is a direct child, and it's under an intervening TokenFactor. It is
11816 // possible to dig deeper under nested TokenFactors.
11817 if (ChainVal == LdVal)
11818 Ld = cast<LoadSDNode>(St->getChain());
11819 else if (St->getValue().hasOneUse() &&
11820 ChainVal->getOpcode() == ISD::TokenFactor) {
11821 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11822 if (ChainVal->getOperand(i).getNode() == LdVal) {
11823 TokenFactorIndex = i;
11824 Ld = cast<LoadSDNode>(St->getValue());
11826 Ops.push_back(ChainVal->getOperand(i));
11830 if (!Ld || !ISD::isNormalLoad(Ld))
11833 // If this is not the MMX case, i.e. we are just turning i64 load/store
11834 // into f64 load/store, avoid the transformation if there are multiple
11835 // uses of the loaded value.
11836 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11839 DebugLoc LdDL = Ld->getDebugLoc();
11840 DebugLoc StDL = N->getDebugLoc();
11841 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11842 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11844 if (Subtarget->is64Bit() || F64IsLegal) {
11845 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11846 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11847 Ld->getPointerInfo(), Ld->isVolatile(),
11848 Ld->isNonTemporal(), Ld->getAlignment());
11849 SDValue NewChain = NewLd.getValue(1);
11850 if (TokenFactorIndex != -1) {
11851 Ops.push_back(NewChain);
11852 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11855 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11856 St->getPointerInfo(),
11857 St->isVolatile(), St->isNonTemporal(),
11858 St->getAlignment());
11861 // Otherwise, lower to two pairs of 32-bit loads / stores.
11862 SDValue LoAddr = Ld->getBasePtr();
11863 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11864 DAG.getConstant(4, MVT::i32));
11866 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11867 Ld->getPointerInfo(),
11868 Ld->isVolatile(), Ld->isNonTemporal(),
11869 Ld->getAlignment());
11870 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11871 Ld->getPointerInfo().getWithOffset(4),
11872 Ld->isVolatile(), Ld->isNonTemporal(),
11873 MinAlign(Ld->getAlignment(), 4));
11875 SDValue NewChain = LoLd.getValue(1);
11876 if (TokenFactorIndex != -1) {
11877 Ops.push_back(LoLd);
11878 Ops.push_back(HiLd);
11879 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11883 LoAddr = St->getBasePtr();
11884 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11885 DAG.getConstant(4, MVT::i32));
11887 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11888 St->getPointerInfo(),
11889 St->isVolatile(), St->isNonTemporal(),
11890 St->getAlignment());
11891 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11892 St->getPointerInfo().getWithOffset(4),
11894 St->isNonTemporal(),
11895 MinAlign(St->getAlignment(), 4));
11896 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11901 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11902 /// X86ISD::FXOR nodes.
11903 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11904 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11905 // F[X]OR(0.0, x) -> x
11906 // F[X]OR(x, 0.0) -> x
11907 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11908 if (C->getValueAPF().isPosZero())
11909 return N->getOperand(1);
11910 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11911 if (C->getValueAPF().isPosZero())
11912 return N->getOperand(0);
11916 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11917 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11918 // FAND(0.0, x) -> 0.0
11919 // FAND(x, 0.0) -> 0.0
11920 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11921 if (C->getValueAPF().isPosZero())
11922 return N->getOperand(0);
11923 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11924 if (C->getValueAPF().isPosZero())
11925 return N->getOperand(1);
11929 static SDValue PerformBTCombine(SDNode *N,
11931 TargetLowering::DAGCombinerInfo &DCI) {
11932 // BT ignores high bits in the bit index operand.
11933 SDValue Op1 = N->getOperand(1);
11934 if (Op1.hasOneUse()) {
11935 unsigned BitWidth = Op1.getValueSizeInBits();
11936 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11937 APInt KnownZero, KnownOne;
11938 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11939 !DCI.isBeforeLegalizeOps());
11940 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11941 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11942 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11943 DCI.CommitTargetLoweringOpt(TLO);
11948 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11949 SDValue Op = N->getOperand(0);
11950 if (Op.getOpcode() == ISD::BITCAST)
11951 Op = Op.getOperand(0);
11952 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11953 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11954 VT.getVectorElementType().getSizeInBits() ==
11955 OpVT.getVectorElementType().getSizeInBits()) {
11956 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11961 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11962 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11963 // (and (i32 x86isd::setcc_carry), 1)
11964 // This eliminates the zext. This transformation is necessary because
11965 // ISD::SETCC is always legalized to i8.
11966 DebugLoc dl = N->getDebugLoc();
11967 SDValue N0 = N->getOperand(0);
11968 EVT VT = N->getValueType(0);
11969 if (N0.getOpcode() == ISD::AND &&
11971 N0.getOperand(0).hasOneUse()) {
11972 SDValue N00 = N0.getOperand(0);
11973 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11975 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11976 if (!C || C->getZExtValue() != 1)
11978 return DAG.getNode(ISD::AND, dl, VT,
11979 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11980 N00.getOperand(0), N00.getOperand(1)),
11981 DAG.getConstant(1, VT));
11987 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11988 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11989 unsigned X86CC = N->getConstantOperandVal(0);
11990 SDValue EFLAG = N->getOperand(1);
11991 DebugLoc DL = N->getDebugLoc();
11993 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11994 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11996 if (X86CC == X86::COND_B)
11997 return DAG.getNode(ISD::AND, DL, MVT::i8,
11998 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11999 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12000 DAG.getConstant(1, MVT::i8));
12005 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12006 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12007 X86TargetLowering::DAGCombinerInfo &DCI) {
12008 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12009 // the result is either zero or one (depending on the input carry bit).
12010 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12011 if (X86::isZeroNode(N->getOperand(0)) &&
12012 X86::isZeroNode(N->getOperand(1)) &&
12013 // We don't have a good way to replace an EFLAGS use, so only do this when
12015 SDValue(N, 1).use_empty()) {
12016 DebugLoc DL = N->getDebugLoc();
12017 EVT VT = N->getValueType(0);
12018 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12019 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12020 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12021 DAG.getConstant(X86::COND_B,MVT::i8),
12023 DAG.getConstant(1, VT));
12024 return DCI.CombineTo(N, Res1, CarryOut);
12030 // fold (add Y, (sete X, 0)) -> adc 0, Y
12031 // (add Y, (setne X, 0)) -> sbb -1, Y
12032 // (sub (sete X, 0), Y) -> sbb 0, Y
12033 // (sub (setne X, 0), Y) -> adc -1, Y
12034 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12035 DebugLoc DL = N->getDebugLoc();
12037 // Look through ZExts.
12038 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12039 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12042 SDValue SetCC = Ext.getOperand(0);
12043 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12046 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12047 if (CC != X86::COND_E && CC != X86::COND_NE)
12050 SDValue Cmp = SetCC.getOperand(1);
12051 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12052 !X86::isZeroNode(Cmp.getOperand(1)) ||
12053 !Cmp.getOperand(0).getValueType().isInteger())
12056 SDValue CmpOp0 = Cmp.getOperand(0);
12057 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12058 DAG.getConstant(1, CmpOp0.getValueType()));
12060 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12061 if (CC == X86::COND_NE)
12062 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12063 DL, OtherVal.getValueType(), OtherVal,
12064 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12065 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12066 DL, OtherVal.getValueType(), OtherVal,
12067 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12070 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12071 DAGCombinerInfo &DCI) const {
12072 SelectionDAG &DAG = DCI.DAG;
12073 switch (N->getOpcode()) {
12075 case ISD::EXTRACT_VECTOR_ELT:
12076 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12077 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12078 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12080 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12081 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12082 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12085 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12086 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12087 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12088 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12090 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12091 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12092 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12093 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12094 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12095 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12096 case X86ISD::SHUFPS: // Handle all target specific shuffles
12097 case X86ISD::SHUFPD:
12098 case X86ISD::PALIGN:
12099 case X86ISD::PUNPCKHBW:
12100 case X86ISD::PUNPCKHWD:
12101 case X86ISD::PUNPCKHDQ:
12102 case X86ISD::PUNPCKHQDQ:
12103 case X86ISD::UNPCKHPS:
12104 case X86ISD::UNPCKHPD:
12105 case X86ISD::PUNPCKLBW:
12106 case X86ISD::PUNPCKLWD:
12107 case X86ISD::PUNPCKLDQ:
12108 case X86ISD::PUNPCKLQDQ:
12109 case X86ISD::UNPCKLPS:
12110 case X86ISD::UNPCKLPD:
12111 case X86ISD::VUNPCKLPS:
12112 case X86ISD::VUNPCKLPD:
12113 case X86ISD::VUNPCKLPSY:
12114 case X86ISD::VUNPCKLPDY:
12115 case X86ISD::MOVHLPS:
12116 case X86ISD::MOVLHPS:
12117 case X86ISD::PSHUFD:
12118 case X86ISD::PSHUFHW:
12119 case X86ISD::PSHUFLW:
12120 case X86ISD::MOVSS:
12121 case X86ISD::MOVSD:
12122 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12128 /// isTypeDesirableForOp - Return true if the target has native support for
12129 /// the specified value type and it is 'desirable' to use the type for the
12130 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12131 /// instruction encodings are longer and some i16 instructions are slow.
12132 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12133 if (!isTypeLegal(VT))
12135 if (VT != MVT::i16)
12142 case ISD::SIGN_EXTEND:
12143 case ISD::ZERO_EXTEND:
12144 case ISD::ANY_EXTEND:
12157 /// IsDesirableToPromoteOp - This method query the target whether it is
12158 /// beneficial for dag combiner to promote the specified node. If true, it
12159 /// should return the desired promotion type by reference.
12160 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12161 EVT VT = Op.getValueType();
12162 if (VT != MVT::i16)
12165 bool Promote = false;
12166 bool Commute = false;
12167 switch (Op.getOpcode()) {
12170 LoadSDNode *LD = cast<LoadSDNode>(Op);
12171 // If the non-extending load has a single use and it's not live out, then it
12172 // might be folded.
12173 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12174 Op.hasOneUse()*/) {
12175 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12176 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12177 // The only case where we'd want to promote LOAD (rather then it being
12178 // promoted as an operand is when it's only use is liveout.
12179 if (UI->getOpcode() != ISD::CopyToReg)
12186 case ISD::SIGN_EXTEND:
12187 case ISD::ZERO_EXTEND:
12188 case ISD::ANY_EXTEND:
12193 SDValue N0 = Op.getOperand(0);
12194 // Look out for (store (shl (load), x)).
12195 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12208 SDValue N0 = Op.getOperand(0);
12209 SDValue N1 = Op.getOperand(1);
12210 if (!Commute && MayFoldLoad(N1))
12212 // Avoid disabling potential load folding opportunities.
12213 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12215 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12225 //===----------------------------------------------------------------------===//
12226 // X86 Inline Assembly Support
12227 //===----------------------------------------------------------------------===//
12229 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12230 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12232 std::string AsmStr = IA->getAsmString();
12234 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12235 SmallVector<StringRef, 4> AsmPieces;
12236 SplitString(AsmStr, AsmPieces, ";\n");
12238 switch (AsmPieces.size()) {
12239 default: return false;
12241 AsmStr = AsmPieces[0];
12243 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12245 // FIXME: this should verify that we are targetting a 486 or better. If not,
12246 // we will turn this bswap into something that will be lowered to logical ops
12247 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12248 // so don't worry about this.
12250 if (AsmPieces.size() == 2 &&
12251 (AsmPieces[0] == "bswap" ||
12252 AsmPieces[0] == "bswapq" ||
12253 AsmPieces[0] == "bswapl") &&
12254 (AsmPieces[1] == "$0" ||
12255 AsmPieces[1] == "${0:q}")) {
12256 // No need to check constraints, nothing other than the equivalent of
12257 // "=r,0" would be valid here.
12258 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12259 if (!Ty || Ty->getBitWidth() % 16 != 0)
12261 return IntrinsicLowering::LowerToByteSwap(CI);
12263 // rorw $$8, ${0:w} --> llvm.bswap.i16
12264 if (CI->getType()->isIntegerTy(16) &&
12265 AsmPieces.size() == 3 &&
12266 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12267 AsmPieces[1] == "$$8," &&
12268 AsmPieces[2] == "${0:w}" &&
12269 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12271 const std::string &ConstraintsStr = IA->getConstraintString();
12272 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12273 std::sort(AsmPieces.begin(), AsmPieces.end());
12274 if (AsmPieces.size() == 4 &&
12275 AsmPieces[0] == "~{cc}" &&
12276 AsmPieces[1] == "~{dirflag}" &&
12277 AsmPieces[2] == "~{flags}" &&
12278 AsmPieces[3] == "~{fpsr}") {
12279 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12280 if (!Ty || Ty->getBitWidth() % 16 != 0)
12282 return IntrinsicLowering::LowerToByteSwap(CI);
12287 if (CI->getType()->isIntegerTy(32) &&
12288 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12289 SmallVector<StringRef, 4> Words;
12290 SplitString(AsmPieces[0], Words, " \t,");
12291 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12292 Words[2] == "${0:w}") {
12294 SplitString(AsmPieces[1], Words, " \t,");
12295 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12296 Words[2] == "$0") {
12298 SplitString(AsmPieces[2], Words, " \t,");
12299 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12300 Words[2] == "${0:w}") {
12302 const std::string &ConstraintsStr = IA->getConstraintString();
12303 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12304 std::sort(AsmPieces.begin(), AsmPieces.end());
12305 if (AsmPieces.size() == 4 &&
12306 AsmPieces[0] == "~{cc}" &&
12307 AsmPieces[1] == "~{dirflag}" &&
12308 AsmPieces[2] == "~{flags}" &&
12309 AsmPieces[3] == "~{fpsr}") {
12310 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12311 if (!Ty || Ty->getBitWidth() % 16 != 0)
12313 return IntrinsicLowering::LowerToByteSwap(CI);
12320 if (CI->getType()->isIntegerTy(64)) {
12321 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12322 if (Constraints.size() >= 2 &&
12323 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12324 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12325 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12326 SmallVector<StringRef, 4> Words;
12327 SplitString(AsmPieces[0], Words, " \t");
12328 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12330 SplitString(AsmPieces[1], Words, " \t");
12331 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12333 SplitString(AsmPieces[2], Words, " \t,");
12334 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12335 Words[2] == "%edx") {
12336 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12337 if (!Ty || Ty->getBitWidth() % 16 != 0)
12339 return IntrinsicLowering::LowerToByteSwap(CI);
12352 /// getConstraintType - Given a constraint letter, return the type of
12353 /// constraint it is for this target.
12354 X86TargetLowering::ConstraintType
12355 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12356 if (Constraint.size() == 1) {
12357 switch (Constraint[0]) {
12367 return C_RegisterClass;
12391 return TargetLowering::getConstraintType(Constraint);
12394 /// Examine constraint type and operand type and determine a weight value.
12395 /// This object must already have been set up with the operand type
12396 /// and the current alternative constraint selected.
12397 TargetLowering::ConstraintWeight
12398 X86TargetLowering::getSingleConstraintMatchWeight(
12399 AsmOperandInfo &info, const char *constraint) const {
12400 ConstraintWeight weight = CW_Invalid;
12401 Value *CallOperandVal = info.CallOperandVal;
12402 // If we don't have a value, we can't do a match,
12403 // but allow it at the lowest weight.
12404 if (CallOperandVal == NULL)
12406 const Type *type = CallOperandVal->getType();
12407 // Look at the constraint type.
12408 switch (*constraint) {
12410 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12421 if (CallOperandVal->getType()->isIntegerTy())
12422 weight = CW_SpecificReg;
12427 if (type->isFloatingPointTy())
12428 weight = CW_SpecificReg;
12431 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12432 weight = CW_SpecificReg;
12436 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12437 weight = CW_Register;
12440 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12441 if (C->getZExtValue() <= 31)
12442 weight = CW_Constant;
12446 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12447 if (C->getZExtValue() <= 63)
12448 weight = CW_Constant;
12452 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12453 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12454 weight = CW_Constant;
12458 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12459 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12460 weight = CW_Constant;
12464 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12465 if (C->getZExtValue() <= 3)
12466 weight = CW_Constant;
12470 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12471 if (C->getZExtValue() <= 0xff)
12472 weight = CW_Constant;
12477 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12478 weight = CW_Constant;
12482 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12483 if ((C->getSExtValue() >= -0x80000000LL) &&
12484 (C->getSExtValue() <= 0x7fffffffLL))
12485 weight = CW_Constant;
12489 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12490 if (C->getZExtValue() <= 0xffffffff)
12491 weight = CW_Constant;
12498 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12499 /// with another that has more specific requirements based on the type of the
12500 /// corresponding operand.
12501 const char *X86TargetLowering::
12502 LowerXConstraint(EVT ConstraintVT) const {
12503 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12504 // 'f' like normal targets.
12505 if (ConstraintVT.isFloatingPoint()) {
12506 if (Subtarget->hasXMMInt())
12508 if (Subtarget->hasXMM())
12512 return TargetLowering::LowerXConstraint(ConstraintVT);
12515 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12516 /// vector. If it is invalid, don't add anything to Ops.
12517 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12519 std::vector<SDValue>&Ops,
12520 SelectionDAG &DAG) const {
12521 SDValue Result(0, 0);
12523 switch (Constraint) {
12526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12527 if (C->getZExtValue() <= 31) {
12528 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12534 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12535 if (C->getZExtValue() <= 63) {
12536 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12543 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12544 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12550 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12551 if (C->getZExtValue() <= 255) {
12552 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12558 // 32-bit signed value
12559 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12560 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12561 C->getSExtValue())) {
12562 // Widen to 64 bits here to get it sign extended.
12563 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12566 // FIXME gcc accepts some relocatable values here too, but only in certain
12567 // memory models; it's complicated.
12572 // 32-bit unsigned value
12573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12574 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12575 C->getZExtValue())) {
12576 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12580 // FIXME gcc accepts some relocatable values here too, but only in certain
12581 // memory models; it's complicated.
12585 // Literal immediates are always ok.
12586 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12587 // Widen to 64 bits here to get it sign extended.
12588 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12592 // In any sort of PIC mode addresses need to be computed at runtime by
12593 // adding in a register or some sort of table lookup. These can't
12594 // be used as immediates.
12595 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12598 // If we are in non-pic codegen mode, we allow the address of a global (with
12599 // an optional displacement) to be used with 'i'.
12600 GlobalAddressSDNode *GA = 0;
12601 int64_t Offset = 0;
12603 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12605 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12606 Offset += GA->getOffset();
12608 } else if (Op.getOpcode() == ISD::ADD) {
12609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12610 Offset += C->getZExtValue();
12611 Op = Op.getOperand(0);
12614 } else if (Op.getOpcode() == ISD::SUB) {
12615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12616 Offset += -C->getZExtValue();
12617 Op = Op.getOperand(0);
12622 // Otherwise, this isn't something we can handle, reject it.
12626 const GlobalValue *GV = GA->getGlobal();
12627 // If we require an extra load to get this address, as in PIC mode, we
12628 // can't accept it.
12629 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12630 getTargetMachine())))
12633 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12634 GA->getValueType(0), Offset);
12639 if (Result.getNode()) {
12640 Ops.push_back(Result);
12643 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12646 std::vector<unsigned> X86TargetLowering::
12647 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12649 if (Constraint.size() == 1) {
12650 // FIXME: not handling fp-stack yet!
12651 switch (Constraint[0]) { // GCC X86 Constraint Letters
12652 default: break; // Unknown constraint letter
12653 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12654 if (Subtarget->is64Bit()) {
12655 if (VT == MVT::i32)
12656 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12657 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12658 X86::R10D,X86::R11D,X86::R12D,
12659 X86::R13D,X86::R14D,X86::R15D,
12660 X86::EBP, X86::ESP, 0);
12661 else if (VT == MVT::i16)
12662 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12663 X86::SI, X86::DI, X86::R8W,X86::R9W,
12664 X86::R10W,X86::R11W,X86::R12W,
12665 X86::R13W,X86::R14W,X86::R15W,
12666 X86::BP, X86::SP, 0);
12667 else if (VT == MVT::i8)
12668 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12669 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12670 X86::R10B,X86::R11B,X86::R12B,
12671 X86::R13B,X86::R14B,X86::R15B,
12672 X86::BPL, X86::SPL, 0);
12674 else if (VT == MVT::i64)
12675 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12676 X86::RSI, X86::RDI, X86::R8, X86::R9,
12677 X86::R10, X86::R11, X86::R12,
12678 X86::R13, X86::R14, X86::R15,
12679 X86::RBP, X86::RSP, 0);
12683 // 32-bit fallthrough
12684 case 'Q': // Q_REGS
12685 if (VT == MVT::i32)
12686 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12687 else if (VT == MVT::i16)
12688 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12689 else if (VT == MVT::i8)
12690 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12691 else if (VT == MVT::i64)
12692 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12697 return std::vector<unsigned>();
12700 std::pair<unsigned, const TargetRegisterClass*>
12701 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12703 // First, see if this is a constraint that directly corresponds to an LLVM
12705 if (Constraint.size() == 1) {
12706 // GCC Constraint Letters
12707 switch (Constraint[0]) {
12709 case 'r': // GENERAL_REGS
12710 case 'l': // INDEX_REGS
12712 return std::make_pair(0U, X86::GR8RegisterClass);
12713 if (VT == MVT::i16)
12714 return std::make_pair(0U, X86::GR16RegisterClass);
12715 if (VT == MVT::i32 || !Subtarget->is64Bit())
12716 return std::make_pair(0U, X86::GR32RegisterClass);
12717 return std::make_pair(0U, X86::GR64RegisterClass);
12718 case 'R': // LEGACY_REGS
12720 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12721 if (VT == MVT::i16)
12722 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12723 if (VT == MVT::i32 || !Subtarget->is64Bit())
12724 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12725 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12726 case 'f': // FP Stack registers.
12727 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12728 // value to the correct fpstack register class.
12729 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12730 return std::make_pair(0U, X86::RFP32RegisterClass);
12731 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12732 return std::make_pair(0U, X86::RFP64RegisterClass);
12733 return std::make_pair(0U, X86::RFP80RegisterClass);
12734 case 'y': // MMX_REGS if MMX allowed.
12735 if (!Subtarget->hasMMX()) break;
12736 return std::make_pair(0U, X86::VR64RegisterClass);
12737 case 'Y': // SSE_REGS if SSE2 allowed
12738 if (!Subtarget->hasXMMInt()) break;
12740 case 'x': // SSE_REGS if SSE1 allowed
12741 if (!Subtarget->hasXMM()) break;
12743 switch (VT.getSimpleVT().SimpleTy) {
12745 // Scalar SSE types.
12748 return std::make_pair(0U, X86::FR32RegisterClass);
12751 return std::make_pair(0U, X86::FR64RegisterClass);
12759 return std::make_pair(0U, X86::VR128RegisterClass);
12765 // Use the default implementation in TargetLowering to convert the register
12766 // constraint into a member of a register class.
12767 std::pair<unsigned, const TargetRegisterClass*> Res;
12768 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12770 // Not found as a standard register?
12771 if (Res.second == 0) {
12772 // Map st(0) -> st(7) -> ST0
12773 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12774 tolower(Constraint[1]) == 's' &&
12775 tolower(Constraint[2]) == 't' &&
12776 Constraint[3] == '(' &&
12777 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12778 Constraint[5] == ')' &&
12779 Constraint[6] == '}') {
12781 Res.first = X86::ST0+Constraint[4]-'0';
12782 Res.second = X86::RFP80RegisterClass;
12786 // GCC allows "st(0)" to be called just plain "st".
12787 if (StringRef("{st}").equals_lower(Constraint)) {
12788 Res.first = X86::ST0;
12789 Res.second = X86::RFP80RegisterClass;
12794 if (StringRef("{flags}").equals_lower(Constraint)) {
12795 Res.first = X86::EFLAGS;
12796 Res.second = X86::CCRRegisterClass;
12800 // 'A' means EAX + EDX.
12801 if (Constraint == "A") {
12802 Res.first = X86::EAX;
12803 Res.second = X86::GR32_ADRegisterClass;
12809 // Otherwise, check to see if this is a register class of the wrong value
12810 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12811 // turn into {ax},{dx}.
12812 if (Res.second->hasType(VT))
12813 return Res; // Correct type already, nothing to do.
12815 // All of the single-register GCC register classes map their values onto
12816 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12817 // really want an 8-bit or 32-bit register, map to the appropriate register
12818 // class and return the appropriate register.
12819 if (Res.second == X86::GR16RegisterClass) {
12820 if (VT == MVT::i8) {
12821 unsigned DestReg = 0;
12822 switch (Res.first) {
12824 case X86::AX: DestReg = X86::AL; break;
12825 case X86::DX: DestReg = X86::DL; break;
12826 case X86::CX: DestReg = X86::CL; break;
12827 case X86::BX: DestReg = X86::BL; break;
12830 Res.first = DestReg;
12831 Res.second = X86::GR8RegisterClass;
12833 } else if (VT == MVT::i32) {
12834 unsigned DestReg = 0;
12835 switch (Res.first) {
12837 case X86::AX: DestReg = X86::EAX; break;
12838 case X86::DX: DestReg = X86::EDX; break;
12839 case X86::CX: DestReg = X86::ECX; break;
12840 case X86::BX: DestReg = X86::EBX; break;
12841 case X86::SI: DestReg = X86::ESI; break;
12842 case X86::DI: DestReg = X86::EDI; break;
12843 case X86::BP: DestReg = X86::EBP; break;
12844 case X86::SP: DestReg = X86::ESP; break;
12847 Res.first = DestReg;
12848 Res.second = X86::GR32RegisterClass;
12850 } else if (VT == MVT::i64) {
12851 unsigned DestReg = 0;
12852 switch (Res.first) {
12854 case X86::AX: DestReg = X86::RAX; break;
12855 case X86::DX: DestReg = X86::RDX; break;
12856 case X86::CX: DestReg = X86::RCX; break;
12857 case X86::BX: DestReg = X86::RBX; break;
12858 case X86::SI: DestReg = X86::RSI; break;
12859 case X86::DI: DestReg = X86::RDI; break;
12860 case X86::BP: DestReg = X86::RBP; break;
12861 case X86::SP: DestReg = X86::RSP; break;
12864 Res.first = DestReg;
12865 Res.second = X86::GR64RegisterClass;
12868 } else if (Res.second == X86::FR32RegisterClass ||
12869 Res.second == X86::FR64RegisterClass ||
12870 Res.second == X86::VR128RegisterClass) {
12871 // Handle references to XMM physical registers that got mapped into the
12872 // wrong class. This can happen with constraints like {xmm0} where the
12873 // target independent register mapper will just pick the first match it can
12874 // find, ignoring the required type.
12875 if (VT == MVT::f32)
12876 Res.second = X86::FR32RegisterClass;
12877 else if (VT == MVT::f64)
12878 Res.second = X86::FR64RegisterClass;
12879 else if (X86::VR128RegisterClass->hasType(VT))
12880 Res.second = X86::VR128RegisterClass;