1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static SDValue Insert128BitVector(SDValue Result,
69 static SDValue Extract128BitVector(SDValue Vec,
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference. Idx is an index in the 128 bits we
77 /// want. It need not be aligned to a 128-bit bounday. That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
83 EVT VT = Vec.getValueType();
84 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85 EVT ElVT = VT.getVectorElementType();
86 int Factor = VT.getSizeInBits()/128;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94 if (isa<ConstantSDNode>(Idx)) {
95 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
98 // we can match to VEXTRACTF128.
99 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101 // This is the index of the first element of the 128-bit chunk
103 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
106 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference. Idx is an index in the 128 bits
119 /// we want. It need not be aligned to a 128-bit bounday. That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
126 if (isa<ConstantSDNode>(Idx)) {
127 EVT VT = Vec.getValueType();
128 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130 EVT ElVT = VT.getVectorElementType();
131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132 EVT ResultVT = Result.getValueType();
134 // Insert the relevant 128 bits.
135 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137 // This is the index of the first element of the 128-bit chunk
139 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
142 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153 bool is64Bit = Subtarget->is64Bit();
155 if (Subtarget->isTargetEnvMacho()) {
157 return new X8664_MachoTargetObjectFile();
158 return new TargetLoweringObjectFileMachO();
161 if (Subtarget->isTargetELF())
162 return new TargetLoweringObjectFileELF();
163 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164 return new TargetLoweringObjectFileCOFF();
165 llvm_unreachable("unknown subtarget type");
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<X86Subtarget>();
171 X86ScalarSSEf64 = Subtarget->hasXMMInt();
172 X86ScalarSSEf32 = Subtarget->hasXMM();
173 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175 RegInfo = TM.getRegisterInfo();
176 TD = getTargetData();
178 // Set up the TargetLowering object.
179 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181 // X86 is weird, it always uses i8 for shift amounts and setcc results.
182 setBooleanContents(ZeroOrOneBooleanContent);
183 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186 // For 64-bit since we have so many registers use the ILP scheduler, for
187 // 32-bit code use the register pressure specific scheduling.
188 if (Subtarget->is64Bit())
189 setSchedulingPreference(Sched::ILP);
191 setSchedulingPreference(Sched::RegPressure);
192 setStackPointerRegisterToSaveRestore(X86StackPtr);
194 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195 // Setup Windows compiler runtime calls.
196 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198 setLibcallName(RTLIB::SREM_I64, "_allrem");
199 setLibcallName(RTLIB::UREM_I64, "_aullrem");
200 setLibcallName(RTLIB::MUL_I64, "_allmul");
201 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
212 if (Subtarget->isTargetDarwin()) {
213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214 setUseUnderscoreSetJmp(false);
215 setUseUnderscoreLongJmp(false);
216 } else if (Subtarget->isTargetMingw()) {
217 // MS runtime is weird: it exports _setjmp, but longjmp!
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(false);
221 setUseUnderscoreSetJmp(true);
222 setUseUnderscoreLongJmp(true);
225 // Set up the register classes.
226 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229 if (Subtarget->is64Bit())
230 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234 // We don't accept any truncstore of integer registers.
235 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
242 // SETOEQ and SETUNE require checking two conditions.
243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
259 } else if (!UseSoftFloat) {
260 // We have an algorithm for SSE2->double, and we turn this into a
261 // 64-bit FILD followed by conditional FADD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
263 // We have an algorithm for SSE2, and we turn this into a 64-bit
264 // FILD for other targets.
265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 // SSE has no i16 to fp conversion, only i32
275 if (X86ScalarSSEf32) {
276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
277 // f32 and f64 cases are Legal, f80 case is not
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
289 // are Legal, f80 is custom lowered.
290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
298 if (X86ScalarSSEf32) {
299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
300 // f32 and f64 cases are Legal, f80 case is not
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
307 // Handle FP_TO_UINT by promoting the destination to a larger signed
309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
313 if (Subtarget->is64Bit()) {
314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
316 } else if (!UseSoftFloat) {
317 // Since AVX is a superset of SSE3, only check for SSE here.
318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319 // Expand FP_TO_UINT into a select.
320 // FIXME: We would like to use a Custom expander here eventually to do
321 // the optimal thing for SSE vs. the default expansion in the legalizer.
322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
324 // With SSE3 we can use fisttpll to convert to a signed i64; without
325 // SSE, we're stuck with a fistpll.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0, e = 4; i != e; ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 if (Subtarget->hasBMI()) {
382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
385 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
387 if (Subtarget->is64Bit())
388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
391 if (Subtarget->hasLZCNT()) {
392 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
394 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
395 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
396 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
397 if (Subtarget->is64Bit())
398 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
401 if (Subtarget->hasPOPCNT()) {
402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
407 if (Subtarget->is64Bit())
408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
412 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
414 // These should be promoted to a larger select which is supported.
415 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
416 // X86 wants to expand cmov itself.
417 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
418 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
419 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
429 if (Subtarget->is64Bit()) {
430 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
431 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
433 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
436 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
437 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
438 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
440 if (Subtarget->is64Bit())
441 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
443 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
444 if (Subtarget->is64Bit()) {
445 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
446 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
447 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
448 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
449 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
451 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
453 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
454 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
457 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
458 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
461 if (Subtarget->hasXMM())
462 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
464 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
465 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
467 // On X86 and X86-64, atomic operations are lowered to locked instructions.
468 // Locked instructions, in turn, have implicit fence semantics (all memory
469 // operations are flushed before issuing the locked instruction, and they
470 // are not buffered), so we can fold away the common pattern of
471 // fence-atomic-fence.
472 setShouldFoldAtomicFences(true);
474 // Expand certain atomics
475 for (unsigned i = 0, e = 4; i != e; ++i) {
477 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
482 if (!Subtarget->is64Bit()) {
483 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
493 if (Subtarget->hasCmpxchg16b()) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
497 // FIXME - use subtarget debug flags
498 if (!Subtarget->isTargetDarwin() &&
499 !Subtarget->isTargetELF() &&
500 !Subtarget->isTargetCygMing()) {
501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
504 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
506 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
508 if (Subtarget->is64Bit()) {
509 setExceptionPointerRegister(X86::RAX);
510 setExceptionSelectorRegister(X86::RDX);
512 setExceptionPointerRegister(X86::EAX);
513 setExceptionSelectorRegister(X86::EDX);
515 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521 setOperationAction(ISD::TRAP, MVT::Other, Legal);
523 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524 setOperationAction(ISD::VASTART , MVT::Other, Custom);
525 setOperationAction(ISD::VAEND , MVT::Other, Expand);
526 if (Subtarget->is64Bit()) {
527 setOperationAction(ISD::VAARG , MVT::Other, Custom);
528 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
530 setOperationAction(ISD::VAARG , MVT::Other, Expand);
531 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
534 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
535 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
537 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539 MVT::i64 : MVT::i32, Custom);
540 else if (EnableSegmentedStacks)
541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542 MVT::i64 : MVT::i32, Custom);
544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545 MVT::i64 : MVT::i32, Expand);
547 if (!UseSoftFloat && X86ScalarSSEf64) {
548 // f32 and f64 use SSE.
549 // Set up the FP register classes.
550 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553 // Use ANDPD to simulate FABS.
554 setOperationAction(ISD::FABS , MVT::f64, Custom);
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f64, Custom);
559 setOperationAction(ISD::FNEG , MVT::f32, Custom);
561 // Use ANDPD and ORPD to simulate FCOPYSIGN.
562 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565 // Lower this to FGETSIGNx86 plus an AND.
566 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569 // We don't support sin/cos/fmod
570 setOperationAction(ISD::FSIN , MVT::f64, Expand);
571 setOperationAction(ISD::FCOS , MVT::f64, Expand);
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 // Expand FP immediates into loads from the stack, except for the special
577 addLegalFPImmediate(APFloat(+0.0)); // xorpd
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 } else if (!UseSoftFloat && X86ScalarSSEf32) {
580 // Use SSE for f32, x87 for f64.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585 // Use ANDPS to simulate FABS.
586 setOperationAction(ISD::FABS , MVT::f32, Custom);
588 // Use XORP to simulate FNEG.
589 setOperationAction(ISD::FNEG , MVT::f32, Custom);
591 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
593 // Use ANDPS and ORPS to simulate FCOPYSIGN.
594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597 // We don't support sin/cos/fmod
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 // Special cases we handle for FP constants.
602 addLegalFPImmediate(APFloat(+0.0f)); // xorps
603 addLegalFPImmediate(APFloat(+0.0)); // FLD0
604 addLegalFPImmediate(APFloat(+1.0)); // FLD1
605 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
610 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
612 } else if (!UseSoftFloat) {
613 // f32 and f64 in x87.
614 // Set up the FP register classes.
615 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
619 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
624 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
625 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
627 addLegalFPImmediate(APFloat(+0.0)); // FLD0
628 addLegalFPImmediate(APFloat(+1.0)); // FLD1
629 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
637 // We don't support FMA.
638 setOperationAction(ISD::FMA, MVT::f64, Expand);
639 setOperationAction(ISD::FMA, MVT::f32, Expand);
641 // Long double always uses X87.
643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648 addLegalFPImmediate(TmpFlt); // FLD0
650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
653 APFloat TmpFlt2(+1.0);
654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656 addLegalFPImmediate(TmpFlt2); // FLD1
657 TmpFlt2.changeSign();
658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
662 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
663 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
666 setOperationAction(ISD::FMA, MVT::f80, Expand);
669 // Always use a library call for pow.
670 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
674 setOperationAction(ISD::FLOG, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 // First set operation action for all vector types to either promote
681 // (for widening) or expand (for scalarization). Then we will selectively
682 // turn on ones that can be effectively codegen'd.
683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742 setTruncStoreAction((MVT::SimpleValueType)VT,
743 (MVT::SimpleValueType)InnerVT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750 // with -msoft-float, disable use of MMX as well.
751 if (!UseSoftFloat && Subtarget->hasMMX()) {
752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753 // No operations on x86mmx supported, everything uses intrinsics.
756 // MMX-sized vectors (other than x86mmx) are expected to be expanded
757 // into smaller operations.
758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
762 setOperationAction(ISD::AND, MVT::v8i8, Expand);
763 setOperationAction(ISD::AND, MVT::v4i16, Expand);
764 setOperationAction(ISD::AND, MVT::v2i32, Expand);
765 setOperationAction(ISD::AND, MVT::v1i64, Expand);
766 setOperationAction(ISD::OR, MVT::v8i8, Expand);
767 setOperationAction(ISD::OR, MVT::v4i16, Expand);
768 setOperationAction(ISD::OR, MVT::v2i32, Expand);
769 setOperationAction(ISD::OR, MVT::v1i64, Expand);
770 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
771 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
772 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
773 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
788 if (!UseSoftFloat && Subtarget->hasXMM()) {
789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
805 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809 // registers cannot be used even for integer operations.
810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
816 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
817 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
818 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851 EVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR,
859 VT.getSimpleVT().SimpleTy, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE,
861 VT.getSimpleVT().SimpleTy, Custom);
862 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863 VT.getSimpleVT().SimpleTy, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873 if (Subtarget->is64Bit()) {
874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
883 // Do not attempt to promote non-128-bit vectors
884 if (!VT.is128BitVector())
887 setOperationAction(ISD::AND, SVT, Promote);
888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
889 setOperationAction(ISD::OR, SVT, Promote);
890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
891 setOperationAction(ISD::XOR, SVT, Promote);
892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
893 setOperationAction(ISD::LOAD, SVT, Promote);
894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
895 setOperationAction(ISD::SELECT, SVT, Promote);
896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
899 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901 // Custom lower v2i64 and v2f64 selects.
902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
911 if (Subtarget->hasSSE41orAVX()) {
912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915 setOperationAction(ISD::FRINT, MVT::f32, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923 // FIXME: Do we need to handle scalar-to-vector here?
924 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
932 // i8 and i16 vectors are custom , because the source register and source
933 // source memory operand types are not the same width. f32 vectors are
934 // custom since the immediate controlling the insert encodes additional
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946 // FIXME: these should be Legal but thats only for the case where
947 // the index is constant. For now custom expand to deal with that
948 if (Subtarget->is64Bit()) {
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
954 if (Subtarget->hasXMMInt()) {
955 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
956 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
959 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
962 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
964 if (Subtarget->hasAVX2()) {
965 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
966 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
968 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
969 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
971 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
973 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
974 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
976 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
977 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
979 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
983 if (Subtarget->hasSSE42orAVX())
984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
986 if (!UseSoftFloat && Subtarget->hasAVX()) {
987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
998 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1046 if (Subtarget->hasAVX2()) {
1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1060 // Don't lower v32i8 because there is no 128-bit byte mul
1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1085 // Don't lower v32i8 because there is no 128-bit byte mul
1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1096 // Custom lower several nodes for 256-bit types.
1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1102 // Extract subvector is special because the value type
1103 // (result) is 128-bit but the source is 256-bit wide.
1104 if (VT.is128BitVector())
1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1107 // Do not attempt to custom lower other non-256-bit vectors
1108 if (!VT.is256BitVector())
1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1124 // Do not attempt to promote non-256-bit vectors
1125 if (!VT.is256BitVector())
1128 setOperationAction(ISD::AND, SVT, Promote);
1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1130 setOperationAction(ISD::OR, SVT, Promote);
1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1132 setOperationAction(ISD::XOR, SVT, Promote);
1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1134 setOperationAction(ISD::LOAD, SVT, Promote);
1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1136 setOperationAction(ISD::SELECT, SVT, Promote);
1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142 // of this type with custom code.
1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1148 // We want to custom lower some of our intrinsics.
1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153 // handle type legalization for these operations here.
1155 // FIXME: We really should do custom legalization for addition and
1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1157 // than generic legalization for 64-bit multiplication-with-overflow, though.
1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159 // Add/Sub/Mul with overflow operations are custom lowered.
1161 setOperationAction(ISD::SADDO, VT, Custom);
1162 setOperationAction(ISD::UADDO, VT, Custom);
1163 setOperationAction(ISD::SSUBO, VT, Custom);
1164 setOperationAction(ISD::USUBO, VT, Custom);
1165 setOperationAction(ISD::SMULO, VT, Custom);
1166 setOperationAction(ISD::UMULO, VT, Custom);
1169 // There are no 8-bit 3-address imul/mul instructions
1170 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1173 if (!Subtarget->is64Bit()) {
1174 // These libcalls are not available in 32-bit.
1175 setLibcallName(RTLIB::SHL_I128, 0);
1176 setLibcallName(RTLIB::SRL_I128, 0);
1177 setLibcallName(RTLIB::SRA_I128, 0);
1180 // We have target-specific dag combine patterns for the following nodes:
1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183 setTargetDAGCombine(ISD::BUILD_VECTOR);
1184 setTargetDAGCombine(ISD::VSELECT);
1185 setTargetDAGCombine(ISD::SELECT);
1186 setTargetDAGCombine(ISD::SHL);
1187 setTargetDAGCombine(ISD::SRA);
1188 setTargetDAGCombine(ISD::SRL);
1189 setTargetDAGCombine(ISD::OR);
1190 setTargetDAGCombine(ISD::AND);
1191 setTargetDAGCombine(ISD::ADD);
1192 setTargetDAGCombine(ISD::FADD);
1193 setTargetDAGCombine(ISD::FSUB);
1194 setTargetDAGCombine(ISD::SUB);
1195 setTargetDAGCombine(ISD::LOAD);
1196 setTargetDAGCombine(ISD::STORE);
1197 setTargetDAGCombine(ISD::ZERO_EXTEND);
1198 setTargetDAGCombine(ISD::SINT_TO_FP);
1199 if (Subtarget->is64Bit())
1200 setTargetDAGCombine(ISD::MUL);
1201 if (Subtarget->hasBMI())
1202 setTargetDAGCombine(ISD::XOR);
1204 computeRegisterProperties();
1206 // On Darwin, -Os means optimize for size without hurting performance,
1207 // do not reduce the limit.
1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214 setPrefLoopAlignment(16);
1215 benefitFromCodePlacementOpt = true;
1217 setPrefFunctionAlignment(4);
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222 if (!VT.isVector()) return MVT::i8;
1223 return VT.changeVectorElementTypeToInteger();
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233 if (VTy->getBitWidth() == 128)
1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236 unsigned EltAlign = 0;
1237 getMaxByValAlign(ATy->getElementType(), EltAlign);
1238 if (EltAlign > MaxAlign)
1239 MaxAlign = EltAlign;
1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242 unsigned EltAlign = 0;
1243 getMaxByValAlign(STy->getElementType(i), EltAlign);
1244 if (EltAlign > MaxAlign)
1245 MaxAlign = EltAlign;
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258 if (Subtarget->is64Bit()) {
1259 // Max of 8 and alignment of type.
1260 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1267 if (Subtarget->hasXMM())
1268 getMaxByValAlign(Ty, Align);
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286 unsigned DstAlign, unsigned SrcAlign,
1289 MachineFunction &MF) const {
1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291 // linux. This is because the stack realignment code can't handle certain
1292 // cases like PR2962. This should be removed when PR2962 is fixed.
1293 const Function *F = MF.getFunction();
1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1297 (Subtarget->isUnalignedMemAccessFast() ||
1298 ((DstAlign == 0 || DstAlign >= 16) &&
1299 (SrcAlign == 0 || SrcAlign >= 16))) &&
1300 Subtarget->getStackAlignment() >= 16) {
1301 if (Subtarget->hasAVX() &&
1302 Subtarget->getStackAlignment() >= 32)
1304 if (Subtarget->hasXMMInt())
1306 if (Subtarget->hasXMM())
1308 } else if (!MemcpyStrSrc && Size >= 8 &&
1309 !Subtarget->is64Bit() &&
1310 Subtarget->getStackAlignment() >= 8 &&
1311 Subtarget->hasXMMInt()) {
1312 // Do not use f64 to lower memcpy if source is string constant. It's
1313 // better to use i32 to avoid the loads.
1317 if (Subtarget->is64Bit() && Size >= 8)
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function. The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329 Subtarget->isPICStyleGOT())
1330 return MachineJumpTableInfo::EK_Custom32;
1332 // Otherwise, use the normal jump table encoding heuristics.
1333 return TargetLowering::getJumpTableEncoding();
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338 const MachineBasicBlock *MBB,
1339 unsigned uid,MCContext &Ctx) const{
1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341 Subtarget->isPICStyleGOT());
1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1344 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351 SelectionDAG &DAG) const {
1352 if (!Subtarget->is64Bit())
1353 // This doesn't have DebugLoc associated with it, but is not really the
1354 // same as a Register.
1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364 MCContext &Ctx) const {
1365 // X86-64 uses RIP relative addressing based on the jump table label.
1366 if (Subtarget->isPICStyleRIPRel())
1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1369 // Otherwise, the reference is relative to the PIC base.
1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376 const TargetRegisterClass *RRC = 0;
1378 switch (VT.getSimpleVT().SimpleTy) {
1380 return TargetLowering::findRepresentativeClass(VT);
1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382 RRC = (Subtarget->is64Bit()
1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1386 RRC = X86::VR64RegisterClass;
1388 case MVT::f32: case MVT::f64:
1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390 case MVT::v4f32: case MVT::v2f64:
1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1393 RRC = X86::VR128RegisterClass;
1396 return std::make_pair(RRC, Cost);
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400 unsigned &Offset) const {
1401 if (!Subtarget->isTargetLinux())
1404 if (Subtarget->is64Bit()) {
1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1420 //===----------------------------------------------------------------------===//
1421 // Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1424 #include "X86GenCallingConv.inc"
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428 MachineFunction &MF, bool isVarArg,
1429 const SmallVectorImpl<ISD::OutputArg> &Outs,
1430 LLVMContext &Context) const {
1431 SmallVector<CCValAssign, 16> RVLocs;
1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1434 return CCInfo.CheckReturn(Outs, RetCC_X86);
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439 CallingConv::ID CallConv, bool isVarArg,
1440 const SmallVectorImpl<ISD::OutputArg> &Outs,
1441 const SmallVectorImpl<SDValue> &OutVals,
1442 DebugLoc dl, SelectionDAG &DAG) const {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448 RVLocs, *DAG.getContext());
1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1451 // Add the regs to the liveout set for the function.
1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453 for (unsigned i = 0; i != RVLocs.size(); ++i)
1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455 MRI.addLiveOut(RVLocs[i].getLocReg());
1459 SmallVector<SDValue, 6> RetOps;
1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461 // Operand #1 = Bytes To Pop
1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1465 // Copy the result values into the output registers.
1466 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467 CCValAssign &VA = RVLocs[i];
1468 assert(VA.isRegLoc() && "Can only return in registers!");
1469 SDValue ValToCopy = OutVals[i];
1470 EVT ValVT = ValToCopy.getValueType();
1472 // If this is x86-64, and we disabled SSE, we can't return FP values,
1473 // or SSE or MMX vectors.
1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477 report_fatal_error("SSE register return with SSE disabled");
1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1480 // llvm-gcc has never done it right and no one has noticed, so this
1481 // should be OK for now.
1482 if (ValVT == MVT::f64 &&
1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484 report_fatal_error("SSE2 register return with SSE2 disabled");
1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487 // the RET instruction and handled by the FP Stackifier.
1488 if (VA.getLocReg() == X86::ST0 ||
1489 VA.getLocReg() == X86::ST1) {
1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491 // change the value to the FP stack register class.
1492 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494 RetOps.push_back(ValToCopy);
1495 // Don't emit a copytoreg.
1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500 // which is returned in RAX / RDX.
1501 if (Subtarget->is64Bit()) {
1502 if (ValVT == MVT::x86mmx) {
1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1507 // If we don't have SSE2 available, convert to v4f32 so the generated
1508 // register is legal.
1509 if (!Subtarget->hasXMMInt())
1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516 Flag = Chain.getValue(1);
1519 // The x86-64 ABI for returning structs by value requires that we copy
1520 // the sret argument into %rax for the return. We saved the argument into
1521 // a virtual register in the entry block, so now we copy the value out
1523 if (Subtarget->is64Bit() &&
1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525 MachineFunction &MF = DAG.getMachineFunction();
1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527 unsigned Reg = FuncInfo->getSRetReturnReg();
1529 "SRetReturnReg should have been set in LowerFormalArguments().");
1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533 Flag = Chain.getValue(1);
1535 // RAX now acts like a return value.
1536 MRI.addLiveOut(X86::RAX);
1539 RetOps[0] = Chain; // Update chain.
1541 // Add the flag if we have it.
1543 RetOps.push_back(Flag);
1545 return DAG.getNode(X86ISD::RET_FLAG, dl,
1546 MVT::Other, &RetOps[0], RetOps.size());
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550 if (N->getNumValues() != 1)
1552 if (!N->hasNUsesOfValue(1, 0))
1555 SDNode *Copy = *N->use_begin();
1556 if (Copy->getOpcode() != ISD::CopyToReg &&
1557 Copy->getOpcode() != ISD::FP_EXTEND)
1560 bool HasRet = false;
1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1563 if (UI->getOpcode() != X86ISD::RET_FLAG)
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573 ISD::NodeType ExtendKind) const {
1575 // TODO: Is this also valid on 32-bit?
1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577 ReturnMVT = MVT::i8;
1579 ReturnMVT = MVT::i32;
1581 EVT MinVT = getRegisterType(Context, ReturnMVT);
1582 return VT.bitsLT(MinVT) ? MinVT : VT;
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590 CallingConv::ID CallConv, bool isVarArg,
1591 const SmallVectorImpl<ISD::InputArg> &Ins,
1592 DebugLoc dl, SelectionDAG &DAG,
1593 SmallVectorImpl<SDValue> &InVals) const {
1595 // Assign locations to each value returned by this call.
1596 SmallVector<CCValAssign, 16> RVLocs;
1597 bool Is64Bit = Subtarget->is64Bit();
1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599 getTargetMachine(), RVLocs, *DAG.getContext());
1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1602 // Copy all of the result registers out of their specified physreg.
1603 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604 CCValAssign &VA = RVLocs[i];
1605 EVT CopyVT = VA.getValVT();
1607 // If this is x86-64, and we disabled SSE, we can't return FP values
1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610 report_fatal_error("SSE register return with SSE disabled");
1615 // If this is a call to a function that returns an fp value on the floating
1616 // point stack, we must guarantee the the value is popped from the stack, so
1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618 // if the return value is not used. We use the FpPOP_RETVAL instruction
1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621 // If we prefer to use the value in xmm registers, copy it out as f80 and
1622 // use a truncate to move it from fp stack reg to xmm reg.
1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624 SDValue Ops[] = { Chain, InFlag };
1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626 MVT::Other, MVT::Glue, Ops, 2), 1);
1627 Val = Chain.getValue(0);
1629 // Round the f80 to the right size, which also moves it to the appropriate
1631 if (CopyVT != VA.getValVT())
1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633 // This truncation won't change the value.
1634 DAG.getIntPtrConstant(1));
1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637 CopyVT, InFlag).getValue(1);
1638 Val = Chain.getValue(0);
1640 InFlag = Chain.getValue(2);
1641 InVals.push_back(Val);
1648 //===----------------------------------------------------------------------===//
1649 // C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 // StdCall calling convention seems to be standard for many Windows' API
1652 // routines and around. It differs from C calling convention just a little:
1653 // callee should clean up the stack, not caller. Symbols should be also
1654 // decorated in some fancy way :) It doesn't support any vector arguments.
1655 // For info on fast calling convention see Fast Calling Convention (tail call)
1656 // implementation LowerX86_32FastCCCallTo.
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1664 return Outs[0].Flags.isSRet();
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1674 return Ins[0].Flags.isSRet();
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688 /*isVolatile*/false, /*AlwaysInline=*/true,
1689 MachinePointerInfo(), MachinePointerInfo());
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699 if (!CI->isTailCall())
1703 CallingConv::ID CalleeCC = CS.getCallingConv();
1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718 CallingConv::ID CallConv,
1719 const SmallVectorImpl<ISD::InputArg> &Ins,
1720 DebugLoc dl, SelectionDAG &DAG,
1721 const CCValAssign &VA,
1722 MachineFrameInfo *MFI,
1724 // Create the nodes corresponding to a load from this parameter slot.
1725 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1730 // If value is passed by pointer we have address passed instead of the value
1732 if (VA.getLocInfo() == CCValAssign::Indirect)
1733 ValVT = VA.getLocVT();
1735 ValVT = VA.getValVT();
1737 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738 // changed with more analysis.
1739 // In case of tail call optimization mark all arguments mutable. Since they
1740 // could be overwritten by lowering of arguments in case of a tail call.
1741 if (Flags.isByVal()) {
1742 unsigned Bytes = Flags.getByValSize();
1743 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745 return DAG.getFrameIndex(FI, getPointerTy());
1747 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748 VA.getLocMemOffset(), isImmutable);
1749 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750 return DAG.getLoad(ValVT, dl, Chain, FIN,
1751 MachinePointerInfo::getFixedStack(FI),
1752 false, false, false, 0);
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758 CallingConv::ID CallConv,
1760 const SmallVectorImpl<ISD::InputArg> &Ins,
1763 SmallVectorImpl<SDValue> &InVals)
1765 MachineFunction &MF = DAG.getMachineFunction();
1766 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1768 const Function* Fn = MF.getFunction();
1769 if (Fn->hasExternalLinkage() &&
1770 Subtarget->isTargetCygMing() &&
1771 Fn->getName() == "main")
1772 FuncInfo->setForceFramePointer(true);
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 bool Is64Bit = Subtarget->is64Bit();
1776 bool IsWin64 = Subtarget->isTargetWin64();
1778 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779 "Var args not supported with calling convention fastcc or ghc");
1781 // Assign locations to all of the incoming arguments.
1782 SmallVector<CCValAssign, 16> ArgLocs;
1783 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784 ArgLocs, *DAG.getContext());
1786 // Allocate shadow area for Win64
1788 CCInfo.AllocateStack(32, 8);
1791 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1793 unsigned LastVal = ~0U;
1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796 CCValAssign &VA = ArgLocs[i];
1797 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1799 assert(VA.getValNo() != LastVal &&
1800 "Don't support value assigned to multiple locs yet");
1802 LastVal = VA.getValNo();
1804 if (VA.isRegLoc()) {
1805 EVT RegVT = VA.getLocVT();
1806 TargetRegisterClass *RC = NULL;
1807 if (RegVT == MVT::i32)
1808 RC = X86::GR32RegisterClass;
1809 else if (Is64Bit && RegVT == MVT::i64)
1810 RC = X86::GR64RegisterClass;
1811 else if (RegVT == MVT::f32)
1812 RC = X86::FR32RegisterClass;
1813 else if (RegVT == MVT::f64)
1814 RC = X86::FR64RegisterClass;
1815 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816 RC = X86::VR256RegisterClass;
1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818 RC = X86::VR128RegisterClass;
1819 else if (RegVT == MVT::x86mmx)
1820 RC = X86::VR64RegisterClass;
1822 llvm_unreachable("Unknown argument type!");
1824 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1827 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1830 if (VA.getLocInfo() == CCValAssign::SExt)
1831 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832 DAG.getValueType(VA.getValVT()));
1833 else if (VA.getLocInfo() == CCValAssign::ZExt)
1834 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835 DAG.getValueType(VA.getValVT()));
1836 else if (VA.getLocInfo() == CCValAssign::BCvt)
1837 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1839 if (VA.isExtInLoc()) {
1840 // Handle MMX values passed in XMM regs.
1841 if (RegVT.isVector()) {
1842 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1845 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1848 assert(VA.isMemLoc());
1849 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1852 // If value is passed via pointer - do a load.
1853 if (VA.getLocInfo() == CCValAssign::Indirect)
1854 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855 MachinePointerInfo(), false, false, false, 0);
1857 InVals.push_back(ArgValue);
1860 // The x86-64 ABI for returning structs by value requires that we copy
1861 // the sret argument into %rax for the return. Save the argument into
1862 // a virtual register so that we can access it from the return points.
1863 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868 FuncInfo->setSRetReturnReg(Reg);
1870 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1874 unsigned StackSize = CCInfo.getNextStackOffset();
1875 // Align stack specially for tail calls.
1876 if (FuncIsMadeTailCallSafe(CallConv))
1877 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1879 // If the function takes variable number of arguments, make a frame index for
1880 // the start of the first vararg value... for expansion of llvm.va_start.
1882 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883 CallConv != CallingConv::X86_ThisCall)) {
1884 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1887 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1889 // FIXME: We should really autogenerate these arrays
1890 static const unsigned GPR64ArgRegsWin64[] = {
1891 X86::RCX, X86::RDX, X86::R8, X86::R9
1893 static const unsigned GPR64ArgRegs64Bit[] = {
1894 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1896 static const unsigned XMMArgRegs64Bit[] = {
1897 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1900 const unsigned *GPR64ArgRegs;
1901 unsigned NumXMMRegs = 0;
1904 // The XMM registers which might contain var arg parameters are shadowed
1905 // in their paired GPR. So we only need to save the GPR to their home
1907 TotalNumIntRegs = 4;
1908 GPR64ArgRegs = GPR64ArgRegsWin64;
1910 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911 GPR64ArgRegs = GPR64ArgRegs64Bit;
1913 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1915 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1918 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920 "SSE register cannot be used when SSE is disabled!");
1921 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922 "SSE register cannot be used when SSE is disabled!");
1923 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924 // Kernel mode asks for SSE to be disabled, so don't push them
1926 TotalNumXMMRegs = 0;
1929 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930 // Get to the caller-allocated home save location. Add 8 to account
1931 // for the return address.
1932 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933 FuncInfo->setRegSaveFrameIndex(
1934 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935 // Fixup to set vararg frame on shadow area (4 x i64).
1937 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1939 // For X86-64, if there are vararg parameters that are passed via
1940 // registers, then we must store them to their spots on the stack so they
1941 // may be loaded by deferencing the result of va_next.
1942 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944 FuncInfo->setRegSaveFrameIndex(
1945 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1949 // Store the integer parameter registers.
1950 SmallVector<SDValue, 8> MemOps;
1951 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1953 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956 DAG.getIntPtrConstant(Offset));
1957 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958 X86::GR64RegisterClass);
1959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1961 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962 MachinePointerInfo::getFixedStack(
1963 FuncInfo->getRegSaveFrameIndex(), Offset),
1965 MemOps.push_back(Store);
1969 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970 // Now store the XMM (fp + vector) parameter registers.
1971 SmallVector<SDValue, 11> SaveXMMOps;
1972 SaveXMMOps.push_back(Chain);
1974 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976 SaveXMMOps.push_back(ALVal);
1978 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979 FuncInfo->getRegSaveFrameIndex()));
1980 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981 FuncInfo->getVarArgsFPOffset()));
1983 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985 X86::VR128RegisterClass);
1986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987 SaveXMMOps.push_back(Val);
1989 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1991 &SaveXMMOps[0], SaveXMMOps.size()));
1994 if (!MemOps.empty())
1995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996 &MemOps[0], MemOps.size());
2000 // Some CCs need callee pop.
2001 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2004 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005 // If this is an sret function, the return should pop the hidden pointer.
2006 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007 FuncInfo->setBytesToPopOnReturn(4);
2011 // RegSaveFrameIndex is X86-64 only.
2012 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013 if (CallConv == CallingConv::X86_FastCall ||
2014 CallConv == CallingConv::X86_ThisCall)
2015 // fastcc functions can't have varargs.
2016 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2019 FuncInfo->setArgumentStackSize(StackSize);
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026 SDValue StackPtr, SDValue Arg,
2027 DebugLoc dl, SelectionDAG &DAG,
2028 const CCValAssign &VA,
2029 ISD::ArgFlagsTy Flags) const {
2030 unsigned LocMemOffset = VA.getLocMemOffset();
2031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033 if (Flags.isByVal())
2034 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2036 return DAG.getStore(Chain, dl, Arg, PtrOff,
2037 MachinePointerInfo::getStack(LocMemOffset),
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045 SDValue &OutRetAddr, SDValue Chain,
2046 bool IsTailCall, bool Is64Bit,
2047 int FPDiff, DebugLoc dl) const {
2048 // Adjust the Return address stack slot.
2049 EVT VT = getPointerTy();
2050 OutRetAddr = getReturnAddressFrameIndex(DAG);
2052 // Load the "old" Return address.
2053 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054 false, false, false, 0);
2055 return SDValue(OutRetAddr.getNode(), 1);
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062 SDValue Chain, SDValue RetAddrFrIdx,
2063 bool Is64Bit, int FPDiff, DebugLoc dl) {
2064 // Store the return address to the appropriate stack slot.
2065 if (!FPDiff) return Chain;
2066 // Calculate the new stack slot for the return address.
2067 int SlotSize = Is64Bit ? 8 : 4;
2068 int NewReturnAddrFI =
2069 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080 CallingConv::ID CallConv, bool isVarArg,
2082 const SmallVectorImpl<ISD::OutputArg> &Outs,
2083 const SmallVectorImpl<SDValue> &OutVals,
2084 const SmallVectorImpl<ISD::InputArg> &Ins,
2085 DebugLoc dl, SelectionDAG &DAG,
2086 SmallVectorImpl<SDValue> &InVals) const {
2087 MachineFunction &MF = DAG.getMachineFunction();
2088 bool Is64Bit = Subtarget->is64Bit();
2089 bool IsWin64 = Subtarget->isTargetWin64();
2090 bool IsStructRet = CallIsStructReturn(Outs);
2091 bool IsSibcall = false;
2094 // Check if it's really possible to do a tail call.
2095 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097 Outs, OutVals, Ins, DAG);
2099 // Sibcalls are automatically detected tailcalls which do not require
2101 if (!GuaranteedTailCallOpt && isTailCall)
2108 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109 "Var args not supported with calling convention fastcc or ghc");
2111 // Analyze operands of the call, assigning locations to each operand.
2112 SmallVector<CCValAssign, 16> ArgLocs;
2113 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114 ArgLocs, *DAG.getContext());
2116 // Allocate shadow area for Win64
2118 CCInfo.AllocateStack(32, 8);
2121 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2123 // Get a count of how many bytes are to be pushed on the stack.
2124 unsigned NumBytes = CCInfo.getNextStackOffset();
2126 // This is a sibcall. The memory operands are available in caller's
2127 // own caller's stack.
2129 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2133 if (isTailCall && !IsSibcall) {
2134 // Lower arguments at fp - stackoffset + fpdiff.
2135 unsigned NumBytesCallerPushed =
2136 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137 FPDiff = NumBytesCallerPushed - NumBytes;
2139 // Set the delta of movement of the returnaddr stackslot.
2140 // But only set if delta is greater than previous delta.
2141 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2146 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2148 SDValue RetAddrFrIdx;
2149 // Load return address for tail calls.
2150 if (isTailCall && FPDiff)
2151 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152 Is64Bit, FPDiff, dl);
2154 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155 SmallVector<SDValue, 8> MemOpChains;
2158 // Walk the register/memloc assignments, inserting copies/loads. In the case
2159 // of tail call optimization arguments are handle later.
2160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161 CCValAssign &VA = ArgLocs[i];
2162 EVT RegVT = VA.getLocVT();
2163 SDValue Arg = OutVals[i];
2164 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165 bool isByVal = Flags.isByVal();
2167 // Promote the value if needed.
2168 switch (VA.getLocInfo()) {
2169 default: llvm_unreachable("Unknown loc info!");
2170 case CCValAssign::Full: break;
2171 case CCValAssign::SExt:
2172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2174 case CCValAssign::ZExt:
2175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2177 case CCValAssign::AExt:
2178 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179 // Special case: passing MMX values in XMM registers.
2180 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2186 case CCValAssign::BCvt:
2187 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2189 case CCValAssign::Indirect: {
2190 // Store the argument.
2191 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194 MachinePointerInfo::getFixedStack(FI),
2201 if (VA.isRegLoc()) {
2202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203 if (isVarArg && IsWin64) {
2204 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205 // shadow reg if callee is a varargs function.
2206 unsigned ShadowReg = 0;
2207 switch (VA.getLocReg()) {
2208 case X86::XMM0: ShadowReg = X86::RCX; break;
2209 case X86::XMM1: ShadowReg = X86::RDX; break;
2210 case X86::XMM2: ShadowReg = X86::R8; break;
2211 case X86::XMM3: ShadowReg = X86::R9; break;
2214 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2216 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217 assert(VA.isMemLoc());
2218 if (StackPtr.getNode() == 0)
2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221 dl, DAG, VA, Flags));
2225 if (!MemOpChains.empty())
2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227 &MemOpChains[0], MemOpChains.size());
2229 // Build a sequence of copy-to-reg nodes chained together with token chain
2230 // and flag operands which copy the outgoing args into registers.
2232 // Tail call byval lowering might overwrite argument registers so in case of
2233 // tail call optimization the copies to registers are lowered later.
2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237 RegsToPass[i].second, InFlag);
2238 InFlag = Chain.getValue(1);
2241 if (Subtarget->isPICStyleGOT()) {
2242 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2245 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246 DAG.getNode(X86ISD::GlobalBaseReg,
2247 DebugLoc(), getPointerTy()),
2249 InFlag = Chain.getValue(1);
2251 // If we are tail calling and generating PIC/GOT style code load the
2252 // address of the callee into ECX. The value in ecx is used as target of
2253 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254 // for tail calls on PIC/GOT architectures. Normally we would just put the
2255 // address of GOT into ebx and then call target@PLT. But for tail calls
2256 // ebx would be restored (since ebx is callee saved) before jumping to the
2259 // Note: The actual moving to ECX is done further down.
2260 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262 !G->getGlobal()->hasProtectedVisibility())
2263 Callee = LowerGlobalAddress(Callee, DAG);
2264 else if (isa<ExternalSymbolSDNode>(Callee))
2265 Callee = LowerExternalSymbol(Callee, DAG);
2269 if (Is64Bit && isVarArg && !IsWin64) {
2270 // From AMD64 ABI document:
2271 // For calls that may call functions that use varargs or stdargs
2272 // (prototype-less calls or calls to functions containing ellipsis (...) in
2273 // the declaration) %al is used as hidden argument to specify the number
2274 // of SSE registers used. The contents of %al do not need to match exactly
2275 // the number of registers, but must be an ubound on the number of SSE
2276 // registers used and is in the range 0 - 8 inclusive.
2278 // Count the number of XMM registers allocated.
2279 static const unsigned XMMArgRegs[] = {
2280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2283 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284 assert((Subtarget->hasXMM() || !NumXMMRegs)
2285 && "SSE registers cannot be used when SSE is disabled");
2287 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289 InFlag = Chain.getValue(1);
2293 // For tail calls lower the arguments to the 'real' stack slot.
2295 // Force all the incoming stack arguments to be loaded from the stack
2296 // before any new outgoing arguments are stored to the stack, because the
2297 // outgoing stack slots may alias the incoming argument stack slots, and
2298 // the alias isn't otherwise explicit. This is slightly more conservative
2299 // than necessary, because it means that each store effectively depends
2300 // on every argument instead of just those arguments it would clobber.
2301 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2303 SmallVector<SDValue, 8> MemOpChains2;
2306 // Do not flag preceding copytoreg stuff together with the following stuff.
2308 if (GuaranteedTailCallOpt) {
2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310 CCValAssign &VA = ArgLocs[i];
2313 assert(VA.isMemLoc());
2314 SDValue Arg = OutVals[i];
2315 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316 // Create frame index.
2317 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320 FIN = DAG.getFrameIndex(FI, getPointerTy());
2322 if (Flags.isByVal()) {
2323 // Copy relative to framepointer.
2324 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325 if (StackPtr.getNode() == 0)
2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2328 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2330 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2334 // Store relative to framepointer.
2335 MemOpChains2.push_back(
2336 DAG.getStore(ArgChain, dl, Arg, FIN,
2337 MachinePointerInfo::getFixedStack(FI),
2343 if (!MemOpChains2.empty())
2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345 &MemOpChains2[0], MemOpChains2.size());
2347 // Copy arguments to their registers.
2348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350 RegsToPass[i].second, InFlag);
2351 InFlag = Chain.getValue(1);
2355 // Store the return address to the appropriate stack slot.
2356 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2360 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362 // In the 64-bit large code model, we have to make all calls
2363 // through a register, since the call instruction's 32-bit
2364 // pc-relative offset may not be large enough to hold the whole
2366 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367 // If the callee is a GlobalAddress node (quite common, every direct call
2368 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2371 // We should use extra load for direct calls to dllimported functions in
2373 const GlobalValue *GV = G->getGlobal();
2374 if (!GV->hasDLLImportLinkage()) {
2375 unsigned char OpFlags = 0;
2376 bool ExtraLoad = false;
2377 unsigned WrapperKind = ISD::DELETED_NODE;
2379 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380 // external symbols most go through the PLT in PIC mode. If the symbol
2381 // has hidden or protected visibility, or if it is static or local, then
2382 // we don't need to use the PLT - we can directly call it.
2383 if (Subtarget->isTargetELF() &&
2384 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386 OpFlags = X86II::MO_PLT;
2387 } else if (Subtarget->isPICStyleStubAny() &&
2388 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389 (!Subtarget->getTargetTriple().isMacOSX() ||
2390 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391 // PC-relative references to external symbols should go through $stub,
2392 // unless we're building with the leopard linker or later, which
2393 // automatically synthesizes these stubs.
2394 OpFlags = X86II::MO_DARWIN_STUB;
2395 } else if (Subtarget->isPICStyleRIPRel() &&
2396 isa<Function>(GV) &&
2397 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398 // If the function is marked as non-lazy, generate an indirect call
2399 // which loads from the GOT directly. This avoids runtime overhead
2400 // at the cost of eager binding (and one extra byte of encoding).
2401 OpFlags = X86II::MO_GOTPCREL;
2402 WrapperKind = X86ISD::WrapperRIP;
2406 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407 G->getOffset(), OpFlags);
2409 // Add a wrapper if needed.
2410 if (WrapperKind != ISD::DELETED_NODE)
2411 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412 // Add extra indirection if needed.
2414 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415 MachinePointerInfo::getGOT(),
2416 false, false, false, 0);
2418 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419 unsigned char OpFlags = 0;
2421 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422 // external symbols should go through the PLT.
2423 if (Subtarget->isTargetELF() &&
2424 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425 OpFlags = X86II::MO_PLT;
2426 } else if (Subtarget->isPICStyleStubAny() &&
2427 (!Subtarget->getTargetTriple().isMacOSX() ||
2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429 // PC-relative references to external symbols should go through $stub,
2430 // unless we're building with the leopard linker or later, which
2431 // automatically synthesizes these stubs.
2432 OpFlags = X86II::MO_DARWIN_STUB;
2435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2439 // Returns a chain & a flag for retval copy to use.
2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441 SmallVector<SDValue, 8> Ops;
2443 if (!IsSibcall && isTailCall) {
2444 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445 DAG.getIntPtrConstant(0, true), InFlag);
2446 InFlag = Chain.getValue(1);
2449 Ops.push_back(Chain);
2450 Ops.push_back(Callee);
2453 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2455 // Add argument registers to the end of the list so that they are known live
2457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459 RegsToPass[i].second.getValueType()));
2461 // Add an implicit use GOT pointer in EBX.
2462 if (!isTailCall && Subtarget->isPICStyleGOT())
2463 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2465 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466 if (Is64Bit && isVarArg && !IsWin64)
2467 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2469 if (InFlag.getNode())
2470 Ops.push_back(InFlag);
2474 //// If this is the first return lowered for this function, add the regs
2475 //// to the liveout set for the function.
2476 // This isn't right, although it's probably harmless on x86; liveouts
2477 // should be computed from returns not tail calls. Consider a void
2478 // function making a tail call to a function returning int.
2479 return DAG.getNode(X86ISD::TC_RETURN, dl,
2480 NodeTys, &Ops[0], Ops.size());
2483 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484 InFlag = Chain.getValue(1);
2486 // Create the CALLSEQ_END node.
2487 unsigned NumBytesForCalleeToPush;
2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2490 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491 // If this is a call to a struct-return function, the callee
2492 // pops the hidden struct pointer, so we have to push it back.
2493 // This is common for Darwin/X86, Linux & Mingw32 targets.
2494 NumBytesForCalleeToPush = 4;
2496 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2498 // Returns a flag for retval copy to use.
2500 Chain = DAG.getCALLSEQ_END(Chain,
2501 DAG.getIntPtrConstant(NumBytes, true),
2502 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2505 InFlag = Chain.getValue(1);
2508 // Handle result values, copying them out of physregs into vregs that we
2510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511 Ins, dl, DAG, InVals);
2515 //===----------------------------------------------------------------------===//
2516 // Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2519 // Like std call, callee cleans arguments, convention except that ECX is
2520 // reserved for storing the tail called function address. Only 2 registers are
2521 // free for argument passing (inreg). Tail call optimization is performed
2523 // * tailcallopt is enabled
2524 // * caller/callee are fastcc
2525 // On X86_64 architecture with GOT-style position independent code only local
2526 // (within module) calls are supported at the moment.
2527 // To keep the stack aligned according to platform abi the function
2528 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 // If a tail called function callee has more arguments than the caller the
2531 // caller needs to make sure that there is room to move the RETADDR to. This is
2532 // achieved by reserving an area the size of the argument delta right after the
2533 // original REtADDR, but before the saved framepointer or the spilled registers
2534 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550 SelectionDAG& DAG) const {
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 const TargetMachine &TM = MF.getTarget();
2553 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554 unsigned StackAlignment = TFI.getStackAlignment();
2555 uint64_t AlignMask = StackAlignment - 1;
2556 int64_t Offset = StackSize;
2557 uint64_t SlotSize = TD->getPointerSize();
2558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559 // Number smaller than 12 so just add the difference.
2560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2562 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563 Offset = ((~AlignMask) & Offset) + StackAlignment +
2564 (StackAlignment-SlotSize);
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575 const X86InstrInfo *TII) {
2576 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2578 if (Arg.getOpcode() == ISD::CopyFromReg) {
2579 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580 if (!TargetRegisterInfo::isVirtualRegister(VR))
2582 MachineInstr *Def = MRI->getVRegDef(VR);
2585 if (!Flags.isByVal()) {
2586 if (!TII->isLoadFromStackSlot(Def, FI))
2589 unsigned Opcode = Def->getOpcode();
2590 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591 Def->getOperand(1).isFI()) {
2592 FI = Def->getOperand(1).getIndex();
2593 Bytes = Flags.getByValSize();
2597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598 if (Flags.isByVal())
2599 // ByVal argument is passed in as a pointer but it's now being
2600 // dereferenced. e.g.
2601 // define @foo(%struct.X* %A) {
2602 // tail call @bar(%struct.X* byval %A)
2605 SDValue Ptr = Ld->getBasePtr();
2606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2609 FI = FINode->getIndex();
2610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612 FI = FINode->getIndex();
2613 Bytes = Flags.getByValSize();
2617 assert(FI != INT_MAX);
2618 if (!MFI->isFixedObjectIndex(FI))
2620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628 CallingConv::ID CalleeCC,
2630 bool isCalleeStructRet,
2631 bool isCallerStructRet,
2632 const SmallVectorImpl<ISD::OutputArg> &Outs,
2633 const SmallVectorImpl<SDValue> &OutVals,
2634 const SmallVectorImpl<ISD::InputArg> &Ins,
2635 SelectionDAG& DAG) const {
2636 if (!IsTailCallConvention(CalleeCC) &&
2637 CalleeCC != CallingConv::C)
2640 // If -tailcallopt is specified, make fastcc functions tail-callable.
2641 const MachineFunction &MF = DAG.getMachineFunction();
2642 const Function *CallerF = DAG.getMachineFunction().getFunction();
2643 CallingConv::ID CallerCC = CallerF->getCallingConv();
2644 bool CCMatch = CallerCC == CalleeCC;
2646 if (GuaranteedTailCallOpt) {
2647 if (IsTailCallConvention(CalleeCC) && CCMatch)
2652 // Look for obvious safe cases to perform tail call optimization that do not
2653 // require ABI changes. This is what gcc calls sibcall.
2655 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656 // emit a special epilogue.
2657 if (RegInfo->needsStackRealignment(MF))
2660 // Also avoid sibcall optimization if either caller or callee uses struct
2661 // return semantics.
2662 if (isCalleeStructRet || isCallerStructRet)
2665 // An stdcall caller is expected to clean up its arguments; the callee
2666 // isn't going to do that.
2667 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2670 // Do not sibcall optimize vararg calls unless all arguments are passed via
2672 if (isVarArg && !Outs.empty()) {
2674 // Optimizing for varargs on Win64 is unlikely to be safe without
2675 // additional testing.
2676 if (Subtarget->isTargetWin64())
2679 SmallVector<CCValAssign, 16> ArgLocs;
2680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681 getTargetMachine(), ArgLocs, *DAG.getContext());
2683 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685 if (!ArgLocs[i].isRegLoc())
2689 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690 // Therefore if it's not used by the call it is not safe to optimize this into
2692 bool Unused = false;
2693 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2700 SmallVector<CCValAssign, 16> RVLocs;
2701 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702 getTargetMachine(), RVLocs, *DAG.getContext());
2703 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705 CCValAssign &VA = RVLocs[i];
2706 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2711 // If the calling conventions do not match, then we'd better make sure the
2712 // results are returned in the same way as what the caller expects.
2714 SmallVector<CCValAssign, 16> RVLocs1;
2715 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716 getTargetMachine(), RVLocs1, *DAG.getContext());
2717 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2719 SmallVector<CCValAssign, 16> RVLocs2;
2720 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721 getTargetMachine(), RVLocs2, *DAG.getContext());
2722 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2724 if (RVLocs1.size() != RVLocs2.size())
2726 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2729 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2731 if (RVLocs1[i].isRegLoc()) {
2732 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2735 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2741 // If the callee takes no arguments then go on to check the results of the
2743 if (!Outs.empty()) {
2744 // Check if stack adjustment is needed. For now, do not do this if any
2745 // argument is passed on the stack.
2746 SmallVector<CCValAssign, 16> ArgLocs;
2747 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748 getTargetMachine(), ArgLocs, *DAG.getContext());
2750 // Allocate shadow area for Win64
2751 if (Subtarget->isTargetWin64()) {
2752 CCInfo.AllocateStack(32, 8);
2755 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756 if (CCInfo.getNextStackOffset()) {
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2761 // Check if the arguments are already laid out in the right way as
2762 // the caller's fixed stack objects.
2763 MachineFrameInfo *MFI = MF.getFrameInfo();
2764 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765 const X86InstrInfo *TII =
2766 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768 CCValAssign &VA = ArgLocs[i];
2769 SDValue Arg = OutVals[i];
2770 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771 if (VA.getLocInfo() == CCValAssign::Indirect)
2773 if (!VA.isRegLoc()) {
2774 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2781 // If the tailcall address may be in a register, then make sure it's
2782 // possible to register allocate for it. In 32-bit, the call address can
2783 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784 // callee-saved registers are restored. These happen to be the same
2785 // registers used to pass 'inreg' arguments so watch out for those.
2786 if (!Subtarget->is64Bit() &&
2787 !isa<GlobalAddressSDNode>(Callee) &&
2788 !isa<ExternalSymbolSDNode>(Callee)) {
2789 unsigned NumInRegs = 0;
2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791 CCValAssign &VA = ArgLocs[i];
2794 unsigned Reg = VA.getLocReg();
2797 case X86::EAX: case X86::EDX: case X86::ECX:
2798 if (++NumInRegs == 3)
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811 return X86::createFastISel(funcInfo);
2815 //===----------------------------------------------------------------------===//
2816 // Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2819 static bool MayFoldLoad(SDValue Op) {
2820 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2823 static bool MayFoldIntoStore(SDValue Op) {
2824 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2827 static bool isTargetShuffle(unsigned Opcode) {
2829 default: return false;
2830 case X86ISD::PSHUFD:
2831 case X86ISD::PSHUFHW:
2832 case X86ISD::PSHUFLW:
2833 case X86ISD::SHUFPD:
2834 case X86ISD::PALIGN:
2835 case X86ISD::SHUFPS:
2836 case X86ISD::MOVLHPS:
2837 case X86ISD::MOVLHPD:
2838 case X86ISD::MOVHLPS:
2839 case X86ISD::MOVLPS:
2840 case X86ISD::MOVLPD:
2841 case X86ISD::MOVSHDUP:
2842 case X86ISD::MOVSLDUP:
2843 case X86ISD::MOVDDUP:
2846 case X86ISD::UNPCKLP:
2847 case X86ISD::PUNPCKL:
2848 case X86ISD::UNPCKHP:
2849 case X86ISD::PUNPCKH:
2850 case X86ISD::VPERMILPS:
2851 case X86ISD::VPERMILPD:
2852 case X86ISD::VPERM2F128:
2858 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2859 SDValue V1, SelectionDAG &DAG) {
2861 default: llvm_unreachable("Unknown x86 shuffle node");
2862 case X86ISD::MOVSHDUP:
2863 case X86ISD::MOVSLDUP:
2864 case X86ISD::MOVDDUP:
2865 return DAG.getNode(Opc, dl, VT, V1);
2871 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2872 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2874 default: llvm_unreachable("Unknown x86 shuffle node");
2875 case X86ISD::PSHUFD:
2876 case X86ISD::PSHUFHW:
2877 case X86ISD::PSHUFLW:
2878 case X86ISD::VPERMILPS:
2879 case X86ISD::VPERMILPD:
2880 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2886 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2887 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2889 default: llvm_unreachable("Unknown x86 shuffle node");
2890 case X86ISD::PALIGN:
2891 case X86ISD::SHUFPD:
2892 case X86ISD::SHUFPS:
2893 case X86ISD::VPERM2F128:
2894 return DAG.getNode(Opc, dl, VT, V1, V2,
2895 DAG.getConstant(TargetMask, MVT::i8));
2900 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2901 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2903 default: llvm_unreachable("Unknown x86 shuffle node");
2904 case X86ISD::MOVLHPS:
2905 case X86ISD::MOVLHPD:
2906 case X86ISD::MOVHLPS:
2907 case X86ISD::MOVLPS:
2908 case X86ISD::MOVLPD:
2911 case X86ISD::UNPCKLP:
2912 case X86ISD::PUNPCKL:
2913 case X86ISD::UNPCKHP:
2914 case X86ISD::PUNPCKH:
2915 return DAG.getNode(Opc, dl, VT, V1, V2);
2920 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2921 MachineFunction &MF = DAG.getMachineFunction();
2922 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2923 int ReturnAddrIndex = FuncInfo->getRAIndex();
2925 if (ReturnAddrIndex == 0) {
2926 // Set up a frame object for the return address.
2927 uint64_t SlotSize = TD->getPointerSize();
2928 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2930 FuncInfo->setRAIndex(ReturnAddrIndex);
2933 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2937 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2938 bool hasSymbolicDisplacement) {
2939 // Offset should fit into 32 bit immediate field.
2940 if (!isInt<32>(Offset))
2943 // If we don't have a symbolic displacement - we don't have any extra
2945 if (!hasSymbolicDisplacement)
2948 // FIXME: Some tweaks might be needed for medium code model.
2949 if (M != CodeModel::Small && M != CodeModel::Kernel)
2952 // For small code model we assume that latest object is 16MB before end of 31
2953 // bits boundary. We may also accept pretty large negative constants knowing
2954 // that all objects are in the positive half of address space.
2955 if (M == CodeModel::Small && Offset < 16*1024*1024)
2958 // For kernel code model we know that all object resist in the negative half
2959 // of 32bits address space. We may not accept negative offsets, since they may
2960 // be just off and we may accept pretty large positive ones.
2961 if (M == CodeModel::Kernel && Offset > 0)
2967 /// isCalleePop - Determines whether the callee is required to pop its
2968 /// own arguments. Callee pop is necessary to support tail calls.
2969 bool X86::isCalleePop(CallingConv::ID CallingConv,
2970 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2974 switch (CallingConv) {
2977 case CallingConv::X86_StdCall:
2979 case CallingConv::X86_FastCall:
2981 case CallingConv::X86_ThisCall:
2983 case CallingConv::Fast:
2985 case CallingConv::GHC:
2990 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2991 /// specific condition code, returning the condition code and the LHS/RHS of the
2992 /// comparison to make.
2993 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2994 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2996 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2997 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2998 // X > -1 -> X == 0, jump !sign.
2999 RHS = DAG.getConstant(0, RHS.getValueType());
3000 return X86::COND_NS;
3001 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3002 // X < 0 -> X == 0, jump on sign.
3004 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3006 RHS = DAG.getConstant(0, RHS.getValueType());
3007 return X86::COND_LE;
3011 switch (SetCCOpcode) {
3012 default: llvm_unreachable("Invalid integer condition!");
3013 case ISD::SETEQ: return X86::COND_E;
3014 case ISD::SETGT: return X86::COND_G;
3015 case ISD::SETGE: return X86::COND_GE;
3016 case ISD::SETLT: return X86::COND_L;
3017 case ISD::SETLE: return X86::COND_LE;
3018 case ISD::SETNE: return X86::COND_NE;
3019 case ISD::SETULT: return X86::COND_B;
3020 case ISD::SETUGT: return X86::COND_A;
3021 case ISD::SETULE: return X86::COND_BE;
3022 case ISD::SETUGE: return X86::COND_AE;
3026 // First determine if it is required or is profitable to flip the operands.
3028 // If LHS is a foldable load, but RHS is not, flip the condition.
3029 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3030 !ISD::isNON_EXTLoad(RHS.getNode())) {
3031 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3032 std::swap(LHS, RHS);
3035 switch (SetCCOpcode) {
3041 std::swap(LHS, RHS);
3045 // On a floating point condition, the flags are set as follows:
3047 // 0 | 0 | 0 | X > Y
3048 // 0 | 0 | 1 | X < Y
3049 // 1 | 0 | 0 | X == Y
3050 // 1 | 1 | 1 | unordered
3051 switch (SetCCOpcode) {
3052 default: llvm_unreachable("Condcode should be pre-legalized away");
3054 case ISD::SETEQ: return X86::COND_E;
3055 case ISD::SETOLT: // flipped
3057 case ISD::SETGT: return X86::COND_A;
3058 case ISD::SETOLE: // flipped
3060 case ISD::SETGE: return X86::COND_AE;
3061 case ISD::SETUGT: // flipped
3063 case ISD::SETLT: return X86::COND_B;
3064 case ISD::SETUGE: // flipped
3066 case ISD::SETLE: return X86::COND_BE;
3068 case ISD::SETNE: return X86::COND_NE;
3069 case ISD::SETUO: return X86::COND_P;
3070 case ISD::SETO: return X86::COND_NP;
3072 case ISD::SETUNE: return X86::COND_INVALID;
3076 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3077 /// code. Current x86 isa includes the following FP cmov instructions:
3078 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3079 static bool hasFPCMov(unsigned X86CC) {
3095 /// isFPImmLegal - Returns true if the target can instruction select the
3096 /// specified FP immediate natively. If false, the legalizer will
3097 /// materialize the FP immediate as a load from a constant pool.
3098 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3099 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3100 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3106 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3107 /// the specified range (L, H].
3108 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3109 return (Val < 0) || (Val >= Low && Val < Hi);
3112 /// isUndefOrInRange - Return true if every element in Mask, begining
3113 /// from position Pos and ending in Pos+Size, falls within the specified
3114 /// range (L, L+Pos]. or is undef.
3115 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3116 int Pos, int Size, int Low, int Hi) {
3117 for (int i = Pos, e = Pos+Size; i != e; ++i)
3118 if (!isUndefOrInRange(Mask[i], Low, Hi))
3123 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3124 /// specified value.
3125 static bool isUndefOrEqual(int Val, int CmpVal) {
3126 if (Val < 0 || Val == CmpVal)
3131 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3132 /// from position Pos and ending in Pos+Size, falls within the specified
3133 /// sequential range (L, L+Pos]. or is undef.
3134 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3135 int Pos, int Size, int Low) {
3136 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3137 if (!isUndefOrEqual(Mask[i], Low))
3142 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3143 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3144 /// the second operand.
3145 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3147 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3148 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3149 return (Mask[0] < 2 && Mask[1] < 2);
3153 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3154 SmallVector<int, 8> M;
3156 return ::isPSHUFDMask(M, N->getValueType(0));
3159 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3160 /// is suitable for input to PSHUFHW.
3161 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3162 if (VT != MVT::v8i16)
3165 // Lower quadword copied in order or undef.
3166 for (int i = 0; i != 4; ++i)
3167 if (Mask[i] >= 0 && Mask[i] != i)
3170 // Upper quadword shuffled.
3171 for (int i = 4; i != 8; ++i)
3172 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3178 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3179 SmallVector<int, 8> M;
3181 return ::isPSHUFHWMask(M, N->getValueType(0));
3184 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3185 /// is suitable for input to PSHUFLW.
3186 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3187 if (VT != MVT::v8i16)
3190 // Upper quadword copied in order.
3191 for (int i = 4; i != 8; ++i)
3192 if (Mask[i] >= 0 && Mask[i] != i)
3195 // Lower quadword shuffled.
3196 for (int i = 0; i != 4; ++i)
3203 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3204 SmallVector<int, 8> M;
3206 return ::isPSHUFLWMask(M, N->getValueType(0));
3209 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3210 /// is suitable for input to PALIGNR.
3211 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3212 bool hasSSSE3OrAVX) {
3213 int i, e = VT.getVectorNumElements();
3214 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3217 // Do not handle v2i64 / v2f64 shuffles with palignr.
3218 if (e < 4 || !hasSSSE3OrAVX)
3221 for (i = 0; i != e; ++i)
3225 // All undef, not a palignr.
3229 // Make sure we're shifting in the right direction.
3233 int s = Mask[i] - i;
3235 // Check the rest of the elements to see if they are consecutive.
3236 for (++i; i != e; ++i) {
3238 if (m >= 0 && m != s+i)
3244 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3245 /// specifies a shuffle of elements that is suitable for input to 256-bit
3247 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3248 const X86Subtarget *Subtarget) {
3249 int NumElems = VT.getVectorNumElements();
3251 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3257 // VSHUFPSY divides the resulting vector into 4 chunks.
3258 // The sources are also splitted into 4 chunks, and each destination
3259 // chunk must come from a different source chunk.
3261 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3262 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3264 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3265 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3267 int QuarterSize = NumElems/4;
3268 int HalfSize = QuarterSize*2;
3269 for (int i = 0; i < QuarterSize; ++i)
3270 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3272 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3273 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3276 // The mask of the second half must be the same as the first but with
3277 // the appropriate offsets. This works in the same way as VPERMILPS
3278 // works with masks.
3279 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3280 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3282 int FstHalfIdx = i-HalfSize;
3283 if (Mask[FstHalfIdx] < 0)
3285 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3288 for (int i = QuarterSize*3; i < NumElems; ++i) {
3289 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3291 int FstHalfIdx = i-HalfSize;
3292 if (Mask[FstHalfIdx] < 0)
3294 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3302 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3303 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3304 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3305 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3306 EVT VT = SVOp->getValueType(0);
3307 int NumElems = VT.getVectorNumElements();
3309 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3310 "Only supports v8i32 and v8f32 types");
3312 int HalfSize = NumElems/2;
3314 for (int i = 0; i != NumElems ; ++i) {
3315 if (SVOp->getMaskElt(i) < 0)
3317 // The mask of the first half must be equal to the second one.
3318 unsigned Shamt = (i%HalfSize)*2;
3319 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3320 Mask |= Elt << Shamt;
3326 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3327 /// specifies a shuffle of elements that is suitable for input to 256-bit
3328 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3329 /// version and the mask of the second half isn't binded with the first
3331 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3332 const X86Subtarget *Subtarget) {
3333 int NumElems = VT.getVectorNumElements();
3335 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3341 // VSHUFPSY divides the resulting vector into 4 chunks.
3342 // The sources are also splitted into 4 chunks, and each destination
3343 // chunk must come from a different source chunk.
3345 // SRC1 => X3 X2 X1 X0
3346 // SRC2 => Y3 Y2 Y1 Y0
3348 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3350 int QuarterSize = NumElems/4;
3351 int HalfSize = QuarterSize*2;
3352 for (int i = 0; i < QuarterSize; ++i)
3353 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3355 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3356 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3358 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3359 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3361 for (int i = QuarterSize*3; i < NumElems; ++i)
3362 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3368 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3369 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3370 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3371 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3372 EVT VT = SVOp->getValueType(0);
3373 int NumElems = VT.getVectorNumElements();
3375 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3376 "Only supports v4i64 and v4f64 types");
3378 int HalfSize = NumElems/2;
3380 for (int i = 0; i != NumElems ; ++i) {
3381 if (SVOp->getMaskElt(i) < 0)
3383 int Elt = SVOp->getMaskElt(i) % HalfSize;
3390 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3391 /// the two vector operands have swapped position.
3392 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3393 unsigned NumElems = VT.getVectorNumElements();
3394 for (unsigned i = 0; i != NumElems; ++i) {
3398 else if (idx < (int)NumElems)
3399 Mask[i] = idx + NumElems;
3401 Mask[i] = idx - NumElems;
3405 /// isCommutedVSHUFP() - Return true if swapping operands will
3406 /// allow to use the "vshufpd" or "vshufps" instruction
3407 /// for 256-bit vectors
3408 static bool isCommutedVSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3409 const X86Subtarget *Subtarget) {
3411 unsigned NumElems = VT.getVectorNumElements();
3412 if ((VT.getSizeInBits() != 256) || ((NumElems != 4) && (NumElems != 8)))
3415 SmallVector<int, 8> CommutedMask;
3416 for (unsigned i = 0; i < NumElems; ++i)
3417 CommutedMask.push_back(Mask[i]);
3419 CommuteVectorShuffleMask(CommutedMask, VT);
3420 return (NumElems == 4) ? isVSHUFPDYMask(CommutedMask, VT, Subtarget):
3421 isVSHUFPSYMask(CommutedMask, VT, Subtarget);
3425 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3426 /// specifies a shuffle of elements that is suitable for input to 128-bit
3427 /// SHUFPS and SHUFPD.
3428 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3429 int NumElems = VT.getVectorNumElements();
3431 if (VT.getSizeInBits() != 128)
3434 if (NumElems != 2 && NumElems != 4)
3437 int Half = NumElems / 2;
3438 for (int i = 0; i < Half; ++i)
3439 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3441 for (int i = Half; i < NumElems; ++i)
3442 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3448 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3449 SmallVector<int, 8> M;
3451 return ::isSHUFPMask(M, N->getValueType(0));
3454 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3455 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3456 /// half elements to come from vector 1 (which would equal the dest.) and
3457 /// the upper half to come from vector 2.
3458 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3459 int NumElems = VT.getVectorNumElements();
3461 if (NumElems != 2 && NumElems != 4)
3464 int Half = NumElems / 2;
3465 for (int i = 0; i < Half; ++i)
3466 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3468 for (int i = Half; i < NumElems; ++i)
3469 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3474 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3475 SmallVector<int, 8> M;
3477 return isCommutedSHUFPMask(M, N->getValueType(0));
3480 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3481 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3482 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3483 EVT VT = N->getValueType(0);
3484 unsigned NumElems = VT.getVectorNumElements();
3486 if (VT.getSizeInBits() != 128)
3492 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3493 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3494 isUndefOrEqual(N->getMaskElt(1), 7) &&
3495 isUndefOrEqual(N->getMaskElt(2), 2) &&
3496 isUndefOrEqual(N->getMaskElt(3), 3);
3499 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3500 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3502 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3503 EVT VT = N->getValueType(0);
3504 unsigned NumElems = VT.getVectorNumElements();
3506 if (VT.getSizeInBits() != 128)
3512 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3513 isUndefOrEqual(N->getMaskElt(1), 3) &&
3514 isUndefOrEqual(N->getMaskElt(2), 2) &&
3515 isUndefOrEqual(N->getMaskElt(3), 3);
3518 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3519 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3520 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3521 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3523 if (NumElems != 2 && NumElems != 4)
3526 for (unsigned i = 0; i < NumElems/2; ++i)
3527 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3530 for (unsigned i = NumElems/2; i < NumElems; ++i)
3531 if (!isUndefOrEqual(N->getMaskElt(i), i))
3537 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3538 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3539 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3540 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3542 if ((NumElems != 2 && NumElems != 4)
3543 || N->getValueType(0).getSizeInBits() > 128)
3546 for (unsigned i = 0; i < NumElems/2; ++i)
3547 if (!isUndefOrEqual(N->getMaskElt(i), i))
3550 for (unsigned i = 0; i < NumElems/2; ++i)
3551 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3557 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3558 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3559 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3560 bool HasAVX2, bool V2IsSplat = false) {
3561 int NumElts = VT.getVectorNumElements();
3563 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3564 "Unsupported vector type for unpckh");
3566 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3567 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3570 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3571 // independently on 128-bit lanes.
3572 unsigned NumLanes = VT.getSizeInBits()/128;
3573 unsigned NumLaneElts = NumElts/NumLanes;
3576 unsigned End = NumLaneElts;
3577 for (unsigned s = 0; s < NumLanes; ++s) {
3578 for (unsigned i = Start, j = s * NumLaneElts;
3582 int BitI1 = Mask[i+1];
3583 if (!isUndefOrEqual(BitI, j))
3586 if (!isUndefOrEqual(BitI1, NumElts))
3589 if (!isUndefOrEqual(BitI1, j + NumElts))
3593 // Process the next 128 bits.
3594 Start += NumLaneElts;
3601 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3602 SmallVector<int, 8> M;
3604 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3607 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3608 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3609 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3610 bool HasAVX2, bool V2IsSplat = false) {
3611 int NumElts = VT.getVectorNumElements();
3613 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3614 "Unsupported vector type for unpckh");
3616 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3617 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3620 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3621 // independently on 128-bit lanes.
3622 unsigned NumLanes = VT.getSizeInBits()/128;
3623 unsigned NumLaneElts = NumElts/NumLanes;
3626 unsigned End = NumLaneElts;
3627 for (unsigned l = 0; l != NumLanes; ++l) {
3628 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3629 i != End; i += 2, ++j) {
3631 int BitI1 = Mask[i+1];
3632 if (!isUndefOrEqual(BitI, j))
3635 if (isUndefOrEqual(BitI1, NumElts))
3638 if (!isUndefOrEqual(BitI1, j+NumElts))
3642 // Process the next 128 bits.
3643 Start += NumLaneElts;
3649 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3650 SmallVector<int, 8> M;
3652 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3655 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3656 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3658 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3659 int NumElems = VT.getVectorNumElements();
3660 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3663 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3664 // FIXME: Need a better way to get rid of this, there's no latency difference
3665 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3666 // the former later. We should also remove the "_undef" special mask.
3667 if (NumElems == 4 && VT.getSizeInBits() == 256)
3670 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3671 // independently on 128-bit lanes.
3672 unsigned NumLanes = VT.getSizeInBits() / 128;
3673 unsigned NumLaneElts = NumElems / NumLanes;
3675 for (unsigned s = 0; s < NumLanes; ++s) {
3676 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3677 i != NumLaneElts * (s + 1);
3680 int BitI1 = Mask[i+1];
3682 if (!isUndefOrEqual(BitI, j))
3684 if (!isUndefOrEqual(BitI1, j))
3692 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3693 SmallVector<int, 8> M;
3695 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3698 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3699 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3701 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3702 int NumElems = VT.getVectorNumElements();
3703 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3706 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3708 int BitI1 = Mask[i+1];
3709 if (!isUndefOrEqual(BitI, j))
3711 if (!isUndefOrEqual(BitI1, j))
3717 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3718 SmallVector<int, 8> M;
3720 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3723 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3724 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3725 /// MOVSD, and MOVD, i.e. setting the lowest element.
3726 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3727 if (VT.getVectorElementType().getSizeInBits() < 32)
3730 int NumElts = VT.getVectorNumElements();
3732 if (!isUndefOrEqual(Mask[0], NumElts))
3735 for (int i = 1; i < NumElts; ++i)
3736 if (!isUndefOrEqual(Mask[i], i))
3742 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3743 SmallVector<int, 8> M;
3745 return ::isMOVLMask(M, N->getValueType(0));
3748 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3749 /// as permutations between 128-bit chunks or halves. As an example: this
3751 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3752 /// The first half comes from the second half of V1 and the second half from the
3753 /// the second half of V2.
3754 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3755 const X86Subtarget *Subtarget) {
3756 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3759 // The shuffle result is divided into half A and half B. In total the two
3760 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3761 // B must come from C, D, E or F.
3762 int HalfSize = VT.getVectorNumElements()/2;
3763 bool MatchA = false, MatchB = false;
3765 // Check if A comes from one of C, D, E, F.
3766 for (int Half = 0; Half < 4; ++Half) {
3767 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3773 // Check if B comes from one of C, D, E, F.
3774 for (int Half = 0; Half < 4; ++Half) {
3775 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3781 return MatchA && MatchB;
3784 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3785 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3786 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3787 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3788 EVT VT = SVOp->getValueType(0);
3790 int HalfSize = VT.getVectorNumElements()/2;
3792 int FstHalf = 0, SndHalf = 0;
3793 for (int i = 0; i < HalfSize; ++i) {
3794 if (SVOp->getMaskElt(i) > 0) {
3795 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3799 for (int i = HalfSize; i < HalfSize*2; ++i) {
3800 if (SVOp->getMaskElt(i) > 0) {
3801 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3806 return (FstHalf | (SndHalf << 4));
3809 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3810 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3811 /// Note that VPERMIL mask matching is different depending whether theunderlying
3812 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3813 /// to the same elements of the low, but to the higher half of the source.
3814 /// In VPERMILPD the two lanes could be shuffled independently of each other
3815 /// with the same restriction that lanes can't be crossed.
3816 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3817 const X86Subtarget *Subtarget) {
3818 int NumElts = VT.getVectorNumElements();
3819 int NumLanes = VT.getSizeInBits()/128;
3821 if (!Subtarget->hasAVX())
3824 // Only match 256-bit with 64-bit types
3825 if (VT.getSizeInBits() != 256 || NumElts != 4)
3828 // The mask on the high lane is independent of the low. Both can match
3829 // any element in inside its own lane, but can't cross.
3830 int LaneSize = NumElts/NumLanes;
3831 for (int l = 0; l < NumLanes; ++l)
3832 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3833 int LaneStart = l*LaneSize;
3834 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3841 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3842 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3843 /// Note that VPERMIL mask matching is different depending whether theunderlying
3844 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3845 /// to the same elements of the low, but to the higher half of the source.
3846 /// In VPERMILPD the two lanes could be shuffled independently of each other
3847 /// with the same restriction that lanes can't be crossed.
3848 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3849 const X86Subtarget *Subtarget) {
3850 unsigned NumElts = VT.getVectorNumElements();
3851 unsigned NumLanes = VT.getSizeInBits()/128;
3853 if (!Subtarget->hasAVX())
3856 // Only match 256-bit with 32-bit types
3857 if (VT.getSizeInBits() != 256 || NumElts != 8)
3860 // The mask on the high lane should be the same as the low. Actually,
3861 // they can differ if any of the corresponding index in a lane is undef
3862 // and the other stays in range.
3863 int LaneSize = NumElts/NumLanes;
3864 for (int i = 0; i < LaneSize; ++i) {
3865 int HighElt = i+LaneSize;
3866 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3867 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3869 if (!HighValid || !LowValid)
3871 if (Mask[i] < 0 || Mask[HighElt] < 0)
3873 if (Mask[HighElt]-Mask[i] != LaneSize)
3880 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3881 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3882 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3883 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3884 EVT VT = SVOp->getValueType(0);
3886 int NumElts = VT.getVectorNumElements();
3887 int NumLanes = VT.getSizeInBits()/128;
3888 int LaneSize = NumElts/NumLanes;
3890 // Although the mask is equal for both lanes do it twice to get the cases
3891 // where a mask will match because the same mask element is undef on the
3892 // first half but valid on the second. This would get pathological cases
3893 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3895 for (int l = 0; l < NumLanes; ++l) {
3896 for (int i = 0; i < LaneSize; ++i) {
3897 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3900 if (MaskElt >= LaneSize)
3901 MaskElt -= LaneSize;
3902 Mask |= MaskElt << (i*2);
3909 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3910 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3911 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3913 EVT VT = SVOp->getValueType(0);
3915 int NumElts = VT.getVectorNumElements();
3916 int NumLanes = VT.getSizeInBits()/128;
3919 int LaneSize = NumElts/NumLanes;
3920 for (int l = 0; l < NumLanes; ++l)
3921 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3922 int MaskElt = SVOp->getMaskElt(i);
3925 Mask |= (MaskElt-l*LaneSize) << i;
3931 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3932 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3933 /// element of vector 2 and the other elements to come from vector 1 in order.
3934 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3935 bool V2IsSplat = false, bool V2IsUndef = false) {
3936 int NumOps = VT.getVectorNumElements();
3937 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3940 if (!isUndefOrEqual(Mask[0], 0))
3943 for (int i = 1; i < NumOps; ++i)
3944 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3945 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3946 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3952 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3953 bool V2IsUndef = false) {
3954 SmallVector<int, 8> M;
3956 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3959 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3961 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3962 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3963 const X86Subtarget *Subtarget) {
3964 if (!Subtarget->hasSSE3orAVX())
3967 // The second vector must be undef
3968 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3971 EVT VT = N->getValueType(0);
3972 unsigned NumElems = VT.getVectorNumElements();
3974 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3975 (VT.getSizeInBits() == 256 && NumElems != 8))
3978 // "i+1" is the value the indexed mask element must have
3979 for (unsigned i = 0; i < NumElems; i += 2)
3980 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3981 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3987 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3989 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3990 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3991 const X86Subtarget *Subtarget) {
3992 if (!Subtarget->hasSSE3orAVX())
3995 // The second vector must be undef
3996 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3999 EVT VT = N->getValueType(0);
4000 unsigned NumElems = VT.getVectorNumElements();
4002 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4003 (VT.getSizeInBits() == 256 && NumElems != 8))
4006 // "i" is the value the indexed mask element must have
4007 for (unsigned i = 0; i < NumElems; i += 2)
4008 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4009 !isUndefOrEqual(N->getMaskElt(i+1), i))
4015 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4016 /// specifies a shuffle of elements that is suitable for input to 256-bit
4017 /// version of MOVDDUP.
4018 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4019 const X86Subtarget *Subtarget) {
4020 EVT VT = N->getValueType(0);
4021 int NumElts = VT.getVectorNumElements();
4022 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4024 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4025 !V2IsUndef || NumElts != 4)
4028 for (int i = 0; i != NumElts/2; ++i)
4029 if (!isUndefOrEqual(N->getMaskElt(i), 0))
4031 for (int i = NumElts/2; i != NumElts; ++i)
4032 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4038 /// specifies a shuffle of elements that is suitable for input to 128-bit
4039 /// version of MOVDDUP.
4040 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4041 EVT VT = N->getValueType(0);
4043 if (VT.getSizeInBits() != 128)
4046 int e = VT.getVectorNumElements() / 2;
4047 for (int i = 0; i < e; ++i)
4048 if (!isUndefOrEqual(N->getMaskElt(i), i))
4050 for (int i = 0; i < e; ++i)
4051 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4056 /// isVEXTRACTF128Index - Return true if the specified
4057 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4058 /// suitable for input to VEXTRACTF128.
4059 bool X86::isVEXTRACTF128Index(SDNode *N) {
4060 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4063 // The index should be aligned on a 128-bit boundary.
4065 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4067 unsigned VL = N->getValueType(0).getVectorNumElements();
4068 unsigned VBits = N->getValueType(0).getSizeInBits();
4069 unsigned ElSize = VBits / VL;
4070 bool Result = (Index * ElSize) % 128 == 0;
4075 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4076 /// operand specifies a subvector insert that is suitable for input to
4078 bool X86::isVINSERTF128Index(SDNode *N) {
4079 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4082 // The index should be aligned on a 128-bit boundary.
4084 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4086 unsigned VL = N->getValueType(0).getVectorNumElements();
4087 unsigned VBits = N->getValueType(0).getSizeInBits();
4088 unsigned ElSize = VBits / VL;
4089 bool Result = (Index * ElSize) % 128 == 0;
4094 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4096 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4097 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4098 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4100 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4102 for (int i = 0; i < NumOperands; ++i) {
4103 int Val = SVOp->getMaskElt(NumOperands-i-1);
4104 if (Val < 0) Val = 0;
4105 if (Val >= NumOperands) Val -= NumOperands;
4107 if (i != NumOperands - 1)
4113 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4115 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4116 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4118 // 8 nodes, but we only care about the last 4.
4119 for (unsigned i = 7; i >= 4; --i) {
4120 int Val = SVOp->getMaskElt(i);
4129 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4130 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4131 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4134 // 8 nodes, but we only care about the first 4.
4135 for (int i = 3; i >= 0; --i) {
4136 int Val = SVOp->getMaskElt(i);
4145 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4146 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4147 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4148 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4149 EVT VVT = N->getValueType(0);
4150 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4154 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4155 Val = SVOp->getMaskElt(i);
4159 assert(Val - i > 0 && "PALIGNR imm should be positive");
4160 return (Val - i) * EltSize;
4163 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4164 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4166 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4167 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4168 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4171 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4173 EVT VecVT = N->getOperand(0).getValueType();
4174 EVT ElVT = VecVT.getVectorElementType();
4176 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4177 return Index / NumElemsPerChunk;
4180 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4181 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4183 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4184 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4185 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4188 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4190 EVT VecVT = N->getValueType(0);
4191 EVT ElVT = VecVT.getVectorElementType();
4193 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4194 return Index / NumElemsPerChunk;
4197 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4199 bool X86::isZeroNode(SDValue Elt) {
4200 return ((isa<ConstantSDNode>(Elt) &&
4201 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4202 (isa<ConstantFPSDNode>(Elt) &&
4203 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4206 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4207 /// their permute mask.
4208 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4209 SelectionDAG &DAG) {
4210 EVT VT = SVOp->getValueType(0);
4211 unsigned NumElems = VT.getVectorNumElements();
4212 SmallVector<int, 8> MaskVec;
4214 for (unsigned i = 0; i != NumElems; ++i) {
4215 int idx = SVOp->getMaskElt(i);
4217 MaskVec.push_back(idx);
4218 else if (idx < (int)NumElems)
4219 MaskVec.push_back(idx + NumElems);
4221 MaskVec.push_back(idx - NumElems);
4223 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4224 SVOp->getOperand(0), &MaskVec[0]);
4227 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4228 /// match movhlps. The lower half elements should come from upper half of
4229 /// V1 (and in order), and the upper half elements should come from the upper
4230 /// half of V2 (and in order).
4231 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4232 EVT VT = Op->getValueType(0);
4233 if (VT.getSizeInBits() != 128)
4235 if (VT.getVectorNumElements() != 4)
4237 for (unsigned i = 0, e = 2; i != e; ++i)
4238 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4240 for (unsigned i = 2; i != 4; ++i)
4241 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4246 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4247 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4249 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4250 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4252 N = N->getOperand(0).getNode();
4253 if (!ISD::isNON_EXTLoad(N))
4256 *LD = cast<LoadSDNode>(N);
4260 // Test whether the given value is a vector value which will be legalized
4262 static bool WillBeConstantPoolLoad(SDNode *N) {
4263 if (N->getOpcode() != ISD::BUILD_VECTOR)
4266 // Check for any non-constant elements.
4267 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4268 switch (N->getOperand(i).getNode()->getOpcode()) {
4270 case ISD::ConstantFP:
4277 // Vectors of all-zeros and all-ones are materialized with special
4278 // instructions rather than being loaded.
4279 return !ISD::isBuildVectorAllZeros(N) &&
4280 !ISD::isBuildVectorAllOnes(N);
4283 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4284 /// match movlp{s|d}. The lower half elements should come from lower half of
4285 /// V1 (and in order), and the upper half elements should come from the upper
4286 /// half of V2 (and in order). And since V1 will become the source of the
4287 /// MOVLP, it must be either a vector load or a scalar load to vector.
4288 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4289 ShuffleVectorSDNode *Op) {
4290 EVT VT = Op->getValueType(0);
4291 if (VT.getSizeInBits() != 128)
4294 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4296 // Is V2 is a vector load, don't do this transformation. We will try to use
4297 // load folding shufps op.
4298 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4301 unsigned NumElems = VT.getVectorNumElements();
4303 if (NumElems != 2 && NumElems != 4)
4305 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4306 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4308 for (unsigned i = NumElems/2; i != NumElems; ++i)
4309 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4314 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4316 static bool isSplatVector(SDNode *N) {
4317 if (N->getOpcode() != ISD::BUILD_VECTOR)
4320 SDValue SplatValue = N->getOperand(0);
4321 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4322 if (N->getOperand(i) != SplatValue)
4327 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4328 /// to an zero vector.
4329 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4330 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4331 SDValue V1 = N->getOperand(0);
4332 SDValue V2 = N->getOperand(1);
4333 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4334 for (unsigned i = 0; i != NumElems; ++i) {
4335 int Idx = N->getMaskElt(i);
4336 if (Idx >= (int)NumElems) {
4337 unsigned Opc = V2.getOpcode();
4338 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4340 if (Opc != ISD::BUILD_VECTOR ||
4341 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4343 } else if (Idx >= 0) {
4344 unsigned Opc = V1.getOpcode();
4345 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4347 if (Opc != ISD::BUILD_VECTOR ||
4348 !X86::isZeroNode(V1.getOperand(Idx)))
4355 /// getZeroVector - Returns a vector of specified type with all zero elements.
4357 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4359 assert(VT.isVector() && "Expected a vector type");
4361 // Always build SSE zero vectors as <4 x i32> bitcasted
4362 // to their dest type. This ensures they get CSE'd.
4364 if (VT.getSizeInBits() == 128) { // SSE
4365 if (HasXMMInt) { // SSE2
4366 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4367 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4369 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4370 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4372 } else if (VT.getSizeInBits() == 256) { // AVX
4373 // 256-bit logic and arithmetic instructions in AVX are
4374 // all floating-point, no support for integer ops. Default
4375 // to emitting fp zeroed vectors then.
4376 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4377 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4378 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4380 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4383 /// getOnesVector - Returns a vector of specified type with all bits set.
4384 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4385 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4386 /// Then bitcast to their original type, ensuring they get CSE'd.
4387 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4389 assert(VT.isVector() && "Expected a vector type");
4390 assert((VT.is128BitVector() || VT.is256BitVector())
4391 && "Expected a 128-bit or 256-bit vector type");
4393 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4395 if (VT.getSizeInBits() == 256) {
4396 if (HasAVX2) { // AVX2
4397 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4398 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4400 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4402 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4403 Vec = Insert128BitVector(InsV, Vec,
4404 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4407 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4410 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4413 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4414 /// that point to V2 points to its first element.
4415 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4416 EVT VT = SVOp->getValueType(0);
4417 unsigned NumElems = VT.getVectorNumElements();
4419 bool Changed = false;
4420 SmallVector<int, 8> MaskVec;
4421 SVOp->getMask(MaskVec);
4423 for (unsigned i = 0; i != NumElems; ++i) {
4424 if (MaskVec[i] > (int)NumElems) {
4425 MaskVec[i] = NumElems;
4430 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4431 SVOp->getOperand(1), &MaskVec[0]);
4432 return SDValue(SVOp, 0);
4435 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4436 /// operation of specified width.
4437 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4439 unsigned NumElems = VT.getVectorNumElements();
4440 SmallVector<int, 8> Mask;
4441 Mask.push_back(NumElems);
4442 for (unsigned i = 1; i != NumElems; ++i)
4444 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4447 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4448 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4450 unsigned NumElems = VT.getVectorNumElements();
4451 SmallVector<int, 8> Mask;
4452 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4454 Mask.push_back(i + NumElems);
4456 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4459 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4460 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4462 unsigned NumElems = VT.getVectorNumElements();
4463 unsigned Half = NumElems/2;
4464 SmallVector<int, 8> Mask;
4465 for (unsigned i = 0; i != Half; ++i) {
4466 Mask.push_back(i + Half);
4467 Mask.push_back(i + NumElems + Half);
4469 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4472 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4473 // a generic shuffle instruction because the target has no such instructions.
4474 // Generate shuffles which repeat i16 and i8 several times until they can be
4475 // represented by v4f32 and then be manipulated by target suported shuffles.
4476 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4477 EVT VT = V.getValueType();
4478 int NumElems = VT.getVectorNumElements();
4479 DebugLoc dl = V.getDebugLoc();
4481 while (NumElems > 4) {
4482 if (EltNo < NumElems/2) {
4483 V = getUnpackl(DAG, dl, VT, V, V);
4485 V = getUnpackh(DAG, dl, VT, V, V);
4486 EltNo -= NumElems/2;
4493 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4494 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4495 EVT VT = V.getValueType();
4496 DebugLoc dl = V.getDebugLoc();
4497 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4498 && "Vector size not supported");
4500 if (VT.getSizeInBits() == 128) {
4501 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4502 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4503 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4506 // To use VPERMILPS to splat scalars, the second half of indicies must
4507 // refer to the higher part, which is a duplication of the lower one,
4508 // because VPERMILPS can only handle in-lane permutations.
4509 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4510 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4512 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4513 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4517 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4520 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4521 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4522 EVT SrcVT = SV->getValueType(0);
4523 SDValue V1 = SV->getOperand(0);
4524 DebugLoc dl = SV->getDebugLoc();
4526 int EltNo = SV->getSplatIndex();
4527 int NumElems = SrcVT.getVectorNumElements();
4528 unsigned Size = SrcVT.getSizeInBits();
4530 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4531 "Unknown how to promote splat for type");
4533 // Extract the 128-bit part containing the splat element and update
4534 // the splat element index when it refers to the higher register.
4536 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4537 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4539 EltNo -= NumElems/2;
4542 // All i16 and i8 vector types can't be used directly by a generic shuffle
4543 // instruction because the target has no such instruction. Generate shuffles
4544 // which repeat i16 and i8 several times until they fit in i32, and then can
4545 // be manipulated by target suported shuffles.
4546 EVT EltVT = SrcVT.getVectorElementType();
4547 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4548 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4550 // Recreate the 256-bit vector and place the same 128-bit vector
4551 // into the low and high part. This is necessary because we want
4552 // to use VPERM* to shuffle the vectors
4554 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4555 DAG.getConstant(0, MVT::i32), DAG, dl);
4556 V1 = Insert128BitVector(InsV, V1,
4557 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4560 return getLegalSplat(DAG, V1, EltNo);
4563 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4564 /// vector of zero or undef vector. This produces a shuffle where the low
4565 /// element of V2 is swizzled into the zero/undef vector, landing at element
4566 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4567 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4568 bool isZero, bool HasXMMInt,
4569 SelectionDAG &DAG) {
4570 EVT VT = V2.getValueType();
4572 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4573 unsigned NumElems = VT.getVectorNumElements();
4574 SmallVector<int, 16> MaskVec;
4575 for (unsigned i = 0; i != NumElems; ++i)
4576 // If this is the insertion idx, put the low elt of V2 here.
4577 MaskVec.push_back(i == Idx ? NumElems : i);
4578 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4581 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4582 /// element of the result of the vector shuffle.
4583 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4586 return SDValue(); // Limit search depth.
4588 SDValue V = SDValue(N, 0);
4589 EVT VT = V.getValueType();
4590 unsigned Opcode = V.getOpcode();
4592 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4593 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4594 Index = SV->getMaskElt(Index);
4597 return DAG.getUNDEF(VT.getVectorElementType());
4599 int NumElems = VT.getVectorNumElements();
4600 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4601 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4604 // Recurse into target specific vector shuffles to find scalars.
4605 if (isTargetShuffle(Opcode)) {
4606 int NumElems = VT.getVectorNumElements();
4607 SmallVector<unsigned, 16> ShuffleMask;
4611 case X86ISD::SHUFPS:
4612 case X86ISD::SHUFPD:
4613 ImmN = N->getOperand(N->getNumOperands()-1);
4614 DecodeSHUFPSMask(NumElems,
4615 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4618 case X86ISD::PUNPCKH:
4619 DecodePUNPCKHMask(NumElems, ShuffleMask);
4621 case X86ISD::UNPCKHP:
4622 DecodeUNPCKHPMask(VT, ShuffleMask);
4624 case X86ISD::PUNPCKL:
4625 DecodePUNPCKLMask(VT, ShuffleMask);
4627 case X86ISD::UNPCKLP:
4628 DecodeUNPCKLPMask(VT, ShuffleMask);
4630 case X86ISD::MOVHLPS:
4631 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4633 case X86ISD::MOVLHPS:
4634 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4636 case X86ISD::PSHUFD:
4637 ImmN = N->getOperand(N->getNumOperands()-1);
4638 DecodePSHUFMask(NumElems,
4639 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4642 case X86ISD::PSHUFHW:
4643 ImmN = N->getOperand(N->getNumOperands()-1);
4644 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4647 case X86ISD::PSHUFLW:
4648 ImmN = N->getOperand(N->getNumOperands()-1);
4649 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4653 case X86ISD::MOVSD: {
4654 // The index 0 always comes from the first element of the second source,
4655 // this is why MOVSS and MOVSD are used in the first place. The other
4656 // elements come from the other positions of the first source vector.
4657 unsigned OpNum = (Index == 0) ? 1 : 0;
4658 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4661 case X86ISD::VPERMILPS:
4662 ImmN = N->getOperand(N->getNumOperands()-1);
4663 DecodeVPERMILPSMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4666 case X86ISD::VPERMILPD:
4667 ImmN = N->getOperand(N->getNumOperands()-1);
4668 DecodeVPERMILPDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4671 case X86ISD::VPERM2F128:
4672 ImmN = N->getOperand(N->getNumOperands()-1);
4673 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4676 case X86ISD::MOVDDUP:
4677 case X86ISD::MOVLHPD:
4678 case X86ISD::MOVLPD:
4679 case X86ISD::MOVLPS:
4680 case X86ISD::MOVSHDUP:
4681 case X86ISD::MOVSLDUP:
4682 case X86ISD::PALIGN:
4683 return SDValue(); // Not yet implemented.
4685 assert(0 && "unknown target shuffle node");
4689 Index = ShuffleMask[Index];
4691 return DAG.getUNDEF(VT.getVectorElementType());
4693 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4694 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4698 // Actual nodes that may contain scalar elements
4699 if (Opcode == ISD::BITCAST) {
4700 V = V.getOperand(0);
4701 EVT SrcVT = V.getValueType();
4702 unsigned NumElems = VT.getVectorNumElements();
4704 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4708 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4709 return (Index == 0) ? V.getOperand(0)
4710 : DAG.getUNDEF(VT.getVectorElementType());
4712 if (V.getOpcode() == ISD::BUILD_VECTOR)
4713 return V.getOperand(Index);
4718 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4719 /// shuffle operation which come from a consecutively from a zero. The
4720 /// search can start in two different directions, from left or right.
4722 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4723 bool ZerosFromLeft, SelectionDAG &DAG) {
4726 while (i < NumElems) {
4727 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4728 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4729 if (!(Elt.getNode() &&
4730 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4738 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4739 /// MaskE correspond consecutively to elements from one of the vector operands,
4740 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4742 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4743 int OpIdx, int NumElems, unsigned &OpNum) {
4744 bool SeenV1 = false;
4745 bool SeenV2 = false;
4747 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4748 int Idx = SVOp->getMaskElt(i);
4749 // Ignore undef indicies
4758 // Only accept consecutive elements from the same vector
4759 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4763 OpNum = SeenV1 ? 0 : 1;
4767 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4768 /// logical left shift of a vector.
4769 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4770 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4771 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4772 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4773 false /* check zeros from right */, DAG);
4779 // Considering the elements in the mask that are not consecutive zeros,
4780 // check if they consecutively come from only one of the source vectors.
4782 // V1 = {X, A, B, C} 0
4784 // vector_shuffle V1, V2 <1, 2, 3, X>
4786 if (!isShuffleMaskConsecutive(SVOp,
4787 0, // Mask Start Index
4788 NumElems-NumZeros-1, // Mask End Index
4789 NumZeros, // Where to start looking in the src vector
4790 NumElems, // Number of elements in vector
4791 OpSrc)) // Which source operand ?
4796 ShVal = SVOp->getOperand(OpSrc);
4800 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4801 /// logical left shift of a vector.
4802 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4803 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4804 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4805 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4806 true /* check zeros from left */, DAG);
4812 // Considering the elements in the mask that are not consecutive zeros,
4813 // check if they consecutively come from only one of the source vectors.
4815 // 0 { A, B, X, X } = V2
4817 // vector_shuffle V1, V2 <X, X, 4, 5>
4819 if (!isShuffleMaskConsecutive(SVOp,
4820 NumZeros, // Mask Start Index
4821 NumElems-1, // Mask End Index
4822 0, // Where to start looking in the src vector
4823 NumElems, // Number of elements in vector
4824 OpSrc)) // Which source operand ?
4829 ShVal = SVOp->getOperand(OpSrc);
4833 /// isVectorShift - Returns true if the shuffle can be implemented as a
4834 /// logical left or right shift of a vector.
4835 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4836 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4837 // Although the logic below support any bitwidth size, there are no
4838 // shift instructions which handle more than 128-bit vectors.
4839 if (SVOp->getValueType(0).getSizeInBits() > 128)
4842 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4843 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4849 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4851 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4852 unsigned NumNonZero, unsigned NumZero,
4854 const TargetLowering &TLI) {
4858 DebugLoc dl = Op.getDebugLoc();
4861 for (unsigned i = 0; i < 16; ++i) {
4862 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4863 if (ThisIsNonZero && First) {
4865 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4867 V = DAG.getUNDEF(MVT::v8i16);
4872 SDValue ThisElt(0, 0), LastElt(0, 0);
4873 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4874 if (LastIsNonZero) {
4875 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4876 MVT::i16, Op.getOperand(i-1));
4878 if (ThisIsNonZero) {
4879 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4880 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4881 ThisElt, DAG.getConstant(8, MVT::i8));
4883 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4887 if (ThisElt.getNode())
4888 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4889 DAG.getIntPtrConstant(i/2));
4893 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4896 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4898 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4899 unsigned NumNonZero, unsigned NumZero,
4901 const TargetLowering &TLI) {
4905 DebugLoc dl = Op.getDebugLoc();
4908 for (unsigned i = 0; i < 8; ++i) {
4909 bool isNonZero = (NonZeros & (1 << i)) != 0;
4913 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4915 V = DAG.getUNDEF(MVT::v8i16);
4918 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4919 MVT::v8i16, V, Op.getOperand(i),
4920 DAG.getIntPtrConstant(i));
4927 /// getVShift - Return a vector logical shift node.
4929 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4930 unsigned NumBits, SelectionDAG &DAG,
4931 const TargetLowering &TLI, DebugLoc dl) {
4932 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4933 EVT ShVT = MVT::v2i64;
4934 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4935 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4936 return DAG.getNode(ISD::BITCAST, dl, VT,
4937 DAG.getNode(Opc, dl, ShVT, SrcOp,
4938 DAG.getConstant(NumBits,
4939 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4943 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4944 SelectionDAG &DAG) const {
4946 // Check if the scalar load can be widened into a vector load. And if
4947 // the address is "base + cst" see if the cst can be "absorbed" into
4948 // the shuffle mask.
4949 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4950 SDValue Ptr = LD->getBasePtr();
4951 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4953 EVT PVT = LD->getValueType(0);
4954 if (PVT != MVT::i32 && PVT != MVT::f32)
4959 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4960 FI = FINode->getIndex();
4962 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4963 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4964 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4965 Offset = Ptr.getConstantOperandVal(1);
4966 Ptr = Ptr.getOperand(0);
4971 // FIXME: 256-bit vector instructions don't require a strict alignment,
4972 // improve this code to support it better.
4973 unsigned RequiredAlign = VT.getSizeInBits()/8;
4974 SDValue Chain = LD->getChain();
4975 // Make sure the stack object alignment is at least 16 or 32.
4976 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4977 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4978 if (MFI->isFixedObjectIndex(FI)) {
4979 // Can't change the alignment. FIXME: It's possible to compute
4980 // the exact stack offset and reference FI + adjust offset instead.
4981 // If someone *really* cares about this. That's the way to implement it.
4984 MFI->setObjectAlignment(FI, RequiredAlign);
4988 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4989 // Ptr + (Offset & ~15).
4992 if ((Offset % RequiredAlign) & 3)
4994 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4996 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4997 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4999 int EltNo = (Offset - StartOffset) >> 2;
5000 int NumElems = VT.getVectorNumElements();
5002 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5003 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5004 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5005 LD->getPointerInfo().getWithOffset(StartOffset),
5006 false, false, false, 0);
5008 // Canonicalize it to a v4i32 or v8i32 shuffle.
5009 SmallVector<int, 8> Mask;
5010 for (int i = 0; i < NumElems; ++i)
5011 Mask.push_back(EltNo);
5013 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5014 return DAG.getNode(ISD::BITCAST, dl, NVT,
5015 DAG.getVectorShuffle(CanonVT, dl, V1,
5016 DAG.getUNDEF(CanonVT),&Mask[0]));
5022 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5023 /// vector of type 'VT', see if the elements can be replaced by a single large
5024 /// load which has the same value as a build_vector whose operands are 'elts'.
5026 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5028 /// FIXME: we'd also like to handle the case where the last elements are zero
5029 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5030 /// There's even a handy isZeroNode for that purpose.
5031 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5032 DebugLoc &DL, SelectionDAG &DAG) {
5033 EVT EltVT = VT.getVectorElementType();
5034 unsigned NumElems = Elts.size();
5036 LoadSDNode *LDBase = NULL;
5037 unsigned LastLoadedElt = -1U;
5039 // For each element in the initializer, see if we've found a load or an undef.
5040 // If we don't find an initial load element, or later load elements are
5041 // non-consecutive, bail out.
5042 for (unsigned i = 0; i < NumElems; ++i) {
5043 SDValue Elt = Elts[i];
5045 if (!Elt.getNode() ||
5046 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5049 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5051 LDBase = cast<LoadSDNode>(Elt.getNode());
5055 if (Elt.getOpcode() == ISD::UNDEF)
5058 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5059 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5064 // If we have found an entire vector of loads and undefs, then return a large
5065 // load of the entire vector width starting at the base pointer. If we found
5066 // consecutive loads for the low half, generate a vzext_load node.
5067 if (LastLoadedElt == NumElems - 1) {
5068 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5069 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5070 LDBase->getPointerInfo(),
5071 LDBase->isVolatile(), LDBase->isNonTemporal(),
5072 LDBase->isInvariant(), 0);
5073 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5074 LDBase->getPointerInfo(),
5075 LDBase->isVolatile(), LDBase->isNonTemporal(),
5076 LDBase->isInvariant(), LDBase->getAlignment());
5077 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5078 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5079 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5080 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5082 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5083 LDBase->getPointerInfo(),
5084 LDBase->getAlignment(),
5085 false/*isVolatile*/, true/*ReadMem*/,
5087 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5092 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5093 /// a vbroadcast node. We support two patterns:
5094 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5095 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5097 /// The scalar load node is returned when a pattern is found,
5098 /// or SDValue() otherwise.
5099 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5100 EVT VT = Op.getValueType();
5103 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5104 V = V.getOperand(0);
5106 //A suspected load to be broadcasted.
5109 switch (V.getOpcode()) {
5111 // Unknown pattern found.
5114 case ISD::BUILD_VECTOR: {
5115 // The BUILD_VECTOR node must be a splat.
5116 if (!isSplatVector(V.getNode()))
5119 Ld = V.getOperand(0);
5121 // The suspected load node has several users. Make sure that all
5122 // of its users are from the BUILD_VECTOR node.
5123 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5128 case ISD::VECTOR_SHUFFLE: {
5129 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5131 // Shuffles must have a splat mask where the first element is
5133 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5136 SDValue Sc = Op.getOperand(0);
5137 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5140 Ld = Sc.getOperand(0);
5142 // The scalar_to_vector node and the suspected
5143 // load node must have exactly one user.
5144 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5150 // The scalar source must be a normal load.
5151 if (!ISD::isNormalLoad(Ld.getNode()))
5154 bool Is256 = VT.getSizeInBits() == 256;
5155 bool Is128 = VT.getSizeInBits() == 128;
5156 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5159 // VBroadcast to YMM
5160 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5161 ScalarSize == 32 || ScalarSize == 64 ))
5164 // VBroadcast to XMM
5165 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5166 ScalarSize == 16 || ScalarSize == 64 ))
5170 // VBroadcast to YMM
5171 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5174 // VBroadcast to XMM
5175 if (Is128 && (ScalarSize == 32))
5179 // Unsupported broadcast.
5184 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5185 DebugLoc dl = Op.getDebugLoc();
5187 EVT VT = Op.getValueType();
5188 EVT ExtVT = VT.getVectorElementType();
5189 unsigned NumElems = Op.getNumOperands();
5191 // Vectors containing all zeros can be matched by pxor and xorps later
5192 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5193 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5194 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5195 if (Op.getValueType() == MVT::v4i32 ||
5196 Op.getValueType() == MVT::v8i32)
5199 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5202 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5203 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5204 // vpcmpeqd on 256-bit vectors.
5205 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5206 if (Op.getValueType() == MVT::v4i32 ||
5207 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5210 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5213 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5214 if (Subtarget->hasAVX() && LD.getNode())
5215 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5217 unsigned EVTBits = ExtVT.getSizeInBits();
5219 unsigned NumZero = 0;
5220 unsigned NumNonZero = 0;
5221 unsigned NonZeros = 0;
5222 bool IsAllConstants = true;
5223 SmallSet<SDValue, 8> Values;
5224 for (unsigned i = 0; i < NumElems; ++i) {
5225 SDValue Elt = Op.getOperand(i);
5226 if (Elt.getOpcode() == ISD::UNDEF)
5229 if (Elt.getOpcode() != ISD::Constant &&
5230 Elt.getOpcode() != ISD::ConstantFP)
5231 IsAllConstants = false;
5232 if (X86::isZeroNode(Elt))
5235 NonZeros |= (1 << i);
5240 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5241 if (NumNonZero == 0)
5242 return DAG.getUNDEF(VT);
5244 // Special case for single non-zero, non-undef, element.
5245 if (NumNonZero == 1) {
5246 unsigned Idx = CountTrailingZeros_32(NonZeros);
5247 SDValue Item = Op.getOperand(Idx);
5249 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5250 // the value are obviously zero, truncate the value to i32 and do the
5251 // insertion that way. Only do this if the value is non-constant or if the
5252 // value is a constant being inserted into element 0. It is cheaper to do
5253 // a constant pool load than it is to do a movd + shuffle.
5254 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5255 (!IsAllConstants || Idx == 0)) {
5256 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5258 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5259 EVT VecVT = MVT::v4i32;
5260 unsigned VecElts = 4;
5262 // Truncate the value (which may itself be a constant) to i32, and
5263 // convert it to a vector with movd (S2V+shuffle to zero extend).
5264 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5265 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5266 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5267 Subtarget->hasXMMInt(), DAG);
5269 // Now we have our 32-bit value zero extended in the low element of
5270 // a vector. If Idx != 0, swizzle it into place.
5272 SmallVector<int, 4> Mask;
5273 Mask.push_back(Idx);
5274 for (unsigned i = 1; i != VecElts; ++i)
5276 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5277 DAG.getUNDEF(Item.getValueType()),
5280 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5284 // If we have a constant or non-constant insertion into the low element of
5285 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5286 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5287 // depending on what the source datatype is.
5290 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5291 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5292 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5293 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5294 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5295 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5297 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5298 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5299 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5300 EVT MiddleVT = MVT::v4i32;
5301 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5302 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5303 Subtarget->hasXMMInt(), DAG);
5304 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5308 // Is it a vector logical left shift?
5309 if (NumElems == 2 && Idx == 1 &&
5310 X86::isZeroNode(Op.getOperand(0)) &&
5311 !X86::isZeroNode(Op.getOperand(1))) {
5312 unsigned NumBits = VT.getSizeInBits();
5313 return getVShift(true, VT,
5314 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5315 VT, Op.getOperand(1)),
5316 NumBits/2, DAG, *this, dl);
5319 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5322 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5323 // is a non-constant being inserted into an element other than the low one,
5324 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5325 // movd/movss) to move this into the low element, then shuffle it into
5327 if (EVTBits == 32) {
5328 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5330 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5331 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5332 Subtarget->hasXMMInt(), DAG);
5333 SmallVector<int, 8> MaskVec;
5334 for (unsigned i = 0; i < NumElems; i++)
5335 MaskVec.push_back(i == Idx ? 0 : 1);
5336 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5340 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5341 if (Values.size() == 1) {
5342 if (EVTBits == 32) {
5343 // Instead of a shuffle like this:
5344 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5345 // Check if it's possible to issue this instead.
5346 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5347 unsigned Idx = CountTrailingZeros_32(NonZeros);
5348 SDValue Item = Op.getOperand(Idx);
5349 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5350 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5355 // A vector full of immediates; various special cases are already
5356 // handled, so this is best done with a single constant-pool load.
5360 // For AVX-length vectors, build the individual 128-bit pieces and use
5361 // shuffles to put them in place.
5362 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5363 SmallVector<SDValue, 32> V;
5364 for (unsigned i = 0; i < NumElems; ++i)
5365 V.push_back(Op.getOperand(i));
5367 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5369 // Build both the lower and upper subvector.
5370 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5371 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5374 // Recreate the wider vector with the lower and upper part.
5375 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5376 DAG.getConstant(0, MVT::i32), DAG, dl);
5377 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5381 // Let legalizer expand 2-wide build_vectors.
5382 if (EVTBits == 64) {
5383 if (NumNonZero == 1) {
5384 // One half is zero or undef.
5385 unsigned Idx = CountTrailingZeros_32(NonZeros);
5386 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5387 Op.getOperand(Idx));
5388 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5389 Subtarget->hasXMMInt(), DAG);
5394 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5395 if (EVTBits == 8 && NumElems == 16) {
5396 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5398 if (V.getNode()) return V;
5401 if (EVTBits == 16 && NumElems == 8) {
5402 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5404 if (V.getNode()) return V;
5407 // If element VT is == 32 bits, turn it into a number of shuffles.
5408 SmallVector<SDValue, 8> V;
5410 if (NumElems == 4 && NumZero > 0) {
5411 for (unsigned i = 0; i < 4; ++i) {
5412 bool isZero = !(NonZeros & (1 << i));
5414 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5416 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5419 for (unsigned i = 0; i < 2; ++i) {
5420 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5423 V[i] = V[i*2]; // Must be a zero vector.
5426 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5429 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5432 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5437 SmallVector<int, 8> MaskVec;
5438 bool Reverse = (NonZeros & 0x3) == 2;
5439 for (unsigned i = 0; i < 2; ++i)
5440 MaskVec.push_back(Reverse ? 1-i : i);
5441 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5442 for (unsigned i = 0; i < 2; ++i)
5443 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5444 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5447 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5448 // Check for a build vector of consecutive loads.
5449 for (unsigned i = 0; i < NumElems; ++i)
5450 V[i] = Op.getOperand(i);
5452 // Check for elements which are consecutive loads.
5453 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5457 // For SSE 4.1, use insertps to put the high elements into the low element.
5458 if (getSubtarget()->hasSSE41orAVX()) {
5460 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5461 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5463 Result = DAG.getUNDEF(VT);
5465 for (unsigned i = 1; i < NumElems; ++i) {
5466 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5467 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5468 Op.getOperand(i), DAG.getIntPtrConstant(i));
5473 // Otherwise, expand into a number of unpckl*, start by extending each of
5474 // our (non-undef) elements to the full vector width with the element in the
5475 // bottom slot of the vector (which generates no code for SSE).
5476 for (unsigned i = 0; i < NumElems; ++i) {
5477 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5478 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5480 V[i] = DAG.getUNDEF(VT);
5483 // Next, we iteratively mix elements, e.g. for v4f32:
5484 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5485 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5486 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5487 unsigned EltStride = NumElems >> 1;
5488 while (EltStride != 0) {
5489 for (unsigned i = 0; i < EltStride; ++i) {
5490 // If V[i+EltStride] is undef and this is the first round of mixing,
5491 // then it is safe to just drop this shuffle: V[i] is already in the
5492 // right place, the one element (since it's the first round) being
5493 // inserted as undef can be dropped. This isn't safe for successive
5494 // rounds because they will permute elements within both vectors.
5495 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5496 EltStride == NumElems/2)
5499 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5508 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5509 // them in a MMX register. This is better than doing a stack convert.
5510 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5511 DebugLoc dl = Op.getDebugLoc();
5512 EVT ResVT = Op.getValueType();
5514 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5515 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5517 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5518 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5519 InVec = Op.getOperand(1);
5520 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5521 unsigned NumElts = ResVT.getVectorNumElements();
5522 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5523 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5524 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5526 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5527 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5528 Mask[0] = 0; Mask[1] = 2;
5529 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5531 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5534 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5535 // to create 256-bit vectors from two other 128-bit ones.
5536 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5537 DebugLoc dl = Op.getDebugLoc();
5538 EVT ResVT = Op.getValueType();
5540 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5542 SDValue V1 = Op.getOperand(0);
5543 SDValue V2 = Op.getOperand(1);
5544 unsigned NumElems = ResVT.getVectorNumElements();
5546 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5547 DAG.getConstant(0, MVT::i32), DAG, dl);
5548 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5553 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5554 EVT ResVT = Op.getValueType();
5556 assert(Op.getNumOperands() == 2);
5557 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5558 "Unsupported CONCAT_VECTORS for value type");
5560 // We support concatenate two MMX registers and place them in a MMX register.
5561 // This is better than doing a stack convert.
5562 if (ResVT.is128BitVector())
5563 return LowerMMXCONCAT_VECTORS(Op, DAG);
5565 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5566 // from two other 128-bit ones.
5567 return LowerAVXCONCAT_VECTORS(Op, DAG);
5570 // v8i16 shuffles - Prefer shuffles in the following order:
5571 // 1. [all] pshuflw, pshufhw, optional move
5572 // 2. [ssse3] 1 x pshufb
5573 // 3. [ssse3] 2 x pshufb + 1 x por
5574 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5576 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5577 SelectionDAG &DAG) const {
5578 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5579 SDValue V1 = SVOp->getOperand(0);
5580 SDValue V2 = SVOp->getOperand(1);
5581 DebugLoc dl = SVOp->getDebugLoc();
5582 SmallVector<int, 8> MaskVals;
5584 // Determine if more than 1 of the words in each of the low and high quadwords
5585 // of the result come from the same quadword of one of the two inputs. Undef
5586 // mask values count as coming from any quadword, for better codegen.
5587 unsigned LoQuad[] = { 0, 0, 0, 0 };
5588 unsigned HiQuad[] = { 0, 0, 0, 0 };
5589 BitVector InputQuads(4);
5590 for (unsigned i = 0; i < 8; ++i) {
5591 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5592 int EltIdx = SVOp->getMaskElt(i);
5593 MaskVals.push_back(EltIdx);
5602 InputQuads.set(EltIdx / 4);
5605 int BestLoQuad = -1;
5606 unsigned MaxQuad = 1;
5607 for (unsigned i = 0; i < 4; ++i) {
5608 if (LoQuad[i] > MaxQuad) {
5610 MaxQuad = LoQuad[i];
5614 int BestHiQuad = -1;
5616 for (unsigned i = 0; i < 4; ++i) {
5617 if (HiQuad[i] > MaxQuad) {
5619 MaxQuad = HiQuad[i];
5623 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5624 // of the two input vectors, shuffle them into one input vector so only a
5625 // single pshufb instruction is necessary. If There are more than 2 input
5626 // quads, disable the next transformation since it does not help SSSE3.
5627 bool V1Used = InputQuads[0] || InputQuads[1];
5628 bool V2Used = InputQuads[2] || InputQuads[3];
5629 if (Subtarget->hasSSSE3orAVX()) {
5630 if (InputQuads.count() == 2 && V1Used && V2Used) {
5631 BestLoQuad = InputQuads.find_first();
5632 BestHiQuad = InputQuads.find_next(BestLoQuad);
5634 if (InputQuads.count() > 2) {
5640 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5641 // the shuffle mask. If a quad is scored as -1, that means that it contains
5642 // words from all 4 input quadwords.
5644 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5645 SmallVector<int, 8> MaskV;
5646 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5647 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5648 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5649 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5650 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5651 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5653 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5654 // source words for the shuffle, to aid later transformations.
5655 bool AllWordsInNewV = true;
5656 bool InOrder[2] = { true, true };
5657 for (unsigned i = 0; i != 8; ++i) {
5658 int idx = MaskVals[i];
5660 InOrder[i/4] = false;
5661 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5663 AllWordsInNewV = false;
5667 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5668 if (AllWordsInNewV) {
5669 for (int i = 0; i != 8; ++i) {
5670 int idx = MaskVals[i];
5673 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5674 if ((idx != i) && idx < 4)
5676 if ((idx != i) && idx > 3)
5685 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5686 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5687 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5688 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5689 unsigned TargetMask = 0;
5690 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5691 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5692 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5693 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5694 V1 = NewV.getOperand(0);
5695 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5699 // If we have SSSE3, and all words of the result are from 1 input vector,
5700 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5701 // is present, fall back to case 4.
5702 if (Subtarget->hasSSSE3orAVX()) {
5703 SmallVector<SDValue,16> pshufbMask;
5705 // If we have elements from both input vectors, set the high bit of the
5706 // shuffle mask element to zero out elements that come from V2 in the V1
5707 // mask, and elements that come from V1 in the V2 mask, so that the two
5708 // results can be OR'd together.
5709 bool TwoInputs = V1Used && V2Used;
5710 for (unsigned i = 0; i != 8; ++i) {
5711 int EltIdx = MaskVals[i] * 2;
5712 if (TwoInputs && (EltIdx >= 16)) {
5713 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5714 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5717 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5718 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5720 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5721 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5722 DAG.getNode(ISD::BUILD_VECTOR, dl,
5723 MVT::v16i8, &pshufbMask[0], 16));
5725 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5727 // Calculate the shuffle mask for the second input, shuffle it, and
5728 // OR it with the first shuffled input.
5730 for (unsigned i = 0; i != 8; ++i) {
5731 int EltIdx = MaskVals[i] * 2;
5733 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5734 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5737 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5738 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5740 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5741 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5742 DAG.getNode(ISD::BUILD_VECTOR, dl,
5743 MVT::v16i8, &pshufbMask[0], 16));
5744 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5745 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5748 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5749 // and update MaskVals with new element order.
5750 BitVector InOrder(8);
5751 if (BestLoQuad >= 0) {
5752 SmallVector<int, 8> MaskV;
5753 for (int i = 0; i != 4; ++i) {
5754 int idx = MaskVals[i];
5756 MaskV.push_back(-1);
5758 } else if ((idx / 4) == BestLoQuad) {
5759 MaskV.push_back(idx & 3);
5762 MaskV.push_back(-1);
5765 for (unsigned i = 4; i != 8; ++i)
5767 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5770 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5771 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5773 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5777 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5778 // and update MaskVals with the new element order.
5779 if (BestHiQuad >= 0) {
5780 SmallVector<int, 8> MaskV;
5781 for (unsigned i = 0; i != 4; ++i)
5783 for (unsigned i = 4; i != 8; ++i) {
5784 int idx = MaskVals[i];
5786 MaskV.push_back(-1);
5788 } else if ((idx / 4) == BestHiQuad) {
5789 MaskV.push_back((idx & 3) + 4);
5792 MaskV.push_back(-1);
5795 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5798 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5799 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5801 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5805 // In case BestHi & BestLo were both -1, which means each quadword has a word
5806 // from each of the four input quadwords, calculate the InOrder bitvector now
5807 // before falling through to the insert/extract cleanup.
5808 if (BestLoQuad == -1 && BestHiQuad == -1) {
5810 for (int i = 0; i != 8; ++i)
5811 if (MaskVals[i] < 0 || MaskVals[i] == i)
5815 // The other elements are put in the right place using pextrw and pinsrw.
5816 for (unsigned i = 0; i != 8; ++i) {
5819 int EltIdx = MaskVals[i];
5822 SDValue ExtOp = (EltIdx < 8)
5823 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5824 DAG.getIntPtrConstant(EltIdx))
5825 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5826 DAG.getIntPtrConstant(EltIdx - 8));
5827 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5828 DAG.getIntPtrConstant(i));
5833 // v16i8 shuffles - Prefer shuffles in the following order:
5834 // 1. [ssse3] 1 x pshufb
5835 // 2. [ssse3] 2 x pshufb + 1 x por
5836 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5838 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5840 const X86TargetLowering &TLI) {
5841 SDValue V1 = SVOp->getOperand(0);
5842 SDValue V2 = SVOp->getOperand(1);
5843 DebugLoc dl = SVOp->getDebugLoc();
5844 SmallVector<int, 16> MaskVals;
5845 SVOp->getMask(MaskVals);
5847 // If we have SSSE3, case 1 is generated when all result bytes come from
5848 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5849 // present, fall back to case 3.
5850 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5853 for (unsigned i = 0; i < 16; ++i) {
5854 int EltIdx = MaskVals[i];
5863 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5864 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5865 SmallVector<SDValue,16> pshufbMask;
5867 // If all result elements are from one input vector, then only translate
5868 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5870 // Otherwise, we have elements from both input vectors, and must zero out
5871 // elements that come from V2 in the first mask, and V1 in the second mask
5872 // so that we can OR them together.
5873 bool TwoInputs = !(V1Only || V2Only);
5874 for (unsigned i = 0; i != 16; ++i) {
5875 int EltIdx = MaskVals[i];
5876 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5877 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5880 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5882 // If all the elements are from V2, assign it to V1 and return after
5883 // building the first pshufb.
5886 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5887 DAG.getNode(ISD::BUILD_VECTOR, dl,
5888 MVT::v16i8, &pshufbMask[0], 16));
5892 // Calculate the shuffle mask for the second input, shuffle it, and
5893 // OR it with the first shuffled input.
5895 for (unsigned i = 0; i != 16; ++i) {
5896 int EltIdx = MaskVals[i];
5898 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5901 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5903 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5904 DAG.getNode(ISD::BUILD_VECTOR, dl,
5905 MVT::v16i8, &pshufbMask[0], 16));
5906 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5909 // No SSSE3 - Calculate in place words and then fix all out of place words
5910 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5911 // the 16 different words that comprise the two doublequadword input vectors.
5912 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5913 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5914 SDValue NewV = V2Only ? V2 : V1;
5915 for (int i = 0; i != 8; ++i) {
5916 int Elt0 = MaskVals[i*2];
5917 int Elt1 = MaskVals[i*2+1];
5919 // This word of the result is all undef, skip it.
5920 if (Elt0 < 0 && Elt1 < 0)
5923 // This word of the result is already in the correct place, skip it.
5924 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5926 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5929 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5930 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5933 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5934 // using a single extract together, load it and store it.
5935 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5936 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5937 DAG.getIntPtrConstant(Elt1 / 2));
5938 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5939 DAG.getIntPtrConstant(i));
5943 // If Elt1 is defined, extract it from the appropriate source. If the
5944 // source byte is not also odd, shift the extracted word left 8 bits
5945 // otherwise clear the bottom 8 bits if we need to do an or.
5947 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5948 DAG.getIntPtrConstant(Elt1 / 2));
5949 if ((Elt1 & 1) == 0)
5950 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5952 TLI.getShiftAmountTy(InsElt.getValueType())));
5954 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5955 DAG.getConstant(0xFF00, MVT::i16));
5957 // If Elt0 is defined, extract it from the appropriate source. If the
5958 // source byte is not also even, shift the extracted word right 8 bits. If
5959 // Elt1 was also defined, OR the extracted values together before
5960 // inserting them in the result.
5962 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5963 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5964 if ((Elt0 & 1) != 0)
5965 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5967 TLI.getShiftAmountTy(InsElt0.getValueType())));
5969 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5970 DAG.getConstant(0x00FF, MVT::i16));
5971 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5974 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5975 DAG.getIntPtrConstant(i));
5977 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5980 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5981 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5982 /// done when every pair / quad of shuffle mask elements point to elements in
5983 /// the right sequence. e.g.
5984 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5986 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5987 SelectionDAG &DAG, DebugLoc dl) {
5988 EVT VT = SVOp->getValueType(0);
5989 SDValue V1 = SVOp->getOperand(0);
5990 SDValue V2 = SVOp->getOperand(1);
5991 unsigned NumElems = VT.getVectorNumElements();
5992 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5994 switch (VT.getSimpleVT().SimpleTy) {
5995 default: assert(false && "Unexpected!");
5996 case MVT::v4f32: NewVT = MVT::v2f64; break;
5997 case MVT::v4i32: NewVT = MVT::v2i64; break;
5998 case MVT::v8i16: NewVT = MVT::v4i32; break;
5999 case MVT::v16i8: NewVT = MVT::v4i32; break;
6002 int Scale = NumElems / NewWidth;
6003 SmallVector<int, 8> MaskVec;
6004 for (unsigned i = 0; i < NumElems; i += Scale) {
6006 for (int j = 0; j < Scale; ++j) {
6007 int EltIdx = SVOp->getMaskElt(i+j);
6011 StartIdx = EltIdx - (EltIdx % Scale);
6012 if (EltIdx != StartIdx + j)
6016 MaskVec.push_back(-1);
6018 MaskVec.push_back(StartIdx / Scale);
6021 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6022 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6023 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6026 /// getVZextMovL - Return a zero-extending vector move low node.
6028 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6029 SDValue SrcOp, SelectionDAG &DAG,
6030 const X86Subtarget *Subtarget, DebugLoc dl) {
6031 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6032 LoadSDNode *LD = NULL;
6033 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6034 LD = dyn_cast<LoadSDNode>(SrcOp);
6036 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6038 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6039 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6040 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6041 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6042 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6044 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6045 return DAG.getNode(ISD::BITCAST, dl, VT,
6046 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6047 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6055 return DAG.getNode(ISD::BITCAST, dl, VT,
6056 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6057 DAG.getNode(ISD::BITCAST, dl,
6061 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6062 /// shuffle node referes to only one lane in the sources.
6063 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6064 EVT VT = SVOp->getValueType(0);
6065 int NumElems = VT.getVectorNumElements();
6066 int HalfSize = NumElems/2;
6067 SmallVector<int, 16> M;
6069 bool MatchA = false, MatchB = false;
6071 for (int l = 0; l < NumElems*2; l += HalfSize) {
6072 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6078 for (int l = 0; l < NumElems*2; l += HalfSize) {
6079 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6085 return MatchA && MatchB;
6088 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6089 /// which could not be matched by any known target speficic shuffle
6091 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6092 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6093 // If each half of a vector shuffle node referes to only one lane in the
6094 // source vectors, extract each used 128-bit lane and shuffle them using
6095 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6096 // the work to the legalizer.
6097 DebugLoc dl = SVOp->getDebugLoc();
6098 EVT VT = SVOp->getValueType(0);
6099 int NumElems = VT.getVectorNumElements();
6100 int HalfSize = NumElems/2;
6102 // Extract the reference for each half
6103 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6104 int FstVecOpNum = 0, SndVecOpNum = 0;
6105 for (int i = 0; i < HalfSize; ++i) {
6106 int Elt = SVOp->getMaskElt(i);
6107 if (SVOp->getMaskElt(i) < 0)
6109 FstVecOpNum = Elt/NumElems;
6110 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6113 for (int i = HalfSize; i < NumElems; ++i) {
6114 int Elt = SVOp->getMaskElt(i);
6115 if (SVOp->getMaskElt(i) < 0)
6117 SndVecOpNum = Elt/NumElems;
6118 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6122 // Extract the subvectors
6123 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6124 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6125 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6126 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6128 // Generate 128-bit shuffles
6129 SmallVector<int, 16> MaskV1, MaskV2;
6130 for (int i = 0; i < HalfSize; ++i) {
6131 int Elt = SVOp->getMaskElt(i);
6132 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6134 for (int i = HalfSize; i < NumElems; ++i) {
6135 int Elt = SVOp->getMaskElt(i);
6136 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6139 EVT NVT = V1.getValueType();
6140 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6141 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6143 // Concatenate the result back
6144 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6145 DAG.getConstant(0, MVT::i32), DAG, dl);
6146 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6153 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6154 /// 4 elements, and match them with several different shuffle types.
6156 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6157 SDValue V1 = SVOp->getOperand(0);
6158 SDValue V2 = SVOp->getOperand(1);
6159 DebugLoc dl = SVOp->getDebugLoc();
6160 EVT VT = SVOp->getValueType(0);
6162 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6164 SmallVector<std::pair<int, int>, 8> Locs;
6166 SmallVector<int, 8> Mask1(4U, -1);
6167 SmallVector<int, 8> PermMask;
6168 SVOp->getMask(PermMask);
6172 for (unsigned i = 0; i != 4; ++i) {
6173 int Idx = PermMask[i];
6175 Locs[i] = std::make_pair(-1, -1);
6177 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6179 Locs[i] = std::make_pair(0, NumLo);
6183 Locs[i] = std::make_pair(1, NumHi);
6185 Mask1[2+NumHi] = Idx;
6191 if (NumLo <= 2 && NumHi <= 2) {
6192 // If no more than two elements come from either vector. This can be
6193 // implemented with two shuffles. First shuffle gather the elements.
6194 // The second shuffle, which takes the first shuffle as both of its
6195 // vector operands, put the elements into the right order.
6196 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6198 SmallVector<int, 8> Mask2(4U, -1);
6200 for (unsigned i = 0; i != 4; ++i) {
6201 if (Locs[i].first == -1)
6204 unsigned Idx = (i < 2) ? 0 : 4;
6205 Idx += Locs[i].first * 2 + Locs[i].second;
6210 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6211 } else if (NumLo == 3 || NumHi == 3) {
6212 // Otherwise, we must have three elements from one vector, call it X, and
6213 // one element from the other, call it Y. First, use a shufps to build an
6214 // intermediate vector with the one element from Y and the element from X
6215 // that will be in the same half in the final destination (the indexes don't
6216 // matter). Then, use a shufps to build the final vector, taking the half
6217 // containing the element from Y from the intermediate, and the other half
6220 // Normalize it so the 3 elements come from V1.
6221 CommuteVectorShuffleMask(PermMask, VT);
6225 // Find the element from V2.
6227 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6228 int Val = PermMask[HiIndex];
6235 Mask1[0] = PermMask[HiIndex];
6237 Mask1[2] = PermMask[HiIndex^1];
6239 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6242 Mask1[0] = PermMask[0];
6243 Mask1[1] = PermMask[1];
6244 Mask1[2] = HiIndex & 1 ? 6 : 4;
6245 Mask1[3] = HiIndex & 1 ? 4 : 6;
6246 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6248 Mask1[0] = HiIndex & 1 ? 2 : 0;
6249 Mask1[1] = HiIndex & 1 ? 0 : 2;
6250 Mask1[2] = PermMask[2];
6251 Mask1[3] = PermMask[3];
6256 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6260 // Break it into (shuffle shuffle_hi, shuffle_lo).
6263 SmallVector<int,8> LoMask(4U, -1);
6264 SmallVector<int,8> HiMask(4U, -1);
6266 SmallVector<int,8> *MaskPtr = &LoMask;
6267 unsigned MaskIdx = 0;
6270 for (unsigned i = 0; i != 4; ++i) {
6277 int Idx = PermMask[i];
6279 Locs[i] = std::make_pair(-1, -1);
6280 } else if (Idx < 4) {
6281 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6282 (*MaskPtr)[LoIdx] = Idx;
6285 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6286 (*MaskPtr)[HiIdx] = Idx;
6291 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6292 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6293 SmallVector<int, 8> MaskOps;
6294 for (unsigned i = 0; i != 4; ++i) {
6295 if (Locs[i].first == -1) {
6296 MaskOps.push_back(-1);
6298 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6299 MaskOps.push_back(Idx);
6302 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6305 static bool MayFoldVectorLoad(SDValue V) {
6306 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6307 V = V.getOperand(0);
6308 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6309 V = V.getOperand(0);
6310 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6311 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6312 // BUILD_VECTOR (load), undef
6313 V = V.getOperand(0);
6319 // FIXME: the version above should always be used. Since there's
6320 // a bug where several vector shuffles can't be folded because the
6321 // DAG is not updated during lowering and a node claims to have two
6322 // uses while it only has one, use this version, and let isel match
6323 // another instruction if the load really happens to have more than
6324 // one use. Remove this version after this bug get fixed.
6325 // rdar://8434668, PR8156
6326 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6327 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6328 V = V.getOperand(0);
6329 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6330 V = V.getOperand(0);
6331 if (ISD::isNormalLoad(V.getNode()))
6336 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6337 /// a vector extract, and if both can be later optimized into a single load.
6338 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6339 /// here because otherwise a target specific shuffle node is going to be
6340 /// emitted for this shuffle, and the optimization not done.
6341 /// FIXME: This is probably not the best approach, but fix the problem
6342 /// until the right path is decided.
6344 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6345 const TargetLowering &TLI) {
6346 EVT VT = V.getValueType();
6347 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6349 // Be sure that the vector shuffle is present in a pattern like this:
6350 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6354 SDNode *N = *V.getNode()->use_begin();
6355 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6358 SDValue EltNo = N->getOperand(1);
6359 if (!isa<ConstantSDNode>(EltNo))
6362 // If the bit convert changed the number of elements, it is unsafe
6363 // to examine the mask.
6364 bool HasShuffleIntoBitcast = false;
6365 if (V.getOpcode() == ISD::BITCAST) {
6366 EVT SrcVT = V.getOperand(0).getValueType();
6367 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6369 V = V.getOperand(0);
6370 HasShuffleIntoBitcast = true;
6373 // Select the input vector, guarding against out of range extract vector.
6374 unsigned NumElems = VT.getVectorNumElements();
6375 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6376 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6377 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6379 // Skip one more bit_convert if necessary
6380 if (V.getOpcode() == ISD::BITCAST)
6381 V = V.getOperand(0);
6383 if (ISD::isNormalLoad(V.getNode())) {
6384 // Is the original load suitable?
6385 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6387 // FIXME: avoid the multi-use bug that is preventing lots of
6388 // of foldings to be detected, this is still wrong of course, but
6389 // give the temporary desired behavior, and if it happens that
6390 // the load has real more uses, during isel it will not fold, and
6391 // will generate poor code.
6392 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6395 if (!HasShuffleIntoBitcast)
6398 // If there's a bitcast before the shuffle, check if the load type and
6399 // alignment is valid.
6400 unsigned Align = LN0->getAlignment();
6402 TLI.getTargetData()->getABITypeAlignment(
6403 VT.getTypeForEVT(*DAG.getContext()));
6405 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6413 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6414 EVT VT = Op.getValueType();
6416 // Canonizalize to v2f64.
6417 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6418 return DAG.getNode(ISD::BITCAST, dl, VT,
6419 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6424 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6426 SDValue V1 = Op.getOperand(0);
6427 SDValue V2 = Op.getOperand(1);
6428 EVT VT = Op.getValueType();
6430 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6432 if (HasXMMInt && VT == MVT::v2f64)
6433 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6435 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6436 return DAG.getNode(ISD::BITCAST, dl, VT,
6437 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6438 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6439 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6443 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6444 SDValue V1 = Op.getOperand(0);
6445 SDValue V2 = Op.getOperand(1);
6446 EVT VT = Op.getValueType();
6448 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6449 "unsupported shuffle type");
6451 if (V2.getOpcode() == ISD::UNDEF)
6455 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6458 static inline unsigned getSHUFPOpcode(EVT VT) {
6459 switch(VT.getSimpleVT().SimpleTy) {
6460 case MVT::v8i32: // Use fp unit for int unpack.
6462 case MVT::v4i32: // Use fp unit for int unpack.
6463 case MVT::v4f32: return X86ISD::SHUFPS;
6464 case MVT::v4i64: // Use fp unit for int unpack.
6466 case MVT::v2i64: // Use fp unit for int unpack.
6467 case MVT::v2f64: return X86ISD::SHUFPD;
6469 llvm_unreachable("Unknown type for shufp*");
6475 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6476 SDValue V1 = Op.getOperand(0);
6477 SDValue V2 = Op.getOperand(1);
6478 EVT VT = Op.getValueType();
6479 unsigned NumElems = VT.getVectorNumElements();
6481 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6482 // operand of these instructions is only memory, so check if there's a
6483 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6485 bool CanFoldLoad = false;
6487 // Trivial case, when V2 comes from a load.
6488 if (MayFoldVectorLoad(V2))
6491 // When V1 is a load, it can be folded later into a store in isel, example:
6492 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6494 // (MOVLPSmr addr:$src1, VR128:$src2)
6495 // So, recognize this potential and also use MOVLPS or MOVLPD
6496 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6499 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6501 if (HasXMMInt && NumElems == 2)
6502 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6505 // If we don't care about the second element, procede to use movss.
6506 if (SVOp->getMaskElt(1) != -1)
6507 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6510 // movl and movlp will both match v2i64, but v2i64 is never matched by
6511 // movl earlier because we make it strict to avoid messing with the movlp load
6512 // folding logic (see the code above getMOVLP call). Match it here then,
6513 // this is horrible, but will stay like this until we move all shuffle
6514 // matching to x86 specific nodes. Note that for the 1st condition all
6515 // types are matched with movsd.
6517 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6518 // as to remove this logic from here, as much as possible
6519 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6520 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6521 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6524 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6526 // Invert the operand order and use SHUFPS to match it.
6527 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6528 X86::getShuffleSHUFImmediate(SVOp), DAG);
6531 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6532 switch(VT.getSimpleVT().SimpleTy) {
6538 case MVT::v2i64: return X86ISD::PUNPCKL;
6541 if (HasAVX2) return X86ISD::PUNPCKL;
6542 // else use fp unit for int unpack.
6546 case MVT::v2f64: return X86ISD::UNPCKLP;
6548 llvm_unreachable("Unknown type for unpckl");
6553 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6554 switch(VT.getSimpleVT().SimpleTy) {
6560 case MVT::v2i64: return X86ISD::PUNPCKH;
6563 if (HasAVX2) return X86ISD::PUNPCKH;
6564 // else use fp unit for int unpack.
6568 case MVT::v2f64: return X86ISD::UNPCKHP;
6570 llvm_unreachable("Unknown type for unpckh");
6575 static inline unsigned getVPERMILOpcode(EVT VT) {
6576 switch(VT.getSimpleVT().SimpleTy) {
6580 case MVT::v8f32: return X86ISD::VPERMILPS;
6584 case MVT::v4f64: return X86ISD::VPERMILPD;
6586 llvm_unreachable("Unknown type for vpermil");
6592 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6593 const TargetLowering &TLI,
6594 const X86Subtarget *Subtarget) {
6595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6596 EVT VT = Op.getValueType();
6597 DebugLoc dl = Op.getDebugLoc();
6598 SDValue V1 = Op.getOperand(0);
6599 SDValue V2 = Op.getOperand(1);
6601 if (isZeroShuffle(SVOp))
6602 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6604 // Handle splat operations
6605 if (SVOp->isSplat()) {
6606 unsigned NumElem = VT.getVectorNumElements();
6607 int Size = VT.getSizeInBits();
6608 // Special case, this is the only place now where it's allowed to return
6609 // a vector_shuffle operation without using a target specific node, because
6610 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6611 // this be moved to DAGCombine instead?
6612 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6615 // Use vbroadcast whenever the splat comes from a foldable load
6616 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6617 if (Subtarget->hasAVX() && LD.getNode())
6618 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6620 // Handle splats by matching through known shuffle masks
6621 if ((Size == 128 && NumElem <= 4) ||
6622 (Size == 256 && NumElem < 8))
6625 // All remaning splats are promoted to target supported vector shuffles.
6626 return PromoteSplat(SVOp, DAG);
6629 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6631 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6632 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6633 if (NewOp.getNode())
6634 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6635 } else if ((VT == MVT::v4i32 ||
6636 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6637 // FIXME: Figure out a cleaner way to do this.
6638 // Try to make use of movq to zero out the top part.
6639 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6640 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6641 if (NewOp.getNode()) {
6642 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6643 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6644 DAG, Subtarget, dl);
6646 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6647 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6648 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6649 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6650 DAG, Subtarget, dl);
6657 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6658 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6659 SDValue V1 = Op.getOperand(0);
6660 SDValue V2 = Op.getOperand(1);
6661 EVT VT = Op.getValueType();
6662 DebugLoc dl = Op.getDebugLoc();
6663 unsigned NumElems = VT.getVectorNumElements();
6664 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6665 bool V1IsSplat = false;
6666 bool V2IsSplat = false;
6667 bool HasXMMInt = Subtarget->hasXMMInt();
6668 bool HasAVX2 = Subtarget->hasAVX2();
6669 MachineFunction &MF = DAG.getMachineFunction();
6670 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6672 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6674 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6676 // Vector shuffle lowering takes 3 steps:
6678 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6679 // narrowing and commutation of operands should be handled.
6680 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6682 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6683 // so the shuffle can be broken into other shuffles and the legalizer can
6684 // try the lowering again.
6686 // The general idea is that no vector_shuffle operation should be left to
6687 // be matched during isel, all of them must be converted to a target specific
6690 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6691 // narrowing and commutation of operands should be handled. The actual code
6692 // doesn't include all of those, work in progress...
6693 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6694 if (NewOp.getNode())
6697 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6698 // unpckh_undef). Only use pshufd if speed is more important than size.
6699 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6700 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6702 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6703 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6706 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6707 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6708 return getMOVDDup(Op, dl, V1, DAG);
6710 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6711 return getMOVHighToLow(Op, dl, DAG);
6713 // Use to match splats
6714 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6715 (VT == MVT::v2f64 || VT == MVT::v2i64))
6716 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6719 if (X86::isPSHUFDMask(SVOp)) {
6720 // The actual implementation will match the mask in the if above and then
6721 // during isel it can match several different instructions, not only pshufd
6722 // as its name says, sad but true, emulate the behavior for now...
6723 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6724 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6726 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6728 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6729 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6731 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6735 // Check if this can be converted into a logical shift.
6736 bool isLeft = false;
6739 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6740 if (isShift && ShVal.hasOneUse()) {
6741 // If the shifted value has multiple uses, it may be cheaper to use
6742 // v_set0 + movlhps or movhlps, etc.
6743 EVT EltVT = VT.getVectorElementType();
6744 ShAmt *= EltVT.getSizeInBits();
6745 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6748 if (X86::isMOVLMask(SVOp)) {
6749 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6750 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6751 if (!X86::isMOVLPMask(SVOp)) {
6752 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6753 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6755 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6756 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6760 // FIXME: fold these into legal mask.
6761 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6762 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6764 if (X86::isMOVHLPSMask(SVOp))
6765 return getMOVHighToLow(Op, dl, DAG);
6767 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6768 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6770 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6771 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6773 if (X86::isMOVLPMask(SVOp))
6774 return getMOVLP(Op, dl, DAG, HasXMMInt);
6776 if (ShouldXformToMOVHLPS(SVOp) ||
6777 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6778 return CommuteVectorShuffle(SVOp, DAG);
6781 // No better options. Use a vshl / vsrl.
6782 EVT EltVT = VT.getVectorElementType();
6783 ShAmt *= EltVT.getSizeInBits();
6784 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6787 bool Commuted = false;
6788 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6789 // 1,1,1,1 -> v8i16 though.
6790 V1IsSplat = isSplatVector(V1.getNode());
6791 V2IsSplat = isSplatVector(V2.getNode());
6793 // Canonicalize the splat or undef, if present, to be on the RHS.
6794 if (V1IsSplat && !V2IsSplat) {
6795 Op = CommuteVectorShuffle(SVOp, DAG);
6796 SVOp = cast<ShuffleVectorSDNode>(Op);
6797 V1 = SVOp->getOperand(0);
6798 V2 = SVOp->getOperand(1);
6799 std::swap(V1IsSplat, V2IsSplat);
6803 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6804 // Shuffling low element of v1 into undef, just return v1.
6807 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6808 // the instruction selector will not match, so get a canonical MOVL with
6809 // swapped operands to undo the commute.
6810 return getMOVL(DAG, dl, VT, V2, V1);
6813 if (X86::isUNPCKLMask(SVOp, HasAVX2))
6814 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6817 if (X86::isUNPCKHMask(SVOp, HasAVX2))
6818 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6822 // Normalize mask so all entries that point to V2 points to its first
6823 // element then try to match unpck{h|l} again. If match, return a
6824 // new vector_shuffle with the corrected mask.
6825 SDValue NewMask = NormalizeMask(SVOp, DAG);
6826 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6827 if (NSVOp != SVOp) {
6828 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6830 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6837 // Commute is back and try unpck* again.
6838 // FIXME: this seems wrong.
6839 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6840 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6842 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6843 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6846 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6847 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6851 // Normalize the node to match x86 shuffle ops if needed
6852 if (!V2IsUndef && isCommutedSHUFP(SVOp))
6853 return CommuteVectorShuffle(SVOp, DAG);
6855 // The checks below are all present in isShuffleMaskLegal, but they are
6856 // inlined here right now to enable us to directly emit target specific
6857 // nodes, and remove one by one until they don't return Op anymore.
6858 SmallVector<int, 16> M;
6861 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6862 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6863 X86::getShufflePALIGNRImmediate(SVOp),
6866 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6867 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6868 if (VT == MVT::v2f64)
6869 return getTargetShuffleNode(X86ISD::UNPCKLP, dl, VT, V1, V1, DAG);
6870 if (VT == MVT::v2i64)
6871 return getTargetShuffleNode(X86ISD::PUNPCKL, dl, VT, V1, V1, DAG);
6874 if (isPSHUFHWMask(M, VT))
6875 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6876 X86::getShufflePSHUFHWImmediate(SVOp),
6879 if (isPSHUFLWMask(M, VT))
6880 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6881 X86::getShufflePSHUFLWImmediate(SVOp),
6884 if (isSHUFPMask(M, VT))
6885 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6886 X86::getShuffleSHUFImmediate(SVOp), DAG);
6888 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6889 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6891 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6892 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6895 //===--------------------------------------------------------------------===//
6896 // Generate target specific nodes for 128 or 256-bit shuffles only
6897 // supported in the AVX instruction set.
6900 // Handle VMOVDDUPY permutations
6901 if (isMOVDDUPYMask(SVOp, Subtarget))
6902 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6904 // Handle VPERMILPS* permutations
6905 if (isVPERMILPSMask(M, VT, Subtarget))
6906 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6907 getShuffleVPERMILPSImmediate(SVOp), DAG);
6909 // Handle VPERMILPD* permutations
6910 if (isVPERMILPDMask(M, VT, Subtarget))
6911 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6912 getShuffleVPERMILPDImmediate(SVOp), DAG);
6914 // Handle VPERM2F128 permutations
6915 if (isVPERM2F128Mask(M, VT, Subtarget))
6916 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6917 getShuffleVPERM2F128Immediate(SVOp), DAG);
6919 // Handle VSHUFPSY permutations
6920 if (isVSHUFPSYMask(M, VT, Subtarget))
6921 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6922 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6924 // Handle VSHUFPDY permutations
6925 if (isVSHUFPDYMask(M, VT, Subtarget))
6926 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6927 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6929 // Try to swap operands in the node to match x86 shuffle ops
6930 if (isCommutedVSHUFPMask(M, VT, Subtarget)) {
6931 // Now we need to commute operands.
6932 SVOp = cast<ShuffleVectorSDNode>(CommuteVectorShuffle(SVOp, DAG));
6933 V1 = SVOp->getOperand(0);
6934 V2 = SVOp->getOperand(1);
6935 unsigned Immediate = (NumElems == 4) ? getShuffleVSHUFPDYImmediate(SVOp):
6936 getShuffleVSHUFPSYImmediate(SVOp);
6937 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, Immediate, DAG);
6940 //===--------------------------------------------------------------------===//
6941 // Since no target specific shuffle was selected for this generic one,
6942 // lower it into other known shuffles. FIXME: this isn't true yet, but
6943 // this is the plan.
6946 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6947 if (VT == MVT::v8i16) {
6948 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6949 if (NewOp.getNode())
6953 if (VT == MVT::v16i8) {
6954 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6955 if (NewOp.getNode())
6959 // Handle all 128-bit wide vectors with 4 elements, and match them with
6960 // several different shuffle types.
6961 if (NumElems == 4 && VT.getSizeInBits() == 128)
6962 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6964 // Handle general 256-bit shuffles
6965 if (VT.is256BitVector())
6966 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6972 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6973 SelectionDAG &DAG) const {
6974 EVT VT = Op.getValueType();
6975 DebugLoc dl = Op.getDebugLoc();
6977 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6980 if (VT.getSizeInBits() == 8) {
6981 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6982 Op.getOperand(0), Op.getOperand(1));
6983 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6984 DAG.getValueType(VT));
6985 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6986 } else if (VT.getSizeInBits() == 16) {
6987 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6988 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6990 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6991 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6992 DAG.getNode(ISD::BITCAST, dl,
6996 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6997 Op.getOperand(0), Op.getOperand(1));
6998 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6999 DAG.getValueType(VT));
7000 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7001 } else if (VT == MVT::f32) {
7002 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7003 // the result back to FR32 register. It's only worth matching if the
7004 // result has a single use which is a store or a bitcast to i32. And in
7005 // the case of a store, it's not worth it if the index is a constant 0,
7006 // because a MOVSSmr can be used instead, which is smaller and faster.
7007 if (!Op.hasOneUse())
7009 SDNode *User = *Op.getNode()->use_begin();
7010 if ((User->getOpcode() != ISD::STORE ||
7011 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7012 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7013 (User->getOpcode() != ISD::BITCAST ||
7014 User->getValueType(0) != MVT::i32))
7016 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7017 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7020 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7021 } else if (VT == MVT::i32 || VT == MVT::i64) {
7022 // ExtractPS/pextrq works with constant index.
7023 if (isa<ConstantSDNode>(Op.getOperand(1)))
7031 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7032 SelectionDAG &DAG) const {
7033 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7036 SDValue Vec = Op.getOperand(0);
7037 EVT VecVT = Vec.getValueType();
7039 // If this is a 256-bit vector result, first extract the 128-bit vector and
7040 // then extract the element from the 128-bit vector.
7041 if (VecVT.getSizeInBits() == 256) {
7042 DebugLoc dl = Op.getNode()->getDebugLoc();
7043 unsigned NumElems = VecVT.getVectorNumElements();
7044 SDValue Idx = Op.getOperand(1);
7045 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7047 // Get the 128-bit vector.
7048 bool Upper = IdxVal >= NumElems/2;
7049 Vec = Extract128BitVector(Vec,
7050 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7053 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7056 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7058 if (Subtarget->hasSSE41orAVX()) {
7059 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7064 EVT VT = Op.getValueType();
7065 DebugLoc dl = Op.getDebugLoc();
7066 // TODO: handle v16i8.
7067 if (VT.getSizeInBits() == 16) {
7068 SDValue Vec = Op.getOperand(0);
7069 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7071 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7072 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7073 DAG.getNode(ISD::BITCAST, dl,
7076 // Transform it so it match pextrw which produces a 32-bit result.
7077 EVT EltVT = MVT::i32;
7078 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7079 Op.getOperand(0), Op.getOperand(1));
7080 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7081 DAG.getValueType(VT));
7082 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7083 } else if (VT.getSizeInBits() == 32) {
7084 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7088 // SHUFPS the element to the lowest double word, then movss.
7089 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7090 EVT VVT = Op.getOperand(0).getValueType();
7091 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7092 DAG.getUNDEF(VVT), Mask);
7093 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7094 DAG.getIntPtrConstant(0));
7095 } else if (VT.getSizeInBits() == 64) {
7096 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7097 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7098 // to match extract_elt for f64.
7099 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7103 // UNPCKHPD the element to the lowest double word, then movsd.
7104 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7105 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7106 int Mask[2] = { 1, -1 };
7107 EVT VVT = Op.getOperand(0).getValueType();
7108 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7109 DAG.getUNDEF(VVT), Mask);
7110 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7111 DAG.getIntPtrConstant(0));
7118 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7119 SelectionDAG &DAG) const {
7120 EVT VT = Op.getValueType();
7121 EVT EltVT = VT.getVectorElementType();
7122 DebugLoc dl = Op.getDebugLoc();
7124 SDValue N0 = Op.getOperand(0);
7125 SDValue N1 = Op.getOperand(1);
7126 SDValue N2 = Op.getOperand(2);
7128 if (VT.getSizeInBits() == 256)
7131 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7132 isa<ConstantSDNode>(N2)) {
7134 if (VT == MVT::v8i16)
7135 Opc = X86ISD::PINSRW;
7136 else if (VT == MVT::v16i8)
7137 Opc = X86ISD::PINSRB;
7139 Opc = X86ISD::PINSRB;
7141 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7143 if (N1.getValueType() != MVT::i32)
7144 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7145 if (N2.getValueType() != MVT::i32)
7146 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7147 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7148 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7149 // Bits [7:6] of the constant are the source select. This will always be
7150 // zero here. The DAG Combiner may combine an extract_elt index into these
7151 // bits. For example (insert (extract, 3), 2) could be matched by putting
7152 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7153 // Bits [5:4] of the constant are the destination select. This is the
7154 // value of the incoming immediate.
7155 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7156 // combine either bitwise AND or insert of float 0.0 to set these bits.
7157 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7158 // Create this as a scalar to vector..
7159 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7160 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7161 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
7162 isa<ConstantSDNode>(N2)) {
7163 // PINSR* works with constant index.
7170 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7171 EVT VT = Op.getValueType();
7172 EVT EltVT = VT.getVectorElementType();
7174 DebugLoc dl = Op.getDebugLoc();
7175 SDValue N0 = Op.getOperand(0);
7176 SDValue N1 = Op.getOperand(1);
7177 SDValue N2 = Op.getOperand(2);
7179 // If this is a 256-bit vector result, first extract the 128-bit vector,
7180 // insert the element into the extracted half and then place it back.
7181 if (VT.getSizeInBits() == 256) {
7182 if (!isa<ConstantSDNode>(N2))
7185 // Get the desired 128-bit vector half.
7186 unsigned NumElems = VT.getVectorNumElements();
7187 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7188 bool Upper = IdxVal >= NumElems/2;
7189 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7190 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7192 // Insert the element into the desired half.
7193 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7194 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7196 // Insert the changed part back to the 256-bit vector
7197 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7200 if (Subtarget->hasSSE41orAVX())
7201 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7203 if (EltVT == MVT::i8)
7206 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7207 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7208 // as its second argument.
7209 if (N1.getValueType() != MVT::i32)
7210 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7211 if (N2.getValueType() != MVT::i32)
7212 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7213 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7219 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7220 LLVMContext *Context = DAG.getContext();
7221 DebugLoc dl = Op.getDebugLoc();
7222 EVT OpVT = Op.getValueType();
7224 // If this is a 256-bit vector result, first insert into a 128-bit
7225 // vector and then insert into the 256-bit vector.
7226 if (OpVT.getSizeInBits() > 128) {
7227 // Insert into a 128-bit vector.
7228 EVT VT128 = EVT::getVectorVT(*Context,
7229 OpVT.getVectorElementType(),
7230 OpVT.getVectorNumElements() / 2);
7232 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7234 // Insert the 128-bit vector.
7235 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7236 DAG.getConstant(0, MVT::i32),
7240 if (Op.getValueType() == MVT::v1i64 &&
7241 Op.getOperand(0).getValueType() == MVT::i64)
7242 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7244 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7245 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7246 "Expected an SSE type!");
7247 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7248 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7251 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7252 // a simple subregister reference or explicit instructions to grab
7253 // upper bits of a vector.
7255 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7256 if (Subtarget->hasAVX()) {
7257 DebugLoc dl = Op.getNode()->getDebugLoc();
7258 SDValue Vec = Op.getNode()->getOperand(0);
7259 SDValue Idx = Op.getNode()->getOperand(1);
7261 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7262 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7263 return Extract128BitVector(Vec, Idx, DAG, dl);
7269 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7270 // simple superregister reference or explicit instructions to insert
7271 // the upper bits of a vector.
7273 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7274 if (Subtarget->hasAVX()) {
7275 DebugLoc dl = Op.getNode()->getDebugLoc();
7276 SDValue Vec = Op.getNode()->getOperand(0);
7277 SDValue SubVec = Op.getNode()->getOperand(1);
7278 SDValue Idx = Op.getNode()->getOperand(2);
7280 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7281 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7282 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7288 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7289 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7290 // one of the above mentioned nodes. It has to be wrapped because otherwise
7291 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7292 // be used to form addressing mode. These wrapped nodes will be selected
7295 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7296 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7298 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7300 unsigned char OpFlag = 0;
7301 unsigned WrapperKind = X86ISD::Wrapper;
7302 CodeModel::Model M = getTargetMachine().getCodeModel();
7304 if (Subtarget->isPICStyleRIPRel() &&
7305 (M == CodeModel::Small || M == CodeModel::Kernel))
7306 WrapperKind = X86ISD::WrapperRIP;
7307 else if (Subtarget->isPICStyleGOT())
7308 OpFlag = X86II::MO_GOTOFF;
7309 else if (Subtarget->isPICStyleStubPIC())
7310 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7312 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7314 CP->getOffset(), OpFlag);
7315 DebugLoc DL = CP->getDebugLoc();
7316 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7317 // With PIC, the address is actually $g + Offset.
7319 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7320 DAG.getNode(X86ISD::GlobalBaseReg,
7321 DebugLoc(), getPointerTy()),
7328 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7329 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7331 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7333 unsigned char OpFlag = 0;
7334 unsigned WrapperKind = X86ISD::Wrapper;
7335 CodeModel::Model M = getTargetMachine().getCodeModel();
7337 if (Subtarget->isPICStyleRIPRel() &&
7338 (M == CodeModel::Small || M == CodeModel::Kernel))
7339 WrapperKind = X86ISD::WrapperRIP;
7340 else if (Subtarget->isPICStyleGOT())
7341 OpFlag = X86II::MO_GOTOFF;
7342 else if (Subtarget->isPICStyleStubPIC())
7343 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7345 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7347 DebugLoc DL = JT->getDebugLoc();
7348 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7350 // With PIC, the address is actually $g + Offset.
7352 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7353 DAG.getNode(X86ISD::GlobalBaseReg,
7354 DebugLoc(), getPointerTy()),
7361 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7362 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7364 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7366 unsigned char OpFlag = 0;
7367 unsigned WrapperKind = X86ISD::Wrapper;
7368 CodeModel::Model M = getTargetMachine().getCodeModel();
7370 if (Subtarget->isPICStyleRIPRel() &&
7371 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7372 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7373 OpFlag = X86II::MO_GOTPCREL;
7374 WrapperKind = X86ISD::WrapperRIP;
7375 } else if (Subtarget->isPICStyleGOT()) {
7376 OpFlag = X86II::MO_GOT;
7377 } else if (Subtarget->isPICStyleStubPIC()) {
7378 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7379 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7380 OpFlag = X86II::MO_DARWIN_NONLAZY;
7383 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7385 DebugLoc DL = Op.getDebugLoc();
7386 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7389 // With PIC, the address is actually $g + Offset.
7390 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7391 !Subtarget->is64Bit()) {
7392 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7393 DAG.getNode(X86ISD::GlobalBaseReg,
7394 DebugLoc(), getPointerTy()),
7398 // For symbols that require a load from a stub to get the address, emit the
7400 if (isGlobalStubReference(OpFlag))
7401 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7402 MachinePointerInfo::getGOT(), false, false, false, 0);
7408 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7409 // Create the TargetBlockAddressAddress node.
7410 unsigned char OpFlags =
7411 Subtarget->ClassifyBlockAddressReference();
7412 CodeModel::Model M = getTargetMachine().getCodeModel();
7413 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7414 DebugLoc dl = Op.getDebugLoc();
7415 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7416 /*isTarget=*/true, OpFlags);
7418 if (Subtarget->isPICStyleRIPRel() &&
7419 (M == CodeModel::Small || M == CodeModel::Kernel))
7420 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7422 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7424 // With PIC, the address is actually $g + Offset.
7425 if (isGlobalRelativeToPICBase(OpFlags)) {
7426 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7427 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7435 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7437 SelectionDAG &DAG) const {
7438 // Create the TargetGlobalAddress node, folding in the constant
7439 // offset if it is legal.
7440 unsigned char OpFlags =
7441 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7442 CodeModel::Model M = getTargetMachine().getCodeModel();
7444 if (OpFlags == X86II::MO_NO_FLAG &&
7445 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7446 // A direct static reference to a global.
7447 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7450 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7453 if (Subtarget->isPICStyleRIPRel() &&
7454 (M == CodeModel::Small || M == CodeModel::Kernel))
7455 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7457 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7459 // With PIC, the address is actually $g + Offset.
7460 if (isGlobalRelativeToPICBase(OpFlags)) {
7461 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7462 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7466 // For globals that require a load from a stub to get the address, emit the
7468 if (isGlobalStubReference(OpFlags))
7469 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7470 MachinePointerInfo::getGOT(), false, false, false, 0);
7472 // If there was a non-zero offset that we didn't fold, create an explicit
7475 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7476 DAG.getConstant(Offset, getPointerTy()));
7482 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7483 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7484 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7485 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7489 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7490 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7491 unsigned char OperandFlags) {
7492 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7493 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7494 DebugLoc dl = GA->getDebugLoc();
7495 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7496 GA->getValueType(0),
7500 SDValue Ops[] = { Chain, TGA, *InFlag };
7501 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7503 SDValue Ops[] = { Chain, TGA };
7504 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7507 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7508 MFI->setAdjustsStack(true);
7510 SDValue Flag = Chain.getValue(1);
7511 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7514 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7516 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7519 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7520 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7521 DAG.getNode(X86ISD::GlobalBaseReg,
7522 DebugLoc(), PtrVT), InFlag);
7523 InFlag = Chain.getValue(1);
7525 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7528 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7530 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7532 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7533 X86::RAX, X86II::MO_TLSGD);
7536 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7537 // "local exec" model.
7538 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7539 const EVT PtrVT, TLSModel::Model model,
7541 DebugLoc dl = GA->getDebugLoc();
7543 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7544 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7545 is64Bit ? 257 : 256));
7547 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7548 DAG.getIntPtrConstant(0),
7549 MachinePointerInfo(Ptr),
7550 false, false, false, 0);
7552 unsigned char OperandFlags = 0;
7553 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7555 unsigned WrapperKind = X86ISD::Wrapper;
7556 if (model == TLSModel::LocalExec) {
7557 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7558 } else if (is64Bit) {
7559 assert(model == TLSModel::InitialExec);
7560 OperandFlags = X86II::MO_GOTTPOFF;
7561 WrapperKind = X86ISD::WrapperRIP;
7563 assert(model == TLSModel::InitialExec);
7564 OperandFlags = X86II::MO_INDNTPOFF;
7567 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7569 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7570 GA->getValueType(0),
7571 GA->getOffset(), OperandFlags);
7572 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7574 if (model == TLSModel::InitialExec)
7575 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7576 MachinePointerInfo::getGOT(), false, false, false, 0);
7578 // The address of the thread local variable is the add of the thread
7579 // pointer with the offset of the variable.
7580 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7584 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7586 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7587 const GlobalValue *GV = GA->getGlobal();
7589 if (Subtarget->isTargetELF()) {
7590 // TODO: implement the "local dynamic" model
7591 // TODO: implement the "initial exec"model for pic executables
7593 // If GV is an alias then use the aliasee for determining
7594 // thread-localness.
7595 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7596 GV = GA->resolveAliasedGlobal(false);
7598 TLSModel::Model model
7599 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7602 case TLSModel::GeneralDynamic:
7603 case TLSModel::LocalDynamic: // not implemented
7604 if (Subtarget->is64Bit())
7605 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7606 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7608 case TLSModel::InitialExec:
7609 case TLSModel::LocalExec:
7610 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7611 Subtarget->is64Bit());
7613 } else if (Subtarget->isTargetDarwin()) {
7614 // Darwin only has one model of TLS. Lower to that.
7615 unsigned char OpFlag = 0;
7616 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7617 X86ISD::WrapperRIP : X86ISD::Wrapper;
7619 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7621 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7622 !Subtarget->is64Bit();
7624 OpFlag = X86II::MO_TLVP_PIC_BASE;
7626 OpFlag = X86II::MO_TLVP;
7627 DebugLoc DL = Op.getDebugLoc();
7628 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7629 GA->getValueType(0),
7630 GA->getOffset(), OpFlag);
7631 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7633 // With PIC32, the address is actually $g + Offset.
7635 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7636 DAG.getNode(X86ISD::GlobalBaseReg,
7637 DebugLoc(), getPointerTy()),
7640 // Lowering the machine isd will make sure everything is in the right
7642 SDValue Chain = DAG.getEntryNode();
7643 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7644 SDValue Args[] = { Chain, Offset };
7645 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7647 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7648 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7649 MFI->setAdjustsStack(true);
7651 // And our return value (tls address) is in the standard call return value
7653 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7654 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7659 "TLS not implemented for this target.");
7661 llvm_unreachable("Unreachable");
7666 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7667 /// take a 2 x i32 value to shift plus a shift amount.
7668 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7669 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7670 EVT VT = Op.getValueType();
7671 unsigned VTBits = VT.getSizeInBits();
7672 DebugLoc dl = Op.getDebugLoc();
7673 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7674 SDValue ShOpLo = Op.getOperand(0);
7675 SDValue ShOpHi = Op.getOperand(1);
7676 SDValue ShAmt = Op.getOperand(2);
7677 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7678 DAG.getConstant(VTBits - 1, MVT::i8))
7679 : DAG.getConstant(0, VT);
7682 if (Op.getOpcode() == ISD::SHL_PARTS) {
7683 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7684 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7686 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7687 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7690 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7691 DAG.getConstant(VTBits, MVT::i8));
7692 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7693 AndNode, DAG.getConstant(0, MVT::i8));
7696 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7697 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7698 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7700 if (Op.getOpcode() == ISD::SHL_PARTS) {
7701 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7702 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7704 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7705 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7708 SDValue Ops[2] = { Lo, Hi };
7709 return DAG.getMergeValues(Ops, 2, dl);
7712 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7713 SelectionDAG &DAG) const {
7714 EVT SrcVT = Op.getOperand(0).getValueType();
7716 if (SrcVT.isVector())
7719 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7720 "Unknown SINT_TO_FP to lower!");
7722 // These are really Legal; return the operand so the caller accepts it as
7724 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7726 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7727 Subtarget->is64Bit()) {
7731 DebugLoc dl = Op.getDebugLoc();
7732 unsigned Size = SrcVT.getSizeInBits()/8;
7733 MachineFunction &MF = DAG.getMachineFunction();
7734 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7735 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7736 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7738 MachinePointerInfo::getFixedStack(SSFI),
7740 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7743 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7745 SelectionDAG &DAG) const {
7747 DebugLoc DL = Op.getDebugLoc();
7749 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7751 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7753 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7755 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7757 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7758 MachineMemOperand *MMO;
7760 int SSFI = FI->getIndex();
7762 DAG.getMachineFunction()
7763 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7764 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7766 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7767 StackSlot = StackSlot.getOperand(1);
7769 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7770 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7772 Tys, Ops, array_lengthof(Ops),
7776 Chain = Result.getValue(1);
7777 SDValue InFlag = Result.getValue(2);
7779 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7780 // shouldn't be necessary except that RFP cannot be live across
7781 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7782 MachineFunction &MF = DAG.getMachineFunction();
7783 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7784 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7785 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7786 Tys = DAG.getVTList(MVT::Other);
7788 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7790 MachineMemOperand *MMO =
7791 DAG.getMachineFunction()
7792 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7793 MachineMemOperand::MOStore, SSFISize, SSFISize);
7795 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7796 Ops, array_lengthof(Ops),
7797 Op.getValueType(), MMO);
7798 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7799 MachinePointerInfo::getFixedStack(SSFI),
7800 false, false, false, 0);
7806 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7807 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7808 SelectionDAG &DAG) const {
7809 // This algorithm is not obvious. Here it is in C code, more or less:
7811 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7812 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7813 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7815 // Copy ints to xmm registers.
7816 __m128i xh = _mm_cvtsi32_si128( hi );
7817 __m128i xl = _mm_cvtsi32_si128( lo );
7819 // Combine into low half of a single xmm register.
7820 __m128i x = _mm_unpacklo_epi32( xh, xl );
7824 // Merge in appropriate exponents to give the integer bits the right
7826 x = _mm_unpacklo_epi32( x, exp );
7828 // Subtract away the biases to deal with the IEEE-754 double precision
7830 d = _mm_sub_pd( (__m128d) x, bias );
7832 // All conversions up to here are exact. The correctly rounded result is
7833 // calculated using the current rounding mode using the following
7835 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7836 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7837 // store doesn't really need to be here (except
7838 // maybe to zero the other double)
7843 DebugLoc dl = Op.getDebugLoc();
7844 LLVMContext *Context = DAG.getContext();
7846 // Build some magic constants.
7847 std::vector<Constant*> CV0;
7848 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7849 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7850 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7851 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7852 Constant *C0 = ConstantVector::get(CV0);
7853 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7855 std::vector<Constant*> CV1;
7857 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7859 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7860 Constant *C1 = ConstantVector::get(CV1);
7861 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7863 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7864 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7866 DAG.getIntPtrConstant(1)));
7867 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7868 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7870 DAG.getIntPtrConstant(0)));
7871 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7872 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7873 MachinePointerInfo::getConstantPool(),
7874 false, false, false, 16);
7875 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7876 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7877 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7878 MachinePointerInfo::getConstantPool(),
7879 false, false, false, 16);
7880 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7882 // Add the halves; easiest way is to swap them into another reg first.
7883 int ShufMask[2] = { 1, -1 };
7884 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7885 DAG.getUNDEF(MVT::v2f64), ShufMask);
7886 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7887 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7888 DAG.getIntPtrConstant(0));
7891 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7892 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7893 SelectionDAG &DAG) const {
7894 DebugLoc dl = Op.getDebugLoc();
7895 // FP constant to bias correct the final result.
7896 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7899 // Load the 32-bit value into an XMM register.
7900 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7903 // Zero out the upper parts of the register.
7904 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7907 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7908 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7909 DAG.getIntPtrConstant(0));
7911 // Or the load with the bias.
7912 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7913 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7914 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7916 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7917 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7918 MVT::v2f64, Bias)));
7919 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7920 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7921 DAG.getIntPtrConstant(0));
7923 // Subtract the bias.
7924 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7926 // Handle final rounding.
7927 EVT DestVT = Op.getValueType();
7929 if (DestVT.bitsLT(MVT::f64)) {
7930 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7931 DAG.getIntPtrConstant(0));
7932 } else if (DestVT.bitsGT(MVT::f64)) {
7933 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7936 // Handle final rounding.
7940 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7941 SelectionDAG &DAG) const {
7942 SDValue N0 = Op.getOperand(0);
7943 DebugLoc dl = Op.getDebugLoc();
7945 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7946 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7947 // the optimization here.
7948 if (DAG.SignBitIsZero(N0))
7949 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7951 EVT SrcVT = N0.getValueType();
7952 EVT DstVT = Op.getValueType();
7953 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7954 return LowerUINT_TO_FP_i64(Op, DAG);
7955 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7956 return LowerUINT_TO_FP_i32(Op, DAG);
7958 // Make a 64-bit buffer, and use it to build an FILD.
7959 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7960 if (SrcVT == MVT::i32) {
7961 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7962 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7963 getPointerTy(), StackSlot, WordOff);
7964 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7965 StackSlot, MachinePointerInfo(),
7967 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7968 OffsetSlot, MachinePointerInfo(),
7970 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7974 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7975 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7976 StackSlot, MachinePointerInfo(),
7978 // For i64 source, we need to add the appropriate power of 2 if the input
7979 // was negative. This is the same as the optimization in
7980 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7981 // we must be careful to do the computation in x87 extended precision, not
7982 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7983 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7984 MachineMemOperand *MMO =
7985 DAG.getMachineFunction()
7986 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7987 MachineMemOperand::MOLoad, 8, 8);
7989 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7990 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7991 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7994 APInt FF(32, 0x5F800000ULL);
7996 // Check whether the sign bit is set.
7997 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7998 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8001 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8002 SDValue FudgePtr = DAG.getConstantPool(
8003 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8006 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8007 SDValue Zero = DAG.getIntPtrConstant(0);
8008 SDValue Four = DAG.getIntPtrConstant(4);
8009 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8011 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8013 // Load the value out, extending it from f32 to f80.
8014 // FIXME: Avoid the extend by constructing the right constant pool?
8015 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8016 FudgePtr, MachinePointerInfo::getConstantPool(),
8017 MVT::f32, false, false, 4);
8018 // Extend everything to 80 bits to force it to be done on x87.
8019 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8020 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8023 std::pair<SDValue,SDValue> X86TargetLowering::
8024 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8025 DebugLoc DL = Op.getDebugLoc();
8027 EVT DstTy = Op.getValueType();
8030 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8034 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8035 DstTy.getSimpleVT() >= MVT::i16 &&
8036 "Unknown FP_TO_SINT to lower!");
8038 // These are really Legal.
8039 if (DstTy == MVT::i32 &&
8040 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8041 return std::make_pair(SDValue(), SDValue());
8042 if (Subtarget->is64Bit() &&
8043 DstTy == MVT::i64 &&
8044 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8045 return std::make_pair(SDValue(), SDValue());
8047 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8049 MachineFunction &MF = DAG.getMachineFunction();
8050 unsigned MemSize = DstTy.getSizeInBits()/8;
8051 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8052 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8057 switch (DstTy.getSimpleVT().SimpleTy) {
8058 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8059 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8060 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8061 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8064 SDValue Chain = DAG.getEntryNode();
8065 SDValue Value = Op.getOperand(0);
8066 EVT TheVT = Op.getOperand(0).getValueType();
8067 if (isScalarFPTypeInSSEReg(TheVT)) {
8068 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8069 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8070 MachinePointerInfo::getFixedStack(SSFI),
8072 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8074 Chain, StackSlot, DAG.getValueType(TheVT)
8077 MachineMemOperand *MMO =
8078 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8079 MachineMemOperand::MOLoad, MemSize, MemSize);
8080 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8082 Chain = Value.getValue(1);
8083 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8084 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8087 MachineMemOperand *MMO =
8088 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8089 MachineMemOperand::MOStore, MemSize, MemSize);
8091 // Build the FP_TO_INT*_IN_MEM
8092 SDValue Ops[] = { Chain, Value, StackSlot };
8093 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8094 Ops, 3, DstTy, MMO);
8096 return std::make_pair(FIST, StackSlot);
8099 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8100 SelectionDAG &DAG) const {
8101 if (Op.getValueType().isVector())
8104 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8105 SDValue FIST = Vals.first, StackSlot = Vals.second;
8106 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8107 if (FIST.getNode() == 0) return Op;
8110 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8111 FIST, StackSlot, MachinePointerInfo(),
8112 false, false, false, 0);
8115 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8116 SelectionDAG &DAG) const {
8117 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8118 SDValue FIST = Vals.first, StackSlot = Vals.second;
8119 assert(FIST.getNode() && "Unexpected failure");
8122 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8123 FIST, StackSlot, MachinePointerInfo(),
8124 false, false, false, 0);
8127 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8128 SelectionDAG &DAG) const {
8129 LLVMContext *Context = DAG.getContext();
8130 DebugLoc dl = Op.getDebugLoc();
8131 EVT VT = Op.getValueType();
8134 EltVT = VT.getVectorElementType();
8135 std::vector<Constant*> CV;
8136 if (EltVT == MVT::f64) {
8137 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8141 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8147 Constant *C = ConstantVector::get(CV);
8148 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8149 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8150 MachinePointerInfo::getConstantPool(),
8151 false, false, false, 16);
8152 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8155 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8156 LLVMContext *Context = DAG.getContext();
8157 DebugLoc dl = Op.getDebugLoc();
8158 EVT VT = Op.getValueType();
8161 EltVT = VT.getVectorElementType();
8162 std::vector<Constant*> CV;
8163 if (EltVT == MVT::f64) {
8164 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8168 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8174 Constant *C = ConstantVector::get(CV);
8175 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8176 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8177 MachinePointerInfo::getConstantPool(),
8178 false, false, false, 16);
8179 if (VT.isVector()) {
8180 return DAG.getNode(ISD::BITCAST, dl, VT,
8181 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8182 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8184 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8186 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8190 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8191 LLVMContext *Context = DAG.getContext();
8192 SDValue Op0 = Op.getOperand(0);
8193 SDValue Op1 = Op.getOperand(1);
8194 DebugLoc dl = Op.getDebugLoc();
8195 EVT VT = Op.getValueType();
8196 EVT SrcVT = Op1.getValueType();
8198 // If second operand is smaller, extend it first.
8199 if (SrcVT.bitsLT(VT)) {
8200 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8203 // And if it is bigger, shrink it first.
8204 if (SrcVT.bitsGT(VT)) {
8205 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8209 // At this point the operands and the result should have the same
8210 // type, and that won't be f80 since that is not custom lowered.
8212 // First get the sign bit of second operand.
8213 std::vector<Constant*> CV;
8214 if (SrcVT == MVT::f64) {
8215 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8216 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8218 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8219 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8220 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8221 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8223 Constant *C = ConstantVector::get(CV);
8224 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8225 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8226 MachinePointerInfo::getConstantPool(),
8227 false, false, false, 16);
8228 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8230 // Shift sign bit right or left if the two operands have different types.
8231 if (SrcVT.bitsGT(VT)) {
8232 // Op0 is MVT::f32, Op1 is MVT::f64.
8233 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8234 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8235 DAG.getConstant(32, MVT::i32));
8236 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8237 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8238 DAG.getIntPtrConstant(0));
8241 // Clear first operand sign bit.
8243 if (VT == MVT::f64) {
8244 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8245 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8247 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8248 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8249 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8250 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8252 C = ConstantVector::get(CV);
8253 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8254 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8255 MachinePointerInfo::getConstantPool(),
8256 false, false, false, 16);
8257 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8259 // Or the value with the sign bit.
8260 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8263 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8264 SDValue N0 = Op.getOperand(0);
8265 DebugLoc dl = Op.getDebugLoc();
8266 EVT VT = Op.getValueType();
8268 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8269 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8270 DAG.getConstant(1, VT));
8271 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8274 /// Emit nodes that will be selected as "test Op0,Op0", or something
8276 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8277 SelectionDAG &DAG) const {
8278 DebugLoc dl = Op.getDebugLoc();
8280 // CF and OF aren't always set the way we want. Determine which
8281 // of these we need.
8282 bool NeedCF = false;
8283 bool NeedOF = false;
8286 case X86::COND_A: case X86::COND_AE:
8287 case X86::COND_B: case X86::COND_BE:
8290 case X86::COND_G: case X86::COND_GE:
8291 case X86::COND_L: case X86::COND_LE:
8292 case X86::COND_O: case X86::COND_NO:
8297 // See if we can use the EFLAGS value from the operand instead of
8298 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8299 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8300 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8301 // Emit a CMP with 0, which is the TEST pattern.
8302 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8303 DAG.getConstant(0, Op.getValueType()));
8305 unsigned Opcode = 0;
8306 unsigned NumOperands = 0;
8307 switch (Op.getNode()->getOpcode()) {
8309 // Due to an isel shortcoming, be conservative if this add is likely to be
8310 // selected as part of a load-modify-store instruction. When the root node
8311 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8312 // uses of other nodes in the match, such as the ADD in this case. This
8313 // leads to the ADD being left around and reselected, with the result being
8314 // two adds in the output. Alas, even if none our users are stores, that
8315 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8316 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8317 // climbing the DAG back to the root, and it doesn't seem to be worth the
8319 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8320 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8321 if (UI->getOpcode() != ISD::CopyToReg &&
8322 UI->getOpcode() != ISD::SETCC &&
8323 UI->getOpcode() != ISD::STORE)
8326 if (ConstantSDNode *C =
8327 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8328 // An add of one will be selected as an INC.
8329 if (C->getAPIntValue() == 1) {
8330 Opcode = X86ISD::INC;
8335 // An add of negative one (subtract of one) will be selected as a DEC.
8336 if (C->getAPIntValue().isAllOnesValue()) {
8337 Opcode = X86ISD::DEC;
8343 // Otherwise use a regular EFLAGS-setting add.
8344 Opcode = X86ISD::ADD;
8348 // If the primary and result isn't used, don't bother using X86ISD::AND,
8349 // because a TEST instruction will be better.
8350 bool NonFlagUse = false;
8351 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8352 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8354 unsigned UOpNo = UI.getOperandNo();
8355 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8356 // Look pass truncate.
8357 UOpNo = User->use_begin().getOperandNo();
8358 User = *User->use_begin();
8361 if (User->getOpcode() != ISD::BRCOND &&
8362 User->getOpcode() != ISD::SETCC &&
8363 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8376 // Due to the ISEL shortcoming noted above, be conservative if this op is
8377 // likely to be selected as part of a load-modify-store instruction.
8378 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8379 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8380 if (UI->getOpcode() == ISD::STORE)
8383 // Otherwise use a regular EFLAGS-setting instruction.
8384 switch (Op.getNode()->getOpcode()) {
8385 default: llvm_unreachable("unexpected operator!");
8386 case ISD::SUB: Opcode = X86ISD::SUB; break;
8387 case ISD::OR: Opcode = X86ISD::OR; break;
8388 case ISD::XOR: Opcode = X86ISD::XOR; break;
8389 case ISD::AND: Opcode = X86ISD::AND; break;
8401 return SDValue(Op.getNode(), 1);
8408 // Emit a CMP with 0, which is the TEST pattern.
8409 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8410 DAG.getConstant(0, Op.getValueType()));
8412 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8413 SmallVector<SDValue, 4> Ops;
8414 for (unsigned i = 0; i != NumOperands; ++i)
8415 Ops.push_back(Op.getOperand(i));
8417 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8418 DAG.ReplaceAllUsesWith(Op, New);
8419 return SDValue(New.getNode(), 1);
8422 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8424 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8425 SelectionDAG &DAG) const {
8426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8427 if (C->getAPIntValue() == 0)
8428 return EmitTest(Op0, X86CC, DAG);
8430 DebugLoc dl = Op0.getDebugLoc();
8431 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8434 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8435 /// if it's possible.
8436 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8437 DebugLoc dl, SelectionDAG &DAG) const {
8438 SDValue Op0 = And.getOperand(0);
8439 SDValue Op1 = And.getOperand(1);
8440 if (Op0.getOpcode() == ISD::TRUNCATE)
8441 Op0 = Op0.getOperand(0);
8442 if (Op1.getOpcode() == ISD::TRUNCATE)
8443 Op1 = Op1.getOperand(0);
8446 if (Op1.getOpcode() == ISD::SHL)
8447 std::swap(Op0, Op1);
8448 if (Op0.getOpcode() == ISD::SHL) {
8449 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8450 if (And00C->getZExtValue() == 1) {
8451 // If we looked past a truncate, check that it's only truncating away
8453 unsigned BitWidth = Op0.getValueSizeInBits();
8454 unsigned AndBitWidth = And.getValueSizeInBits();
8455 if (BitWidth > AndBitWidth) {
8456 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8457 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8458 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8462 RHS = Op0.getOperand(1);
8464 } else if (Op1.getOpcode() == ISD::Constant) {
8465 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8466 uint64_t AndRHSVal = AndRHS->getZExtValue();
8467 SDValue AndLHS = Op0;
8469 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8470 LHS = AndLHS.getOperand(0);
8471 RHS = AndLHS.getOperand(1);
8474 // Use BT if the immediate can't be encoded in a TEST instruction.
8475 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8477 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8481 if (LHS.getNode()) {
8482 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8483 // instruction. Since the shift amount is in-range-or-undefined, we know
8484 // that doing a bittest on the i32 value is ok. We extend to i32 because
8485 // the encoding for the i16 version is larger than the i32 version.
8486 // Also promote i16 to i32 for performance / code size reason.
8487 if (LHS.getValueType() == MVT::i8 ||
8488 LHS.getValueType() == MVT::i16)
8489 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8491 // If the operand types disagree, extend the shift amount to match. Since
8492 // BT ignores high bits (like shifts) we can use anyextend.
8493 if (LHS.getValueType() != RHS.getValueType())
8494 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8496 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8497 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8498 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8499 DAG.getConstant(Cond, MVT::i8), BT);
8505 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8507 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8509 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8510 SDValue Op0 = Op.getOperand(0);
8511 SDValue Op1 = Op.getOperand(1);
8512 DebugLoc dl = Op.getDebugLoc();
8513 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8515 // Optimize to BT if possible.
8516 // Lower (X & (1 << N)) == 0 to BT(X, N).
8517 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8518 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8519 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8520 Op1.getOpcode() == ISD::Constant &&
8521 cast<ConstantSDNode>(Op1)->isNullValue() &&
8522 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8523 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8524 if (NewSetCC.getNode())
8528 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8530 if (Op1.getOpcode() == ISD::Constant &&
8531 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8532 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8533 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8535 // If the input is a setcc, then reuse the input setcc or use a new one with
8536 // the inverted condition.
8537 if (Op0.getOpcode() == X86ISD::SETCC) {
8538 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8539 bool Invert = (CC == ISD::SETNE) ^
8540 cast<ConstantSDNode>(Op1)->isNullValue();
8541 if (!Invert) return Op0;
8543 CCode = X86::GetOppositeBranchCondition(CCode);
8544 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8545 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8549 bool isFP = Op1.getValueType().isFloatingPoint();
8550 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8551 if (X86CC == X86::COND_INVALID)
8554 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8555 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8556 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8559 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8560 // ones, and then concatenate the result back.
8561 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8562 EVT VT = Op.getValueType();
8564 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8565 "Unsupported value type for operation");
8567 int NumElems = VT.getVectorNumElements();
8568 DebugLoc dl = Op.getDebugLoc();
8569 SDValue CC = Op.getOperand(2);
8570 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8571 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8573 // Extract the LHS vectors
8574 SDValue LHS = Op.getOperand(0);
8575 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8576 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8578 // Extract the RHS vectors
8579 SDValue RHS = Op.getOperand(1);
8580 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8581 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8583 // Issue the operation on the smaller types and concatenate the result back
8584 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8585 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8586 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8587 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8588 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8592 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8594 SDValue Op0 = Op.getOperand(0);
8595 SDValue Op1 = Op.getOperand(1);
8596 SDValue CC = Op.getOperand(2);
8597 EVT VT = Op.getValueType();
8598 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8599 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8600 DebugLoc dl = Op.getDebugLoc();
8604 EVT EltVT = Op0.getValueType().getVectorElementType();
8605 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8607 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8610 // SSE Condition code mapping:
8619 switch (SetCCOpcode) {
8622 case ISD::SETEQ: SSECC = 0; break;
8624 case ISD::SETGT: Swap = true; // Fallthrough
8626 case ISD::SETOLT: SSECC = 1; break;
8628 case ISD::SETGE: Swap = true; // Fallthrough
8630 case ISD::SETOLE: SSECC = 2; break;
8631 case ISD::SETUO: SSECC = 3; break;
8633 case ISD::SETNE: SSECC = 4; break;
8634 case ISD::SETULE: Swap = true;
8635 case ISD::SETUGE: SSECC = 5; break;
8636 case ISD::SETULT: Swap = true;
8637 case ISD::SETUGT: SSECC = 6; break;
8638 case ISD::SETO: SSECC = 7; break;
8641 std::swap(Op0, Op1);
8643 // In the two special cases we can't handle, emit two comparisons.
8645 if (SetCCOpcode == ISD::SETUEQ) {
8647 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8648 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8649 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8650 } else if (SetCCOpcode == ISD::SETONE) {
8652 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8653 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8654 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8656 llvm_unreachable("Illegal FP comparison");
8658 // Handle all other FP comparisons here.
8659 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8662 // Break 256-bit integer vector compare into smaller ones.
8663 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8664 return Lower256IntVSETCC(Op, DAG);
8666 // We are handling one of the integer comparisons here. Since SSE only has
8667 // GT and EQ comparisons for integer, swapping operands and multiple
8668 // operations may be required for some comparisons.
8669 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8670 bool Swap = false, Invert = false, FlipSigns = false;
8672 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8674 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8675 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8676 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8677 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8680 switch (SetCCOpcode) {
8682 case ISD::SETNE: Invert = true;
8683 case ISD::SETEQ: Opc = EQOpc; break;
8684 case ISD::SETLT: Swap = true;
8685 case ISD::SETGT: Opc = GTOpc; break;
8686 case ISD::SETGE: Swap = true;
8687 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8688 case ISD::SETULT: Swap = true;
8689 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8690 case ISD::SETUGE: Swap = true;
8691 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8694 std::swap(Op0, Op1);
8696 // Check that the operation in question is available (most are plain SSE2,
8697 // but PCMPGTQ and PCMPEQQ have different requirements).
8698 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8700 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8703 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8704 // bits of the inputs before performing those operations.
8706 EVT EltVT = VT.getVectorElementType();
8707 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8709 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8710 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8712 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8713 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8716 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8718 // If the logical-not of the result is required, perform that now.
8720 Result = DAG.getNOT(dl, Result, VT);
8725 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8726 static bool isX86LogicalCmp(SDValue Op) {
8727 unsigned Opc = Op.getNode()->getOpcode();
8728 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8730 if (Op.getResNo() == 1 &&
8731 (Opc == X86ISD::ADD ||
8732 Opc == X86ISD::SUB ||
8733 Opc == X86ISD::ADC ||
8734 Opc == X86ISD::SBB ||
8735 Opc == X86ISD::SMUL ||
8736 Opc == X86ISD::UMUL ||
8737 Opc == X86ISD::INC ||
8738 Opc == X86ISD::DEC ||
8739 Opc == X86ISD::OR ||
8740 Opc == X86ISD::XOR ||
8741 Opc == X86ISD::AND))
8744 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8750 static bool isZero(SDValue V) {
8751 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8752 return C && C->isNullValue();
8755 static bool isAllOnes(SDValue V) {
8756 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8757 return C && C->isAllOnesValue();
8760 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8761 bool addTest = true;
8762 SDValue Cond = Op.getOperand(0);
8763 SDValue Op1 = Op.getOperand(1);
8764 SDValue Op2 = Op.getOperand(2);
8765 DebugLoc DL = Op.getDebugLoc();
8768 if (Cond.getOpcode() == ISD::SETCC) {
8769 SDValue NewCond = LowerSETCC(Cond, DAG);
8770 if (NewCond.getNode())
8774 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8775 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8776 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8777 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8778 if (Cond.getOpcode() == X86ISD::SETCC &&
8779 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8780 isZero(Cond.getOperand(1).getOperand(1))) {
8781 SDValue Cmp = Cond.getOperand(1);
8783 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8785 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8786 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8787 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8789 SDValue CmpOp0 = Cmp.getOperand(0);
8790 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8791 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8793 SDValue Res = // Res = 0 or -1.
8794 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8795 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8797 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8798 Res = DAG.getNOT(DL, Res, Res.getValueType());
8800 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8801 if (N2C == 0 || !N2C->isNullValue())
8802 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8807 // Look past (and (setcc_carry (cmp ...)), 1).
8808 if (Cond.getOpcode() == ISD::AND &&
8809 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8810 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8811 if (C && C->getAPIntValue() == 1)
8812 Cond = Cond.getOperand(0);
8815 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8816 // setting operand in place of the X86ISD::SETCC.
8817 unsigned CondOpcode = Cond.getOpcode();
8818 if (CondOpcode == X86ISD::SETCC ||
8819 CondOpcode == X86ISD::SETCC_CARRY) {
8820 CC = Cond.getOperand(0);
8822 SDValue Cmp = Cond.getOperand(1);
8823 unsigned Opc = Cmp.getOpcode();
8824 EVT VT = Op.getValueType();
8826 bool IllegalFPCMov = false;
8827 if (VT.isFloatingPoint() && !VT.isVector() &&
8828 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8829 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8831 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8832 Opc == X86ISD::BT) { // FIXME
8836 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8837 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8838 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8839 Cond.getOperand(0).getValueType() != MVT::i8)) {
8840 SDValue LHS = Cond.getOperand(0);
8841 SDValue RHS = Cond.getOperand(1);
8845 switch (CondOpcode) {
8846 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8847 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8848 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8849 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8850 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8851 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8852 default: llvm_unreachable("unexpected overflowing operator");
8854 if (CondOpcode == ISD::UMULO)
8855 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8858 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8860 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8862 if (CondOpcode == ISD::UMULO)
8863 Cond = X86Op.getValue(2);
8865 Cond = X86Op.getValue(1);
8867 CC = DAG.getConstant(X86Cond, MVT::i8);
8872 // Look pass the truncate.
8873 if (Cond.getOpcode() == ISD::TRUNCATE)
8874 Cond = Cond.getOperand(0);
8876 // We know the result of AND is compared against zero. Try to match
8878 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8879 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8880 if (NewSetCC.getNode()) {
8881 CC = NewSetCC.getOperand(0);
8882 Cond = NewSetCC.getOperand(1);
8889 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8890 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8893 // a < b ? -1 : 0 -> RES = ~setcc_carry
8894 // a < b ? 0 : -1 -> RES = setcc_carry
8895 // a >= b ? -1 : 0 -> RES = setcc_carry
8896 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8897 if (Cond.getOpcode() == X86ISD::CMP) {
8898 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8900 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8901 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8902 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8903 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8904 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8905 return DAG.getNOT(DL, Res, Res.getValueType());
8910 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8911 // condition is true.
8912 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8913 SDValue Ops[] = { Op2, Op1, CC, Cond };
8914 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8917 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8918 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8919 // from the AND / OR.
8920 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8921 Opc = Op.getOpcode();
8922 if (Opc != ISD::OR && Opc != ISD::AND)
8924 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8925 Op.getOperand(0).hasOneUse() &&
8926 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8927 Op.getOperand(1).hasOneUse());
8930 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8931 // 1 and that the SETCC node has a single use.
8932 static bool isXor1OfSetCC(SDValue Op) {
8933 if (Op.getOpcode() != ISD::XOR)
8935 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8936 if (N1C && N1C->getAPIntValue() == 1) {
8937 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8938 Op.getOperand(0).hasOneUse();
8943 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8944 bool addTest = true;
8945 SDValue Chain = Op.getOperand(0);
8946 SDValue Cond = Op.getOperand(1);
8947 SDValue Dest = Op.getOperand(2);
8948 DebugLoc dl = Op.getDebugLoc();
8950 bool Inverted = false;
8952 if (Cond.getOpcode() == ISD::SETCC) {
8953 // Check for setcc([su]{add,sub,mul}o == 0).
8954 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8955 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8956 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8957 Cond.getOperand(0).getResNo() == 1 &&
8958 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8959 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8960 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8961 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8962 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8963 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8965 Cond = Cond.getOperand(0);
8967 SDValue NewCond = LowerSETCC(Cond, DAG);
8968 if (NewCond.getNode())
8973 // FIXME: LowerXALUO doesn't handle these!!
8974 else if (Cond.getOpcode() == X86ISD::ADD ||
8975 Cond.getOpcode() == X86ISD::SUB ||
8976 Cond.getOpcode() == X86ISD::SMUL ||
8977 Cond.getOpcode() == X86ISD::UMUL)
8978 Cond = LowerXALUO(Cond, DAG);
8981 // Look pass (and (setcc_carry (cmp ...)), 1).
8982 if (Cond.getOpcode() == ISD::AND &&
8983 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8984 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8985 if (C && C->getAPIntValue() == 1)
8986 Cond = Cond.getOperand(0);
8989 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8990 // setting operand in place of the X86ISD::SETCC.
8991 unsigned CondOpcode = Cond.getOpcode();
8992 if (CondOpcode == X86ISD::SETCC ||
8993 CondOpcode == X86ISD::SETCC_CARRY) {
8994 CC = Cond.getOperand(0);
8996 SDValue Cmp = Cond.getOperand(1);
8997 unsigned Opc = Cmp.getOpcode();
8998 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8999 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9003 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9007 // These can only come from an arithmetic instruction with overflow,
9008 // e.g. SADDO, UADDO.
9009 Cond = Cond.getNode()->getOperand(1);
9015 CondOpcode = Cond.getOpcode();
9016 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9017 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9018 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9019 Cond.getOperand(0).getValueType() != MVT::i8)) {
9020 SDValue LHS = Cond.getOperand(0);
9021 SDValue RHS = Cond.getOperand(1);
9025 switch (CondOpcode) {
9026 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9027 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9028 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9029 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9030 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9031 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9032 default: llvm_unreachable("unexpected overflowing operator");
9035 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9036 if (CondOpcode == ISD::UMULO)
9037 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9040 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9042 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9044 if (CondOpcode == ISD::UMULO)
9045 Cond = X86Op.getValue(2);
9047 Cond = X86Op.getValue(1);
9049 CC = DAG.getConstant(X86Cond, MVT::i8);
9053 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9054 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9055 if (CondOpc == ISD::OR) {
9056 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9057 // two branches instead of an explicit OR instruction with a
9059 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9060 isX86LogicalCmp(Cmp)) {
9061 CC = Cond.getOperand(0).getOperand(0);
9062 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9063 Chain, Dest, CC, Cmp);
9064 CC = Cond.getOperand(1).getOperand(0);
9068 } else { // ISD::AND
9069 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9070 // two branches instead of an explicit AND instruction with a
9071 // separate test. However, we only do this if this block doesn't
9072 // have a fall-through edge, because this requires an explicit
9073 // jmp when the condition is false.
9074 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9075 isX86LogicalCmp(Cmp) &&
9076 Op.getNode()->hasOneUse()) {
9077 X86::CondCode CCode =
9078 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9079 CCode = X86::GetOppositeBranchCondition(CCode);
9080 CC = DAG.getConstant(CCode, MVT::i8);
9081 SDNode *User = *Op.getNode()->use_begin();
9082 // Look for an unconditional branch following this conditional branch.
9083 // We need this because we need to reverse the successors in order
9084 // to implement FCMP_OEQ.
9085 if (User->getOpcode() == ISD::BR) {
9086 SDValue FalseBB = User->getOperand(1);
9088 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9089 assert(NewBR == User);
9093 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9094 Chain, Dest, CC, Cmp);
9095 X86::CondCode CCode =
9096 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9097 CCode = X86::GetOppositeBranchCondition(CCode);
9098 CC = DAG.getConstant(CCode, MVT::i8);
9104 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9105 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9106 // It should be transformed during dag combiner except when the condition
9107 // is set by a arithmetics with overflow node.
9108 X86::CondCode CCode =
9109 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9110 CCode = X86::GetOppositeBranchCondition(CCode);
9111 CC = DAG.getConstant(CCode, MVT::i8);
9112 Cond = Cond.getOperand(0).getOperand(1);
9114 } else if (Cond.getOpcode() == ISD::SETCC &&
9115 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9116 // For FCMP_OEQ, we can emit
9117 // two branches instead of an explicit AND instruction with a
9118 // separate test. However, we only do this if this block doesn't
9119 // have a fall-through edge, because this requires an explicit
9120 // jmp when the condition is false.
9121 if (Op.getNode()->hasOneUse()) {
9122 SDNode *User = *Op.getNode()->use_begin();
9123 // Look for an unconditional branch following this conditional branch.
9124 // We need this because we need to reverse the successors in order
9125 // to implement FCMP_OEQ.
9126 if (User->getOpcode() == ISD::BR) {
9127 SDValue FalseBB = User->getOperand(1);
9129 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9130 assert(NewBR == User);
9134 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9135 Cond.getOperand(0), Cond.getOperand(1));
9136 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9137 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9138 Chain, Dest, CC, Cmp);
9139 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9144 } else if (Cond.getOpcode() == ISD::SETCC &&
9145 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9146 // For FCMP_UNE, we can emit
9147 // two branches instead of an explicit AND instruction with a
9148 // separate test. However, we only do this if this block doesn't
9149 // have a fall-through edge, because this requires an explicit
9150 // jmp when the condition is false.
9151 if (Op.getNode()->hasOneUse()) {
9152 SDNode *User = *Op.getNode()->use_begin();
9153 // Look for an unconditional branch following this conditional branch.
9154 // We need this because we need to reverse the successors in order
9155 // to implement FCMP_UNE.
9156 if (User->getOpcode() == ISD::BR) {
9157 SDValue FalseBB = User->getOperand(1);
9159 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9160 assert(NewBR == User);
9163 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9164 Cond.getOperand(0), Cond.getOperand(1));
9165 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9166 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9167 Chain, Dest, CC, Cmp);
9168 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9178 // Look pass the truncate.
9179 if (Cond.getOpcode() == ISD::TRUNCATE)
9180 Cond = Cond.getOperand(0);
9182 // We know the result of AND is compared against zero. Try to match
9184 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9185 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9186 if (NewSetCC.getNode()) {
9187 CC = NewSetCC.getOperand(0);
9188 Cond = NewSetCC.getOperand(1);
9195 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9196 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9198 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9199 Chain, Dest, CC, Cond);
9203 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9204 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9205 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9206 // that the guard pages used by the OS virtual memory manager are allocated in
9207 // correct sequence.
9209 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9210 SelectionDAG &DAG) const {
9211 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9212 EnableSegmentedStacks) &&
9213 "This should be used only on Windows targets or when segmented stacks "
9215 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9216 DebugLoc dl = Op.getDebugLoc();
9219 SDValue Chain = Op.getOperand(0);
9220 SDValue Size = Op.getOperand(1);
9221 // FIXME: Ensure alignment here
9223 bool Is64Bit = Subtarget->is64Bit();
9224 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9226 if (EnableSegmentedStacks) {
9227 MachineFunction &MF = DAG.getMachineFunction();
9228 MachineRegisterInfo &MRI = MF.getRegInfo();
9231 // The 64 bit implementation of segmented stacks needs to clobber both r10
9232 // r11. This makes it impossible to use it along with nested parameters.
9233 const Function *F = MF.getFunction();
9235 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9237 if (I->hasNestAttr())
9238 report_fatal_error("Cannot use segmented stacks with functions that "
9239 "have nested arguments.");
9242 const TargetRegisterClass *AddrRegClass =
9243 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9244 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9245 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9246 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9247 DAG.getRegister(Vreg, SPTy));
9248 SDValue Ops1[2] = { Value, Chain };
9249 return DAG.getMergeValues(Ops1, 2, dl);
9252 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9254 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9255 Flag = Chain.getValue(1);
9256 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9258 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9259 Flag = Chain.getValue(1);
9261 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9263 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9264 return DAG.getMergeValues(Ops1, 2, dl);
9268 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9269 MachineFunction &MF = DAG.getMachineFunction();
9270 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9272 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9273 DebugLoc DL = Op.getDebugLoc();
9275 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9276 // vastart just stores the address of the VarArgsFrameIndex slot into the
9277 // memory location argument.
9278 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9280 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9281 MachinePointerInfo(SV), false, false, 0);
9285 // gp_offset (0 - 6 * 8)
9286 // fp_offset (48 - 48 + 8 * 16)
9287 // overflow_arg_area (point to parameters coming in memory).
9289 SmallVector<SDValue, 8> MemOps;
9290 SDValue FIN = Op.getOperand(1);
9292 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9293 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9295 FIN, MachinePointerInfo(SV), false, false, 0);
9296 MemOps.push_back(Store);
9299 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9300 FIN, DAG.getIntPtrConstant(4));
9301 Store = DAG.getStore(Op.getOperand(0), DL,
9302 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9304 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9305 MemOps.push_back(Store);
9307 // Store ptr to overflow_arg_area
9308 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9309 FIN, DAG.getIntPtrConstant(4));
9310 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9312 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9313 MachinePointerInfo(SV, 8),
9315 MemOps.push_back(Store);
9317 // Store ptr to reg_save_area.
9318 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9319 FIN, DAG.getIntPtrConstant(8));
9320 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9322 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9323 MachinePointerInfo(SV, 16), false, false, 0);
9324 MemOps.push_back(Store);
9325 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9326 &MemOps[0], MemOps.size());
9329 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9330 assert(Subtarget->is64Bit() &&
9331 "LowerVAARG only handles 64-bit va_arg!");
9332 assert((Subtarget->isTargetLinux() ||
9333 Subtarget->isTargetDarwin()) &&
9334 "Unhandled target in LowerVAARG");
9335 assert(Op.getNode()->getNumOperands() == 4);
9336 SDValue Chain = Op.getOperand(0);
9337 SDValue SrcPtr = Op.getOperand(1);
9338 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9339 unsigned Align = Op.getConstantOperandVal(3);
9340 DebugLoc dl = Op.getDebugLoc();
9342 EVT ArgVT = Op.getNode()->getValueType(0);
9343 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9344 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9347 // Decide which area this value should be read from.
9348 // TODO: Implement the AMD64 ABI in its entirety. This simple
9349 // selection mechanism works only for the basic types.
9350 if (ArgVT == MVT::f80) {
9351 llvm_unreachable("va_arg for f80 not yet implemented");
9352 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9353 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9354 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9355 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9357 llvm_unreachable("Unhandled argument type in LowerVAARG");
9361 // Sanity Check: Make sure using fp_offset makes sense.
9362 assert(!UseSoftFloat &&
9363 !(DAG.getMachineFunction()
9364 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9365 Subtarget->hasXMM());
9368 // Insert VAARG_64 node into the DAG
9369 // VAARG_64 returns two values: Variable Argument Address, Chain
9370 SmallVector<SDValue, 11> InstOps;
9371 InstOps.push_back(Chain);
9372 InstOps.push_back(SrcPtr);
9373 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9374 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9375 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9376 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9377 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9378 VTs, &InstOps[0], InstOps.size(),
9380 MachinePointerInfo(SV),
9385 Chain = VAARG.getValue(1);
9387 // Load the next argument and return it
9388 return DAG.getLoad(ArgVT, dl,
9391 MachinePointerInfo(),
9392 false, false, false, 0);
9395 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9396 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9397 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9398 SDValue Chain = Op.getOperand(0);
9399 SDValue DstPtr = Op.getOperand(1);
9400 SDValue SrcPtr = Op.getOperand(2);
9401 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9402 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9403 DebugLoc DL = Op.getDebugLoc();
9405 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9406 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9408 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9412 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9413 DebugLoc dl = Op.getDebugLoc();
9414 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9416 default: return SDValue(); // Don't custom lower most intrinsics.
9417 // Comparison intrinsics.
9418 case Intrinsic::x86_sse_comieq_ss:
9419 case Intrinsic::x86_sse_comilt_ss:
9420 case Intrinsic::x86_sse_comile_ss:
9421 case Intrinsic::x86_sse_comigt_ss:
9422 case Intrinsic::x86_sse_comige_ss:
9423 case Intrinsic::x86_sse_comineq_ss:
9424 case Intrinsic::x86_sse_ucomieq_ss:
9425 case Intrinsic::x86_sse_ucomilt_ss:
9426 case Intrinsic::x86_sse_ucomile_ss:
9427 case Intrinsic::x86_sse_ucomigt_ss:
9428 case Intrinsic::x86_sse_ucomige_ss:
9429 case Intrinsic::x86_sse_ucomineq_ss:
9430 case Intrinsic::x86_sse2_comieq_sd:
9431 case Intrinsic::x86_sse2_comilt_sd:
9432 case Intrinsic::x86_sse2_comile_sd:
9433 case Intrinsic::x86_sse2_comigt_sd:
9434 case Intrinsic::x86_sse2_comige_sd:
9435 case Intrinsic::x86_sse2_comineq_sd:
9436 case Intrinsic::x86_sse2_ucomieq_sd:
9437 case Intrinsic::x86_sse2_ucomilt_sd:
9438 case Intrinsic::x86_sse2_ucomile_sd:
9439 case Intrinsic::x86_sse2_ucomigt_sd:
9440 case Intrinsic::x86_sse2_ucomige_sd:
9441 case Intrinsic::x86_sse2_ucomineq_sd: {
9443 ISD::CondCode CC = ISD::SETCC_INVALID;
9446 case Intrinsic::x86_sse_comieq_ss:
9447 case Intrinsic::x86_sse2_comieq_sd:
9451 case Intrinsic::x86_sse_comilt_ss:
9452 case Intrinsic::x86_sse2_comilt_sd:
9456 case Intrinsic::x86_sse_comile_ss:
9457 case Intrinsic::x86_sse2_comile_sd:
9461 case Intrinsic::x86_sse_comigt_ss:
9462 case Intrinsic::x86_sse2_comigt_sd:
9466 case Intrinsic::x86_sse_comige_ss:
9467 case Intrinsic::x86_sse2_comige_sd:
9471 case Intrinsic::x86_sse_comineq_ss:
9472 case Intrinsic::x86_sse2_comineq_sd:
9476 case Intrinsic::x86_sse_ucomieq_ss:
9477 case Intrinsic::x86_sse2_ucomieq_sd:
9478 Opc = X86ISD::UCOMI;
9481 case Intrinsic::x86_sse_ucomilt_ss:
9482 case Intrinsic::x86_sse2_ucomilt_sd:
9483 Opc = X86ISD::UCOMI;
9486 case Intrinsic::x86_sse_ucomile_ss:
9487 case Intrinsic::x86_sse2_ucomile_sd:
9488 Opc = X86ISD::UCOMI;
9491 case Intrinsic::x86_sse_ucomigt_ss:
9492 case Intrinsic::x86_sse2_ucomigt_sd:
9493 Opc = X86ISD::UCOMI;
9496 case Intrinsic::x86_sse_ucomige_ss:
9497 case Intrinsic::x86_sse2_ucomige_sd:
9498 Opc = X86ISD::UCOMI;
9501 case Intrinsic::x86_sse_ucomineq_ss:
9502 case Intrinsic::x86_sse2_ucomineq_sd:
9503 Opc = X86ISD::UCOMI;
9508 SDValue LHS = Op.getOperand(1);
9509 SDValue RHS = Op.getOperand(2);
9510 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9511 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9512 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9513 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9514 DAG.getConstant(X86CC, MVT::i8), Cond);
9515 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9517 // Arithmetic intrinsics.
9518 case Intrinsic::x86_sse3_hadd_ps:
9519 case Intrinsic::x86_sse3_hadd_pd:
9520 case Intrinsic::x86_avx_hadd_ps_256:
9521 case Intrinsic::x86_avx_hadd_pd_256:
9522 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9523 Op.getOperand(1), Op.getOperand(2));
9524 case Intrinsic::x86_sse3_hsub_ps:
9525 case Intrinsic::x86_sse3_hsub_pd:
9526 case Intrinsic::x86_avx_hsub_ps_256:
9527 case Intrinsic::x86_avx_hsub_pd_256:
9528 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9529 Op.getOperand(1), Op.getOperand(2));
9530 case Intrinsic::x86_avx2_psllv_d:
9531 case Intrinsic::x86_avx2_psllv_q:
9532 case Intrinsic::x86_avx2_psllv_d_256:
9533 case Intrinsic::x86_avx2_psllv_q_256:
9534 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9535 Op.getOperand(1), Op.getOperand(2));
9536 case Intrinsic::x86_avx2_psrlv_d:
9537 case Intrinsic::x86_avx2_psrlv_q:
9538 case Intrinsic::x86_avx2_psrlv_d_256:
9539 case Intrinsic::x86_avx2_psrlv_q_256:
9540 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9541 Op.getOperand(1), Op.getOperand(2));
9542 case Intrinsic::x86_avx2_psrav_d:
9543 case Intrinsic::x86_avx2_psrav_d_256:
9544 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9545 Op.getOperand(1), Op.getOperand(2));
9547 // ptest and testp intrinsics. The intrinsic these come from are designed to
9548 // return an integer value, not just an instruction so lower it to the ptest
9549 // or testp pattern and a setcc for the result.
9550 case Intrinsic::x86_sse41_ptestz:
9551 case Intrinsic::x86_sse41_ptestc:
9552 case Intrinsic::x86_sse41_ptestnzc:
9553 case Intrinsic::x86_avx_ptestz_256:
9554 case Intrinsic::x86_avx_ptestc_256:
9555 case Intrinsic::x86_avx_ptestnzc_256:
9556 case Intrinsic::x86_avx_vtestz_ps:
9557 case Intrinsic::x86_avx_vtestc_ps:
9558 case Intrinsic::x86_avx_vtestnzc_ps:
9559 case Intrinsic::x86_avx_vtestz_pd:
9560 case Intrinsic::x86_avx_vtestc_pd:
9561 case Intrinsic::x86_avx_vtestnzc_pd:
9562 case Intrinsic::x86_avx_vtestz_ps_256:
9563 case Intrinsic::x86_avx_vtestc_ps_256:
9564 case Intrinsic::x86_avx_vtestnzc_ps_256:
9565 case Intrinsic::x86_avx_vtestz_pd_256:
9566 case Intrinsic::x86_avx_vtestc_pd_256:
9567 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9568 bool IsTestPacked = false;
9571 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9572 case Intrinsic::x86_avx_vtestz_ps:
9573 case Intrinsic::x86_avx_vtestz_pd:
9574 case Intrinsic::x86_avx_vtestz_ps_256:
9575 case Intrinsic::x86_avx_vtestz_pd_256:
9576 IsTestPacked = true; // Fallthrough
9577 case Intrinsic::x86_sse41_ptestz:
9578 case Intrinsic::x86_avx_ptestz_256:
9580 X86CC = X86::COND_E;
9582 case Intrinsic::x86_avx_vtestc_ps:
9583 case Intrinsic::x86_avx_vtestc_pd:
9584 case Intrinsic::x86_avx_vtestc_ps_256:
9585 case Intrinsic::x86_avx_vtestc_pd_256:
9586 IsTestPacked = true; // Fallthrough
9587 case Intrinsic::x86_sse41_ptestc:
9588 case Intrinsic::x86_avx_ptestc_256:
9590 X86CC = X86::COND_B;
9592 case Intrinsic::x86_avx_vtestnzc_ps:
9593 case Intrinsic::x86_avx_vtestnzc_pd:
9594 case Intrinsic::x86_avx_vtestnzc_ps_256:
9595 case Intrinsic::x86_avx_vtestnzc_pd_256:
9596 IsTestPacked = true; // Fallthrough
9597 case Intrinsic::x86_sse41_ptestnzc:
9598 case Intrinsic::x86_avx_ptestnzc_256:
9600 X86CC = X86::COND_A;
9604 SDValue LHS = Op.getOperand(1);
9605 SDValue RHS = Op.getOperand(2);
9606 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9607 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9608 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9609 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9610 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9613 // Fix vector shift instructions where the last operand is a non-immediate
9615 case Intrinsic::x86_avx2_pslli_w:
9616 case Intrinsic::x86_avx2_pslli_d:
9617 case Intrinsic::x86_avx2_pslli_q:
9618 case Intrinsic::x86_avx2_psrli_w:
9619 case Intrinsic::x86_avx2_psrli_d:
9620 case Intrinsic::x86_avx2_psrli_q:
9621 case Intrinsic::x86_avx2_psrai_w:
9622 case Intrinsic::x86_avx2_psrai_d:
9623 case Intrinsic::x86_sse2_pslli_w:
9624 case Intrinsic::x86_sse2_pslli_d:
9625 case Intrinsic::x86_sse2_pslli_q:
9626 case Intrinsic::x86_sse2_psrli_w:
9627 case Intrinsic::x86_sse2_psrli_d:
9628 case Intrinsic::x86_sse2_psrli_q:
9629 case Intrinsic::x86_sse2_psrai_w:
9630 case Intrinsic::x86_sse2_psrai_d:
9631 case Intrinsic::x86_mmx_pslli_w:
9632 case Intrinsic::x86_mmx_pslli_d:
9633 case Intrinsic::x86_mmx_pslli_q:
9634 case Intrinsic::x86_mmx_psrli_w:
9635 case Intrinsic::x86_mmx_psrli_d:
9636 case Intrinsic::x86_mmx_psrli_q:
9637 case Intrinsic::x86_mmx_psrai_w:
9638 case Intrinsic::x86_mmx_psrai_d: {
9639 SDValue ShAmt = Op.getOperand(2);
9640 if (isa<ConstantSDNode>(ShAmt))
9643 unsigned NewIntNo = 0;
9644 EVT ShAmtVT = MVT::v4i32;
9646 case Intrinsic::x86_sse2_pslli_w:
9647 NewIntNo = Intrinsic::x86_sse2_psll_w;
9649 case Intrinsic::x86_sse2_pslli_d:
9650 NewIntNo = Intrinsic::x86_sse2_psll_d;
9652 case Intrinsic::x86_sse2_pslli_q:
9653 NewIntNo = Intrinsic::x86_sse2_psll_q;
9655 case Intrinsic::x86_sse2_psrli_w:
9656 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9658 case Intrinsic::x86_sse2_psrli_d:
9659 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9661 case Intrinsic::x86_sse2_psrli_q:
9662 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9664 case Intrinsic::x86_sse2_psrai_w:
9665 NewIntNo = Intrinsic::x86_sse2_psra_w;
9667 case Intrinsic::x86_sse2_psrai_d:
9668 NewIntNo = Intrinsic::x86_sse2_psra_d;
9670 case Intrinsic::x86_avx2_pslli_w:
9671 NewIntNo = Intrinsic::x86_avx2_psll_w;
9673 case Intrinsic::x86_avx2_pslli_d:
9674 NewIntNo = Intrinsic::x86_avx2_psll_d;
9676 case Intrinsic::x86_avx2_pslli_q:
9677 NewIntNo = Intrinsic::x86_avx2_psll_q;
9679 case Intrinsic::x86_avx2_psrli_w:
9680 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9682 case Intrinsic::x86_avx2_psrli_d:
9683 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9685 case Intrinsic::x86_avx2_psrli_q:
9686 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9688 case Intrinsic::x86_avx2_psrai_w:
9689 NewIntNo = Intrinsic::x86_avx2_psra_w;
9691 case Intrinsic::x86_avx2_psrai_d:
9692 NewIntNo = Intrinsic::x86_avx2_psra_d;
9695 ShAmtVT = MVT::v2i32;
9697 case Intrinsic::x86_mmx_pslli_w:
9698 NewIntNo = Intrinsic::x86_mmx_psll_w;
9700 case Intrinsic::x86_mmx_pslli_d:
9701 NewIntNo = Intrinsic::x86_mmx_psll_d;
9703 case Intrinsic::x86_mmx_pslli_q:
9704 NewIntNo = Intrinsic::x86_mmx_psll_q;
9706 case Intrinsic::x86_mmx_psrli_w:
9707 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9709 case Intrinsic::x86_mmx_psrli_d:
9710 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9712 case Intrinsic::x86_mmx_psrli_q:
9713 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9715 case Intrinsic::x86_mmx_psrai_w:
9716 NewIntNo = Intrinsic::x86_mmx_psra_w;
9718 case Intrinsic::x86_mmx_psrai_d:
9719 NewIntNo = Intrinsic::x86_mmx_psra_d;
9721 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9727 // The vector shift intrinsics with scalars uses 32b shift amounts but
9728 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9732 ShOps[1] = DAG.getConstant(0, MVT::i32);
9733 if (ShAmtVT == MVT::v4i32) {
9734 ShOps[2] = DAG.getUNDEF(MVT::i32);
9735 ShOps[3] = DAG.getUNDEF(MVT::i32);
9736 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9738 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9739 // FIXME this must be lowered to get rid of the invalid type.
9742 EVT VT = Op.getValueType();
9743 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9744 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9745 DAG.getConstant(NewIntNo, MVT::i32),
9746 Op.getOperand(1), ShAmt);
9751 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9752 SelectionDAG &DAG) const {
9753 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9754 MFI->setReturnAddressIsTaken(true);
9756 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9757 DebugLoc dl = Op.getDebugLoc();
9760 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9762 DAG.getConstant(TD->getPointerSize(),
9763 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9764 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9765 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9767 MachinePointerInfo(), false, false, false, 0);
9770 // Just load the return address.
9771 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9772 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9773 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9776 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9777 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9778 MFI->setFrameAddressIsTaken(true);
9780 EVT VT = Op.getValueType();
9781 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9782 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9783 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9784 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9786 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9787 MachinePointerInfo(),
9788 false, false, false, 0);
9792 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9793 SelectionDAG &DAG) const {
9794 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9797 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9798 MachineFunction &MF = DAG.getMachineFunction();
9799 SDValue Chain = Op.getOperand(0);
9800 SDValue Offset = Op.getOperand(1);
9801 SDValue Handler = Op.getOperand(2);
9802 DebugLoc dl = Op.getDebugLoc();
9804 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9805 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9807 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9809 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9810 DAG.getIntPtrConstant(TD->getPointerSize()));
9811 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9812 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9814 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9815 MF.getRegInfo().addLiveOut(StoreAddrReg);
9817 return DAG.getNode(X86ISD::EH_RETURN, dl,
9819 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9822 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9823 SelectionDAG &DAG) const {
9824 return Op.getOperand(0);
9827 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9828 SelectionDAG &DAG) const {
9829 SDValue Root = Op.getOperand(0);
9830 SDValue Trmp = Op.getOperand(1); // trampoline
9831 SDValue FPtr = Op.getOperand(2); // nested function
9832 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9833 DebugLoc dl = Op.getDebugLoc();
9835 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9837 if (Subtarget->is64Bit()) {
9838 SDValue OutChains[6];
9840 // Large code-model.
9841 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9842 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9844 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9845 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9847 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9849 // Load the pointer to the nested function into R11.
9850 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9851 SDValue Addr = Trmp;
9852 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9853 Addr, MachinePointerInfo(TrmpAddr),
9856 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9857 DAG.getConstant(2, MVT::i64));
9858 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9859 MachinePointerInfo(TrmpAddr, 2),
9862 // Load the 'nest' parameter value into R10.
9863 // R10 is specified in X86CallingConv.td
9864 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9865 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9866 DAG.getConstant(10, MVT::i64));
9867 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9868 Addr, MachinePointerInfo(TrmpAddr, 10),
9871 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9872 DAG.getConstant(12, MVT::i64));
9873 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9874 MachinePointerInfo(TrmpAddr, 12),
9877 // Jump to the nested function.
9878 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9879 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9880 DAG.getConstant(20, MVT::i64));
9881 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9882 Addr, MachinePointerInfo(TrmpAddr, 20),
9885 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9886 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9887 DAG.getConstant(22, MVT::i64));
9888 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9889 MachinePointerInfo(TrmpAddr, 22),
9892 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9894 const Function *Func =
9895 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9896 CallingConv::ID CC = Func->getCallingConv();
9901 llvm_unreachable("Unsupported calling convention");
9902 case CallingConv::C:
9903 case CallingConv::X86_StdCall: {
9904 // Pass 'nest' parameter in ECX.
9905 // Must be kept in sync with X86CallingConv.td
9908 // Check that ECX wasn't needed by an 'inreg' parameter.
9909 FunctionType *FTy = Func->getFunctionType();
9910 const AttrListPtr &Attrs = Func->getAttributes();
9912 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9913 unsigned InRegCount = 0;
9916 for (FunctionType::param_iterator I = FTy->param_begin(),
9917 E = FTy->param_end(); I != E; ++I, ++Idx)
9918 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9919 // FIXME: should only count parameters that are lowered to integers.
9920 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9922 if (InRegCount > 2) {
9923 report_fatal_error("Nest register in use - reduce number of inreg"
9929 case CallingConv::X86_FastCall:
9930 case CallingConv::X86_ThisCall:
9931 case CallingConv::Fast:
9932 // Pass 'nest' parameter in EAX.
9933 // Must be kept in sync with X86CallingConv.td
9938 SDValue OutChains[4];
9941 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9942 DAG.getConstant(10, MVT::i32));
9943 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9945 // This is storing the opcode for MOV32ri.
9946 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9947 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9948 OutChains[0] = DAG.getStore(Root, dl,
9949 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9950 Trmp, MachinePointerInfo(TrmpAddr),
9953 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9954 DAG.getConstant(1, MVT::i32));
9955 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9956 MachinePointerInfo(TrmpAddr, 1),
9959 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9960 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9961 DAG.getConstant(5, MVT::i32));
9962 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9963 MachinePointerInfo(TrmpAddr, 5),
9966 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9967 DAG.getConstant(6, MVT::i32));
9968 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9969 MachinePointerInfo(TrmpAddr, 6),
9972 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9976 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9977 SelectionDAG &DAG) const {
9979 The rounding mode is in bits 11:10 of FPSR, and has the following
9986 FLT_ROUNDS, on the other hand, expects the following:
9993 To perform the conversion, we do:
9994 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9997 MachineFunction &MF = DAG.getMachineFunction();
9998 const TargetMachine &TM = MF.getTarget();
9999 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10000 unsigned StackAlignment = TFI.getStackAlignment();
10001 EVT VT = Op.getValueType();
10002 DebugLoc DL = Op.getDebugLoc();
10004 // Save FP Control Word to stack slot
10005 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10006 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10009 MachineMemOperand *MMO =
10010 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10011 MachineMemOperand::MOStore, 2, 2);
10013 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10014 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10015 DAG.getVTList(MVT::Other),
10016 Ops, 2, MVT::i16, MMO);
10018 // Load FP Control Word from stack slot
10019 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10020 MachinePointerInfo(), false, false, false, 0);
10022 // Transform as necessary
10024 DAG.getNode(ISD::SRL, DL, MVT::i16,
10025 DAG.getNode(ISD::AND, DL, MVT::i16,
10026 CWD, DAG.getConstant(0x800, MVT::i16)),
10027 DAG.getConstant(11, MVT::i8));
10029 DAG.getNode(ISD::SRL, DL, MVT::i16,
10030 DAG.getNode(ISD::AND, DL, MVT::i16,
10031 CWD, DAG.getConstant(0x400, MVT::i16)),
10032 DAG.getConstant(9, MVT::i8));
10035 DAG.getNode(ISD::AND, DL, MVT::i16,
10036 DAG.getNode(ISD::ADD, DL, MVT::i16,
10037 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10038 DAG.getConstant(1, MVT::i16)),
10039 DAG.getConstant(3, MVT::i16));
10042 return DAG.getNode((VT.getSizeInBits() < 16 ?
10043 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10046 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10047 EVT VT = Op.getValueType();
10049 unsigned NumBits = VT.getSizeInBits();
10050 DebugLoc dl = Op.getDebugLoc();
10052 Op = Op.getOperand(0);
10053 if (VT == MVT::i8) {
10054 // Zero extend to i32 since there is not an i8 bsr.
10056 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10059 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10060 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10061 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10063 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10066 DAG.getConstant(NumBits+NumBits-1, OpVT),
10067 DAG.getConstant(X86::COND_E, MVT::i8),
10070 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10072 // Finally xor with NumBits-1.
10073 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10076 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10080 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10081 EVT VT = Op.getValueType();
10083 unsigned NumBits = VT.getSizeInBits();
10084 DebugLoc dl = Op.getDebugLoc();
10086 Op = Op.getOperand(0);
10087 if (VT == MVT::i8) {
10089 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10092 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10093 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10094 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10096 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10099 DAG.getConstant(NumBits, OpVT),
10100 DAG.getConstant(X86::COND_E, MVT::i8),
10103 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10106 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10110 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10111 // ones, and then concatenate the result back.
10112 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10113 EVT VT = Op.getValueType();
10115 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10116 "Unsupported value type for operation");
10118 int NumElems = VT.getVectorNumElements();
10119 DebugLoc dl = Op.getDebugLoc();
10120 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10121 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10123 // Extract the LHS vectors
10124 SDValue LHS = Op.getOperand(0);
10125 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10126 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10128 // Extract the RHS vectors
10129 SDValue RHS = Op.getOperand(1);
10130 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10131 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10133 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10134 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10136 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10137 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10138 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10141 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10142 assert(Op.getValueType().getSizeInBits() == 256 &&
10143 Op.getValueType().isInteger() &&
10144 "Only handle AVX 256-bit vector integer operation");
10145 return Lower256IntArith(Op, DAG);
10148 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10149 assert(Op.getValueType().getSizeInBits() == 256 &&
10150 Op.getValueType().isInteger() &&
10151 "Only handle AVX 256-bit vector integer operation");
10152 return Lower256IntArith(Op, DAG);
10155 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10156 EVT VT = Op.getValueType();
10158 // Decompose 256-bit ops into smaller 128-bit ops.
10159 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10160 return Lower256IntArith(Op, DAG);
10162 DebugLoc dl = Op.getDebugLoc();
10164 SDValue A = Op.getOperand(0);
10165 SDValue B = Op.getOperand(1);
10167 if (VT == MVT::v4i64) {
10168 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10170 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10171 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10172 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10173 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10174 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10176 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10177 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10178 // return AloBlo + AloBhi + AhiBlo;
10180 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10181 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10182 A, DAG.getConstant(32, MVT::i32));
10183 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10184 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10185 B, DAG.getConstant(32, MVT::i32));
10186 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10187 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10189 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10190 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10192 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10193 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10195 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10196 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10197 AloBhi, DAG.getConstant(32, MVT::i32));
10198 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10199 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10200 AhiBlo, DAG.getConstant(32, MVT::i32));
10201 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10202 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10206 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10208 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10209 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10210 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10211 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10212 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10214 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10215 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10216 // return AloBlo + AloBhi + AhiBlo;
10218 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10219 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10220 A, DAG.getConstant(32, MVT::i32));
10221 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10222 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10223 B, DAG.getConstant(32, MVT::i32));
10224 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10225 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10227 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10230 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10231 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10233 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10234 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10235 AloBhi, DAG.getConstant(32, MVT::i32));
10236 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10237 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10238 AhiBlo, DAG.getConstant(32, MVT::i32));
10239 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10240 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10244 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10246 EVT VT = Op.getValueType();
10247 DebugLoc dl = Op.getDebugLoc();
10248 SDValue R = Op.getOperand(0);
10249 SDValue Amt = Op.getOperand(1);
10250 LLVMContext *Context = DAG.getContext();
10252 if (!Subtarget->hasXMMInt())
10255 // Optimize shl/srl/sra with constant shift amount.
10256 if (isSplatVector(Amt.getNode())) {
10257 SDValue SclrAmt = Amt->getOperand(0);
10258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10259 uint64_t ShiftAmt = C->getZExtValue();
10261 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10262 // Make a large shift.
10264 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10265 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10266 R, DAG.getConstant(ShiftAmt, MVT::i32));
10267 // Zero out the rightmost bits.
10268 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10270 return DAG.getNode(ISD::AND, dl, VT, SHL,
10271 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10274 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10275 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10276 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10277 R, DAG.getConstant(ShiftAmt, MVT::i32));
10279 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10280 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10281 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10282 R, DAG.getConstant(ShiftAmt, MVT::i32));
10284 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10285 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10286 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10287 R, DAG.getConstant(ShiftAmt, MVT::i32));
10289 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10290 // Make a large shift.
10292 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10293 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10294 R, DAG.getConstant(ShiftAmt, MVT::i32));
10295 // Zero out the leftmost bits.
10296 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10298 return DAG.getNode(ISD::AND, dl, VT, SRL,
10299 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10302 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10303 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10304 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10305 R, DAG.getConstant(ShiftAmt, MVT::i32));
10307 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10308 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10309 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10310 R, DAG.getConstant(ShiftAmt, MVT::i32));
10312 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10313 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10314 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10315 R, DAG.getConstant(ShiftAmt, MVT::i32));
10317 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10318 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10319 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10320 R, DAG.getConstant(ShiftAmt, MVT::i32));
10322 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10323 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10324 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10325 R, DAG.getConstant(ShiftAmt, MVT::i32));
10327 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10328 if (ShiftAmt == 7) {
10329 // R s>> 7 === R s< 0
10330 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10331 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10334 // R s>> a === ((R u>> a) ^ m) - m
10335 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10336 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10338 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10339 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10340 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10344 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10345 if (Op.getOpcode() == ISD::SHL) {
10346 // Make a large shift.
10348 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10349 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10350 R, DAG.getConstant(ShiftAmt, MVT::i32));
10351 // Zero out the rightmost bits.
10352 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10354 return DAG.getNode(ISD::AND, dl, VT, SHL,
10355 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10357 if (Op.getOpcode() == ISD::SRL) {
10358 // Make a large shift.
10360 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10361 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10362 R, DAG.getConstant(ShiftAmt, MVT::i32));
10363 // Zero out the leftmost bits.
10364 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10366 return DAG.getNode(ISD::AND, dl, VT, SRL,
10367 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10369 if (Op.getOpcode() == ISD::SRA) {
10370 if (ShiftAmt == 7) {
10371 // R s>> 7 === R s< 0
10372 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10373 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10376 // R s>> a === ((R u>> a) ^ m) - m
10377 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10378 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10380 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10381 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10382 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10389 // Lower SHL with variable shift amount.
10390 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10391 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10392 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10393 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10395 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10397 std::vector<Constant*> CV(4, CI);
10398 Constant *C = ConstantVector::get(CV);
10399 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10400 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10401 MachinePointerInfo::getConstantPool(),
10402 false, false, false, 16);
10404 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10405 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10406 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10407 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10409 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10411 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10412 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10413 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10415 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10416 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10418 std::vector<Constant*> CVM1(16, CM1);
10419 std::vector<Constant*> CVM2(16, CM2);
10420 Constant *C = ConstantVector::get(CVM1);
10421 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10422 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10423 MachinePointerInfo::getConstantPool(),
10424 false, false, false, 16);
10426 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10427 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10428 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10429 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10430 DAG.getConstant(4, MVT::i32));
10431 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10433 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10435 C = ConstantVector::get(CVM2);
10436 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10437 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10438 MachinePointerInfo::getConstantPool(),
10439 false, false, false, 16);
10441 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10442 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10443 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10444 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10445 DAG.getConstant(2, MVT::i32));
10446 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10448 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10450 // return pblendv(r, r+r, a);
10451 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10452 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10456 // Decompose 256-bit shifts into smaller 128-bit shifts.
10457 if (VT.getSizeInBits() == 256) {
10458 int NumElems = VT.getVectorNumElements();
10459 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10460 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10462 // Extract the two vectors
10463 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10464 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10467 // Recreate the shift amount vectors
10468 SDValue Amt1, Amt2;
10469 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10470 // Constant shift amount
10471 SmallVector<SDValue, 4> Amt1Csts;
10472 SmallVector<SDValue, 4> Amt2Csts;
10473 for (int i = 0; i < NumElems/2; ++i)
10474 Amt1Csts.push_back(Amt->getOperand(i));
10475 for (int i = NumElems/2; i < NumElems; ++i)
10476 Amt2Csts.push_back(Amt->getOperand(i));
10478 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10479 &Amt1Csts[0], NumElems/2);
10480 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10481 &Amt2Csts[0], NumElems/2);
10483 // Variable shift amount
10484 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10485 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10489 // Issue new vector shifts for the smaller types
10490 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10491 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10493 // Concatenate the result back
10494 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10500 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10501 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10502 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10503 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10504 // has only one use.
10505 SDNode *N = Op.getNode();
10506 SDValue LHS = N->getOperand(0);
10507 SDValue RHS = N->getOperand(1);
10508 unsigned BaseOp = 0;
10510 DebugLoc DL = Op.getDebugLoc();
10511 switch (Op.getOpcode()) {
10512 default: llvm_unreachable("Unknown ovf instruction!");
10514 // A subtract of one will be selected as a INC. Note that INC doesn't
10515 // set CF, so we can't do this for UADDO.
10516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10518 BaseOp = X86ISD::INC;
10519 Cond = X86::COND_O;
10522 BaseOp = X86ISD::ADD;
10523 Cond = X86::COND_O;
10526 BaseOp = X86ISD::ADD;
10527 Cond = X86::COND_B;
10530 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10531 // set CF, so we can't do this for USUBO.
10532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10534 BaseOp = X86ISD::DEC;
10535 Cond = X86::COND_O;
10538 BaseOp = X86ISD::SUB;
10539 Cond = X86::COND_O;
10542 BaseOp = X86ISD::SUB;
10543 Cond = X86::COND_B;
10546 BaseOp = X86ISD::SMUL;
10547 Cond = X86::COND_O;
10549 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10550 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10552 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10555 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10556 DAG.getConstant(X86::COND_O, MVT::i32),
10557 SDValue(Sum.getNode(), 2));
10559 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10563 // Also sets EFLAGS.
10564 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10565 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10568 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10569 DAG.getConstant(Cond, MVT::i32),
10570 SDValue(Sum.getNode(), 1));
10572 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10575 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10576 DebugLoc dl = Op.getDebugLoc();
10577 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10578 EVT VT = Op.getValueType();
10580 if (Subtarget->hasXMMInt() && VT.isVector()) {
10581 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10582 ExtraVT.getScalarType().getSizeInBits();
10583 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10585 unsigned SHLIntrinsicsID = 0;
10586 unsigned SRAIntrinsicsID = 0;
10587 switch (VT.getSimpleVT().SimpleTy) {
10591 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10592 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10595 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10596 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10600 if (!Subtarget->hasAVX())
10602 if (!Subtarget->hasAVX2()) {
10603 // needs to be split
10604 int NumElems = VT.getVectorNumElements();
10605 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10606 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10608 // Extract the LHS vectors
10609 SDValue LHS = Op.getOperand(0);
10610 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10611 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10613 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10614 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10616 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10617 int ExtraNumElems = ExtraVT.getVectorNumElements();
10618 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10620 SDValue Extra = DAG.getValueType(ExtraVT);
10622 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10623 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10625 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10627 if (VT == MVT::v8i32) {
10628 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10629 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10631 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10632 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10636 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10637 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10638 Op.getOperand(0), ShAmt);
10640 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10641 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10649 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10650 DebugLoc dl = Op.getDebugLoc();
10652 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10653 // There isn't any reason to disable it if the target processor supports it.
10654 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10655 SDValue Chain = Op.getOperand(0);
10656 SDValue Zero = DAG.getConstant(0, MVT::i32);
10658 DAG.getRegister(X86::ESP, MVT::i32), // Base
10659 DAG.getTargetConstant(1, MVT::i8), // Scale
10660 DAG.getRegister(0, MVT::i32), // Index
10661 DAG.getTargetConstant(0, MVT::i32), // Disp
10662 DAG.getRegister(0, MVT::i32), // Segment.
10667 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10668 array_lengthof(Ops));
10669 return SDValue(Res, 0);
10672 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10674 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10676 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10677 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10678 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10679 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10681 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10682 if (!Op1 && !Op2 && !Op3 && Op4)
10683 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10685 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10686 if (Op1 && !Op2 && !Op3 && !Op4)
10687 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10689 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10691 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10694 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10695 SelectionDAG &DAG) const {
10696 DebugLoc dl = Op.getDebugLoc();
10697 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10698 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10699 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10700 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10702 // The only fence that needs an instruction is a sequentially-consistent
10703 // cross-thread fence.
10704 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10705 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10706 // no-sse2). There isn't any reason to disable it if the target processor
10708 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10709 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10711 SDValue Chain = Op.getOperand(0);
10712 SDValue Zero = DAG.getConstant(0, MVT::i32);
10714 DAG.getRegister(X86::ESP, MVT::i32), // Base
10715 DAG.getTargetConstant(1, MVT::i8), // Scale
10716 DAG.getRegister(0, MVT::i32), // Index
10717 DAG.getTargetConstant(0, MVT::i32), // Disp
10718 DAG.getRegister(0, MVT::i32), // Segment.
10723 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10724 array_lengthof(Ops));
10725 return SDValue(Res, 0);
10728 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10729 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10733 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10734 EVT T = Op.getValueType();
10735 DebugLoc DL = Op.getDebugLoc();
10738 switch(T.getSimpleVT().SimpleTy) {
10740 assert(false && "Invalid value type!");
10741 case MVT::i8: Reg = X86::AL; size = 1; break;
10742 case MVT::i16: Reg = X86::AX; size = 2; break;
10743 case MVT::i32: Reg = X86::EAX; size = 4; break;
10745 assert(Subtarget->is64Bit() && "Node not type legal!");
10746 Reg = X86::RAX; size = 8;
10749 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10750 Op.getOperand(2), SDValue());
10751 SDValue Ops[] = { cpIn.getValue(0),
10754 DAG.getTargetConstant(size, MVT::i8),
10755 cpIn.getValue(1) };
10756 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10757 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10758 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10761 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10765 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10766 SelectionDAG &DAG) const {
10767 assert(Subtarget->is64Bit() && "Result not type legalized?");
10768 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10769 SDValue TheChain = Op.getOperand(0);
10770 DebugLoc dl = Op.getDebugLoc();
10771 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10772 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10773 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10775 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10776 DAG.getConstant(32, MVT::i8));
10778 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10781 return DAG.getMergeValues(Ops, 2, dl);
10784 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10785 SelectionDAG &DAG) const {
10786 EVT SrcVT = Op.getOperand(0).getValueType();
10787 EVT DstVT = Op.getValueType();
10788 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10789 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10790 assert((DstVT == MVT::i64 ||
10791 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10792 "Unexpected custom BITCAST");
10793 // i64 <=> MMX conversions are Legal.
10794 if (SrcVT==MVT::i64 && DstVT.isVector())
10796 if (DstVT==MVT::i64 && SrcVT.isVector())
10798 // MMX <=> MMX conversions are Legal.
10799 if (SrcVT.isVector() && DstVT.isVector())
10801 // All other conversions need to be expanded.
10805 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10806 SDNode *Node = Op.getNode();
10807 DebugLoc dl = Node->getDebugLoc();
10808 EVT T = Node->getValueType(0);
10809 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10810 DAG.getConstant(0, T), Node->getOperand(2));
10811 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10812 cast<AtomicSDNode>(Node)->getMemoryVT(),
10813 Node->getOperand(0),
10814 Node->getOperand(1), negOp,
10815 cast<AtomicSDNode>(Node)->getSrcValue(),
10816 cast<AtomicSDNode>(Node)->getAlignment(),
10817 cast<AtomicSDNode>(Node)->getOrdering(),
10818 cast<AtomicSDNode>(Node)->getSynchScope());
10821 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10822 SDNode *Node = Op.getNode();
10823 DebugLoc dl = Node->getDebugLoc();
10824 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10826 // Convert seq_cst store -> xchg
10827 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10828 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10829 // (The only way to get a 16-byte store is cmpxchg16b)
10830 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10831 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10832 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10833 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10834 cast<AtomicSDNode>(Node)->getMemoryVT(),
10835 Node->getOperand(0),
10836 Node->getOperand(1), Node->getOperand(2),
10837 cast<AtomicSDNode>(Node)->getMemOperand(),
10838 cast<AtomicSDNode>(Node)->getOrdering(),
10839 cast<AtomicSDNode>(Node)->getSynchScope());
10840 return Swap.getValue(1);
10842 // Other atomic stores have a simple pattern.
10846 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10847 EVT VT = Op.getNode()->getValueType(0);
10849 // Let legalize expand this if it isn't a legal type yet.
10850 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10853 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10856 bool ExtraOp = false;
10857 switch (Op.getOpcode()) {
10858 default: assert(0 && "Invalid code");
10859 case ISD::ADDC: Opc = X86ISD::ADD; break;
10860 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10861 case ISD::SUBC: Opc = X86ISD::SUB; break;
10862 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10866 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10868 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10869 Op.getOperand(1), Op.getOperand(2));
10872 /// LowerOperation - Provide custom lowering hooks for some operations.
10874 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10875 switch (Op.getOpcode()) {
10876 default: llvm_unreachable("Should not custom lower this!");
10877 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10878 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10879 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10880 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10881 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10882 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10883 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10884 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10885 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10886 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10887 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10888 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10889 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10890 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10891 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10892 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10893 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10894 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10895 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10896 case ISD::SHL_PARTS:
10897 case ISD::SRA_PARTS:
10898 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10899 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10900 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10901 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10902 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10903 case ISD::FABS: return LowerFABS(Op, DAG);
10904 case ISD::FNEG: return LowerFNEG(Op, DAG);
10905 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10906 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10907 case ISD::SETCC: return LowerSETCC(Op, DAG);
10908 case ISD::SELECT: return LowerSELECT(Op, DAG);
10909 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10910 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10911 case ISD::VASTART: return LowerVASTART(Op, DAG);
10912 case ISD::VAARG: return LowerVAARG(Op, DAG);
10913 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10914 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10915 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10916 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10917 case ISD::FRAME_TO_ARGS_OFFSET:
10918 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10919 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10920 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10921 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10922 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10923 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10924 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10925 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10926 case ISD::MUL: return LowerMUL(Op, DAG);
10929 case ISD::SHL: return LowerShift(Op, DAG);
10935 case ISD::UMULO: return LowerXALUO(Op, DAG);
10936 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10937 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10941 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10942 case ISD::ADD: return LowerADD(Op, DAG);
10943 case ISD::SUB: return LowerSUB(Op, DAG);
10947 static void ReplaceATOMIC_LOAD(SDNode *Node,
10948 SmallVectorImpl<SDValue> &Results,
10949 SelectionDAG &DAG) {
10950 DebugLoc dl = Node->getDebugLoc();
10951 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10953 // Convert wide load -> cmpxchg8b/cmpxchg16b
10954 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10955 // (The only way to get a 16-byte load is cmpxchg16b)
10956 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10957 SDValue Zero = DAG.getConstant(0, VT);
10958 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10959 Node->getOperand(0),
10960 Node->getOperand(1), Zero, Zero,
10961 cast<AtomicSDNode>(Node)->getMemOperand(),
10962 cast<AtomicSDNode>(Node)->getOrdering(),
10963 cast<AtomicSDNode>(Node)->getSynchScope());
10964 Results.push_back(Swap.getValue(0));
10965 Results.push_back(Swap.getValue(1));
10968 void X86TargetLowering::
10969 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10970 SelectionDAG &DAG, unsigned NewOp) const {
10971 DebugLoc dl = Node->getDebugLoc();
10972 assert (Node->getValueType(0) == MVT::i64 &&
10973 "Only know how to expand i64 atomics");
10975 SDValue Chain = Node->getOperand(0);
10976 SDValue In1 = Node->getOperand(1);
10977 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10978 Node->getOperand(2), DAG.getIntPtrConstant(0));
10979 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10980 Node->getOperand(2), DAG.getIntPtrConstant(1));
10981 SDValue Ops[] = { Chain, In1, In2L, In2H };
10982 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10984 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10985 cast<MemSDNode>(Node)->getMemOperand());
10986 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10987 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10988 Results.push_back(Result.getValue(2));
10991 /// ReplaceNodeResults - Replace a node with an illegal result type
10992 /// with a new node built out of custom code.
10993 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10994 SmallVectorImpl<SDValue>&Results,
10995 SelectionDAG &DAG) const {
10996 DebugLoc dl = N->getDebugLoc();
10997 switch (N->getOpcode()) {
10999 assert(false && "Do not know how to custom type legalize this operation!");
11001 case ISD::SIGN_EXTEND_INREG:
11006 // We don't want to expand or promote these.
11008 case ISD::FP_TO_SINT: {
11009 std::pair<SDValue,SDValue> Vals =
11010 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11011 SDValue FIST = Vals.first, StackSlot = Vals.second;
11012 if (FIST.getNode() != 0) {
11013 EVT VT = N->getValueType(0);
11014 // Return a load from the stack slot.
11015 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11016 MachinePointerInfo(),
11017 false, false, false, 0));
11021 case ISD::READCYCLECOUNTER: {
11022 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11023 SDValue TheChain = N->getOperand(0);
11024 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11025 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11027 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11029 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11030 SDValue Ops[] = { eax, edx };
11031 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11032 Results.push_back(edx.getValue(1));
11035 case ISD::ATOMIC_CMP_SWAP: {
11036 EVT T = N->getValueType(0);
11037 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11038 bool Regs64bit = T == MVT::i128;
11039 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11040 SDValue cpInL, cpInH;
11041 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11042 DAG.getConstant(0, HalfT));
11043 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11044 DAG.getConstant(1, HalfT));
11045 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11046 Regs64bit ? X86::RAX : X86::EAX,
11048 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11049 Regs64bit ? X86::RDX : X86::EDX,
11050 cpInH, cpInL.getValue(1));
11051 SDValue swapInL, swapInH;
11052 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11053 DAG.getConstant(0, HalfT));
11054 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11055 DAG.getConstant(1, HalfT));
11056 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11057 Regs64bit ? X86::RBX : X86::EBX,
11058 swapInL, cpInH.getValue(1));
11059 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11060 Regs64bit ? X86::RCX : X86::ECX,
11061 swapInH, swapInL.getValue(1));
11062 SDValue Ops[] = { swapInH.getValue(0),
11064 swapInH.getValue(1) };
11065 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11066 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11067 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11068 X86ISD::LCMPXCHG8_DAG;
11069 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11071 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11072 Regs64bit ? X86::RAX : X86::EAX,
11073 HalfT, Result.getValue(1));
11074 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11075 Regs64bit ? X86::RDX : X86::EDX,
11076 HalfT, cpOutL.getValue(2));
11077 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11078 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11079 Results.push_back(cpOutH.getValue(1));
11082 case ISD::ATOMIC_LOAD_ADD:
11083 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11085 case ISD::ATOMIC_LOAD_AND:
11086 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11088 case ISD::ATOMIC_LOAD_NAND:
11089 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11091 case ISD::ATOMIC_LOAD_OR:
11092 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11094 case ISD::ATOMIC_LOAD_SUB:
11095 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11097 case ISD::ATOMIC_LOAD_XOR:
11098 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11100 case ISD::ATOMIC_SWAP:
11101 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11103 case ISD::ATOMIC_LOAD:
11104 ReplaceATOMIC_LOAD(N, Results, DAG);
11108 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11110 default: return NULL;
11111 case X86ISD::BSF: return "X86ISD::BSF";
11112 case X86ISD::BSR: return "X86ISD::BSR";
11113 case X86ISD::SHLD: return "X86ISD::SHLD";
11114 case X86ISD::SHRD: return "X86ISD::SHRD";
11115 case X86ISD::FAND: return "X86ISD::FAND";
11116 case X86ISD::FOR: return "X86ISD::FOR";
11117 case X86ISD::FXOR: return "X86ISD::FXOR";
11118 case X86ISD::FSRL: return "X86ISD::FSRL";
11119 case X86ISD::FILD: return "X86ISD::FILD";
11120 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11121 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11122 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11123 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11124 case X86ISD::FLD: return "X86ISD::FLD";
11125 case X86ISD::FST: return "X86ISD::FST";
11126 case X86ISD::CALL: return "X86ISD::CALL";
11127 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11128 case X86ISD::BT: return "X86ISD::BT";
11129 case X86ISD::CMP: return "X86ISD::CMP";
11130 case X86ISD::COMI: return "X86ISD::COMI";
11131 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11132 case X86ISD::SETCC: return "X86ISD::SETCC";
11133 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11134 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11135 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11136 case X86ISD::CMOV: return "X86ISD::CMOV";
11137 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11138 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11139 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11140 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11141 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11142 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11143 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11144 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11145 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11146 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11147 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11148 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11149 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11150 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11151 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11152 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11153 case X86ISD::FHADD: return "X86ISD::FHADD";
11154 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11155 case X86ISD::FMAX: return "X86ISD::FMAX";
11156 case X86ISD::FMIN: return "X86ISD::FMIN";
11157 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11158 case X86ISD::FRCP: return "X86ISD::FRCP";
11159 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11160 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11161 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11162 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11163 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11164 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11165 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11166 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11167 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11168 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11169 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11170 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11171 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11172 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11173 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11174 case X86ISD::VSHL: return "X86ISD::VSHL";
11175 case X86ISD::VSRL: return "X86ISD::VSRL";
11176 case X86ISD::CMPPD: return "X86ISD::CMPPD";
11177 case X86ISD::CMPPS: return "X86ISD::CMPPS";
11178 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
11179 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
11180 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
11181 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
11182 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
11183 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
11184 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
11185 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
11186 case X86ISD::ADD: return "X86ISD::ADD";
11187 case X86ISD::SUB: return "X86ISD::SUB";
11188 case X86ISD::ADC: return "X86ISD::ADC";
11189 case X86ISD::SBB: return "X86ISD::SBB";
11190 case X86ISD::SMUL: return "X86ISD::SMUL";
11191 case X86ISD::UMUL: return "X86ISD::UMUL";
11192 case X86ISD::INC: return "X86ISD::INC";
11193 case X86ISD::DEC: return "X86ISD::DEC";
11194 case X86ISD::OR: return "X86ISD::OR";
11195 case X86ISD::XOR: return "X86ISD::XOR";
11196 case X86ISD::AND: return "X86ISD::AND";
11197 case X86ISD::ANDN: return "X86ISD::ANDN";
11198 case X86ISD::BLSI: return "X86ISD::BLSI";
11199 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11200 case X86ISD::BLSR: return "X86ISD::BLSR";
11201 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11202 case X86ISD::PTEST: return "X86ISD::PTEST";
11203 case X86ISD::TESTP: return "X86ISD::TESTP";
11204 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11205 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11206 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11207 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11208 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11209 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11210 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
11211 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
11212 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11213 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11214 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11215 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
11216 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11217 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11218 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11219 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11220 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11221 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11222 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11223 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11224 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11225 case X86ISD::UNPCKLP: return "X86ISD::UNPCKLP";
11226 case X86ISD::UNPCKHP: return "X86ISD::UNPCKHP";
11227 case X86ISD::PUNPCKL: return "X86ISD::PUNPCKL";
11228 case X86ISD::PUNPCKH: return "X86ISD::PUNPCKH";
11229 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11230 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
11231 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
11232 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
11233 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11234 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11235 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11236 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11237 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11241 // isLegalAddressingMode - Return true if the addressing mode represented
11242 // by AM is legal for this target, for a load/store of the specified type.
11243 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11245 // X86 supports extremely general addressing modes.
11246 CodeModel::Model M = getTargetMachine().getCodeModel();
11247 Reloc::Model R = getTargetMachine().getRelocationModel();
11249 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11250 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11255 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11257 // If a reference to this global requires an extra load, we can't fold it.
11258 if (isGlobalStubReference(GVFlags))
11261 // If BaseGV requires a register for the PIC base, we cannot also have a
11262 // BaseReg specified.
11263 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11266 // If lower 4G is not available, then we must use rip-relative addressing.
11267 if ((M != CodeModel::Small || R != Reloc::Static) &&
11268 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11272 switch (AM.Scale) {
11278 // These scales always work.
11283 // These scales are formed with basereg+scalereg. Only accept if there is
11288 default: // Other stuff never works.
11296 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11297 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11299 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11300 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11301 if (NumBits1 <= NumBits2)
11306 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11307 if (!VT1.isInteger() || !VT2.isInteger())
11309 unsigned NumBits1 = VT1.getSizeInBits();
11310 unsigned NumBits2 = VT2.getSizeInBits();
11311 if (NumBits1 <= NumBits2)
11316 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11317 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11318 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11321 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11322 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11323 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11326 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11327 // i16 instructions are longer (0x66 prefix) and potentially slower.
11328 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11331 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11332 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11333 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11334 /// are assumed to be legal.
11336 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11338 // Very little shuffling can be done for 64-bit vectors right now.
11339 if (VT.getSizeInBits() == 64)
11340 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11342 // FIXME: pshufb, blends, shifts.
11343 return (VT.getVectorNumElements() == 2 ||
11344 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11345 isMOVLMask(M, VT) ||
11346 isSHUFPMask(M, VT) ||
11347 isPSHUFDMask(M, VT) ||
11348 isPSHUFHWMask(M, VT) ||
11349 isPSHUFLWMask(M, VT) ||
11350 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11351 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11352 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11353 isUNPCKL_v_undef_Mask(M, VT) ||
11354 isUNPCKH_v_undef_Mask(M, VT));
11358 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11360 unsigned NumElts = VT.getVectorNumElements();
11361 // FIXME: This collection of masks seems suspect.
11364 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11365 return (isMOVLMask(Mask, VT) ||
11366 isCommutedMOVLMask(Mask, VT, true) ||
11367 isSHUFPMask(Mask, VT) ||
11368 isCommutedSHUFPMask(Mask, VT));
11373 //===----------------------------------------------------------------------===//
11374 // X86 Scheduler Hooks
11375 //===----------------------------------------------------------------------===//
11377 // private utility function
11378 MachineBasicBlock *
11379 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11380 MachineBasicBlock *MBB,
11387 TargetRegisterClass *RC,
11388 bool invSrc) const {
11389 // For the atomic bitwise operator, we generate
11392 // ld t1 = [bitinstr.addr]
11393 // op t2 = t1, [bitinstr.val]
11395 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11397 // fallthrough -->nextMBB
11398 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11399 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11400 MachineFunction::iterator MBBIter = MBB;
11403 /// First build the CFG
11404 MachineFunction *F = MBB->getParent();
11405 MachineBasicBlock *thisMBB = MBB;
11406 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11407 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11408 F->insert(MBBIter, newMBB);
11409 F->insert(MBBIter, nextMBB);
11411 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11412 nextMBB->splice(nextMBB->begin(), thisMBB,
11413 llvm::next(MachineBasicBlock::iterator(bInstr)),
11415 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11417 // Update thisMBB to fall through to newMBB
11418 thisMBB->addSuccessor(newMBB);
11420 // newMBB jumps to itself and fall through to nextMBB
11421 newMBB->addSuccessor(nextMBB);
11422 newMBB->addSuccessor(newMBB);
11424 // Insert instructions into newMBB based on incoming instruction
11425 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11426 "unexpected number of operands");
11427 DebugLoc dl = bInstr->getDebugLoc();
11428 MachineOperand& destOper = bInstr->getOperand(0);
11429 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11430 int numArgs = bInstr->getNumOperands() - 1;
11431 for (int i=0; i < numArgs; ++i)
11432 argOpers[i] = &bInstr->getOperand(i+1);
11434 // x86 address has 4 operands: base, index, scale, and displacement
11435 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11436 int valArgIndx = lastAddrIndx + 1;
11438 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11439 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11440 for (int i=0; i <= lastAddrIndx; ++i)
11441 (*MIB).addOperand(*argOpers[i]);
11443 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11445 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11450 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11451 assert((argOpers[valArgIndx]->isReg() ||
11452 argOpers[valArgIndx]->isImm()) &&
11453 "invalid operand");
11454 if (argOpers[valArgIndx]->isReg())
11455 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11457 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11459 (*MIB).addOperand(*argOpers[valArgIndx]);
11461 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11464 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11465 for (int i=0; i <= lastAddrIndx; ++i)
11466 (*MIB).addOperand(*argOpers[i]);
11468 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11469 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11470 bInstr->memoperands_end());
11472 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11473 MIB.addReg(EAXreg);
11476 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11478 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11482 // private utility function: 64 bit atomics on 32 bit host.
11483 MachineBasicBlock *
11484 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11485 MachineBasicBlock *MBB,
11490 bool invSrc) const {
11491 // For the atomic bitwise operator, we generate
11492 // thisMBB (instructions are in pairs, except cmpxchg8b)
11493 // ld t1,t2 = [bitinstr.addr]
11495 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11496 // op t5, t6 <- out1, out2, [bitinstr.val]
11497 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11498 // mov ECX, EBX <- t5, t6
11499 // mov EAX, EDX <- t1, t2
11500 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11501 // mov t3, t4 <- EAX, EDX
11503 // result in out1, out2
11504 // fallthrough -->nextMBB
11506 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11507 const unsigned LoadOpc = X86::MOV32rm;
11508 const unsigned NotOpc = X86::NOT32r;
11509 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11510 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11511 MachineFunction::iterator MBBIter = MBB;
11514 /// First build the CFG
11515 MachineFunction *F = MBB->getParent();
11516 MachineBasicBlock *thisMBB = MBB;
11517 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11518 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11519 F->insert(MBBIter, newMBB);
11520 F->insert(MBBIter, nextMBB);
11522 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11523 nextMBB->splice(nextMBB->begin(), thisMBB,
11524 llvm::next(MachineBasicBlock::iterator(bInstr)),
11526 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11528 // Update thisMBB to fall through to newMBB
11529 thisMBB->addSuccessor(newMBB);
11531 // newMBB jumps to itself and fall through to nextMBB
11532 newMBB->addSuccessor(nextMBB);
11533 newMBB->addSuccessor(newMBB);
11535 DebugLoc dl = bInstr->getDebugLoc();
11536 // Insert instructions into newMBB based on incoming instruction
11537 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11538 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11539 "unexpected number of operands");
11540 MachineOperand& dest1Oper = bInstr->getOperand(0);
11541 MachineOperand& dest2Oper = bInstr->getOperand(1);
11542 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11543 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11544 argOpers[i] = &bInstr->getOperand(i+2);
11546 // We use some of the operands multiple times, so conservatively just
11547 // clear any kill flags that might be present.
11548 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11549 argOpers[i]->setIsKill(false);
11552 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11553 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11555 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11556 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11557 for (int i=0; i <= lastAddrIndx; ++i)
11558 (*MIB).addOperand(*argOpers[i]);
11559 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11560 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11561 // add 4 to displacement.
11562 for (int i=0; i <= lastAddrIndx-2; ++i)
11563 (*MIB).addOperand(*argOpers[i]);
11564 MachineOperand newOp3 = *(argOpers[3]);
11565 if (newOp3.isImm())
11566 newOp3.setImm(newOp3.getImm()+4);
11568 newOp3.setOffset(newOp3.getOffset()+4);
11569 (*MIB).addOperand(newOp3);
11570 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11572 // t3/4 are defined later, at the bottom of the loop
11573 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11574 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11575 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11576 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11577 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11578 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11580 // The subsequent operations should be using the destination registers of
11581 //the PHI instructions.
11583 t1 = F->getRegInfo().createVirtualRegister(RC);
11584 t2 = F->getRegInfo().createVirtualRegister(RC);
11585 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11586 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11588 t1 = dest1Oper.getReg();
11589 t2 = dest2Oper.getReg();
11592 int valArgIndx = lastAddrIndx + 1;
11593 assert((argOpers[valArgIndx]->isReg() ||
11594 argOpers[valArgIndx]->isImm()) &&
11595 "invalid operand");
11596 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11597 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11598 if (argOpers[valArgIndx]->isReg())
11599 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11601 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11602 if (regOpcL != X86::MOV32rr)
11604 (*MIB).addOperand(*argOpers[valArgIndx]);
11605 assert(argOpers[valArgIndx + 1]->isReg() ==
11606 argOpers[valArgIndx]->isReg());
11607 assert(argOpers[valArgIndx + 1]->isImm() ==
11608 argOpers[valArgIndx]->isImm());
11609 if (argOpers[valArgIndx + 1]->isReg())
11610 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11612 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11613 if (regOpcH != X86::MOV32rr)
11615 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11617 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11619 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11622 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11624 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11627 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11628 for (int i=0; i <= lastAddrIndx; ++i)
11629 (*MIB).addOperand(*argOpers[i]);
11631 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11632 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11633 bInstr->memoperands_end());
11635 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11636 MIB.addReg(X86::EAX);
11637 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11638 MIB.addReg(X86::EDX);
11641 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11643 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11647 // private utility function
11648 MachineBasicBlock *
11649 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11650 MachineBasicBlock *MBB,
11651 unsigned cmovOpc) const {
11652 // For the atomic min/max operator, we generate
11655 // ld t1 = [min/max.addr]
11656 // mov t2 = [min/max.val]
11658 // cmov[cond] t2 = t1
11660 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11662 // fallthrough -->nextMBB
11664 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11665 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11666 MachineFunction::iterator MBBIter = MBB;
11669 /// First build the CFG
11670 MachineFunction *F = MBB->getParent();
11671 MachineBasicBlock *thisMBB = MBB;
11672 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11673 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11674 F->insert(MBBIter, newMBB);
11675 F->insert(MBBIter, nextMBB);
11677 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11678 nextMBB->splice(nextMBB->begin(), thisMBB,
11679 llvm::next(MachineBasicBlock::iterator(mInstr)),
11681 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11683 // Update thisMBB to fall through to newMBB
11684 thisMBB->addSuccessor(newMBB);
11686 // newMBB jumps to newMBB and fall through to nextMBB
11687 newMBB->addSuccessor(nextMBB);
11688 newMBB->addSuccessor(newMBB);
11690 DebugLoc dl = mInstr->getDebugLoc();
11691 // Insert instructions into newMBB based on incoming instruction
11692 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11693 "unexpected number of operands");
11694 MachineOperand& destOper = mInstr->getOperand(0);
11695 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11696 int numArgs = mInstr->getNumOperands() - 1;
11697 for (int i=0; i < numArgs; ++i)
11698 argOpers[i] = &mInstr->getOperand(i+1);
11700 // x86 address has 4 operands: base, index, scale, and displacement
11701 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11702 int valArgIndx = lastAddrIndx + 1;
11704 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11705 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11706 for (int i=0; i <= lastAddrIndx; ++i)
11707 (*MIB).addOperand(*argOpers[i]);
11709 // We only support register and immediate values
11710 assert((argOpers[valArgIndx]->isReg() ||
11711 argOpers[valArgIndx]->isImm()) &&
11712 "invalid operand");
11714 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11715 if (argOpers[valArgIndx]->isReg())
11716 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11718 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11719 (*MIB).addOperand(*argOpers[valArgIndx]);
11721 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11724 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11729 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11730 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11734 // Cmp and exchange if none has modified the memory location
11735 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11736 for (int i=0; i <= lastAddrIndx; ++i)
11737 (*MIB).addOperand(*argOpers[i]);
11739 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11740 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11741 mInstr->memoperands_end());
11743 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11744 MIB.addReg(X86::EAX);
11747 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11749 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11753 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11754 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11755 // in the .td file.
11756 MachineBasicBlock *
11757 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11758 unsigned numArgs, bool memArg) const {
11759 assert(Subtarget->hasSSE42orAVX() &&
11760 "Target must have SSE4.2 or AVX features enabled");
11762 DebugLoc dl = MI->getDebugLoc();
11763 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11765 if (!Subtarget->hasAVX()) {
11767 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11769 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11772 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11774 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11777 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11778 for (unsigned i = 0; i < numArgs; ++i) {
11779 MachineOperand &Op = MI->getOperand(i+1);
11780 if (!(Op.isReg() && Op.isImplicit()))
11781 MIB.addOperand(Op);
11783 BuildMI(*BB, MI, dl,
11784 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11785 MI->getOperand(0).getReg())
11786 .addReg(X86::XMM0);
11788 MI->eraseFromParent();
11792 MachineBasicBlock *
11793 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11794 DebugLoc dl = MI->getDebugLoc();
11795 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11797 // Address into RAX/EAX, other two args into ECX, EDX.
11798 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11799 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11800 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11801 for (int i = 0; i < X86::AddrNumOperands; ++i)
11802 MIB.addOperand(MI->getOperand(i));
11804 unsigned ValOps = X86::AddrNumOperands;
11805 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11806 .addReg(MI->getOperand(ValOps).getReg());
11807 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11808 .addReg(MI->getOperand(ValOps+1).getReg());
11810 // The instruction doesn't actually take any operands though.
11811 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11813 MI->eraseFromParent(); // The pseudo is gone now.
11817 MachineBasicBlock *
11818 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11819 DebugLoc dl = MI->getDebugLoc();
11820 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11822 // First arg in ECX, the second in EAX.
11823 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11824 .addReg(MI->getOperand(0).getReg());
11825 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11826 .addReg(MI->getOperand(1).getReg());
11828 // The instruction doesn't actually take any operands though.
11829 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11831 MI->eraseFromParent(); // The pseudo is gone now.
11835 MachineBasicBlock *
11836 X86TargetLowering::EmitVAARG64WithCustomInserter(
11838 MachineBasicBlock *MBB) const {
11839 // Emit va_arg instruction on X86-64.
11841 // Operands to this pseudo-instruction:
11842 // 0 ) Output : destination address (reg)
11843 // 1-5) Input : va_list address (addr, i64mem)
11844 // 6 ) ArgSize : Size (in bytes) of vararg type
11845 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11846 // 8 ) Align : Alignment of type
11847 // 9 ) EFLAGS (implicit-def)
11849 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11850 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11852 unsigned DestReg = MI->getOperand(0).getReg();
11853 MachineOperand &Base = MI->getOperand(1);
11854 MachineOperand &Scale = MI->getOperand(2);
11855 MachineOperand &Index = MI->getOperand(3);
11856 MachineOperand &Disp = MI->getOperand(4);
11857 MachineOperand &Segment = MI->getOperand(5);
11858 unsigned ArgSize = MI->getOperand(6).getImm();
11859 unsigned ArgMode = MI->getOperand(7).getImm();
11860 unsigned Align = MI->getOperand(8).getImm();
11862 // Memory Reference
11863 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11864 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11865 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11867 // Machine Information
11868 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11869 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11870 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11871 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11872 DebugLoc DL = MI->getDebugLoc();
11874 // struct va_list {
11877 // i64 overflow_area (address)
11878 // i64 reg_save_area (address)
11880 // sizeof(va_list) = 24
11881 // alignment(va_list) = 8
11883 unsigned TotalNumIntRegs = 6;
11884 unsigned TotalNumXMMRegs = 8;
11885 bool UseGPOffset = (ArgMode == 1);
11886 bool UseFPOffset = (ArgMode == 2);
11887 unsigned MaxOffset = TotalNumIntRegs * 8 +
11888 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11890 /* Align ArgSize to a multiple of 8 */
11891 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11892 bool NeedsAlign = (Align > 8);
11894 MachineBasicBlock *thisMBB = MBB;
11895 MachineBasicBlock *overflowMBB;
11896 MachineBasicBlock *offsetMBB;
11897 MachineBasicBlock *endMBB;
11899 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11900 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11901 unsigned OffsetReg = 0;
11903 if (!UseGPOffset && !UseFPOffset) {
11904 // If we only pull from the overflow region, we don't create a branch.
11905 // We don't need to alter control flow.
11906 OffsetDestReg = 0; // unused
11907 OverflowDestReg = DestReg;
11910 overflowMBB = thisMBB;
11913 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11914 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11915 // If not, pull from overflow_area. (branch to overflowMBB)
11920 // offsetMBB overflowMBB
11925 // Registers for the PHI in endMBB
11926 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11927 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11929 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11930 MachineFunction *MF = MBB->getParent();
11931 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11932 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11933 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11935 MachineFunction::iterator MBBIter = MBB;
11938 // Insert the new basic blocks
11939 MF->insert(MBBIter, offsetMBB);
11940 MF->insert(MBBIter, overflowMBB);
11941 MF->insert(MBBIter, endMBB);
11943 // Transfer the remainder of MBB and its successor edges to endMBB.
11944 endMBB->splice(endMBB->begin(), thisMBB,
11945 llvm::next(MachineBasicBlock::iterator(MI)),
11947 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11949 // Make offsetMBB and overflowMBB successors of thisMBB
11950 thisMBB->addSuccessor(offsetMBB);
11951 thisMBB->addSuccessor(overflowMBB);
11953 // endMBB is a successor of both offsetMBB and overflowMBB
11954 offsetMBB->addSuccessor(endMBB);
11955 overflowMBB->addSuccessor(endMBB);
11957 // Load the offset value into a register
11958 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11959 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11963 .addDisp(Disp, UseFPOffset ? 4 : 0)
11964 .addOperand(Segment)
11965 .setMemRefs(MMOBegin, MMOEnd);
11967 // Check if there is enough room left to pull this argument.
11968 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11970 .addImm(MaxOffset + 8 - ArgSizeA8);
11972 // Branch to "overflowMBB" if offset >= max
11973 // Fall through to "offsetMBB" otherwise
11974 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11975 .addMBB(overflowMBB);
11978 // In offsetMBB, emit code to use the reg_save_area.
11980 assert(OffsetReg != 0);
11982 // Read the reg_save_area address.
11983 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11984 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11989 .addOperand(Segment)
11990 .setMemRefs(MMOBegin, MMOEnd);
11992 // Zero-extend the offset
11993 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11994 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11997 .addImm(X86::sub_32bit);
11999 // Add the offset to the reg_save_area to get the final address.
12000 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12001 .addReg(OffsetReg64)
12002 .addReg(RegSaveReg);
12004 // Compute the offset for the next argument
12005 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12006 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12008 .addImm(UseFPOffset ? 16 : 8);
12010 // Store it back into the va_list.
12011 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12015 .addDisp(Disp, UseFPOffset ? 4 : 0)
12016 .addOperand(Segment)
12017 .addReg(NextOffsetReg)
12018 .setMemRefs(MMOBegin, MMOEnd);
12021 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12026 // Emit code to use overflow area
12029 // Load the overflow_area address into a register.
12030 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12031 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12036 .addOperand(Segment)
12037 .setMemRefs(MMOBegin, MMOEnd);
12039 // If we need to align it, do so. Otherwise, just copy the address
12040 // to OverflowDestReg.
12042 // Align the overflow address
12043 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12044 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12046 // aligned_addr = (addr + (align-1)) & ~(align-1)
12047 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12048 .addReg(OverflowAddrReg)
12051 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12053 .addImm(~(uint64_t)(Align-1));
12055 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12056 .addReg(OverflowAddrReg);
12059 // Compute the next overflow address after this argument.
12060 // (the overflow address should be kept 8-byte aligned)
12061 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12062 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12063 .addReg(OverflowDestReg)
12064 .addImm(ArgSizeA8);
12066 // Store the new overflow address.
12067 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12072 .addOperand(Segment)
12073 .addReg(NextAddrReg)
12074 .setMemRefs(MMOBegin, MMOEnd);
12076 // If we branched, emit the PHI to the front of endMBB.
12078 BuildMI(*endMBB, endMBB->begin(), DL,
12079 TII->get(X86::PHI), DestReg)
12080 .addReg(OffsetDestReg).addMBB(offsetMBB)
12081 .addReg(OverflowDestReg).addMBB(overflowMBB);
12084 // Erase the pseudo instruction
12085 MI->eraseFromParent();
12090 MachineBasicBlock *
12091 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12093 MachineBasicBlock *MBB) const {
12094 // Emit code to save XMM registers to the stack. The ABI says that the
12095 // number of registers to save is given in %al, so it's theoretically
12096 // possible to do an indirect jump trick to avoid saving all of them,
12097 // however this code takes a simpler approach and just executes all
12098 // of the stores if %al is non-zero. It's less code, and it's probably
12099 // easier on the hardware branch predictor, and stores aren't all that
12100 // expensive anyway.
12102 // Create the new basic blocks. One block contains all the XMM stores,
12103 // and one block is the final destination regardless of whether any
12104 // stores were performed.
12105 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12106 MachineFunction *F = MBB->getParent();
12107 MachineFunction::iterator MBBIter = MBB;
12109 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12110 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12111 F->insert(MBBIter, XMMSaveMBB);
12112 F->insert(MBBIter, EndMBB);
12114 // Transfer the remainder of MBB and its successor edges to EndMBB.
12115 EndMBB->splice(EndMBB->begin(), MBB,
12116 llvm::next(MachineBasicBlock::iterator(MI)),
12118 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12120 // The original block will now fall through to the XMM save block.
12121 MBB->addSuccessor(XMMSaveMBB);
12122 // The XMMSaveMBB will fall through to the end block.
12123 XMMSaveMBB->addSuccessor(EndMBB);
12125 // Now add the instructions.
12126 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12127 DebugLoc DL = MI->getDebugLoc();
12129 unsigned CountReg = MI->getOperand(0).getReg();
12130 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12131 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12133 if (!Subtarget->isTargetWin64()) {
12134 // If %al is 0, branch around the XMM save block.
12135 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12136 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12137 MBB->addSuccessor(EndMBB);
12140 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12141 // In the XMM save block, save all the XMM argument registers.
12142 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12143 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12144 MachineMemOperand *MMO =
12145 F->getMachineMemOperand(
12146 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12147 MachineMemOperand::MOStore,
12148 /*Size=*/16, /*Align=*/16);
12149 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12150 .addFrameIndex(RegSaveFrameIndex)
12151 .addImm(/*Scale=*/1)
12152 .addReg(/*IndexReg=*/0)
12153 .addImm(/*Disp=*/Offset)
12154 .addReg(/*Segment=*/0)
12155 .addReg(MI->getOperand(i).getReg())
12156 .addMemOperand(MMO);
12159 MI->eraseFromParent(); // The pseudo instruction is gone now.
12164 MachineBasicBlock *
12165 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12166 MachineBasicBlock *BB) const {
12167 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12168 DebugLoc DL = MI->getDebugLoc();
12170 // To "insert" a SELECT_CC instruction, we actually have to insert the
12171 // diamond control-flow pattern. The incoming instruction knows the
12172 // destination vreg to set, the condition code register to branch on, the
12173 // true/false values to select between, and a branch opcode to use.
12174 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12175 MachineFunction::iterator It = BB;
12181 // cmpTY ccX, r1, r2
12183 // fallthrough --> copy0MBB
12184 MachineBasicBlock *thisMBB = BB;
12185 MachineFunction *F = BB->getParent();
12186 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12187 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12188 F->insert(It, copy0MBB);
12189 F->insert(It, sinkMBB);
12191 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12192 // live into the sink and copy blocks.
12193 if (!MI->killsRegister(X86::EFLAGS)) {
12194 copy0MBB->addLiveIn(X86::EFLAGS);
12195 sinkMBB->addLiveIn(X86::EFLAGS);
12198 // Transfer the remainder of BB and its successor edges to sinkMBB.
12199 sinkMBB->splice(sinkMBB->begin(), BB,
12200 llvm::next(MachineBasicBlock::iterator(MI)),
12202 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12204 // Add the true and fallthrough blocks as its successors.
12205 BB->addSuccessor(copy0MBB);
12206 BB->addSuccessor(sinkMBB);
12208 // Create the conditional branch instruction.
12210 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12211 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12214 // %FalseValue = ...
12215 // # fallthrough to sinkMBB
12216 copy0MBB->addSuccessor(sinkMBB);
12219 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12221 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12222 TII->get(X86::PHI), MI->getOperand(0).getReg())
12223 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12224 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12226 MI->eraseFromParent(); // The pseudo instruction is gone now.
12230 MachineBasicBlock *
12231 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12232 bool Is64Bit) const {
12233 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12234 DebugLoc DL = MI->getDebugLoc();
12235 MachineFunction *MF = BB->getParent();
12236 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12238 assert(EnableSegmentedStacks);
12240 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12241 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12244 // ... [Till the alloca]
12245 // If stacklet is not large enough, jump to mallocMBB
12248 // Allocate by subtracting from RSP
12249 // Jump to continueMBB
12252 // Allocate by call to runtime
12256 // [rest of original BB]
12259 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12260 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12261 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12263 MachineRegisterInfo &MRI = MF->getRegInfo();
12264 const TargetRegisterClass *AddrRegClass =
12265 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12267 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12268 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12269 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12270 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12271 sizeVReg = MI->getOperand(1).getReg(),
12272 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12274 MachineFunction::iterator MBBIter = BB;
12277 MF->insert(MBBIter, bumpMBB);
12278 MF->insert(MBBIter, mallocMBB);
12279 MF->insert(MBBIter, continueMBB);
12281 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12282 (MachineBasicBlock::iterator(MI)), BB->end());
12283 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12285 // Add code to the main basic block to check if the stack limit has been hit,
12286 // and if so, jump to mallocMBB otherwise to bumpMBB.
12287 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12288 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12289 .addReg(tmpSPVReg).addReg(sizeVReg);
12290 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12291 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12292 .addReg(SPLimitVReg);
12293 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12295 // bumpMBB simply decreases the stack pointer, since we know the current
12296 // stacklet has enough space.
12297 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12298 .addReg(SPLimitVReg);
12299 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12300 .addReg(SPLimitVReg);
12301 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12303 // Calls into a routine in libgcc to allocate more space from the heap.
12305 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12307 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12308 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12310 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12312 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12313 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12314 .addExternalSymbol("__morestack_allocate_stack_space");
12318 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12321 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12322 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12323 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12325 // Set up the CFG correctly.
12326 BB->addSuccessor(bumpMBB);
12327 BB->addSuccessor(mallocMBB);
12328 mallocMBB->addSuccessor(continueMBB);
12329 bumpMBB->addSuccessor(continueMBB);
12331 // Take care of the PHI nodes.
12332 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12333 MI->getOperand(0).getReg())
12334 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12335 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12337 // Delete the original pseudo instruction.
12338 MI->eraseFromParent();
12341 return continueMBB;
12344 MachineBasicBlock *
12345 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12346 MachineBasicBlock *BB) const {
12347 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12348 DebugLoc DL = MI->getDebugLoc();
12350 assert(!Subtarget->isTargetEnvMacho());
12352 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12353 // non-trivial part is impdef of ESP.
12355 if (Subtarget->isTargetWin64()) {
12356 if (Subtarget->isTargetCygMing()) {
12357 // ___chkstk(Mingw64):
12358 // Clobbers R10, R11, RAX and EFLAGS.
12360 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12361 .addExternalSymbol("___chkstk")
12362 .addReg(X86::RAX, RegState::Implicit)
12363 .addReg(X86::RSP, RegState::Implicit)
12364 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12365 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12366 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12368 // __chkstk(MSVCRT): does not update stack pointer.
12369 // Clobbers R10, R11 and EFLAGS.
12370 // FIXME: RAX(allocated size) might be reused and not killed.
12371 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12372 .addExternalSymbol("__chkstk")
12373 .addReg(X86::RAX, RegState::Implicit)
12374 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12375 // RAX has the offset to subtracted from RSP.
12376 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12381 const char *StackProbeSymbol =
12382 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12384 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12385 .addExternalSymbol(StackProbeSymbol)
12386 .addReg(X86::EAX, RegState::Implicit)
12387 .addReg(X86::ESP, RegState::Implicit)
12388 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12389 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12390 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12393 MI->eraseFromParent(); // The pseudo instruction is gone now.
12397 MachineBasicBlock *
12398 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12399 MachineBasicBlock *BB) const {
12400 // This is pretty easy. We're taking the value that we received from
12401 // our load from the relocation, sticking it in either RDI (x86-64)
12402 // or EAX and doing an indirect call. The return value will then
12403 // be in the normal return register.
12404 const X86InstrInfo *TII
12405 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12406 DebugLoc DL = MI->getDebugLoc();
12407 MachineFunction *F = BB->getParent();
12409 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12410 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12412 if (Subtarget->is64Bit()) {
12413 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12414 TII->get(X86::MOV64rm), X86::RDI)
12416 .addImm(0).addReg(0)
12417 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12418 MI->getOperand(3).getTargetFlags())
12420 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12421 addDirectMem(MIB, X86::RDI);
12422 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12423 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12424 TII->get(X86::MOV32rm), X86::EAX)
12426 .addImm(0).addReg(0)
12427 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12428 MI->getOperand(3).getTargetFlags())
12430 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12431 addDirectMem(MIB, X86::EAX);
12433 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12434 TII->get(X86::MOV32rm), X86::EAX)
12435 .addReg(TII->getGlobalBaseReg(F))
12436 .addImm(0).addReg(0)
12437 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12438 MI->getOperand(3).getTargetFlags())
12440 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12441 addDirectMem(MIB, X86::EAX);
12444 MI->eraseFromParent(); // The pseudo instruction is gone now.
12448 MachineBasicBlock *
12449 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12450 MachineBasicBlock *BB) const {
12451 switch (MI->getOpcode()) {
12452 default: assert(0 && "Unexpected instr type to insert");
12453 case X86::TAILJMPd64:
12454 case X86::TAILJMPr64:
12455 case X86::TAILJMPm64:
12456 assert(0 && "TAILJMP64 would not be touched here.");
12457 case X86::TCRETURNdi64:
12458 case X86::TCRETURNri64:
12459 case X86::TCRETURNmi64:
12460 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12461 // On AMD64, additional defs should be added before register allocation.
12462 if (!Subtarget->isTargetWin64()) {
12463 MI->addRegisterDefined(X86::RSI);
12464 MI->addRegisterDefined(X86::RDI);
12465 MI->addRegisterDefined(X86::XMM6);
12466 MI->addRegisterDefined(X86::XMM7);
12467 MI->addRegisterDefined(X86::XMM8);
12468 MI->addRegisterDefined(X86::XMM9);
12469 MI->addRegisterDefined(X86::XMM10);
12470 MI->addRegisterDefined(X86::XMM11);
12471 MI->addRegisterDefined(X86::XMM12);
12472 MI->addRegisterDefined(X86::XMM13);
12473 MI->addRegisterDefined(X86::XMM14);
12474 MI->addRegisterDefined(X86::XMM15);
12477 case X86::WIN_ALLOCA:
12478 return EmitLoweredWinAlloca(MI, BB);
12479 case X86::SEG_ALLOCA_32:
12480 return EmitLoweredSegAlloca(MI, BB, false);
12481 case X86::SEG_ALLOCA_64:
12482 return EmitLoweredSegAlloca(MI, BB, true);
12483 case X86::TLSCall_32:
12484 case X86::TLSCall_64:
12485 return EmitLoweredTLSCall(MI, BB);
12486 case X86::CMOV_GR8:
12487 case X86::CMOV_FR32:
12488 case X86::CMOV_FR64:
12489 case X86::CMOV_V4F32:
12490 case X86::CMOV_V2F64:
12491 case X86::CMOV_V2I64:
12492 case X86::CMOV_V8F32:
12493 case X86::CMOV_V4F64:
12494 case X86::CMOV_V4I64:
12495 case X86::CMOV_GR16:
12496 case X86::CMOV_GR32:
12497 case X86::CMOV_RFP32:
12498 case X86::CMOV_RFP64:
12499 case X86::CMOV_RFP80:
12500 return EmitLoweredSelect(MI, BB);
12502 case X86::FP32_TO_INT16_IN_MEM:
12503 case X86::FP32_TO_INT32_IN_MEM:
12504 case X86::FP32_TO_INT64_IN_MEM:
12505 case X86::FP64_TO_INT16_IN_MEM:
12506 case X86::FP64_TO_INT32_IN_MEM:
12507 case X86::FP64_TO_INT64_IN_MEM:
12508 case X86::FP80_TO_INT16_IN_MEM:
12509 case X86::FP80_TO_INT32_IN_MEM:
12510 case X86::FP80_TO_INT64_IN_MEM: {
12511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12512 DebugLoc DL = MI->getDebugLoc();
12514 // Change the floating point control register to use "round towards zero"
12515 // mode when truncating to an integer value.
12516 MachineFunction *F = BB->getParent();
12517 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12518 addFrameReference(BuildMI(*BB, MI, DL,
12519 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12521 // Load the old value of the high byte of the control word...
12523 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12524 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12527 // Set the high part to be round to zero...
12528 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12531 // Reload the modified control word now...
12532 addFrameReference(BuildMI(*BB, MI, DL,
12533 TII->get(X86::FLDCW16m)), CWFrameIdx);
12535 // Restore the memory image of control word to original value
12536 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12539 // Get the X86 opcode to use.
12541 switch (MI->getOpcode()) {
12542 default: llvm_unreachable("illegal opcode!");
12543 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12544 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12545 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12546 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12547 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12548 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12549 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12550 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12551 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12555 MachineOperand &Op = MI->getOperand(0);
12557 AM.BaseType = X86AddressMode::RegBase;
12558 AM.Base.Reg = Op.getReg();
12560 AM.BaseType = X86AddressMode::FrameIndexBase;
12561 AM.Base.FrameIndex = Op.getIndex();
12563 Op = MI->getOperand(1);
12565 AM.Scale = Op.getImm();
12566 Op = MI->getOperand(2);
12568 AM.IndexReg = Op.getImm();
12569 Op = MI->getOperand(3);
12570 if (Op.isGlobal()) {
12571 AM.GV = Op.getGlobal();
12573 AM.Disp = Op.getImm();
12575 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12576 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12578 // Reload the original control word now.
12579 addFrameReference(BuildMI(*BB, MI, DL,
12580 TII->get(X86::FLDCW16m)), CWFrameIdx);
12582 MI->eraseFromParent(); // The pseudo instruction is gone now.
12585 // String/text processing lowering.
12586 case X86::PCMPISTRM128REG:
12587 case X86::VPCMPISTRM128REG:
12588 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12589 case X86::PCMPISTRM128MEM:
12590 case X86::VPCMPISTRM128MEM:
12591 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12592 case X86::PCMPESTRM128REG:
12593 case X86::VPCMPESTRM128REG:
12594 return EmitPCMP(MI, BB, 5, false /* in mem */);
12595 case X86::PCMPESTRM128MEM:
12596 case X86::VPCMPESTRM128MEM:
12597 return EmitPCMP(MI, BB, 5, true /* in mem */);
12599 // Thread synchronization.
12601 return EmitMonitor(MI, BB);
12603 return EmitMwait(MI, BB);
12605 // Atomic Lowering.
12606 case X86::ATOMAND32:
12607 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12608 X86::AND32ri, X86::MOV32rm,
12610 X86::NOT32r, X86::EAX,
12611 X86::GR32RegisterClass);
12612 case X86::ATOMOR32:
12613 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12614 X86::OR32ri, X86::MOV32rm,
12616 X86::NOT32r, X86::EAX,
12617 X86::GR32RegisterClass);
12618 case X86::ATOMXOR32:
12619 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12620 X86::XOR32ri, X86::MOV32rm,
12622 X86::NOT32r, X86::EAX,
12623 X86::GR32RegisterClass);
12624 case X86::ATOMNAND32:
12625 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12626 X86::AND32ri, X86::MOV32rm,
12628 X86::NOT32r, X86::EAX,
12629 X86::GR32RegisterClass, true);
12630 case X86::ATOMMIN32:
12631 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12632 case X86::ATOMMAX32:
12633 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12634 case X86::ATOMUMIN32:
12635 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12636 case X86::ATOMUMAX32:
12637 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12639 case X86::ATOMAND16:
12640 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12641 X86::AND16ri, X86::MOV16rm,
12643 X86::NOT16r, X86::AX,
12644 X86::GR16RegisterClass);
12645 case X86::ATOMOR16:
12646 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12647 X86::OR16ri, X86::MOV16rm,
12649 X86::NOT16r, X86::AX,
12650 X86::GR16RegisterClass);
12651 case X86::ATOMXOR16:
12652 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12653 X86::XOR16ri, X86::MOV16rm,
12655 X86::NOT16r, X86::AX,
12656 X86::GR16RegisterClass);
12657 case X86::ATOMNAND16:
12658 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12659 X86::AND16ri, X86::MOV16rm,
12661 X86::NOT16r, X86::AX,
12662 X86::GR16RegisterClass, true);
12663 case X86::ATOMMIN16:
12664 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12665 case X86::ATOMMAX16:
12666 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12667 case X86::ATOMUMIN16:
12668 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12669 case X86::ATOMUMAX16:
12670 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12672 case X86::ATOMAND8:
12673 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12674 X86::AND8ri, X86::MOV8rm,
12676 X86::NOT8r, X86::AL,
12677 X86::GR8RegisterClass);
12679 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12680 X86::OR8ri, X86::MOV8rm,
12682 X86::NOT8r, X86::AL,
12683 X86::GR8RegisterClass);
12684 case X86::ATOMXOR8:
12685 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12686 X86::XOR8ri, X86::MOV8rm,
12688 X86::NOT8r, X86::AL,
12689 X86::GR8RegisterClass);
12690 case X86::ATOMNAND8:
12691 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12692 X86::AND8ri, X86::MOV8rm,
12694 X86::NOT8r, X86::AL,
12695 X86::GR8RegisterClass, true);
12696 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12697 // This group is for 64-bit host.
12698 case X86::ATOMAND64:
12699 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12700 X86::AND64ri32, X86::MOV64rm,
12702 X86::NOT64r, X86::RAX,
12703 X86::GR64RegisterClass);
12704 case X86::ATOMOR64:
12705 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12706 X86::OR64ri32, X86::MOV64rm,
12708 X86::NOT64r, X86::RAX,
12709 X86::GR64RegisterClass);
12710 case X86::ATOMXOR64:
12711 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12712 X86::XOR64ri32, X86::MOV64rm,
12714 X86::NOT64r, X86::RAX,
12715 X86::GR64RegisterClass);
12716 case X86::ATOMNAND64:
12717 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12718 X86::AND64ri32, X86::MOV64rm,
12720 X86::NOT64r, X86::RAX,
12721 X86::GR64RegisterClass, true);
12722 case X86::ATOMMIN64:
12723 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12724 case X86::ATOMMAX64:
12725 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12726 case X86::ATOMUMIN64:
12727 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12728 case X86::ATOMUMAX64:
12729 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12731 // This group does 64-bit operations on a 32-bit host.
12732 case X86::ATOMAND6432:
12733 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12734 X86::AND32rr, X86::AND32rr,
12735 X86::AND32ri, X86::AND32ri,
12737 case X86::ATOMOR6432:
12738 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12739 X86::OR32rr, X86::OR32rr,
12740 X86::OR32ri, X86::OR32ri,
12742 case X86::ATOMXOR6432:
12743 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12744 X86::XOR32rr, X86::XOR32rr,
12745 X86::XOR32ri, X86::XOR32ri,
12747 case X86::ATOMNAND6432:
12748 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12749 X86::AND32rr, X86::AND32rr,
12750 X86::AND32ri, X86::AND32ri,
12752 case X86::ATOMADD6432:
12753 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12754 X86::ADD32rr, X86::ADC32rr,
12755 X86::ADD32ri, X86::ADC32ri,
12757 case X86::ATOMSUB6432:
12758 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12759 X86::SUB32rr, X86::SBB32rr,
12760 X86::SUB32ri, X86::SBB32ri,
12762 case X86::ATOMSWAP6432:
12763 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12764 X86::MOV32rr, X86::MOV32rr,
12765 X86::MOV32ri, X86::MOV32ri,
12767 case X86::VASTART_SAVE_XMM_REGS:
12768 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12770 case X86::VAARG_64:
12771 return EmitVAARG64WithCustomInserter(MI, BB);
12775 //===----------------------------------------------------------------------===//
12776 // X86 Optimization Hooks
12777 //===----------------------------------------------------------------------===//
12779 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12783 const SelectionDAG &DAG,
12784 unsigned Depth) const {
12785 unsigned Opc = Op.getOpcode();
12786 assert((Opc >= ISD::BUILTIN_OP_END ||
12787 Opc == ISD::INTRINSIC_WO_CHAIN ||
12788 Opc == ISD::INTRINSIC_W_CHAIN ||
12789 Opc == ISD::INTRINSIC_VOID) &&
12790 "Should use MaskedValueIsZero if you don't know whether Op"
12791 " is a target node!");
12793 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12807 // These nodes' second result is a boolean.
12808 if (Op.getResNo() == 0)
12811 case X86ISD::SETCC:
12812 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12813 Mask.getBitWidth() - 1);
12815 case ISD::INTRINSIC_WO_CHAIN: {
12816 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12817 unsigned NumLoBits = 0;
12820 case Intrinsic::x86_sse_movmsk_ps:
12821 case Intrinsic::x86_avx_movmsk_ps_256:
12822 case Intrinsic::x86_sse2_movmsk_pd:
12823 case Intrinsic::x86_avx_movmsk_pd_256:
12824 case Intrinsic::x86_mmx_pmovmskb:
12825 case Intrinsic::x86_sse2_pmovmskb_128: {
12826 // High bits of movmskp{s|d}, pmovmskb are known zero.
12828 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12829 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12830 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12831 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12832 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12833 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12835 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12836 Mask.getBitWidth() - NumLoBits);
12845 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12846 unsigned Depth) const {
12847 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12848 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12849 return Op.getValueType().getScalarType().getSizeInBits();
12855 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12856 /// node is a GlobalAddress + offset.
12857 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12858 const GlobalValue* &GA,
12859 int64_t &Offset) const {
12860 if (N->getOpcode() == X86ISD::Wrapper) {
12861 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12862 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12863 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12867 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12870 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12871 /// same as extracting the high 128-bit part of 256-bit vector and then
12872 /// inserting the result into the low part of a new 256-bit vector
12873 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12874 EVT VT = SVOp->getValueType(0);
12875 int NumElems = VT.getVectorNumElements();
12877 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12878 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12879 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12880 SVOp->getMaskElt(j) >= 0)
12886 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12887 /// same as extracting the low 128-bit part of 256-bit vector and then
12888 /// inserting the result into the high part of a new 256-bit vector
12889 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12890 EVT VT = SVOp->getValueType(0);
12891 int NumElems = VT.getVectorNumElements();
12893 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12894 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12895 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12896 SVOp->getMaskElt(j) >= 0)
12902 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12903 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12904 TargetLowering::DAGCombinerInfo &DCI) {
12905 DebugLoc dl = N->getDebugLoc();
12906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12907 SDValue V1 = SVOp->getOperand(0);
12908 SDValue V2 = SVOp->getOperand(1);
12909 EVT VT = SVOp->getValueType(0);
12910 int NumElems = VT.getVectorNumElements();
12912 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12913 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12917 // V UNDEF BUILD_VECTOR UNDEF
12919 // CONCAT_VECTOR CONCAT_VECTOR
12922 // RESULT: V + zero extended
12924 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12925 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12926 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12929 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12932 // To match the shuffle mask, the first half of the mask should
12933 // be exactly the first vector, and all the rest a splat with the
12934 // first element of the second one.
12935 for (int i = 0; i < NumElems/2; ++i)
12936 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12937 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12940 // Emit a zeroed vector and insert the desired subvector on its
12942 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12943 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12944 DAG.getConstant(0, MVT::i32), DAG, dl);
12945 return DCI.CombineTo(N, InsV);
12948 //===--------------------------------------------------------------------===//
12949 // Combine some shuffles into subvector extracts and inserts:
12952 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12953 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12954 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12956 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12957 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12958 return DCI.CombineTo(N, InsV);
12961 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12962 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12963 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12964 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12965 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12966 return DCI.CombineTo(N, InsV);
12972 /// PerformShuffleCombine - Performs several different shuffle combines.
12973 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12974 TargetLowering::DAGCombinerInfo &DCI,
12975 const X86Subtarget *Subtarget) {
12976 DebugLoc dl = N->getDebugLoc();
12977 EVT VT = N->getValueType(0);
12979 // Don't create instructions with illegal types after legalize types has run.
12980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12981 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12984 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12985 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12986 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12987 return PerformShuffleCombine256(N, DAG, DCI);
12989 // Only handle 128 wide vector from here on.
12990 if (VT.getSizeInBits() != 128)
12993 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12994 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12995 // consecutive, non-overlapping, and in the right order.
12996 SmallVector<SDValue, 16> Elts;
12997 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12998 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13000 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13003 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13004 /// generation and convert it from being a bunch of shuffles and extracts
13005 /// to a simple store and scalar loads to extract the elements.
13006 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13007 const TargetLowering &TLI) {
13008 SDValue InputVector = N->getOperand(0);
13010 // Only operate on vectors of 4 elements, where the alternative shuffling
13011 // gets to be more expensive.
13012 if (InputVector.getValueType() != MVT::v4i32)
13015 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13016 // single use which is a sign-extend or zero-extend, and all elements are
13018 SmallVector<SDNode *, 4> Uses;
13019 unsigned ExtractedElements = 0;
13020 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13021 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13022 if (UI.getUse().getResNo() != InputVector.getResNo())
13025 SDNode *Extract = *UI;
13026 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13029 if (Extract->getValueType(0) != MVT::i32)
13031 if (!Extract->hasOneUse())
13033 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13034 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13036 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13039 // Record which element was extracted.
13040 ExtractedElements |=
13041 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13043 Uses.push_back(Extract);
13046 // If not all the elements were used, this may not be worthwhile.
13047 if (ExtractedElements != 15)
13050 // Ok, we've now decided to do the transformation.
13051 DebugLoc dl = InputVector.getDebugLoc();
13053 // Store the value to a temporary stack slot.
13054 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13055 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13056 MachinePointerInfo(), false, false, 0);
13058 // Replace each use (extract) with a load of the appropriate element.
13059 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13060 UE = Uses.end(); UI != UE; ++UI) {
13061 SDNode *Extract = *UI;
13063 // cOMpute the element's address.
13064 SDValue Idx = Extract->getOperand(1);
13066 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13067 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13068 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13070 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13071 StackPtr, OffsetVal);
13073 // Load the scalar.
13074 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13075 ScalarAddr, MachinePointerInfo(),
13076 false, false, false, 0);
13078 // Replace the exact with the load.
13079 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13082 // The replacement was made in place; don't return anything.
13086 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13088 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13089 const X86Subtarget *Subtarget) {
13090 DebugLoc DL = N->getDebugLoc();
13091 SDValue Cond = N->getOperand(0);
13092 // Get the LHS/RHS of the select.
13093 SDValue LHS = N->getOperand(1);
13094 SDValue RHS = N->getOperand(2);
13095 EVT VT = LHS.getValueType();
13097 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13098 // instructions match the semantics of the common C idiom x<y?x:y but not
13099 // x<=y?x:y, because of how they handle negative zero (which can be
13100 // ignored in unsafe-math mode).
13101 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13102 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13103 (Subtarget->hasXMMInt() ||
13104 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13105 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13107 unsigned Opcode = 0;
13108 // Check for x CC y ? x : y.
13109 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13110 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13114 // Converting this to a min would handle NaNs incorrectly, and swapping
13115 // the operands would cause it to handle comparisons between positive
13116 // and negative zero incorrectly.
13117 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13118 if (!UnsafeFPMath &&
13119 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13121 std::swap(LHS, RHS);
13123 Opcode = X86ISD::FMIN;
13126 // Converting this to a min would handle comparisons between positive
13127 // and negative zero incorrectly.
13128 if (!UnsafeFPMath &&
13129 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13131 Opcode = X86ISD::FMIN;
13134 // Converting this to a min would handle both negative zeros and NaNs
13135 // incorrectly, but we can swap the operands to fix both.
13136 std::swap(LHS, RHS);
13140 Opcode = X86ISD::FMIN;
13144 // Converting this to a max would handle comparisons between positive
13145 // and negative zero incorrectly.
13146 if (!UnsafeFPMath &&
13147 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13149 Opcode = X86ISD::FMAX;
13152 // Converting this to a max would handle NaNs incorrectly, and swapping
13153 // the operands would cause it to handle comparisons between positive
13154 // and negative zero incorrectly.
13155 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13156 if (!UnsafeFPMath &&
13157 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13159 std::swap(LHS, RHS);
13161 Opcode = X86ISD::FMAX;
13164 // Converting this to a max would handle both negative zeros and NaNs
13165 // incorrectly, but we can swap the operands to fix both.
13166 std::swap(LHS, RHS);
13170 Opcode = X86ISD::FMAX;
13173 // Check for x CC y ? y : x -- a min/max with reversed arms.
13174 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13175 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13179 // Converting this to a min would handle comparisons between positive
13180 // and negative zero incorrectly, and swapping the operands would
13181 // cause it to handle NaNs incorrectly.
13182 if (!UnsafeFPMath &&
13183 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13184 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13186 std::swap(LHS, RHS);
13188 Opcode = X86ISD::FMIN;
13191 // Converting this to a min would handle NaNs incorrectly.
13192 if (!UnsafeFPMath &&
13193 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13195 Opcode = X86ISD::FMIN;
13198 // Converting this to a min would handle both negative zeros and NaNs
13199 // incorrectly, but we can swap the operands to fix both.
13200 std::swap(LHS, RHS);
13204 Opcode = X86ISD::FMIN;
13208 // Converting this to a max would handle NaNs incorrectly.
13209 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13211 Opcode = X86ISD::FMAX;
13214 // Converting this to a max would handle comparisons between positive
13215 // and negative zero incorrectly, and swapping the operands would
13216 // cause it to handle NaNs incorrectly.
13217 if (!UnsafeFPMath &&
13218 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13219 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13221 std::swap(LHS, RHS);
13223 Opcode = X86ISD::FMAX;
13226 // Converting this to a max would handle both negative zeros and NaNs
13227 // incorrectly, but we can swap the operands to fix both.
13228 std::swap(LHS, RHS);
13232 Opcode = X86ISD::FMAX;
13238 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13241 // If this is a select between two integer constants, try to do some
13243 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13244 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13245 // Don't do this for crazy integer types.
13246 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13247 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13248 // so that TrueC (the true value) is larger than FalseC.
13249 bool NeedsCondInvert = false;
13251 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13252 // Efficiently invertible.
13253 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13254 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13255 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13256 NeedsCondInvert = true;
13257 std::swap(TrueC, FalseC);
13260 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13261 if (FalseC->getAPIntValue() == 0 &&
13262 TrueC->getAPIntValue().isPowerOf2()) {
13263 if (NeedsCondInvert) // Invert the condition if needed.
13264 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13265 DAG.getConstant(1, Cond.getValueType()));
13267 // Zero extend the condition if needed.
13268 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13270 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13271 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13272 DAG.getConstant(ShAmt, MVT::i8));
13275 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13276 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13277 if (NeedsCondInvert) // Invert the condition if needed.
13278 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13279 DAG.getConstant(1, Cond.getValueType()));
13281 // Zero extend the condition if needed.
13282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13283 FalseC->getValueType(0), Cond);
13284 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13285 SDValue(FalseC, 0));
13288 // Optimize cases that will turn into an LEA instruction. This requires
13289 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13290 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13291 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13292 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13294 bool isFastMultiplier = false;
13296 switch ((unsigned char)Diff) {
13298 case 1: // result = add base, cond
13299 case 2: // result = lea base( , cond*2)
13300 case 3: // result = lea base(cond, cond*2)
13301 case 4: // result = lea base( , cond*4)
13302 case 5: // result = lea base(cond, cond*4)
13303 case 8: // result = lea base( , cond*8)
13304 case 9: // result = lea base(cond, cond*8)
13305 isFastMultiplier = true;
13310 if (isFastMultiplier) {
13311 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13312 if (NeedsCondInvert) // Invert the condition if needed.
13313 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13314 DAG.getConstant(1, Cond.getValueType()));
13316 // Zero extend the condition if needed.
13317 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13319 // Scale the condition by the difference.
13321 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13322 DAG.getConstant(Diff, Cond.getValueType()));
13324 // Add the base if non-zero.
13325 if (FalseC->getAPIntValue() != 0)
13326 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13327 SDValue(FalseC, 0));
13337 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13338 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13339 TargetLowering::DAGCombinerInfo &DCI) {
13340 DebugLoc DL = N->getDebugLoc();
13342 // If the flag operand isn't dead, don't touch this CMOV.
13343 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13346 SDValue FalseOp = N->getOperand(0);
13347 SDValue TrueOp = N->getOperand(1);
13348 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13349 SDValue Cond = N->getOperand(3);
13350 if (CC == X86::COND_E || CC == X86::COND_NE) {
13351 switch (Cond.getOpcode()) {
13355 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13356 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13357 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13361 // If this is a select between two integer constants, try to do some
13362 // optimizations. Note that the operands are ordered the opposite of SELECT
13364 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13365 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13366 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13367 // larger than FalseC (the false value).
13368 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13369 CC = X86::GetOppositeBranchCondition(CC);
13370 std::swap(TrueC, FalseC);
13373 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13374 // This is efficient for any integer data type (including i8/i16) and
13376 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13377 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13378 DAG.getConstant(CC, MVT::i8), Cond);
13380 // Zero extend the condition if needed.
13381 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13383 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13384 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13385 DAG.getConstant(ShAmt, MVT::i8));
13386 if (N->getNumValues() == 2) // Dead flag value?
13387 return DCI.CombineTo(N, Cond, SDValue());
13391 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13392 // for any integer data type, including i8/i16.
13393 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13394 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13395 DAG.getConstant(CC, MVT::i8), Cond);
13397 // Zero extend the condition if needed.
13398 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13399 FalseC->getValueType(0), Cond);
13400 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13401 SDValue(FalseC, 0));
13403 if (N->getNumValues() == 2) // Dead flag value?
13404 return DCI.CombineTo(N, Cond, SDValue());
13408 // Optimize cases that will turn into an LEA instruction. This requires
13409 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13410 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13411 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13412 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13414 bool isFastMultiplier = false;
13416 switch ((unsigned char)Diff) {
13418 case 1: // result = add base, cond
13419 case 2: // result = lea base( , cond*2)
13420 case 3: // result = lea base(cond, cond*2)
13421 case 4: // result = lea base( , cond*4)
13422 case 5: // result = lea base(cond, cond*4)
13423 case 8: // result = lea base( , cond*8)
13424 case 9: // result = lea base(cond, cond*8)
13425 isFastMultiplier = true;
13430 if (isFastMultiplier) {
13431 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13432 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13433 DAG.getConstant(CC, MVT::i8), Cond);
13434 // Zero extend the condition if needed.
13435 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13437 // Scale the condition by the difference.
13439 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13440 DAG.getConstant(Diff, Cond.getValueType()));
13442 // Add the base if non-zero.
13443 if (FalseC->getAPIntValue() != 0)
13444 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13445 SDValue(FalseC, 0));
13446 if (N->getNumValues() == 2) // Dead flag value?
13447 return DCI.CombineTo(N, Cond, SDValue());
13457 /// PerformMulCombine - Optimize a single multiply with constant into two
13458 /// in order to implement it with two cheaper instructions, e.g.
13459 /// LEA + SHL, LEA + LEA.
13460 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13461 TargetLowering::DAGCombinerInfo &DCI) {
13462 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13465 EVT VT = N->getValueType(0);
13466 if (VT != MVT::i64)
13469 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13472 uint64_t MulAmt = C->getZExtValue();
13473 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13476 uint64_t MulAmt1 = 0;
13477 uint64_t MulAmt2 = 0;
13478 if ((MulAmt % 9) == 0) {
13480 MulAmt2 = MulAmt / 9;
13481 } else if ((MulAmt % 5) == 0) {
13483 MulAmt2 = MulAmt / 5;
13484 } else if ((MulAmt % 3) == 0) {
13486 MulAmt2 = MulAmt / 3;
13489 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13490 DebugLoc DL = N->getDebugLoc();
13492 if (isPowerOf2_64(MulAmt2) &&
13493 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13494 // If second multiplifer is pow2, issue it first. We want the multiply by
13495 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13497 std::swap(MulAmt1, MulAmt2);
13500 if (isPowerOf2_64(MulAmt1))
13501 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13502 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13504 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13505 DAG.getConstant(MulAmt1, VT));
13507 if (isPowerOf2_64(MulAmt2))
13508 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13509 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13511 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13512 DAG.getConstant(MulAmt2, VT));
13514 // Do not add new nodes to DAG combiner worklist.
13515 DCI.CombineTo(N, NewMul, false);
13520 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13521 SDValue N0 = N->getOperand(0);
13522 SDValue N1 = N->getOperand(1);
13523 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13524 EVT VT = N0.getValueType();
13526 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13527 // since the result of setcc_c is all zero's or all ones.
13528 if (VT.isInteger() && !VT.isVector() &&
13529 N1C && N0.getOpcode() == ISD::AND &&
13530 N0.getOperand(1).getOpcode() == ISD::Constant) {
13531 SDValue N00 = N0.getOperand(0);
13532 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13533 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13534 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13535 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13536 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13537 APInt ShAmt = N1C->getAPIntValue();
13538 Mask = Mask.shl(ShAmt);
13540 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13541 N00, DAG.getConstant(Mask, VT));
13546 // Hardware support for vector shifts is sparse which makes us scalarize the
13547 // vector operations in many cases. Also, on sandybridge ADD is faster than
13549 // (shl V, 1) -> add V,V
13550 if (isSplatVector(N1.getNode())) {
13551 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13552 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13553 // We shift all of the values by one. In many cases we do not have
13554 // hardware support for this operation. This is better expressed as an ADD
13556 if (N1C && (1 == N1C->getZExtValue())) {
13557 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13564 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13566 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13567 const X86Subtarget *Subtarget) {
13568 EVT VT = N->getValueType(0);
13569 if (N->getOpcode() == ISD::SHL) {
13570 SDValue V = PerformSHLCombine(N, DAG);
13571 if (V.getNode()) return V;
13574 // On X86 with SSE2 support, we can transform this to a vector shift if
13575 // all elements are shifted by the same amount. We can't do this in legalize
13576 // because the a constant vector is typically transformed to a constant pool
13577 // so we have no knowledge of the shift amount.
13578 if (!Subtarget->hasXMMInt())
13581 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13582 (!Subtarget->hasAVX2() ||
13583 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13586 SDValue ShAmtOp = N->getOperand(1);
13587 EVT EltVT = VT.getVectorElementType();
13588 DebugLoc DL = N->getDebugLoc();
13589 SDValue BaseShAmt = SDValue();
13590 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13591 unsigned NumElts = VT.getVectorNumElements();
13593 for (; i != NumElts; ++i) {
13594 SDValue Arg = ShAmtOp.getOperand(i);
13595 if (Arg.getOpcode() == ISD::UNDEF) continue;
13599 for (; i != NumElts; ++i) {
13600 SDValue Arg = ShAmtOp.getOperand(i);
13601 if (Arg.getOpcode() == ISD::UNDEF) continue;
13602 if (Arg != BaseShAmt) {
13606 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13607 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13608 SDValue InVec = ShAmtOp.getOperand(0);
13609 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13610 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13612 for (; i != NumElts; ++i) {
13613 SDValue Arg = InVec.getOperand(i);
13614 if (Arg.getOpcode() == ISD::UNDEF) continue;
13618 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13620 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13621 if (C->getZExtValue() == SplatIdx)
13622 BaseShAmt = InVec.getOperand(1);
13625 if (BaseShAmt.getNode() == 0)
13626 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13627 DAG.getIntPtrConstant(0));
13631 // The shift amount is an i32.
13632 if (EltVT.bitsGT(MVT::i32))
13633 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13634 else if (EltVT.bitsLT(MVT::i32))
13635 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13637 // The shift amount is identical so we can do a vector shift.
13638 SDValue ValOp = N->getOperand(0);
13639 switch (N->getOpcode()) {
13641 llvm_unreachable("Unknown shift opcode!");
13644 if (VT == MVT::v2i64)
13645 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13646 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13648 if (VT == MVT::v4i32)
13649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13650 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13652 if (VT == MVT::v8i16)
13653 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13654 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13656 if (VT == MVT::v4i64)
13657 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13658 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13660 if (VT == MVT::v8i32)
13661 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13662 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13664 if (VT == MVT::v16i16)
13665 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13666 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13670 if (VT == MVT::v4i32)
13671 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13672 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13674 if (VT == MVT::v8i16)
13675 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13676 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13678 if (VT == MVT::v8i32)
13679 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13680 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13682 if (VT == MVT::v16i16)
13683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13684 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13688 if (VT == MVT::v2i64)
13689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13690 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13692 if (VT == MVT::v4i32)
13693 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13694 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13696 if (VT == MVT::v8i16)
13697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13698 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13700 if (VT == MVT::v4i64)
13701 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13702 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13704 if (VT == MVT::v8i32)
13705 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13706 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13708 if (VT == MVT::v16i16)
13709 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13710 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13718 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13719 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13720 // and friends. Likewise for OR -> CMPNEQSS.
13721 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13722 TargetLowering::DAGCombinerInfo &DCI,
13723 const X86Subtarget *Subtarget) {
13726 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13727 // we're requiring SSE2 for both.
13728 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13729 SDValue N0 = N->getOperand(0);
13730 SDValue N1 = N->getOperand(1);
13731 SDValue CMP0 = N0->getOperand(1);
13732 SDValue CMP1 = N1->getOperand(1);
13733 DebugLoc DL = N->getDebugLoc();
13735 // The SETCCs should both refer to the same CMP.
13736 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13739 SDValue CMP00 = CMP0->getOperand(0);
13740 SDValue CMP01 = CMP0->getOperand(1);
13741 EVT VT = CMP00.getValueType();
13743 if (VT == MVT::f32 || VT == MVT::f64) {
13744 bool ExpectingFlags = false;
13745 // Check for any users that want flags:
13746 for (SDNode::use_iterator UI = N->use_begin(),
13748 !ExpectingFlags && UI != UE; ++UI)
13749 switch (UI->getOpcode()) {
13754 ExpectingFlags = true;
13756 case ISD::CopyToReg:
13757 case ISD::SIGN_EXTEND:
13758 case ISD::ZERO_EXTEND:
13759 case ISD::ANY_EXTEND:
13763 if (!ExpectingFlags) {
13764 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13765 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13767 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13768 X86::CondCode tmp = cc0;
13773 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13774 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13775 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13776 X86ISD::NodeType NTOperator = is64BitFP ?
13777 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13778 // FIXME: need symbolic constants for these magic numbers.
13779 // See X86ATTInstPrinter.cpp:printSSECC().
13780 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13781 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13782 DAG.getConstant(x86cc, MVT::i8));
13783 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13785 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13786 DAG.getConstant(1, MVT::i32));
13787 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13788 return OneBitOfTruth;
13796 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13797 /// so it can be folded inside ANDNP.
13798 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13799 EVT VT = N->getValueType(0);
13801 // Match direct AllOnes for 128 and 256-bit vectors
13802 if (ISD::isBuildVectorAllOnes(N))
13805 // Look through a bit convert.
13806 if (N->getOpcode() == ISD::BITCAST)
13807 N = N->getOperand(0).getNode();
13809 // Sometimes the operand may come from a insert_subvector building a 256-bit
13811 if (VT.getSizeInBits() == 256 &&
13812 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13813 SDValue V1 = N->getOperand(0);
13814 SDValue V2 = N->getOperand(1);
13816 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13817 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13818 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13819 ISD::isBuildVectorAllOnes(V2.getNode()))
13826 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13827 TargetLowering::DAGCombinerInfo &DCI,
13828 const X86Subtarget *Subtarget) {
13829 if (DCI.isBeforeLegalizeOps())
13832 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13836 EVT VT = N->getValueType(0);
13838 // Create ANDN, BLSI, and BLSR instructions
13839 // BLSI is X & (-X)
13840 // BLSR is X & (X-1)
13841 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13842 SDValue N0 = N->getOperand(0);
13843 SDValue N1 = N->getOperand(1);
13844 DebugLoc DL = N->getDebugLoc();
13846 // Check LHS for not
13847 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13848 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13849 // Check RHS for not
13850 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13851 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13853 // Check LHS for neg
13854 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13855 isZero(N0.getOperand(0)))
13856 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13858 // Check RHS for neg
13859 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13860 isZero(N1.getOperand(0)))
13861 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13863 // Check LHS for X-1
13864 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13865 isAllOnes(N0.getOperand(1)))
13866 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13868 // Check RHS for X-1
13869 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13870 isAllOnes(N1.getOperand(1)))
13871 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13876 // Want to form ANDNP nodes:
13877 // 1) In the hopes of then easily combining them with OR and AND nodes
13878 // to form PBLEND/PSIGN.
13879 // 2) To match ANDN packed intrinsics
13880 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13883 SDValue N0 = N->getOperand(0);
13884 SDValue N1 = N->getOperand(1);
13885 DebugLoc DL = N->getDebugLoc();
13887 // Check LHS for vnot
13888 if (N0.getOpcode() == ISD::XOR &&
13889 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13890 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13891 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13893 // Check RHS for vnot
13894 if (N1.getOpcode() == ISD::XOR &&
13895 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13896 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13897 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13902 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13903 TargetLowering::DAGCombinerInfo &DCI,
13904 const X86Subtarget *Subtarget) {
13905 if (DCI.isBeforeLegalizeOps())
13908 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13912 EVT VT = N->getValueType(0);
13914 SDValue N0 = N->getOperand(0);
13915 SDValue N1 = N->getOperand(1);
13917 // look for psign/blend
13918 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13919 if (!Subtarget->hasSSSE3orAVX() ||
13920 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13923 // Canonicalize pandn to RHS
13924 if (N0.getOpcode() == X86ISD::ANDNP)
13926 // or (and (m, x), (pandn m, y))
13927 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13928 SDValue Mask = N1.getOperand(0);
13929 SDValue X = N1.getOperand(1);
13931 if (N0.getOperand(0) == Mask)
13932 Y = N0.getOperand(1);
13933 if (N0.getOperand(1) == Mask)
13934 Y = N0.getOperand(0);
13936 // Check to see if the mask appeared in both the AND and ANDNP and
13940 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13941 if (Mask.getOpcode() != ISD::BITCAST ||
13942 X.getOpcode() != ISD::BITCAST ||
13943 Y.getOpcode() != ISD::BITCAST)
13946 // Look through mask bitcast.
13947 Mask = Mask.getOperand(0);
13948 EVT MaskVT = Mask.getValueType();
13950 // Validate that the Mask operand is a vector sra node. The sra node
13951 // will be an intrinsic.
13952 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13955 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13956 // there is no psrai.b
13957 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13958 case Intrinsic::x86_sse2_psrai_w:
13959 case Intrinsic::x86_sse2_psrai_d:
13960 case Intrinsic::x86_avx2_psrai_w:
13961 case Intrinsic::x86_avx2_psrai_d:
13963 default: return SDValue();
13966 // Check that the SRA is all signbits.
13967 SDValue SraC = Mask.getOperand(2);
13968 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13969 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13970 if ((SraAmt + 1) != EltBits)
13973 DebugLoc DL = N->getDebugLoc();
13975 // Now we know we at least have a plendvb with the mask val. See if
13976 // we can form a psignb/w/d.
13977 // psign = x.type == y.type == mask.type && y = sub(0, x);
13978 X = X.getOperand(0);
13979 Y = Y.getOperand(0);
13980 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13981 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13982 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13983 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13984 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13985 Mask.getOperand(1));
13986 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13988 // PBLENDVB only available on SSE 4.1
13989 if (!Subtarget->hasSSE41orAVX())
13992 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13994 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13995 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13996 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13997 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
13998 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14002 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14005 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14006 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14008 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14010 if (!N0.hasOneUse() || !N1.hasOneUse())
14013 SDValue ShAmt0 = N0.getOperand(1);
14014 if (ShAmt0.getValueType() != MVT::i8)
14016 SDValue ShAmt1 = N1.getOperand(1);
14017 if (ShAmt1.getValueType() != MVT::i8)
14019 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14020 ShAmt0 = ShAmt0.getOperand(0);
14021 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14022 ShAmt1 = ShAmt1.getOperand(0);
14024 DebugLoc DL = N->getDebugLoc();
14025 unsigned Opc = X86ISD::SHLD;
14026 SDValue Op0 = N0.getOperand(0);
14027 SDValue Op1 = N1.getOperand(0);
14028 if (ShAmt0.getOpcode() == ISD::SUB) {
14029 Opc = X86ISD::SHRD;
14030 std::swap(Op0, Op1);
14031 std::swap(ShAmt0, ShAmt1);
14034 unsigned Bits = VT.getSizeInBits();
14035 if (ShAmt1.getOpcode() == ISD::SUB) {
14036 SDValue Sum = ShAmt1.getOperand(0);
14037 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14038 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14039 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14040 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14041 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14042 return DAG.getNode(Opc, DL, VT,
14044 DAG.getNode(ISD::TRUNCATE, DL,
14047 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14048 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14050 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14051 return DAG.getNode(Opc, DL, VT,
14052 N0.getOperand(0), N1.getOperand(0),
14053 DAG.getNode(ISD::TRUNCATE, DL,
14060 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14061 TargetLowering::DAGCombinerInfo &DCI,
14062 const X86Subtarget *Subtarget) {
14063 if (DCI.isBeforeLegalizeOps())
14066 EVT VT = N->getValueType(0);
14068 if (VT != MVT::i32 && VT != MVT::i64)
14071 // Create BLSMSK instructions by finding X ^ (X-1)
14072 SDValue N0 = N->getOperand(0);
14073 SDValue N1 = N->getOperand(1);
14074 DebugLoc DL = N->getDebugLoc();
14076 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14077 isAllOnes(N0.getOperand(1)))
14078 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14080 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14081 isAllOnes(N1.getOperand(1)))
14082 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14087 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14088 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14089 const X86Subtarget *Subtarget) {
14090 LoadSDNode *Ld = cast<LoadSDNode>(N);
14091 EVT RegVT = Ld->getValueType(0);
14092 EVT MemVT = Ld->getMemoryVT();
14093 DebugLoc dl = Ld->getDebugLoc();
14094 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14096 ISD::LoadExtType Ext = Ld->getExtensionType();
14098 // If this is a vector EXT Load then attempt to optimize it using a
14099 // shuffle. We need SSE4 for the shuffles.
14100 // TODO: It is possible to support ZExt by zeroing the undef values
14101 // during the shuffle phase or after the shuffle.
14102 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14103 assert(MemVT != RegVT && "Cannot extend to the same type");
14104 assert(MemVT.isVector() && "Must load a vector from memory");
14106 unsigned NumElems = RegVT.getVectorNumElements();
14107 unsigned RegSz = RegVT.getSizeInBits();
14108 unsigned MemSz = MemVT.getSizeInBits();
14109 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14110 // All sizes must be a power of two
14111 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14113 // Attempt to load the original value using a single load op.
14114 // Find a scalar type which is equal to the loaded word size.
14115 MVT SclrLoadTy = MVT::i8;
14116 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14117 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14118 MVT Tp = (MVT::SimpleValueType)tp;
14119 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14125 // Proceed if a load word is found.
14126 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14128 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14129 RegSz/SclrLoadTy.getSizeInBits());
14131 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14132 RegSz/MemVT.getScalarType().getSizeInBits());
14133 // Can't shuffle using an illegal type.
14134 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14136 // Perform a single load.
14137 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14139 Ld->getPointerInfo(), Ld->isVolatile(),
14140 Ld->isNonTemporal(), Ld->isInvariant(),
14141 Ld->getAlignment());
14143 // Insert the word loaded into a vector.
14144 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14145 LoadUnitVecVT, ScalarLoad);
14147 // Bitcast the loaded value to a vector of the original element type, in
14148 // the size of the target vector type.
14149 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14150 unsigned SizeRatio = RegSz/MemSz;
14152 // Redistribute the loaded elements into the different locations.
14153 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14154 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14156 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14157 DAG.getUNDEF(SlicedVec.getValueType()),
14158 ShuffleVec.data());
14160 // Bitcast to the requested type.
14161 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14162 // Replace the original load with the new sequence
14163 // and return the new chain.
14164 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14165 return SDValue(ScalarLoad.getNode(), 1);
14171 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14172 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14173 const X86Subtarget *Subtarget) {
14174 StoreSDNode *St = cast<StoreSDNode>(N);
14175 EVT VT = St->getValue().getValueType();
14176 EVT StVT = St->getMemoryVT();
14177 DebugLoc dl = St->getDebugLoc();
14178 SDValue StoredVal = St->getOperand(1);
14179 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14181 // If we are saving a concatination of two XMM registers, perform two stores.
14182 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14183 // 128-bit ones. If in the future the cost becomes only one memory access the
14184 // first version would be better.
14185 if (VT.getSizeInBits() == 256 &&
14186 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14187 StoredVal.getNumOperands() == 2) {
14189 SDValue Value0 = StoredVal.getOperand(0);
14190 SDValue Value1 = StoredVal.getOperand(1);
14192 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14193 SDValue Ptr0 = St->getBasePtr();
14194 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14196 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14197 St->getPointerInfo(), St->isVolatile(),
14198 St->isNonTemporal(), St->getAlignment());
14199 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14200 St->getPointerInfo(), St->isVolatile(),
14201 St->isNonTemporal(), St->getAlignment());
14202 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14205 // Optimize trunc store (of multiple scalars) to shuffle and store.
14206 // First, pack all of the elements in one place. Next, store to memory
14207 // in fewer chunks.
14208 if (St->isTruncatingStore() && VT.isVector()) {
14209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14210 unsigned NumElems = VT.getVectorNumElements();
14211 assert(StVT != VT && "Cannot truncate to the same type");
14212 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14213 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14215 // From, To sizes and ElemCount must be pow of two
14216 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14217 // We are going to use the original vector elt for storing.
14218 // Accumulated smaller vector elements must be a multiple of the store size.
14219 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14221 unsigned SizeRatio = FromSz / ToSz;
14223 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14225 // Create a type on which we perform the shuffle
14226 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14227 StVT.getScalarType(), NumElems*SizeRatio);
14229 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14231 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14232 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14233 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14235 // Can't shuffle using an illegal type
14236 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14238 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14239 DAG.getUNDEF(WideVec.getValueType()),
14240 ShuffleVec.data());
14241 // At this point all of the data is stored at the bottom of the
14242 // register. We now need to save it to mem.
14244 // Find the largest store unit
14245 MVT StoreType = MVT::i8;
14246 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14247 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14248 MVT Tp = (MVT::SimpleValueType)tp;
14249 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14253 // Bitcast the original vector into a vector of store-size units
14254 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14255 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14256 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14257 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14258 SmallVector<SDValue, 8> Chains;
14259 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14260 TLI.getPointerTy());
14261 SDValue Ptr = St->getBasePtr();
14263 // Perform one or more big stores into memory.
14264 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14265 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14266 StoreType, ShuffWide,
14267 DAG.getIntPtrConstant(i));
14268 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14269 St->getPointerInfo(), St->isVolatile(),
14270 St->isNonTemporal(), St->getAlignment());
14271 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14272 Chains.push_back(Ch);
14275 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14280 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14281 // the FP state in cases where an emms may be missing.
14282 // A preferable solution to the general problem is to figure out the right
14283 // places to insert EMMS. This qualifies as a quick hack.
14285 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14286 if (VT.getSizeInBits() != 64)
14289 const Function *F = DAG.getMachineFunction().getFunction();
14290 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14291 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14292 && Subtarget->hasXMMInt();
14293 if ((VT.isVector() ||
14294 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14295 isa<LoadSDNode>(St->getValue()) &&
14296 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14297 St->getChain().hasOneUse() && !St->isVolatile()) {
14298 SDNode* LdVal = St->getValue().getNode();
14299 LoadSDNode *Ld = 0;
14300 int TokenFactorIndex = -1;
14301 SmallVector<SDValue, 8> Ops;
14302 SDNode* ChainVal = St->getChain().getNode();
14303 // Must be a store of a load. We currently handle two cases: the load
14304 // is a direct child, and it's under an intervening TokenFactor. It is
14305 // possible to dig deeper under nested TokenFactors.
14306 if (ChainVal == LdVal)
14307 Ld = cast<LoadSDNode>(St->getChain());
14308 else if (St->getValue().hasOneUse() &&
14309 ChainVal->getOpcode() == ISD::TokenFactor) {
14310 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14311 if (ChainVal->getOperand(i).getNode() == LdVal) {
14312 TokenFactorIndex = i;
14313 Ld = cast<LoadSDNode>(St->getValue());
14315 Ops.push_back(ChainVal->getOperand(i));
14319 if (!Ld || !ISD::isNormalLoad(Ld))
14322 // If this is not the MMX case, i.e. we are just turning i64 load/store
14323 // into f64 load/store, avoid the transformation if there are multiple
14324 // uses of the loaded value.
14325 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14328 DebugLoc LdDL = Ld->getDebugLoc();
14329 DebugLoc StDL = N->getDebugLoc();
14330 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14331 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14333 if (Subtarget->is64Bit() || F64IsLegal) {
14334 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14335 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14336 Ld->getPointerInfo(), Ld->isVolatile(),
14337 Ld->isNonTemporal(), Ld->isInvariant(),
14338 Ld->getAlignment());
14339 SDValue NewChain = NewLd.getValue(1);
14340 if (TokenFactorIndex != -1) {
14341 Ops.push_back(NewChain);
14342 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14345 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14346 St->getPointerInfo(),
14347 St->isVolatile(), St->isNonTemporal(),
14348 St->getAlignment());
14351 // Otherwise, lower to two pairs of 32-bit loads / stores.
14352 SDValue LoAddr = Ld->getBasePtr();
14353 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14354 DAG.getConstant(4, MVT::i32));
14356 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14357 Ld->getPointerInfo(),
14358 Ld->isVolatile(), Ld->isNonTemporal(),
14359 Ld->isInvariant(), Ld->getAlignment());
14360 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14361 Ld->getPointerInfo().getWithOffset(4),
14362 Ld->isVolatile(), Ld->isNonTemporal(),
14364 MinAlign(Ld->getAlignment(), 4));
14366 SDValue NewChain = LoLd.getValue(1);
14367 if (TokenFactorIndex != -1) {
14368 Ops.push_back(LoLd);
14369 Ops.push_back(HiLd);
14370 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14374 LoAddr = St->getBasePtr();
14375 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14376 DAG.getConstant(4, MVT::i32));
14378 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14379 St->getPointerInfo(),
14380 St->isVolatile(), St->isNonTemporal(),
14381 St->getAlignment());
14382 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14383 St->getPointerInfo().getWithOffset(4),
14385 St->isNonTemporal(),
14386 MinAlign(St->getAlignment(), 4));
14387 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14392 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14393 /// and return the operands for the horizontal operation in LHS and RHS. A
14394 /// horizontal operation performs the binary operation on successive elements
14395 /// of its first operand, then on successive elements of its second operand,
14396 /// returning the resulting values in a vector. For example, if
14397 /// A = < float a0, float a1, float a2, float a3 >
14399 /// B = < float b0, float b1, float b2, float b3 >
14400 /// then the result of doing a horizontal operation on A and B is
14401 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14402 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14403 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14404 /// set to A, RHS to B, and the routine returns 'true'.
14405 /// Note that the binary operation should have the property that if one of the
14406 /// operands is UNDEF then the result is UNDEF.
14407 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14408 // Look for the following pattern: if
14409 // A = < float a0, float a1, float a2, float a3 >
14410 // B = < float b0, float b1, float b2, float b3 >
14412 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14413 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14414 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14415 // which is A horizontal-op B.
14417 // At least one of the operands should be a vector shuffle.
14418 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14419 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14422 EVT VT = LHS.getValueType();
14423 unsigned N = VT.getVectorNumElements();
14425 // View LHS in the form
14426 // LHS = VECTOR_SHUFFLE A, B, LMask
14427 // If LHS is not a shuffle then pretend it is the shuffle
14428 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14429 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14432 SmallVector<int, 8> LMask(N);
14433 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14434 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14435 A = LHS.getOperand(0);
14436 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14437 B = LHS.getOperand(1);
14438 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14440 if (LHS.getOpcode() != ISD::UNDEF)
14442 for (unsigned i = 0; i != N; ++i)
14446 // Likewise, view RHS in the form
14447 // RHS = VECTOR_SHUFFLE C, D, RMask
14449 SmallVector<int, 8> RMask(N);
14450 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14451 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14452 C = RHS.getOperand(0);
14453 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14454 D = RHS.getOperand(1);
14455 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14457 if (RHS.getOpcode() != ISD::UNDEF)
14459 for (unsigned i = 0; i != N; ++i)
14463 // Check that the shuffles are both shuffling the same vectors.
14464 if (!(A == C && B == D) && !(A == D && B == C))
14467 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14468 if (!A.getNode() && !B.getNode())
14471 // If A and B occur in reverse order in RHS, then "swap" them (which means
14472 // rewriting the mask).
14474 for (unsigned i = 0; i != N; ++i) {
14475 unsigned Idx = RMask[i];
14478 else if (Idx < 2*N)
14482 // At this point LHS and RHS are equivalent to
14483 // LHS = VECTOR_SHUFFLE A, B, LMask
14484 // RHS = VECTOR_SHUFFLE A, B, RMask
14485 // Check that the masks correspond to performing a horizontal operation.
14486 for (unsigned i = 0; i != N; ++i) {
14487 unsigned LIdx = LMask[i], RIdx = RMask[i];
14489 // Ignore any UNDEF components.
14490 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14491 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14494 // Check that successive elements are being operated on. If not, this is
14495 // not a horizontal operation.
14496 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14497 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14501 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14502 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14506 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14507 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14508 const X86Subtarget *Subtarget) {
14509 EVT VT = N->getValueType(0);
14510 SDValue LHS = N->getOperand(0);
14511 SDValue RHS = N->getOperand(1);
14513 // Try to synthesize horizontal adds from adds of shuffles.
14514 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14515 isHorizontalBinOp(LHS, RHS, true))
14516 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14520 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14521 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14522 const X86Subtarget *Subtarget) {
14523 EVT VT = N->getValueType(0);
14524 SDValue LHS = N->getOperand(0);
14525 SDValue RHS = N->getOperand(1);
14527 // Try to synthesize horizontal subs from subs of shuffles.
14528 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14529 isHorizontalBinOp(LHS, RHS, false))
14530 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14534 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14535 /// X86ISD::FXOR nodes.
14536 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14537 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14538 // F[X]OR(0.0, x) -> x
14539 // F[X]OR(x, 0.0) -> x
14540 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14541 if (C->getValueAPF().isPosZero())
14542 return N->getOperand(1);
14543 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14544 if (C->getValueAPF().isPosZero())
14545 return N->getOperand(0);
14549 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14550 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14551 // FAND(0.0, x) -> 0.0
14552 // FAND(x, 0.0) -> 0.0
14553 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14554 if (C->getValueAPF().isPosZero())
14555 return N->getOperand(0);
14556 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14557 if (C->getValueAPF().isPosZero())
14558 return N->getOperand(1);
14562 static SDValue PerformBTCombine(SDNode *N,
14564 TargetLowering::DAGCombinerInfo &DCI) {
14565 // BT ignores high bits in the bit index operand.
14566 SDValue Op1 = N->getOperand(1);
14567 if (Op1.hasOneUse()) {
14568 unsigned BitWidth = Op1.getValueSizeInBits();
14569 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14570 APInt KnownZero, KnownOne;
14571 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14572 !DCI.isBeforeLegalizeOps());
14573 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14574 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14575 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14576 DCI.CommitTargetLoweringOpt(TLO);
14581 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14582 SDValue Op = N->getOperand(0);
14583 if (Op.getOpcode() == ISD::BITCAST)
14584 Op = Op.getOperand(0);
14585 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14586 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14587 VT.getVectorElementType().getSizeInBits() ==
14588 OpVT.getVectorElementType().getSizeInBits()) {
14589 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14594 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14595 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14596 // (and (i32 x86isd::setcc_carry), 1)
14597 // This eliminates the zext. This transformation is necessary because
14598 // ISD::SETCC is always legalized to i8.
14599 DebugLoc dl = N->getDebugLoc();
14600 SDValue N0 = N->getOperand(0);
14601 EVT VT = N->getValueType(0);
14602 if (N0.getOpcode() == ISD::AND &&
14604 N0.getOperand(0).hasOneUse()) {
14605 SDValue N00 = N0.getOperand(0);
14606 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14608 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14609 if (!C || C->getZExtValue() != 1)
14611 return DAG.getNode(ISD::AND, dl, VT,
14612 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14613 N00.getOperand(0), N00.getOperand(1)),
14614 DAG.getConstant(1, VT));
14620 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14621 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14622 unsigned X86CC = N->getConstantOperandVal(0);
14623 SDValue EFLAG = N->getOperand(1);
14624 DebugLoc DL = N->getDebugLoc();
14626 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14627 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14629 if (X86CC == X86::COND_B)
14630 return DAG.getNode(ISD::AND, DL, MVT::i8,
14631 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14632 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14633 DAG.getConstant(1, MVT::i8));
14638 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14639 const X86TargetLowering *XTLI) {
14640 SDValue Op0 = N->getOperand(0);
14641 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14642 // a 32-bit target where SSE doesn't support i64->FP operations.
14643 if (Op0.getOpcode() == ISD::LOAD) {
14644 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14645 EVT VT = Ld->getValueType(0);
14646 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14647 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14648 !XTLI->getSubtarget()->is64Bit() &&
14649 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14650 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14651 Ld->getChain(), Op0, DAG);
14652 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14659 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14660 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14661 X86TargetLowering::DAGCombinerInfo &DCI) {
14662 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14663 // the result is either zero or one (depending on the input carry bit).
14664 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14665 if (X86::isZeroNode(N->getOperand(0)) &&
14666 X86::isZeroNode(N->getOperand(1)) &&
14667 // We don't have a good way to replace an EFLAGS use, so only do this when
14669 SDValue(N, 1).use_empty()) {
14670 DebugLoc DL = N->getDebugLoc();
14671 EVT VT = N->getValueType(0);
14672 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14673 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14674 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14675 DAG.getConstant(X86::COND_B,MVT::i8),
14677 DAG.getConstant(1, VT));
14678 return DCI.CombineTo(N, Res1, CarryOut);
14684 // fold (add Y, (sete X, 0)) -> adc 0, Y
14685 // (add Y, (setne X, 0)) -> sbb -1, Y
14686 // (sub (sete X, 0), Y) -> sbb 0, Y
14687 // (sub (setne X, 0), Y) -> adc -1, Y
14688 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14689 DebugLoc DL = N->getDebugLoc();
14691 // Look through ZExts.
14692 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14693 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14696 SDValue SetCC = Ext.getOperand(0);
14697 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14700 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14701 if (CC != X86::COND_E && CC != X86::COND_NE)
14704 SDValue Cmp = SetCC.getOperand(1);
14705 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14706 !X86::isZeroNode(Cmp.getOperand(1)) ||
14707 !Cmp.getOperand(0).getValueType().isInteger())
14710 SDValue CmpOp0 = Cmp.getOperand(0);
14711 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14712 DAG.getConstant(1, CmpOp0.getValueType()));
14714 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14715 if (CC == X86::COND_NE)
14716 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14717 DL, OtherVal.getValueType(), OtherVal,
14718 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14719 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14720 DL, OtherVal.getValueType(), OtherVal,
14721 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14724 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14725 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14726 const X86Subtarget *Subtarget) {
14727 EVT VT = N->getValueType(0);
14728 SDValue Op0 = N->getOperand(0);
14729 SDValue Op1 = N->getOperand(1);
14731 // Try to synthesize horizontal adds from adds of shuffles.
14732 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14733 isHorizontalBinOp(Op0, Op1, true))
14734 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14736 return OptimizeConditionalInDecrement(N, DAG);
14739 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14740 const X86Subtarget *Subtarget) {
14741 SDValue Op0 = N->getOperand(0);
14742 SDValue Op1 = N->getOperand(1);
14744 // X86 can't encode an immediate LHS of a sub. See if we can push the
14745 // negation into a preceding instruction.
14746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14747 // If the RHS of the sub is a XOR with one use and a constant, invert the
14748 // immediate. Then add one to the LHS of the sub so we can turn
14749 // X-Y -> X+~Y+1, saving one register.
14750 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14751 isa<ConstantSDNode>(Op1.getOperand(1))) {
14752 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14753 EVT VT = Op0.getValueType();
14754 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14756 DAG.getConstant(~XorC, VT));
14757 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14758 DAG.getConstant(C->getAPIntValue()+1, VT));
14762 // Try to synthesize horizontal adds from adds of shuffles.
14763 EVT VT = N->getValueType(0);
14764 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14765 isHorizontalBinOp(Op0, Op1, false))
14766 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14768 return OptimizeConditionalInDecrement(N, DAG);
14771 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14772 DAGCombinerInfo &DCI) const {
14773 SelectionDAG &DAG = DCI.DAG;
14774 switch (N->getOpcode()) {
14776 case ISD::EXTRACT_VECTOR_ELT:
14777 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14779 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14780 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14781 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14782 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14783 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14784 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14787 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14788 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14789 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14790 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14791 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14792 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14793 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14794 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14795 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14797 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14798 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14799 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14800 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14801 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14802 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14803 case X86ISD::SHUFPS: // Handle all target specific shuffles
14804 case X86ISD::SHUFPD:
14805 case X86ISD::PALIGN:
14806 case X86ISD::PUNPCKH:
14807 case X86ISD::UNPCKHP:
14808 case X86ISD::PUNPCKL:
14809 case X86ISD::UNPCKLP:
14810 case X86ISD::MOVHLPS:
14811 case X86ISD::MOVLHPS:
14812 case X86ISD::PSHUFD:
14813 case X86ISD::PSHUFHW:
14814 case X86ISD::PSHUFLW:
14815 case X86ISD::MOVSS:
14816 case X86ISD::MOVSD:
14817 case X86ISD::VPERMILPS:
14818 case X86ISD::VPERMILPD:
14819 case X86ISD::VPERM2F128:
14820 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14826 /// isTypeDesirableForOp - Return true if the target has native support for
14827 /// the specified value type and it is 'desirable' to use the type for the
14828 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14829 /// instruction encodings are longer and some i16 instructions are slow.
14830 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14831 if (!isTypeLegal(VT))
14833 if (VT != MVT::i16)
14840 case ISD::SIGN_EXTEND:
14841 case ISD::ZERO_EXTEND:
14842 case ISD::ANY_EXTEND:
14855 /// IsDesirableToPromoteOp - This method query the target whether it is
14856 /// beneficial for dag combiner to promote the specified node. If true, it
14857 /// should return the desired promotion type by reference.
14858 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14859 EVT VT = Op.getValueType();
14860 if (VT != MVT::i16)
14863 bool Promote = false;
14864 bool Commute = false;
14865 switch (Op.getOpcode()) {
14868 LoadSDNode *LD = cast<LoadSDNode>(Op);
14869 // If the non-extending load has a single use and it's not live out, then it
14870 // might be folded.
14871 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14872 Op.hasOneUse()*/) {
14873 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14874 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14875 // The only case where we'd want to promote LOAD (rather then it being
14876 // promoted as an operand is when it's only use is liveout.
14877 if (UI->getOpcode() != ISD::CopyToReg)
14884 case ISD::SIGN_EXTEND:
14885 case ISD::ZERO_EXTEND:
14886 case ISD::ANY_EXTEND:
14891 SDValue N0 = Op.getOperand(0);
14892 // Look out for (store (shl (load), x)).
14893 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14906 SDValue N0 = Op.getOperand(0);
14907 SDValue N1 = Op.getOperand(1);
14908 if (!Commute && MayFoldLoad(N1))
14910 // Avoid disabling potential load folding opportunities.
14911 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14913 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14923 //===----------------------------------------------------------------------===//
14924 // X86 Inline Assembly Support
14925 //===----------------------------------------------------------------------===//
14927 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14928 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14930 std::string AsmStr = IA->getAsmString();
14932 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14933 SmallVector<StringRef, 4> AsmPieces;
14934 SplitString(AsmStr, AsmPieces, ";\n");
14936 switch (AsmPieces.size()) {
14937 default: return false;
14939 AsmStr = AsmPieces[0];
14941 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14943 // FIXME: this should verify that we are targeting a 486 or better. If not,
14944 // we will turn this bswap into something that will be lowered to logical ops
14945 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14946 // so don't worry about this.
14948 if (AsmPieces.size() == 2 &&
14949 (AsmPieces[0] == "bswap" ||
14950 AsmPieces[0] == "bswapq" ||
14951 AsmPieces[0] == "bswapl") &&
14952 (AsmPieces[1] == "$0" ||
14953 AsmPieces[1] == "${0:q}")) {
14954 // No need to check constraints, nothing other than the equivalent of
14955 // "=r,0" would be valid here.
14956 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14957 if (!Ty || Ty->getBitWidth() % 16 != 0)
14959 return IntrinsicLowering::LowerToByteSwap(CI);
14961 // rorw $$8, ${0:w} --> llvm.bswap.i16
14962 if (CI->getType()->isIntegerTy(16) &&
14963 AsmPieces.size() == 3 &&
14964 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14965 AsmPieces[1] == "$$8," &&
14966 AsmPieces[2] == "${0:w}" &&
14967 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14969 const std::string &ConstraintsStr = IA->getConstraintString();
14970 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14971 std::sort(AsmPieces.begin(), AsmPieces.end());
14972 if (AsmPieces.size() == 4 &&
14973 AsmPieces[0] == "~{cc}" &&
14974 AsmPieces[1] == "~{dirflag}" &&
14975 AsmPieces[2] == "~{flags}" &&
14976 AsmPieces[3] == "~{fpsr}") {
14977 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14978 if (!Ty || Ty->getBitWidth() % 16 != 0)
14980 return IntrinsicLowering::LowerToByteSwap(CI);
14985 if (CI->getType()->isIntegerTy(32) &&
14986 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14987 SmallVector<StringRef, 4> Words;
14988 SplitString(AsmPieces[0], Words, " \t,");
14989 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14990 Words[2] == "${0:w}") {
14992 SplitString(AsmPieces[1], Words, " \t,");
14993 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14994 Words[2] == "$0") {
14996 SplitString(AsmPieces[2], Words, " \t,");
14997 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14998 Words[2] == "${0:w}") {
15000 const std::string &ConstraintsStr = IA->getConstraintString();
15001 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15002 std::sort(AsmPieces.begin(), AsmPieces.end());
15003 if (AsmPieces.size() == 4 &&
15004 AsmPieces[0] == "~{cc}" &&
15005 AsmPieces[1] == "~{dirflag}" &&
15006 AsmPieces[2] == "~{flags}" &&
15007 AsmPieces[3] == "~{fpsr}") {
15008 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15009 if (!Ty || Ty->getBitWidth() % 16 != 0)
15011 return IntrinsicLowering::LowerToByteSwap(CI);
15018 if (CI->getType()->isIntegerTy(64)) {
15019 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15020 if (Constraints.size() >= 2 &&
15021 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15022 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15023 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15024 SmallVector<StringRef, 4> Words;
15025 SplitString(AsmPieces[0], Words, " \t");
15026 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15028 SplitString(AsmPieces[1], Words, " \t");
15029 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15031 SplitString(AsmPieces[2], Words, " \t,");
15032 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15033 Words[2] == "%edx") {
15034 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15035 if (!Ty || Ty->getBitWidth() % 16 != 0)
15037 return IntrinsicLowering::LowerToByteSwap(CI);
15050 /// getConstraintType - Given a constraint letter, return the type of
15051 /// constraint it is for this target.
15052 X86TargetLowering::ConstraintType
15053 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15054 if (Constraint.size() == 1) {
15055 switch (Constraint[0]) {
15066 return C_RegisterClass;
15090 return TargetLowering::getConstraintType(Constraint);
15093 /// Examine constraint type and operand type and determine a weight value.
15094 /// This object must already have been set up with the operand type
15095 /// and the current alternative constraint selected.
15096 TargetLowering::ConstraintWeight
15097 X86TargetLowering::getSingleConstraintMatchWeight(
15098 AsmOperandInfo &info, const char *constraint) const {
15099 ConstraintWeight weight = CW_Invalid;
15100 Value *CallOperandVal = info.CallOperandVal;
15101 // If we don't have a value, we can't do a match,
15102 // but allow it at the lowest weight.
15103 if (CallOperandVal == NULL)
15105 Type *type = CallOperandVal->getType();
15106 // Look at the constraint type.
15107 switch (*constraint) {
15109 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15120 if (CallOperandVal->getType()->isIntegerTy())
15121 weight = CW_SpecificReg;
15126 if (type->isFloatingPointTy())
15127 weight = CW_SpecificReg;
15130 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15131 weight = CW_SpecificReg;
15135 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15136 weight = CW_Register;
15139 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15140 if (C->getZExtValue() <= 31)
15141 weight = CW_Constant;
15145 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15146 if (C->getZExtValue() <= 63)
15147 weight = CW_Constant;
15151 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15152 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15153 weight = CW_Constant;
15157 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15158 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15159 weight = CW_Constant;
15163 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15164 if (C->getZExtValue() <= 3)
15165 weight = CW_Constant;
15169 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15170 if (C->getZExtValue() <= 0xff)
15171 weight = CW_Constant;
15176 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15177 weight = CW_Constant;
15181 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15182 if ((C->getSExtValue() >= -0x80000000LL) &&
15183 (C->getSExtValue() <= 0x7fffffffLL))
15184 weight = CW_Constant;
15188 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15189 if (C->getZExtValue() <= 0xffffffff)
15190 weight = CW_Constant;
15197 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15198 /// with another that has more specific requirements based on the type of the
15199 /// corresponding operand.
15200 const char *X86TargetLowering::
15201 LowerXConstraint(EVT ConstraintVT) const {
15202 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15203 // 'f' like normal targets.
15204 if (ConstraintVT.isFloatingPoint()) {
15205 if (Subtarget->hasXMMInt())
15207 if (Subtarget->hasXMM())
15211 return TargetLowering::LowerXConstraint(ConstraintVT);
15214 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15215 /// vector. If it is invalid, don't add anything to Ops.
15216 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15217 std::string &Constraint,
15218 std::vector<SDValue>&Ops,
15219 SelectionDAG &DAG) const {
15220 SDValue Result(0, 0);
15222 // Only support length 1 constraints for now.
15223 if (Constraint.length() > 1) return;
15225 char ConstraintLetter = Constraint[0];
15226 switch (ConstraintLetter) {
15229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15230 if (C->getZExtValue() <= 31) {
15231 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15238 if (C->getZExtValue() <= 63) {
15239 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15246 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15247 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15254 if (C->getZExtValue() <= 255) {
15255 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15261 // 32-bit signed value
15262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15263 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15264 C->getSExtValue())) {
15265 // Widen to 64 bits here to get it sign extended.
15266 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15269 // FIXME gcc accepts some relocatable values here too, but only in certain
15270 // memory models; it's complicated.
15275 // 32-bit unsigned value
15276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15277 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15278 C->getZExtValue())) {
15279 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15283 // FIXME gcc accepts some relocatable values here too, but only in certain
15284 // memory models; it's complicated.
15288 // Literal immediates are always ok.
15289 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15290 // Widen to 64 bits here to get it sign extended.
15291 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15295 // In any sort of PIC mode addresses need to be computed at runtime by
15296 // adding in a register or some sort of table lookup. These can't
15297 // be used as immediates.
15298 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15301 // If we are in non-pic codegen mode, we allow the address of a global (with
15302 // an optional displacement) to be used with 'i'.
15303 GlobalAddressSDNode *GA = 0;
15304 int64_t Offset = 0;
15306 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15308 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15309 Offset += GA->getOffset();
15311 } else if (Op.getOpcode() == ISD::ADD) {
15312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15313 Offset += C->getZExtValue();
15314 Op = Op.getOperand(0);
15317 } else if (Op.getOpcode() == ISD::SUB) {
15318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15319 Offset += -C->getZExtValue();
15320 Op = Op.getOperand(0);
15325 // Otherwise, this isn't something we can handle, reject it.
15329 const GlobalValue *GV = GA->getGlobal();
15330 // If we require an extra load to get this address, as in PIC mode, we
15331 // can't accept it.
15332 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15333 getTargetMachine())))
15336 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15337 GA->getValueType(0), Offset);
15342 if (Result.getNode()) {
15343 Ops.push_back(Result);
15346 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15349 std::pair<unsigned, const TargetRegisterClass*>
15350 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15352 // First, see if this is a constraint that directly corresponds to an LLVM
15354 if (Constraint.size() == 1) {
15355 // GCC Constraint Letters
15356 switch (Constraint[0]) {
15358 // TODO: Slight differences here in allocation order and leaving
15359 // RIP in the class. Do they matter any more here than they do
15360 // in the normal allocation?
15361 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15362 if (Subtarget->is64Bit()) {
15363 if (VT == MVT::i32 || VT == MVT::f32)
15364 return std::make_pair(0U, X86::GR32RegisterClass);
15365 else if (VT == MVT::i16)
15366 return std::make_pair(0U, X86::GR16RegisterClass);
15367 else if (VT == MVT::i8 || VT == MVT::i1)
15368 return std::make_pair(0U, X86::GR8RegisterClass);
15369 else if (VT == MVT::i64 || VT == MVT::f64)
15370 return std::make_pair(0U, X86::GR64RegisterClass);
15373 // 32-bit fallthrough
15374 case 'Q': // Q_REGS
15375 if (VT == MVT::i32 || VT == MVT::f32)
15376 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15377 else if (VT == MVT::i16)
15378 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15379 else if (VT == MVT::i8 || VT == MVT::i1)
15380 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15381 else if (VT == MVT::i64)
15382 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15384 case 'r': // GENERAL_REGS
15385 case 'l': // INDEX_REGS
15386 if (VT == MVT::i8 || VT == MVT::i1)
15387 return std::make_pair(0U, X86::GR8RegisterClass);
15388 if (VT == MVT::i16)
15389 return std::make_pair(0U, X86::GR16RegisterClass);
15390 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15391 return std::make_pair(0U, X86::GR32RegisterClass);
15392 return std::make_pair(0U, X86::GR64RegisterClass);
15393 case 'R': // LEGACY_REGS
15394 if (VT == MVT::i8 || VT == MVT::i1)
15395 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15396 if (VT == MVT::i16)
15397 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15398 if (VT == MVT::i32 || !Subtarget->is64Bit())
15399 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15400 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15401 case 'f': // FP Stack registers.
15402 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15403 // value to the correct fpstack register class.
15404 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15405 return std::make_pair(0U, X86::RFP32RegisterClass);
15406 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15407 return std::make_pair(0U, X86::RFP64RegisterClass);
15408 return std::make_pair(0U, X86::RFP80RegisterClass);
15409 case 'y': // MMX_REGS if MMX allowed.
15410 if (!Subtarget->hasMMX()) break;
15411 return std::make_pair(0U, X86::VR64RegisterClass);
15412 case 'Y': // SSE_REGS if SSE2 allowed
15413 if (!Subtarget->hasXMMInt()) break;
15415 case 'x': // SSE_REGS if SSE1 allowed
15416 if (!Subtarget->hasXMM()) break;
15418 switch (VT.getSimpleVT().SimpleTy) {
15420 // Scalar SSE types.
15423 return std::make_pair(0U, X86::FR32RegisterClass);
15426 return std::make_pair(0U, X86::FR64RegisterClass);
15434 return std::make_pair(0U, X86::VR128RegisterClass);
15440 // Use the default implementation in TargetLowering to convert the register
15441 // constraint into a member of a register class.
15442 std::pair<unsigned, const TargetRegisterClass*> Res;
15443 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15445 // Not found as a standard register?
15446 if (Res.second == 0) {
15447 // Map st(0) -> st(7) -> ST0
15448 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15449 tolower(Constraint[1]) == 's' &&
15450 tolower(Constraint[2]) == 't' &&
15451 Constraint[3] == '(' &&
15452 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15453 Constraint[5] == ')' &&
15454 Constraint[6] == '}') {
15456 Res.first = X86::ST0+Constraint[4]-'0';
15457 Res.second = X86::RFP80RegisterClass;
15461 // GCC allows "st(0)" to be called just plain "st".
15462 if (StringRef("{st}").equals_lower(Constraint)) {
15463 Res.first = X86::ST0;
15464 Res.second = X86::RFP80RegisterClass;
15469 if (StringRef("{flags}").equals_lower(Constraint)) {
15470 Res.first = X86::EFLAGS;
15471 Res.second = X86::CCRRegisterClass;
15475 // 'A' means EAX + EDX.
15476 if (Constraint == "A") {
15477 Res.first = X86::EAX;
15478 Res.second = X86::GR32_ADRegisterClass;
15484 // Otherwise, check to see if this is a register class of the wrong value
15485 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15486 // turn into {ax},{dx}.
15487 if (Res.second->hasType(VT))
15488 return Res; // Correct type already, nothing to do.
15490 // All of the single-register GCC register classes map their values onto
15491 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15492 // really want an 8-bit or 32-bit register, map to the appropriate register
15493 // class and return the appropriate register.
15494 if (Res.second == X86::GR16RegisterClass) {
15495 if (VT == MVT::i8) {
15496 unsigned DestReg = 0;
15497 switch (Res.first) {
15499 case X86::AX: DestReg = X86::AL; break;
15500 case X86::DX: DestReg = X86::DL; break;
15501 case X86::CX: DestReg = X86::CL; break;
15502 case X86::BX: DestReg = X86::BL; break;
15505 Res.first = DestReg;
15506 Res.second = X86::GR8RegisterClass;
15508 } else if (VT == MVT::i32) {
15509 unsigned DestReg = 0;
15510 switch (Res.first) {
15512 case X86::AX: DestReg = X86::EAX; break;
15513 case X86::DX: DestReg = X86::EDX; break;
15514 case X86::CX: DestReg = X86::ECX; break;
15515 case X86::BX: DestReg = X86::EBX; break;
15516 case X86::SI: DestReg = X86::ESI; break;
15517 case X86::DI: DestReg = X86::EDI; break;
15518 case X86::BP: DestReg = X86::EBP; break;
15519 case X86::SP: DestReg = X86::ESP; break;
15522 Res.first = DestReg;
15523 Res.second = X86::GR32RegisterClass;
15525 } else if (VT == MVT::i64) {
15526 unsigned DestReg = 0;
15527 switch (Res.first) {
15529 case X86::AX: DestReg = X86::RAX; break;
15530 case X86::DX: DestReg = X86::RDX; break;
15531 case X86::CX: DestReg = X86::RCX; break;
15532 case X86::BX: DestReg = X86::RBX; break;
15533 case X86::SI: DestReg = X86::RSI; break;
15534 case X86::DI: DestReg = X86::RDI; break;
15535 case X86::BP: DestReg = X86::RBP; break;
15536 case X86::SP: DestReg = X86::RSP; break;
15539 Res.first = DestReg;
15540 Res.second = X86::GR64RegisterClass;
15543 } else if (Res.second == X86::FR32RegisterClass ||
15544 Res.second == X86::FR64RegisterClass ||
15545 Res.second == X86::VR128RegisterClass) {
15546 // Handle references to XMM physical registers that got mapped into the
15547 // wrong class. This can happen with constraints like {xmm0} where the
15548 // target independent register mapper will just pick the first match it can
15549 // find, ignoring the required type.
15550 if (VT == MVT::f32)
15551 Res.second = X86::FR32RegisterClass;
15552 else if (VT == MVT::f64)
15553 Res.second = X86::FR64RegisterClass;
15554 else if (X86::VR128RegisterClass->hasType(VT))
15555 Res.second = X86::VR128RegisterClass;