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 (!TM.Options.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);
273 if (!TM.Options.UseSoftFloat) {
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 (!TM.Options.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 (TM.Options.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 (!TM.Options.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 (!TM.Options.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
608 if (!TM.Options.UnsafeFPMath) {
609 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
610 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
612 } else if (!TM.Options.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);
623 if (!TM.Options.UnsafeFPMath) {
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.
642 if (!TM.Options.UseSoftFloat) {
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
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
663 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
666 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
667 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
668 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
669 setOperationAction(ISD::FRINT, MVT::f80, Expand);
670 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
671 setOperationAction(ISD::FMA, MVT::f80, Expand);
674 // Always use a library call for pow.
675 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
676 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
677 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
679 setOperationAction(ISD::FLOG, MVT::f80, Expand);
680 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
681 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
682 setOperationAction(ISD::FEXP, MVT::f80, Expand);
683 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685 // First set operation action for all vector types to either promote
686 // (for widening) or expand (for scalarization). Then we will selectively
687 // turn on ones that can be effectively codegen'd.
688 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
689 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
690 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
707 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
740 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
745 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747 setTruncStoreAction((MVT::SimpleValueType)VT,
748 (MVT::SimpleValueType)InnerVT, Expand);
749 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
754 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755 // with -msoft-float, disable use of MMX as well.
756 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
757 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758 // No operations on x86mmx supported, everything uses intrinsics.
761 // MMX-sized vectors (other than x86mmx) are expected to be expanded
762 // into smaller operations.
763 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
764 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
765 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
766 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
767 setOperationAction(ISD::AND, MVT::v8i8, Expand);
768 setOperationAction(ISD::AND, MVT::v4i16, Expand);
769 setOperationAction(ISD::AND, MVT::v2i32, Expand);
770 setOperationAction(ISD::AND, MVT::v1i64, Expand);
771 setOperationAction(ISD::OR, MVT::v8i8, Expand);
772 setOperationAction(ISD::OR, MVT::v4i16, Expand);
773 setOperationAction(ISD::OR, MVT::v2i32, Expand);
774 setOperationAction(ISD::OR, MVT::v1i64, Expand);
775 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
784 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
785 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
786 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
787 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
788 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
789 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
790 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
791 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
793 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
794 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
796 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
800 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
801 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
802 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
803 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
804 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
805 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
807 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
810 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
811 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
813 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814 // registers cannot be used even for integer operations.
815 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
820 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
821 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
822 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
823 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
825 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
826 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
827 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
828 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
829 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
830 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
831 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
832 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
833 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
834 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
835 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
837 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
838 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
839 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
840 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
842 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
849 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
850 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
851 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
852 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
854 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856 EVT VT = (MVT::SimpleValueType)i;
857 // Do not attempt to custom lower non-power-of-2 vectors
858 if (!isPowerOf2_32(VT.getVectorNumElements()))
860 // Do not attempt to custom lower non-128-bit vectors
861 if (!VT.is128BitVector())
863 setOperationAction(ISD::BUILD_VECTOR,
864 VT.getSimpleVT().SimpleTy, Custom);
865 setOperationAction(ISD::VECTOR_SHUFFLE,
866 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868 VT.getSimpleVT().SimpleTy, Custom);
871 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
878 if (Subtarget->is64Bit()) {
879 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
880 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
883 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
888 // Do not attempt to promote non-128-bit vectors
889 if (!VT.is128BitVector())
892 setOperationAction(ISD::AND, SVT, Promote);
893 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
894 setOperationAction(ISD::OR, SVT, Promote);
895 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
896 setOperationAction(ISD::XOR, SVT, Promote);
897 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
898 setOperationAction(ISD::LOAD, SVT, Promote);
899 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
900 setOperationAction(ISD::SELECT, SVT, Promote);
901 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
904 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
906 // Custom lower v2i64 and v2f64 selects.
907 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
908 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
909 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
910 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
912 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
913 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
916 if (Subtarget->hasSSE41orAVX()) {
917 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
920 setOperationAction(ISD::FRINT, MVT::f32, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
922 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
923 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
924 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
925 setOperationAction(ISD::FRINT, MVT::f64, Legal);
926 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
928 // FIXME: Do we need to handle scalar-to-vector here?
929 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
931 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
932 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
933 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
934 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
935 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
937 // i8 and i16 vectors are custom , because the source register and source
938 // source memory operand types are not the same width. f32 vectors are
939 // custom since the immediate controlling the insert encodes additional
941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
946 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
951 // FIXME: these should be Legal but thats only for the case where
952 // the index is constant. For now custom expand to deal with that
953 if (Subtarget->is64Bit()) {
954 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
955 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
959 if (Subtarget->hasXMMInt()) {
960 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
961 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
963 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
964 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
966 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
967 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
969 if (Subtarget->hasAVX2()) {
970 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
971 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
973 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
974 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
976 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
978 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
979 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
981 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
982 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
984 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
988 if (Subtarget->hasSSE42orAVX())
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
991 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
992 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
993 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
994 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
995 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
996 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
997 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
999 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1000 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1001 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1003 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1004 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1005 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1006 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1007 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1008 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1010 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1011 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1012 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1013 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1014 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1015 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1017 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1018 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1019 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1022 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1023 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1024 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1025 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1026 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1028 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1029 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1031 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1032 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1034 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1035 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1037 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1038 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1039 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1040 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1042 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1043 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1044 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1046 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1047 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1048 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1049 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1051 if (Subtarget->hasAVX2()) {
1052 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1053 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1054 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1055 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1057 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1058 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1059 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1060 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1062 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1063 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1064 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1065 // Don't lower v32i8 because there is no 128-bit byte mul
1067 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1069 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1070 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1072 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1073 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1075 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1077 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1078 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1079 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1080 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1083 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1084 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1085 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1087 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1089 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1090 // Don't lower v32i8 because there is no 128-bit byte mul
1092 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1093 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1095 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1096 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1098 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1101 // Custom lower several nodes for 256-bit types.
1102 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1103 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1104 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1107 // Extract subvector is special because the value type
1108 // (result) is 128-bit but the source is 256-bit wide.
1109 if (VT.is128BitVector())
1110 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1112 // Do not attempt to custom lower other non-256-bit vectors
1113 if (!VT.is256BitVector())
1116 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1117 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1118 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1119 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1120 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1121 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1124 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1125 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1126 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1129 // Do not attempt to promote non-256-bit vectors
1130 if (!VT.is256BitVector())
1133 setOperationAction(ISD::AND, SVT, Promote);
1134 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1135 setOperationAction(ISD::OR, SVT, Promote);
1136 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1137 setOperationAction(ISD::XOR, SVT, Promote);
1138 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1139 setOperationAction(ISD::LOAD, SVT, Promote);
1140 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1141 setOperationAction(ISD::SELECT, SVT, Promote);
1142 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1146 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1147 // of this type with custom code.
1148 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1149 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1150 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1153 // We want to custom lower some of our intrinsics.
1154 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1157 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1158 // handle type legalization for these operations here.
1160 // FIXME: We really should do custom legalization for addition and
1161 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1162 // than generic legalization for 64-bit multiplication-with-overflow, though.
1163 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1164 // Add/Sub/Mul with overflow operations are custom lowered.
1166 setOperationAction(ISD::SADDO, VT, Custom);
1167 setOperationAction(ISD::UADDO, VT, Custom);
1168 setOperationAction(ISD::SSUBO, VT, Custom);
1169 setOperationAction(ISD::USUBO, VT, Custom);
1170 setOperationAction(ISD::SMULO, VT, Custom);
1171 setOperationAction(ISD::UMULO, VT, Custom);
1174 // There are no 8-bit 3-address imul/mul instructions
1175 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1176 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1178 if (!Subtarget->is64Bit()) {
1179 // These libcalls are not available in 32-bit.
1180 setLibcallName(RTLIB::SHL_I128, 0);
1181 setLibcallName(RTLIB::SRL_I128, 0);
1182 setLibcallName(RTLIB::SRA_I128, 0);
1185 // We have target-specific dag combine patterns for the following nodes:
1186 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1187 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1188 setTargetDAGCombine(ISD::BUILD_VECTOR);
1189 setTargetDAGCombine(ISD::VSELECT);
1190 setTargetDAGCombine(ISD::SELECT);
1191 setTargetDAGCombine(ISD::SHL);
1192 setTargetDAGCombine(ISD::SRA);
1193 setTargetDAGCombine(ISD::SRL);
1194 setTargetDAGCombine(ISD::OR);
1195 setTargetDAGCombine(ISD::AND);
1196 setTargetDAGCombine(ISD::ADD);
1197 setTargetDAGCombine(ISD::FADD);
1198 setTargetDAGCombine(ISD::FSUB);
1199 setTargetDAGCombine(ISD::SUB);
1200 setTargetDAGCombine(ISD::LOAD);
1201 setTargetDAGCombine(ISD::STORE);
1202 setTargetDAGCombine(ISD::ZERO_EXTEND);
1203 setTargetDAGCombine(ISD::SINT_TO_FP);
1204 if (Subtarget->is64Bit())
1205 setTargetDAGCombine(ISD::MUL);
1206 if (Subtarget->hasBMI())
1207 setTargetDAGCombine(ISD::XOR);
1209 computeRegisterProperties();
1211 // On Darwin, -Os means optimize for size without hurting performance,
1212 // do not reduce the limit.
1213 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1214 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1215 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1216 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1217 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1218 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1219 setPrefLoopAlignment(4); // 2^4 bytes.
1220 benefitFromCodePlacementOpt = true;
1222 setPrefFunctionAlignment(4); // 2^4 bytes.
1226 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1227 if (!VT.isVector()) return MVT::i8;
1228 return VT.changeVectorElementTypeToInteger();
1232 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1233 /// the desired ByVal argument alignment.
1234 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1237 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1238 if (VTy->getBitWidth() == 128)
1240 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1241 unsigned EltAlign = 0;
1242 getMaxByValAlign(ATy->getElementType(), EltAlign);
1243 if (EltAlign > MaxAlign)
1244 MaxAlign = EltAlign;
1245 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1247 unsigned EltAlign = 0;
1248 getMaxByValAlign(STy->getElementType(i), EltAlign);
1249 if (EltAlign > MaxAlign)
1250 MaxAlign = EltAlign;
1258 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1259 /// function arguments in the caller parameter area. For X86, aggregates
1260 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1261 /// are at 4-byte boundaries.
1262 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1263 if (Subtarget->is64Bit()) {
1264 // Max of 8 and alignment of type.
1265 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1272 if (Subtarget->hasXMM())
1273 getMaxByValAlign(Ty, Align);
1277 /// getOptimalMemOpType - Returns the target specific optimal type for load
1278 /// and store operations as a result of memset, memcpy, and memmove
1279 /// lowering. If DstAlign is zero that means it's safe to destination
1280 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1281 /// means there isn't a need to check it against alignment requirement,
1282 /// probably because the source does not need to be loaded. If
1283 /// 'IsZeroVal' is true, that means it's safe to return a
1284 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1285 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1286 /// constant so it does not need to be loaded.
1287 /// It returns EVT::Other if the type should be determined using generic
1288 /// target-independent logic.
1290 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1291 unsigned DstAlign, unsigned SrcAlign,
1294 MachineFunction &MF) const {
1295 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1296 // linux. This is because the stack realignment code can't handle certain
1297 // cases like PR2962. This should be removed when PR2962 is fixed.
1298 const Function *F = MF.getFunction();
1300 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1302 (Subtarget->isUnalignedMemAccessFast() ||
1303 ((DstAlign == 0 || DstAlign >= 16) &&
1304 (SrcAlign == 0 || SrcAlign >= 16))) &&
1305 Subtarget->getStackAlignment() >= 16) {
1306 if (Subtarget->hasAVX() &&
1307 Subtarget->getStackAlignment() >= 32)
1309 if (Subtarget->hasXMMInt())
1311 if (Subtarget->hasXMM())
1313 } else if (!MemcpyStrSrc && Size >= 8 &&
1314 !Subtarget->is64Bit() &&
1315 Subtarget->getStackAlignment() >= 8 &&
1316 Subtarget->hasXMMInt()) {
1317 // Do not use f64 to lower memcpy if source is string constant. It's
1318 // better to use i32 to avoid the loads.
1322 if (Subtarget->is64Bit() && Size >= 8)
1327 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1328 /// current function. The returned value is a member of the
1329 /// MachineJumpTableInfo::JTEntryKind enum.
1330 unsigned X86TargetLowering::getJumpTableEncoding() const {
1331 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1333 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1334 Subtarget->isPICStyleGOT())
1335 return MachineJumpTableInfo::EK_Custom32;
1337 // Otherwise, use the normal jump table encoding heuristics.
1338 return TargetLowering::getJumpTableEncoding();
1342 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1343 const MachineBasicBlock *MBB,
1344 unsigned uid,MCContext &Ctx) const{
1345 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1346 Subtarget->isPICStyleGOT());
1347 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1349 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1350 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1353 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1355 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1356 SelectionDAG &DAG) const {
1357 if (!Subtarget->is64Bit())
1358 // This doesn't have DebugLoc associated with it, but is not really the
1359 // same as a Register.
1360 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1364 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1365 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1367 const MCExpr *X86TargetLowering::
1368 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1369 MCContext &Ctx) const {
1370 // X86-64 uses RIP relative addressing based on the jump table label.
1371 if (Subtarget->isPICStyleRIPRel())
1372 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1374 // Otherwise, the reference is relative to the PIC base.
1375 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1378 // FIXME: Why this routine is here? Move to RegInfo!
1379 std::pair<const TargetRegisterClass*, uint8_t>
1380 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1381 const TargetRegisterClass *RRC = 0;
1383 switch (VT.getSimpleVT().SimpleTy) {
1385 return TargetLowering::findRepresentativeClass(VT);
1386 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1387 RRC = (Subtarget->is64Bit()
1388 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1391 RRC = X86::VR64RegisterClass;
1393 case MVT::f32: case MVT::f64:
1394 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1395 case MVT::v4f32: case MVT::v2f64:
1396 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1398 RRC = X86::VR128RegisterClass;
1401 return std::make_pair(RRC, Cost);
1404 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1405 unsigned &Offset) const {
1406 if (!Subtarget->isTargetLinux())
1409 if (Subtarget->is64Bit()) {
1410 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1412 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1425 //===----------------------------------------------------------------------===//
1426 // Return Value Calling Convention Implementation
1427 //===----------------------------------------------------------------------===//
1429 #include "X86GenCallingConv.inc"
1432 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1433 MachineFunction &MF, bool isVarArg,
1434 const SmallVectorImpl<ISD::OutputArg> &Outs,
1435 LLVMContext &Context) const {
1436 SmallVector<CCValAssign, 16> RVLocs;
1437 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1439 return CCInfo.CheckReturn(Outs, RetCC_X86);
1443 X86TargetLowering::LowerReturn(SDValue Chain,
1444 CallingConv::ID CallConv, bool isVarArg,
1445 const SmallVectorImpl<ISD::OutputArg> &Outs,
1446 const SmallVectorImpl<SDValue> &OutVals,
1447 DebugLoc dl, SelectionDAG &DAG) const {
1448 MachineFunction &MF = DAG.getMachineFunction();
1449 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1451 SmallVector<CCValAssign, 16> RVLocs;
1452 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1453 RVLocs, *DAG.getContext());
1454 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1456 // Add the regs to the liveout set for the function.
1457 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1458 for (unsigned i = 0; i != RVLocs.size(); ++i)
1459 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1460 MRI.addLiveOut(RVLocs[i].getLocReg());
1464 SmallVector<SDValue, 6> RetOps;
1465 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1466 // Operand #1 = Bytes To Pop
1467 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1470 // Copy the result values into the output registers.
1471 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1472 CCValAssign &VA = RVLocs[i];
1473 assert(VA.isRegLoc() && "Can only return in registers!");
1474 SDValue ValToCopy = OutVals[i];
1475 EVT ValVT = ValToCopy.getValueType();
1477 // If this is x86-64, and we disabled SSE, we can't return FP values,
1478 // or SSE or MMX vectors.
1479 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1480 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1481 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1482 report_fatal_error("SSE register return with SSE disabled");
1484 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1485 // llvm-gcc has never done it right and no one has noticed, so this
1486 // should be OK for now.
1487 if (ValVT == MVT::f64 &&
1488 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1489 report_fatal_error("SSE2 register return with SSE2 disabled");
1491 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1492 // the RET instruction and handled by the FP Stackifier.
1493 if (VA.getLocReg() == X86::ST0 ||
1494 VA.getLocReg() == X86::ST1) {
1495 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1496 // change the value to the FP stack register class.
1497 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1498 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1499 RetOps.push_back(ValToCopy);
1500 // Don't emit a copytoreg.
1504 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1505 // which is returned in RAX / RDX.
1506 if (Subtarget->is64Bit()) {
1507 if (ValVT == MVT::x86mmx) {
1508 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1509 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1510 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1512 // If we don't have SSE2 available, convert to v4f32 so the generated
1513 // register is legal.
1514 if (!Subtarget->hasXMMInt())
1515 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1520 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1521 Flag = Chain.getValue(1);
1524 // The x86-64 ABI for returning structs by value requires that we copy
1525 // the sret argument into %rax for the return. We saved the argument into
1526 // a virtual register in the entry block, so now we copy the value out
1528 if (Subtarget->is64Bit() &&
1529 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1530 MachineFunction &MF = DAG.getMachineFunction();
1531 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1532 unsigned Reg = FuncInfo->getSRetReturnReg();
1534 "SRetReturnReg should have been set in LowerFormalArguments().");
1535 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1537 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1538 Flag = Chain.getValue(1);
1540 // RAX now acts like a return value.
1541 MRI.addLiveOut(X86::RAX);
1544 RetOps[0] = Chain; // Update chain.
1546 // Add the flag if we have it.
1548 RetOps.push_back(Flag);
1550 return DAG.getNode(X86ISD::RET_FLAG, dl,
1551 MVT::Other, &RetOps[0], RetOps.size());
1554 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1555 if (N->getNumValues() != 1)
1557 if (!N->hasNUsesOfValue(1, 0))
1560 SDNode *Copy = *N->use_begin();
1561 if (Copy->getOpcode() != ISD::CopyToReg &&
1562 Copy->getOpcode() != ISD::FP_EXTEND)
1565 bool HasRet = false;
1566 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1568 if (UI->getOpcode() != X86ISD::RET_FLAG)
1577 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1578 ISD::NodeType ExtendKind) const {
1580 // TODO: Is this also valid on 32-bit?
1581 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1582 ReturnMVT = MVT::i8;
1584 ReturnMVT = MVT::i32;
1586 EVT MinVT = getRegisterType(Context, ReturnMVT);
1587 return VT.bitsLT(MinVT) ? MinVT : VT;
1590 /// LowerCallResult - Lower the result values of a call into the
1591 /// appropriate copies out of appropriate physical registers.
1594 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1595 CallingConv::ID CallConv, bool isVarArg,
1596 const SmallVectorImpl<ISD::InputArg> &Ins,
1597 DebugLoc dl, SelectionDAG &DAG,
1598 SmallVectorImpl<SDValue> &InVals) const {
1600 // Assign locations to each value returned by this call.
1601 SmallVector<CCValAssign, 16> RVLocs;
1602 bool Is64Bit = Subtarget->is64Bit();
1603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1604 getTargetMachine(), RVLocs, *DAG.getContext());
1605 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1607 // Copy all of the result registers out of their specified physreg.
1608 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1609 CCValAssign &VA = RVLocs[i];
1610 EVT CopyVT = VA.getValVT();
1612 // If this is x86-64, and we disabled SSE, we can't return FP values
1613 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1614 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1615 report_fatal_error("SSE register return with SSE disabled");
1620 // If this is a call to a function that returns an fp value on the floating
1621 // point stack, we must guarantee the the value is popped from the stack, so
1622 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1623 // if the return value is not used. We use the FpPOP_RETVAL instruction
1625 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1626 // If we prefer to use the value in xmm registers, copy it out as f80 and
1627 // use a truncate to move it from fp stack reg to xmm reg.
1628 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1629 SDValue Ops[] = { Chain, InFlag };
1630 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1631 MVT::Other, MVT::Glue, Ops, 2), 1);
1632 Val = Chain.getValue(0);
1634 // Round the f80 to the right size, which also moves it to the appropriate
1636 if (CopyVT != VA.getValVT())
1637 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1638 // This truncation won't change the value.
1639 DAG.getIntPtrConstant(1));
1641 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1642 CopyVT, InFlag).getValue(1);
1643 Val = Chain.getValue(0);
1645 InFlag = Chain.getValue(2);
1646 InVals.push_back(Val);
1653 //===----------------------------------------------------------------------===//
1654 // C & StdCall & Fast Calling Convention implementation
1655 //===----------------------------------------------------------------------===//
1656 // StdCall calling convention seems to be standard for many Windows' API
1657 // routines and around. It differs from C calling convention just a little:
1658 // callee should clean up the stack, not caller. Symbols should be also
1659 // decorated in some fancy way :) It doesn't support any vector arguments.
1660 // For info on fast calling convention see Fast Calling Convention (tail call)
1661 // implementation LowerX86_32FastCCCallTo.
1663 /// CallIsStructReturn - Determines whether a call uses struct return
1665 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1669 return Outs[0].Flags.isSRet();
1672 /// ArgsAreStructReturn - Determines whether a function uses struct
1673 /// return semantics.
1675 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1679 return Ins[0].Flags.isSRet();
1682 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1683 /// by "Src" to address "Dst" with size and alignment information specified by
1684 /// the specific parameter attribute. The copy will be passed as a byval
1685 /// function parameter.
1687 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1688 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1690 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1692 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1693 /*isVolatile*/false, /*AlwaysInline=*/true,
1694 MachinePointerInfo(), MachinePointerInfo());
1697 /// IsTailCallConvention - Return true if the calling convention is one that
1698 /// supports tail call optimization.
1699 static bool IsTailCallConvention(CallingConv::ID CC) {
1700 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1703 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1704 if (!CI->isTailCall())
1708 CallingConv::ID CalleeCC = CS.getCallingConv();
1709 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1715 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1716 /// a tailcall target by changing its ABI.
1717 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1718 bool GuaranteedTailCallOpt) {
1719 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1723 X86TargetLowering::LowerMemArgument(SDValue Chain,
1724 CallingConv::ID CallConv,
1725 const SmallVectorImpl<ISD::InputArg> &Ins,
1726 DebugLoc dl, SelectionDAG &DAG,
1727 const CCValAssign &VA,
1728 MachineFrameInfo *MFI,
1730 // Create the nodes corresponding to a load from this parameter slot.
1731 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1732 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1733 getTargetMachine().Options.GuaranteedTailCallOpt);
1734 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1737 // If value is passed by pointer we have address passed instead of the value
1739 if (VA.getLocInfo() == CCValAssign::Indirect)
1740 ValVT = VA.getLocVT();
1742 ValVT = VA.getValVT();
1744 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1745 // changed with more analysis.
1746 // In case of tail call optimization mark all arguments mutable. Since they
1747 // could be overwritten by lowering of arguments in case of a tail call.
1748 if (Flags.isByVal()) {
1749 unsigned Bytes = Flags.getByValSize();
1750 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1751 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1752 return DAG.getFrameIndex(FI, getPointerTy());
1754 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1755 VA.getLocMemOffset(), isImmutable);
1756 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1757 return DAG.getLoad(ValVT, dl, Chain, FIN,
1758 MachinePointerInfo::getFixedStack(FI),
1759 false, false, false, 0);
1764 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1765 CallingConv::ID CallConv,
1767 const SmallVectorImpl<ISD::InputArg> &Ins,
1770 SmallVectorImpl<SDValue> &InVals)
1772 MachineFunction &MF = DAG.getMachineFunction();
1773 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1775 const Function* Fn = MF.getFunction();
1776 if (Fn->hasExternalLinkage() &&
1777 Subtarget->isTargetCygMing() &&
1778 Fn->getName() == "main")
1779 FuncInfo->setForceFramePointer(true);
1781 MachineFrameInfo *MFI = MF.getFrameInfo();
1782 bool Is64Bit = Subtarget->is64Bit();
1783 bool IsWin64 = Subtarget->isTargetWin64();
1785 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1786 "Var args not supported with calling convention fastcc or ghc");
1788 // Assign locations to all of the incoming arguments.
1789 SmallVector<CCValAssign, 16> ArgLocs;
1790 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1791 ArgLocs, *DAG.getContext());
1793 // Allocate shadow area for Win64
1795 CCInfo.AllocateStack(32, 8);
1798 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1800 unsigned LastVal = ~0U;
1802 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1803 CCValAssign &VA = ArgLocs[i];
1804 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1806 assert(VA.getValNo() != LastVal &&
1807 "Don't support value assigned to multiple locs yet");
1809 LastVal = VA.getValNo();
1811 if (VA.isRegLoc()) {
1812 EVT RegVT = VA.getLocVT();
1813 TargetRegisterClass *RC = NULL;
1814 if (RegVT == MVT::i32)
1815 RC = X86::GR32RegisterClass;
1816 else if (Is64Bit && RegVT == MVT::i64)
1817 RC = X86::GR64RegisterClass;
1818 else if (RegVT == MVT::f32)
1819 RC = X86::FR32RegisterClass;
1820 else if (RegVT == MVT::f64)
1821 RC = X86::FR64RegisterClass;
1822 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1823 RC = X86::VR256RegisterClass;
1824 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1825 RC = X86::VR128RegisterClass;
1826 else if (RegVT == MVT::x86mmx)
1827 RC = X86::VR64RegisterClass;
1829 llvm_unreachable("Unknown argument type!");
1831 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1832 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1834 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1835 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1837 if (VA.getLocInfo() == CCValAssign::SExt)
1838 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1839 DAG.getValueType(VA.getValVT()));
1840 else if (VA.getLocInfo() == CCValAssign::ZExt)
1841 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1842 DAG.getValueType(VA.getValVT()));
1843 else if (VA.getLocInfo() == CCValAssign::BCvt)
1844 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1846 if (VA.isExtInLoc()) {
1847 // Handle MMX values passed in XMM regs.
1848 if (RegVT.isVector()) {
1849 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1852 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1855 assert(VA.isMemLoc());
1856 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1859 // If value is passed via pointer - do a load.
1860 if (VA.getLocInfo() == CCValAssign::Indirect)
1861 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1862 MachinePointerInfo(), false, false, false, 0);
1864 InVals.push_back(ArgValue);
1867 // The x86-64 ABI for returning structs by value requires that we copy
1868 // the sret argument into %rax for the return. Save the argument into
1869 // a virtual register so that we can access it from the return points.
1870 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1871 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1872 unsigned Reg = FuncInfo->getSRetReturnReg();
1874 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1875 FuncInfo->setSRetReturnReg(Reg);
1877 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1878 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1881 unsigned StackSize = CCInfo.getNextStackOffset();
1882 // Align stack specially for tail calls.
1883 if (FuncIsMadeTailCallSafe(CallConv,
1884 MF.getTarget().Options.GuaranteedTailCallOpt))
1885 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1887 // If the function takes variable number of arguments, make a frame index for
1888 // the start of the first vararg value... for expansion of llvm.va_start.
1890 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1891 CallConv != CallingConv::X86_ThisCall)) {
1892 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1895 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1897 // FIXME: We should really autogenerate these arrays
1898 static const unsigned GPR64ArgRegsWin64[] = {
1899 X86::RCX, X86::RDX, X86::R8, X86::R9
1901 static const unsigned GPR64ArgRegs64Bit[] = {
1902 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1904 static const unsigned XMMArgRegs64Bit[] = {
1905 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1906 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1908 const unsigned *GPR64ArgRegs;
1909 unsigned NumXMMRegs = 0;
1912 // The XMM registers which might contain var arg parameters are shadowed
1913 // in their paired GPR. So we only need to save the GPR to their home
1915 TotalNumIntRegs = 4;
1916 GPR64ArgRegs = GPR64ArgRegsWin64;
1918 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1919 GPR64ArgRegs = GPR64ArgRegs64Bit;
1921 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1923 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1926 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1927 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1928 "SSE register cannot be used when SSE is disabled!");
1929 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1930 NoImplicitFloatOps) &&
1931 "SSE register cannot be used when SSE is disabled!");
1932 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1933 !Subtarget->hasXMM())
1934 // Kernel mode asks for SSE to be disabled, so don't push them
1936 TotalNumXMMRegs = 0;
1939 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1940 // Get to the caller-allocated home save location. Add 8 to account
1941 // for the return address.
1942 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1943 FuncInfo->setRegSaveFrameIndex(
1944 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1945 // Fixup to set vararg frame on shadow area (4 x i64).
1947 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1949 // For X86-64, if there are vararg parameters that are passed via
1950 // registers, then we must store them to their spots on the stack so they
1951 // may be loaded by deferencing the result of va_next.
1952 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1953 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1954 FuncInfo->setRegSaveFrameIndex(
1955 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1959 // Store the integer parameter registers.
1960 SmallVector<SDValue, 8> MemOps;
1961 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1963 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1964 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1965 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1966 DAG.getIntPtrConstant(Offset));
1967 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1968 X86::GR64RegisterClass);
1969 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1971 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1972 MachinePointerInfo::getFixedStack(
1973 FuncInfo->getRegSaveFrameIndex(), Offset),
1975 MemOps.push_back(Store);
1979 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1980 // Now store the XMM (fp + vector) parameter registers.
1981 SmallVector<SDValue, 11> SaveXMMOps;
1982 SaveXMMOps.push_back(Chain);
1984 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1985 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1986 SaveXMMOps.push_back(ALVal);
1988 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1989 FuncInfo->getRegSaveFrameIndex()));
1990 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1991 FuncInfo->getVarArgsFPOffset()));
1993 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1994 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1995 X86::VR128RegisterClass);
1996 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1997 SaveXMMOps.push_back(Val);
1999 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2001 &SaveXMMOps[0], SaveXMMOps.size()));
2004 if (!MemOps.empty())
2005 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2006 &MemOps[0], MemOps.size());
2010 // Some CCs need callee pop.
2011 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2012 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2013 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2015 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2016 // If this is an sret function, the return should pop the hidden pointer.
2017 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2018 FuncInfo->setBytesToPopOnReturn(4);
2022 // RegSaveFrameIndex is X86-64 only.
2023 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2024 if (CallConv == CallingConv::X86_FastCall ||
2025 CallConv == CallingConv::X86_ThisCall)
2026 // fastcc functions can't have varargs.
2027 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2030 FuncInfo->setArgumentStackSize(StackSize);
2036 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2037 SDValue StackPtr, SDValue Arg,
2038 DebugLoc dl, SelectionDAG &DAG,
2039 const CCValAssign &VA,
2040 ISD::ArgFlagsTy Flags) const {
2041 unsigned LocMemOffset = VA.getLocMemOffset();
2042 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2043 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2044 if (Flags.isByVal())
2045 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2047 return DAG.getStore(Chain, dl, Arg, PtrOff,
2048 MachinePointerInfo::getStack(LocMemOffset),
2052 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2053 /// optimization is performed and it is required.
2055 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2056 SDValue &OutRetAddr, SDValue Chain,
2057 bool IsTailCall, bool Is64Bit,
2058 int FPDiff, DebugLoc dl) const {
2059 // Adjust the Return address stack slot.
2060 EVT VT = getPointerTy();
2061 OutRetAddr = getReturnAddressFrameIndex(DAG);
2063 // Load the "old" Return address.
2064 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2065 false, false, false, 0);
2066 return SDValue(OutRetAddr.getNode(), 1);
2069 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2070 /// optimization is performed and it is required (FPDiff!=0).
2072 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2073 SDValue Chain, SDValue RetAddrFrIdx,
2074 bool Is64Bit, int FPDiff, DebugLoc dl) {
2075 // Store the return address to the appropriate stack slot.
2076 if (!FPDiff) return Chain;
2077 // Calculate the new stack slot for the return address.
2078 int SlotSize = Is64Bit ? 8 : 4;
2079 int NewReturnAddrFI =
2080 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2081 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2082 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2083 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2084 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2090 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2091 CallingConv::ID CallConv, bool isVarArg,
2093 const SmallVectorImpl<ISD::OutputArg> &Outs,
2094 const SmallVectorImpl<SDValue> &OutVals,
2095 const SmallVectorImpl<ISD::InputArg> &Ins,
2096 DebugLoc dl, SelectionDAG &DAG,
2097 SmallVectorImpl<SDValue> &InVals) const {
2098 MachineFunction &MF = DAG.getMachineFunction();
2099 bool Is64Bit = Subtarget->is64Bit();
2100 bool IsWin64 = Subtarget->isTargetWin64();
2101 bool IsStructRet = CallIsStructReturn(Outs);
2102 bool IsSibcall = false;
2105 // Check if it's really possible to do a tail call.
2106 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2107 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2108 Outs, OutVals, Ins, DAG);
2110 // Sibcalls are automatically detected tailcalls which do not require
2112 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2119 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2120 "Var args not supported with calling convention fastcc or ghc");
2122 // Analyze operands of the call, assigning locations to each operand.
2123 SmallVector<CCValAssign, 16> ArgLocs;
2124 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2125 ArgLocs, *DAG.getContext());
2127 // Allocate shadow area for Win64
2129 CCInfo.AllocateStack(32, 8);
2132 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2134 // Get a count of how many bytes are to be pushed on the stack.
2135 unsigned NumBytes = CCInfo.getNextStackOffset();
2137 // This is a sibcall. The memory operands are available in caller's
2138 // own caller's stack.
2140 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2141 IsTailCallConvention(CallConv))
2142 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2145 if (isTailCall && !IsSibcall) {
2146 // Lower arguments at fp - stackoffset + fpdiff.
2147 unsigned NumBytesCallerPushed =
2148 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2149 FPDiff = NumBytesCallerPushed - NumBytes;
2151 // Set the delta of movement of the returnaddr stackslot.
2152 // But only set if delta is greater than previous delta.
2153 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2154 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2158 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2160 SDValue RetAddrFrIdx;
2161 // Load return address for tail calls.
2162 if (isTailCall && FPDiff)
2163 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2164 Is64Bit, FPDiff, dl);
2166 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2167 SmallVector<SDValue, 8> MemOpChains;
2170 // Walk the register/memloc assignments, inserting copies/loads. In the case
2171 // of tail call optimization arguments are handle later.
2172 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2173 CCValAssign &VA = ArgLocs[i];
2174 EVT RegVT = VA.getLocVT();
2175 SDValue Arg = OutVals[i];
2176 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2177 bool isByVal = Flags.isByVal();
2179 // Promote the value if needed.
2180 switch (VA.getLocInfo()) {
2181 default: llvm_unreachable("Unknown loc info!");
2182 case CCValAssign::Full: break;
2183 case CCValAssign::SExt:
2184 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2186 case CCValAssign::ZExt:
2187 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2189 case CCValAssign::AExt:
2190 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2191 // Special case: passing MMX values in XMM registers.
2192 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2193 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2194 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2196 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2198 case CCValAssign::BCvt:
2199 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2201 case CCValAssign::Indirect: {
2202 // Store the argument.
2203 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2204 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2205 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2206 MachinePointerInfo::getFixedStack(FI),
2213 if (VA.isRegLoc()) {
2214 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2215 if (isVarArg && IsWin64) {
2216 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2217 // shadow reg if callee is a varargs function.
2218 unsigned ShadowReg = 0;
2219 switch (VA.getLocReg()) {
2220 case X86::XMM0: ShadowReg = X86::RCX; break;
2221 case X86::XMM1: ShadowReg = X86::RDX; break;
2222 case X86::XMM2: ShadowReg = X86::R8; break;
2223 case X86::XMM3: ShadowReg = X86::R9; break;
2226 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2228 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2229 assert(VA.isMemLoc());
2230 if (StackPtr.getNode() == 0)
2231 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2232 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2233 dl, DAG, VA, Flags));
2237 if (!MemOpChains.empty())
2238 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2239 &MemOpChains[0], MemOpChains.size());
2241 // Build a sequence of copy-to-reg nodes chained together with token chain
2242 // and flag operands which copy the outgoing args into registers.
2244 // Tail call byval lowering might overwrite argument registers so in case of
2245 // tail call optimization the copies to registers are lowered later.
2247 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2248 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2249 RegsToPass[i].second, InFlag);
2250 InFlag = Chain.getValue(1);
2253 if (Subtarget->isPICStyleGOT()) {
2254 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2257 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2258 DAG.getNode(X86ISD::GlobalBaseReg,
2259 DebugLoc(), getPointerTy()),
2261 InFlag = Chain.getValue(1);
2263 // If we are tail calling and generating PIC/GOT style code load the
2264 // address of the callee into ECX. The value in ecx is used as target of
2265 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2266 // for tail calls on PIC/GOT architectures. Normally we would just put the
2267 // address of GOT into ebx and then call target@PLT. But for tail calls
2268 // ebx would be restored (since ebx is callee saved) before jumping to the
2271 // Note: The actual moving to ECX is done further down.
2272 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2273 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2274 !G->getGlobal()->hasProtectedVisibility())
2275 Callee = LowerGlobalAddress(Callee, DAG);
2276 else if (isa<ExternalSymbolSDNode>(Callee))
2277 Callee = LowerExternalSymbol(Callee, DAG);
2281 if (Is64Bit && isVarArg && !IsWin64) {
2282 // From AMD64 ABI document:
2283 // For calls that may call functions that use varargs or stdargs
2284 // (prototype-less calls or calls to functions containing ellipsis (...) in
2285 // the declaration) %al is used as hidden argument to specify the number
2286 // of SSE registers used. The contents of %al do not need to match exactly
2287 // the number of registers, but must be an ubound on the number of SSE
2288 // registers used and is in the range 0 - 8 inclusive.
2290 // Count the number of XMM registers allocated.
2291 static const unsigned XMMArgRegs[] = {
2292 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2293 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2295 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2296 assert((Subtarget->hasXMM() || !NumXMMRegs)
2297 && "SSE registers cannot be used when SSE is disabled");
2299 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2300 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2301 InFlag = Chain.getValue(1);
2305 // For tail calls lower the arguments to the 'real' stack slot.
2307 // Force all the incoming stack arguments to be loaded from the stack
2308 // before any new outgoing arguments are stored to the stack, because the
2309 // outgoing stack slots may alias the incoming argument stack slots, and
2310 // the alias isn't otherwise explicit. This is slightly more conservative
2311 // than necessary, because it means that each store effectively depends
2312 // on every argument instead of just those arguments it would clobber.
2313 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2315 SmallVector<SDValue, 8> MemOpChains2;
2318 // Do not flag preceding copytoreg stuff together with the following stuff.
2320 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2321 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2322 CCValAssign &VA = ArgLocs[i];
2325 assert(VA.isMemLoc());
2326 SDValue Arg = OutVals[i];
2327 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2328 // Create frame index.
2329 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2330 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2331 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2332 FIN = DAG.getFrameIndex(FI, getPointerTy());
2334 if (Flags.isByVal()) {
2335 // Copy relative to framepointer.
2336 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2337 if (StackPtr.getNode() == 0)
2338 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2340 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2342 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2346 // Store relative to framepointer.
2347 MemOpChains2.push_back(
2348 DAG.getStore(ArgChain, dl, Arg, FIN,
2349 MachinePointerInfo::getFixedStack(FI),
2355 if (!MemOpChains2.empty())
2356 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2357 &MemOpChains2[0], MemOpChains2.size());
2359 // Copy arguments to their registers.
2360 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2361 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2362 RegsToPass[i].second, InFlag);
2363 InFlag = Chain.getValue(1);
2367 // Store the return address to the appropriate stack slot.
2368 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2372 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2373 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2374 // In the 64-bit large code model, we have to make all calls
2375 // through a register, since the call instruction's 32-bit
2376 // pc-relative offset may not be large enough to hold the whole
2378 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2379 // If the callee is a GlobalAddress node (quite common, every direct call
2380 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2383 // We should use extra load for direct calls to dllimported functions in
2385 const GlobalValue *GV = G->getGlobal();
2386 if (!GV->hasDLLImportLinkage()) {
2387 unsigned char OpFlags = 0;
2388 bool ExtraLoad = false;
2389 unsigned WrapperKind = ISD::DELETED_NODE;
2391 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2392 // external symbols most go through the PLT in PIC mode. If the symbol
2393 // has hidden or protected visibility, or if it is static or local, then
2394 // we don't need to use the PLT - we can directly call it.
2395 if (Subtarget->isTargetELF() &&
2396 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2397 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2398 OpFlags = X86II::MO_PLT;
2399 } else if (Subtarget->isPICStyleStubAny() &&
2400 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2401 (!Subtarget->getTargetTriple().isMacOSX() ||
2402 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2403 // PC-relative references to external symbols should go through $stub,
2404 // unless we're building with the leopard linker or later, which
2405 // automatically synthesizes these stubs.
2406 OpFlags = X86II::MO_DARWIN_STUB;
2407 } else if (Subtarget->isPICStyleRIPRel() &&
2408 isa<Function>(GV) &&
2409 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2410 // If the function is marked as non-lazy, generate an indirect call
2411 // which loads from the GOT directly. This avoids runtime overhead
2412 // at the cost of eager binding (and one extra byte of encoding).
2413 OpFlags = X86II::MO_GOTPCREL;
2414 WrapperKind = X86ISD::WrapperRIP;
2418 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2419 G->getOffset(), OpFlags);
2421 // Add a wrapper if needed.
2422 if (WrapperKind != ISD::DELETED_NODE)
2423 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2424 // Add extra indirection if needed.
2426 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2427 MachinePointerInfo::getGOT(),
2428 false, false, false, 0);
2430 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2431 unsigned char OpFlags = 0;
2433 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2434 // external symbols should go through the PLT.
2435 if (Subtarget->isTargetELF() &&
2436 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2437 OpFlags = X86II::MO_PLT;
2438 } else if (Subtarget->isPICStyleStubAny() &&
2439 (!Subtarget->getTargetTriple().isMacOSX() ||
2440 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2441 // PC-relative references to external symbols should go through $stub,
2442 // unless we're building with the leopard linker or later, which
2443 // automatically synthesizes these stubs.
2444 OpFlags = X86II::MO_DARWIN_STUB;
2447 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2451 // Returns a chain & a flag for retval copy to use.
2452 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2453 SmallVector<SDValue, 8> Ops;
2455 if (!IsSibcall && isTailCall) {
2456 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2457 DAG.getIntPtrConstant(0, true), InFlag);
2458 InFlag = Chain.getValue(1);
2461 Ops.push_back(Chain);
2462 Ops.push_back(Callee);
2465 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2467 // Add argument registers to the end of the list so that they are known live
2469 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2470 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2471 RegsToPass[i].second.getValueType()));
2473 // Add an implicit use GOT pointer in EBX.
2474 if (!isTailCall && Subtarget->isPICStyleGOT())
2475 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2477 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2478 if (Is64Bit && isVarArg && !IsWin64)
2479 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2481 if (InFlag.getNode())
2482 Ops.push_back(InFlag);
2486 //// If this is the first return lowered for this function, add the regs
2487 //// to the liveout set for the function.
2488 // This isn't right, although it's probably harmless on x86; liveouts
2489 // should be computed from returns not tail calls. Consider a void
2490 // function making a tail call to a function returning int.
2491 return DAG.getNode(X86ISD::TC_RETURN, dl,
2492 NodeTys, &Ops[0], Ops.size());
2495 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2496 InFlag = Chain.getValue(1);
2498 // Create the CALLSEQ_END node.
2499 unsigned NumBytesForCalleeToPush;
2500 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2501 getTargetMachine().Options.GuaranteedTailCallOpt))
2502 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2503 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2504 // If this is a call to a struct-return function, the callee
2505 // pops the hidden struct pointer, so we have to push it back.
2506 // This is common for Darwin/X86, Linux & Mingw32 targets.
2507 NumBytesForCalleeToPush = 4;
2509 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2511 // Returns a flag for retval copy to use.
2513 Chain = DAG.getCALLSEQ_END(Chain,
2514 DAG.getIntPtrConstant(NumBytes, true),
2515 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2518 InFlag = Chain.getValue(1);
2521 // Handle result values, copying them out of physregs into vregs that we
2523 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2524 Ins, dl, DAG, InVals);
2528 //===----------------------------------------------------------------------===//
2529 // Fast Calling Convention (tail call) implementation
2530 //===----------------------------------------------------------------------===//
2532 // Like std call, callee cleans arguments, convention except that ECX is
2533 // reserved for storing the tail called function address. Only 2 registers are
2534 // free for argument passing (inreg). Tail call optimization is performed
2536 // * tailcallopt is enabled
2537 // * caller/callee are fastcc
2538 // On X86_64 architecture with GOT-style position independent code only local
2539 // (within module) calls are supported at the moment.
2540 // To keep the stack aligned according to platform abi the function
2541 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2542 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2543 // If a tail called function callee has more arguments than the caller the
2544 // caller needs to make sure that there is room to move the RETADDR to. This is
2545 // achieved by reserving an area the size of the argument delta right after the
2546 // original REtADDR, but before the saved framepointer or the spilled registers
2547 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2559 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2560 /// for a 16 byte align requirement.
2562 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2563 SelectionDAG& DAG) const {
2564 MachineFunction &MF = DAG.getMachineFunction();
2565 const TargetMachine &TM = MF.getTarget();
2566 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2567 unsigned StackAlignment = TFI.getStackAlignment();
2568 uint64_t AlignMask = StackAlignment - 1;
2569 int64_t Offset = StackSize;
2570 uint64_t SlotSize = TD->getPointerSize();
2571 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2572 // Number smaller than 12 so just add the difference.
2573 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2575 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2576 Offset = ((~AlignMask) & Offset) + StackAlignment +
2577 (StackAlignment-SlotSize);
2582 /// MatchingStackOffset - Return true if the given stack call argument is
2583 /// already available in the same position (relatively) of the caller's
2584 /// incoming argument stack.
2586 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2587 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2588 const X86InstrInfo *TII) {
2589 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2591 if (Arg.getOpcode() == ISD::CopyFromReg) {
2592 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2593 if (!TargetRegisterInfo::isVirtualRegister(VR))
2595 MachineInstr *Def = MRI->getVRegDef(VR);
2598 if (!Flags.isByVal()) {
2599 if (!TII->isLoadFromStackSlot(Def, FI))
2602 unsigned Opcode = Def->getOpcode();
2603 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2604 Def->getOperand(1).isFI()) {
2605 FI = Def->getOperand(1).getIndex();
2606 Bytes = Flags.getByValSize();
2610 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2611 if (Flags.isByVal())
2612 // ByVal argument is passed in as a pointer but it's now being
2613 // dereferenced. e.g.
2614 // define @foo(%struct.X* %A) {
2615 // tail call @bar(%struct.X* byval %A)
2618 SDValue Ptr = Ld->getBasePtr();
2619 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2622 FI = FINode->getIndex();
2623 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2624 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2625 FI = FINode->getIndex();
2626 Bytes = Flags.getByValSize();
2630 assert(FI != INT_MAX);
2631 if (!MFI->isFixedObjectIndex(FI))
2633 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2636 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2637 /// for tail call optimization. Targets which want to do tail call
2638 /// optimization should implement this function.
2640 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2641 CallingConv::ID CalleeCC,
2643 bool isCalleeStructRet,
2644 bool isCallerStructRet,
2645 const SmallVectorImpl<ISD::OutputArg> &Outs,
2646 const SmallVectorImpl<SDValue> &OutVals,
2647 const SmallVectorImpl<ISD::InputArg> &Ins,
2648 SelectionDAG& DAG) const {
2649 if (!IsTailCallConvention(CalleeCC) &&
2650 CalleeCC != CallingConv::C)
2653 // If -tailcallopt is specified, make fastcc functions tail-callable.
2654 const MachineFunction &MF = DAG.getMachineFunction();
2655 const Function *CallerF = DAG.getMachineFunction().getFunction();
2656 CallingConv::ID CallerCC = CallerF->getCallingConv();
2657 bool CCMatch = CallerCC == CalleeCC;
2659 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2660 if (IsTailCallConvention(CalleeCC) && CCMatch)
2665 // Look for obvious safe cases to perform tail call optimization that do not
2666 // require ABI changes. This is what gcc calls sibcall.
2668 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2669 // emit a special epilogue.
2670 if (RegInfo->needsStackRealignment(MF))
2673 // Also avoid sibcall optimization if either caller or callee uses struct
2674 // return semantics.
2675 if (isCalleeStructRet || isCallerStructRet)
2678 // An stdcall caller is expected to clean up its arguments; the callee
2679 // isn't going to do that.
2680 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2683 // Do not sibcall optimize vararg calls unless all arguments are passed via
2685 if (isVarArg && !Outs.empty()) {
2687 // Optimizing for varargs on Win64 is unlikely to be safe without
2688 // additional testing.
2689 if (Subtarget->isTargetWin64())
2692 SmallVector<CCValAssign, 16> ArgLocs;
2693 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2694 getTargetMachine(), ArgLocs, *DAG.getContext());
2696 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2697 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2698 if (!ArgLocs[i].isRegLoc())
2702 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2703 // Therefore if it's not used by the call it is not safe to optimize this into
2705 bool Unused = false;
2706 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2713 SmallVector<CCValAssign, 16> RVLocs;
2714 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2715 getTargetMachine(), RVLocs, *DAG.getContext());
2716 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2717 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2718 CCValAssign &VA = RVLocs[i];
2719 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2724 // If the calling conventions do not match, then we'd better make sure the
2725 // results are returned in the same way as what the caller expects.
2727 SmallVector<CCValAssign, 16> RVLocs1;
2728 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2729 getTargetMachine(), RVLocs1, *DAG.getContext());
2730 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2732 SmallVector<CCValAssign, 16> RVLocs2;
2733 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2734 getTargetMachine(), RVLocs2, *DAG.getContext());
2735 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2737 if (RVLocs1.size() != RVLocs2.size())
2739 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2740 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2742 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2744 if (RVLocs1[i].isRegLoc()) {
2745 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2748 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2754 // If the callee takes no arguments then go on to check the results of the
2756 if (!Outs.empty()) {
2757 // Check if stack adjustment is needed. For now, do not do this if any
2758 // argument is passed on the stack.
2759 SmallVector<CCValAssign, 16> ArgLocs;
2760 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2761 getTargetMachine(), ArgLocs, *DAG.getContext());
2763 // Allocate shadow area for Win64
2764 if (Subtarget->isTargetWin64()) {
2765 CCInfo.AllocateStack(32, 8);
2768 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2769 if (CCInfo.getNextStackOffset()) {
2770 MachineFunction &MF = DAG.getMachineFunction();
2771 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2774 // Check if the arguments are already laid out in the right way as
2775 // the caller's fixed stack objects.
2776 MachineFrameInfo *MFI = MF.getFrameInfo();
2777 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2778 const X86InstrInfo *TII =
2779 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2780 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2781 CCValAssign &VA = ArgLocs[i];
2782 SDValue Arg = OutVals[i];
2783 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2784 if (VA.getLocInfo() == CCValAssign::Indirect)
2786 if (!VA.isRegLoc()) {
2787 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2794 // If the tailcall address may be in a register, then make sure it's
2795 // possible to register allocate for it. In 32-bit, the call address can
2796 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2797 // callee-saved registers are restored. These happen to be the same
2798 // registers used to pass 'inreg' arguments so watch out for those.
2799 if (!Subtarget->is64Bit() &&
2800 !isa<GlobalAddressSDNode>(Callee) &&
2801 !isa<ExternalSymbolSDNode>(Callee)) {
2802 unsigned NumInRegs = 0;
2803 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2804 CCValAssign &VA = ArgLocs[i];
2807 unsigned Reg = VA.getLocReg();
2810 case X86::EAX: case X86::EDX: case X86::ECX:
2811 if (++NumInRegs == 3)
2823 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2824 return X86::createFastISel(funcInfo);
2828 //===----------------------------------------------------------------------===//
2829 // Other Lowering Hooks
2830 //===----------------------------------------------------------------------===//
2832 static bool MayFoldLoad(SDValue Op) {
2833 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2836 static bool MayFoldIntoStore(SDValue Op) {
2837 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2840 static bool isTargetShuffle(unsigned Opcode) {
2842 default: return false;
2843 case X86ISD::PSHUFD:
2844 case X86ISD::PSHUFHW:
2845 case X86ISD::PSHUFLW:
2846 case X86ISD::SHUFPD:
2847 case X86ISD::PALIGN:
2848 case X86ISD::SHUFPS:
2849 case X86ISD::MOVLHPS:
2850 case X86ISD::MOVLHPD:
2851 case X86ISD::MOVHLPS:
2852 case X86ISD::MOVLPS:
2853 case X86ISD::MOVLPD:
2854 case X86ISD::MOVSHDUP:
2855 case X86ISD::MOVSLDUP:
2856 case X86ISD::MOVDDUP:
2859 case X86ISD::UNPCKL:
2860 case X86ISD::UNPCKH:
2861 case X86ISD::VPERMILP:
2862 case X86ISD::VPERM2X128:
2868 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2869 SDValue V1, SelectionDAG &DAG) {
2871 default: llvm_unreachable("Unknown x86 shuffle node");
2872 case X86ISD::MOVSHDUP:
2873 case X86ISD::MOVSLDUP:
2874 case X86ISD::MOVDDUP:
2875 return DAG.getNode(Opc, dl, VT, V1);
2881 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2882 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2884 default: llvm_unreachable("Unknown x86 shuffle node");
2885 case X86ISD::PSHUFD:
2886 case X86ISD::PSHUFHW:
2887 case X86ISD::PSHUFLW:
2888 case X86ISD::VPERMILP:
2889 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2895 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2896 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2898 default: llvm_unreachable("Unknown x86 shuffle node");
2899 case X86ISD::PALIGN:
2900 case X86ISD::SHUFPD:
2901 case X86ISD::SHUFPS:
2902 case X86ISD::VPERM2X128:
2903 return DAG.getNode(Opc, dl, VT, V1, V2,
2904 DAG.getConstant(TargetMask, MVT::i8));
2909 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2910 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2912 default: llvm_unreachable("Unknown x86 shuffle node");
2913 case X86ISD::MOVLHPS:
2914 case X86ISD::MOVLHPD:
2915 case X86ISD::MOVHLPS:
2916 case X86ISD::MOVLPS:
2917 case X86ISD::MOVLPD:
2920 case X86ISD::UNPCKL:
2921 case X86ISD::UNPCKH:
2922 return DAG.getNode(Opc, dl, VT, V1, V2);
2927 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2928 MachineFunction &MF = DAG.getMachineFunction();
2929 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2930 int ReturnAddrIndex = FuncInfo->getRAIndex();
2932 if (ReturnAddrIndex == 0) {
2933 // Set up a frame object for the return address.
2934 uint64_t SlotSize = TD->getPointerSize();
2935 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2937 FuncInfo->setRAIndex(ReturnAddrIndex);
2940 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2944 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2945 bool hasSymbolicDisplacement) {
2946 // Offset should fit into 32 bit immediate field.
2947 if (!isInt<32>(Offset))
2950 // If we don't have a symbolic displacement - we don't have any extra
2952 if (!hasSymbolicDisplacement)
2955 // FIXME: Some tweaks might be needed for medium code model.
2956 if (M != CodeModel::Small && M != CodeModel::Kernel)
2959 // For small code model we assume that latest object is 16MB before end of 31
2960 // bits boundary. We may also accept pretty large negative constants knowing
2961 // that all objects are in the positive half of address space.
2962 if (M == CodeModel::Small && Offset < 16*1024*1024)
2965 // For kernel code model we know that all object resist in the negative half
2966 // of 32bits address space. We may not accept negative offsets, since they may
2967 // be just off and we may accept pretty large positive ones.
2968 if (M == CodeModel::Kernel && Offset > 0)
2974 /// isCalleePop - Determines whether the callee is required to pop its
2975 /// own arguments. Callee pop is necessary to support tail calls.
2976 bool X86::isCalleePop(CallingConv::ID CallingConv,
2977 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2981 switch (CallingConv) {
2984 case CallingConv::X86_StdCall:
2986 case CallingConv::X86_FastCall:
2988 case CallingConv::X86_ThisCall:
2990 case CallingConv::Fast:
2992 case CallingConv::GHC:
2997 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2998 /// specific condition code, returning the condition code and the LHS/RHS of the
2999 /// comparison to make.
3000 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3001 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3003 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3004 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3005 // X > -1 -> X == 0, jump !sign.
3006 RHS = DAG.getConstant(0, RHS.getValueType());
3007 return X86::COND_NS;
3008 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3009 // X < 0 -> X == 0, jump on sign.
3011 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3013 RHS = DAG.getConstant(0, RHS.getValueType());
3014 return X86::COND_LE;
3018 switch (SetCCOpcode) {
3019 default: llvm_unreachable("Invalid integer condition!");
3020 case ISD::SETEQ: return X86::COND_E;
3021 case ISD::SETGT: return X86::COND_G;
3022 case ISD::SETGE: return X86::COND_GE;
3023 case ISD::SETLT: return X86::COND_L;
3024 case ISD::SETLE: return X86::COND_LE;
3025 case ISD::SETNE: return X86::COND_NE;
3026 case ISD::SETULT: return X86::COND_B;
3027 case ISD::SETUGT: return X86::COND_A;
3028 case ISD::SETULE: return X86::COND_BE;
3029 case ISD::SETUGE: return X86::COND_AE;
3033 // First determine if it is required or is profitable to flip the operands.
3035 // If LHS is a foldable load, but RHS is not, flip the condition.
3036 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3037 !ISD::isNON_EXTLoad(RHS.getNode())) {
3038 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3039 std::swap(LHS, RHS);
3042 switch (SetCCOpcode) {
3048 std::swap(LHS, RHS);
3052 // On a floating point condition, the flags are set as follows:
3054 // 0 | 0 | 0 | X > Y
3055 // 0 | 0 | 1 | X < Y
3056 // 1 | 0 | 0 | X == Y
3057 // 1 | 1 | 1 | unordered
3058 switch (SetCCOpcode) {
3059 default: llvm_unreachable("Condcode should be pre-legalized away");
3061 case ISD::SETEQ: return X86::COND_E;
3062 case ISD::SETOLT: // flipped
3064 case ISD::SETGT: return X86::COND_A;
3065 case ISD::SETOLE: // flipped
3067 case ISD::SETGE: return X86::COND_AE;
3068 case ISD::SETUGT: // flipped
3070 case ISD::SETLT: return X86::COND_B;
3071 case ISD::SETUGE: // flipped
3073 case ISD::SETLE: return X86::COND_BE;
3075 case ISD::SETNE: return X86::COND_NE;
3076 case ISD::SETUO: return X86::COND_P;
3077 case ISD::SETO: return X86::COND_NP;
3079 case ISD::SETUNE: return X86::COND_INVALID;
3083 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3084 /// code. Current x86 isa includes the following FP cmov instructions:
3085 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3086 static bool hasFPCMov(unsigned X86CC) {
3102 /// isFPImmLegal - Returns true if the target can instruction select the
3103 /// specified FP immediate natively. If false, the legalizer will
3104 /// materialize the FP immediate as a load from a constant pool.
3105 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3106 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3107 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3113 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3114 /// the specified range (L, H].
3115 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3116 return (Val < 0) || (Val >= Low && Val < Hi);
3119 /// isUndefOrInRange - Return true if every element in Mask, begining
3120 /// from position Pos and ending in Pos+Size, falls within the specified
3121 /// range (L, L+Pos]. or is undef.
3122 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3123 int Pos, int Size, int Low, int Hi) {
3124 for (int i = Pos, e = Pos+Size; i != e; ++i)
3125 if (!isUndefOrInRange(Mask[i], Low, Hi))
3130 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3131 /// specified value.
3132 static bool isUndefOrEqual(int Val, int CmpVal) {
3133 if (Val < 0 || Val == CmpVal)
3138 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3139 /// from position Pos and ending in Pos+Size, falls within the specified
3140 /// sequential range (L, L+Pos]. or is undef.
3141 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3142 int Pos, int Size, int Low) {
3143 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3144 if (!isUndefOrEqual(Mask[i], Low))
3149 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3150 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3151 /// the second operand.
3152 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3153 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3154 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3155 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3156 return (Mask[0] < 2 && Mask[1] < 2);
3160 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3161 SmallVector<int, 8> M;
3163 return ::isPSHUFDMask(M, N->getValueType(0));
3166 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3167 /// is suitable for input to PSHUFHW.
3168 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3169 if (VT != MVT::v8i16)
3172 // Lower quadword copied in order or undef.
3173 for (int i = 0; i != 4; ++i)
3174 if (Mask[i] >= 0 && Mask[i] != i)
3177 // Upper quadword shuffled.
3178 for (int i = 4; i != 8; ++i)
3179 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3185 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3186 SmallVector<int, 8> M;
3188 return ::isPSHUFHWMask(M, N->getValueType(0));
3191 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3192 /// is suitable for input to PSHUFLW.
3193 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3194 if (VT != MVT::v8i16)
3197 // Upper quadword copied in order.
3198 for (int i = 4; i != 8; ++i)
3199 if (Mask[i] >= 0 && Mask[i] != i)
3202 // Lower quadword shuffled.
3203 for (int i = 0; i != 4; ++i)
3210 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3211 SmallVector<int, 8> M;
3213 return ::isPSHUFLWMask(M, N->getValueType(0));
3216 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3217 /// is suitable for input to PALIGNR.
3218 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3219 bool hasSSSE3OrAVX) {
3220 int i, e = VT.getVectorNumElements();
3221 if (VT.getSizeInBits() != 128)
3224 // Do not handle v2i64 / v2f64 shuffles with palignr.
3225 if (e < 4 || !hasSSSE3OrAVX)
3228 for (i = 0; i != e; ++i)
3232 // All undef, not a palignr.
3236 // Make sure we're shifting in the right direction.
3240 int s = Mask[i] - i;
3242 // Check the rest of the elements to see if they are consecutive.
3243 for (++i; i != e; ++i) {
3245 if (m >= 0 && m != s+i)
3251 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3252 /// specifies a shuffle of elements that is suitable for input to 256-bit
3254 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3255 bool HasAVX, bool Commuted = false) {
3256 int NumElems = VT.getVectorNumElements();
3258 if (!HasAVX || VT.getSizeInBits() != 256)
3261 if (NumElems != 4 && NumElems != 8)
3264 // VSHUFPSY divides the resulting vector into 4 chunks.
3265 // The sources are also splitted into 4 chunks, and each destination
3266 // chunk must come from a different source chunk.
3268 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3269 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3271 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3272 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3274 // VSHUFPDY divides the resulting vector into 4 chunks.
3275 // The sources are also splitted into 4 chunks, and each destination
3276 // chunk must come from a different source chunk.
3278 // SRC1 => X3 X2 X1 X0
3279 // SRC2 => Y3 Y2 Y1 Y0
3281 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3283 unsigned QuarterSize = NumElems/4;
3284 unsigned HalfSize = QuarterSize*2;
3285 for (unsigned l = 0; l != 2; ++l) {
3286 unsigned LaneStart = l*HalfSize;
3287 for (unsigned s = 0; s != 2; ++s) {
3288 unsigned QuarterStart = s*QuarterSize;
3289 unsigned Src = (Commuted) ? (1-s) : s;
3290 unsigned SrcStart = Src*NumElems + LaneStart;
3291 for (unsigned i = 0; i != QuarterSize; ++i) {
3292 int Idx = Mask[i+QuarterStart+LaneStart];
3293 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3295 // For VSHUFPSY, the mask of the second half must be the same as the first
3296 // but with the appropriate offsets. This works in the same way as
3297 // VPERMILPS works with masks.
3298 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3300 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3309 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3310 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3311 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3312 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3313 EVT VT = SVOp->getValueType(0);
3314 int NumElems = VT.getVectorNumElements();
3316 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3317 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3319 int HalfSize = NumElems/2;
3320 unsigned Mul = (NumElems == 8) ? 2 : 1;
3322 for (int i = 0; i != NumElems; ++i) {
3323 int Elt = SVOp->getMaskElt(i);
3328 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3329 if (NumElems == 8) Shamt %= HalfSize;
3330 Mask |= Elt << (Shamt*Mul);
3336 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3337 /// the two vector operands have swapped position.
3338 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3339 unsigned NumElems) {
3340 for (unsigned i = 0; i != NumElems; ++i) {
3344 else if (idx < (int)NumElems)
3345 Mask[i] = idx + NumElems;
3347 Mask[i] = idx - NumElems;
3351 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3352 /// specifies a shuffle of elements that is suitable for input to 128-bit
3353 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3354 /// reverse of what x86 shuffles want.
3355 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3356 bool Commuted = false) {
3357 unsigned NumElems = VT.getVectorNumElements();
3359 if (VT.getSizeInBits() != 128)
3362 if (NumElems != 2 && NumElems != 4)
3365 unsigned Half = NumElems / 2;
3366 unsigned SrcStart = Commuted ? NumElems : 0;
3367 for (unsigned i = 0; i != Half; ++i)
3368 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3370 SrcStart = Commuted ? 0 : NumElems;
3371 for (unsigned i = Half; i != NumElems; ++i)
3372 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3378 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3379 SmallVector<int, 8> M;
3381 return ::isSHUFPMask(M, N->getValueType(0));
3384 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3385 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3386 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3387 EVT VT = N->getValueType(0);
3388 unsigned NumElems = VT.getVectorNumElements();
3390 if (VT.getSizeInBits() != 128)
3396 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3397 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3398 isUndefOrEqual(N->getMaskElt(1), 7) &&
3399 isUndefOrEqual(N->getMaskElt(2), 2) &&
3400 isUndefOrEqual(N->getMaskElt(3), 3);
3403 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3404 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3406 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3407 EVT VT = N->getValueType(0);
3408 unsigned NumElems = VT.getVectorNumElements();
3410 if (VT.getSizeInBits() != 128)
3416 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3417 isUndefOrEqual(N->getMaskElt(1), 3) &&
3418 isUndefOrEqual(N->getMaskElt(2), 2) &&
3419 isUndefOrEqual(N->getMaskElt(3), 3);
3422 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3423 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3424 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3425 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3427 if (NumElems != 2 && NumElems != 4)
3430 for (unsigned i = 0; i < NumElems/2; ++i)
3431 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3434 for (unsigned i = NumElems/2; i < NumElems; ++i)
3435 if (!isUndefOrEqual(N->getMaskElt(i), i))
3441 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3442 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3443 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3444 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3446 if ((NumElems != 2 && NumElems != 4)
3447 || N->getValueType(0).getSizeInBits() > 128)
3450 for (unsigned i = 0; i < NumElems/2; ++i)
3451 if (!isUndefOrEqual(N->getMaskElt(i), i))
3454 for (unsigned i = 0; i < NumElems/2; ++i)
3455 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3461 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3462 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3463 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3464 bool HasAVX2, bool V2IsSplat = false) {
3465 int NumElts = VT.getVectorNumElements();
3467 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3468 "Unsupported vector type for unpckh");
3470 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3471 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3474 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3475 // independently on 128-bit lanes.
3476 unsigned NumLanes = VT.getSizeInBits()/128;
3477 unsigned NumLaneElts = NumElts/NumLanes;
3480 unsigned End = NumLaneElts;
3481 for (unsigned s = 0; s < NumLanes; ++s) {
3482 for (unsigned i = Start, j = s * NumLaneElts;
3486 int BitI1 = Mask[i+1];
3487 if (!isUndefOrEqual(BitI, j))
3490 if (!isUndefOrEqual(BitI1, NumElts))
3493 if (!isUndefOrEqual(BitI1, j + NumElts))
3497 // Process the next 128 bits.
3498 Start += NumLaneElts;
3505 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3506 SmallVector<int, 8> M;
3508 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3511 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3513 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3514 bool HasAVX2, bool V2IsSplat = false) {
3515 int NumElts = VT.getVectorNumElements();
3517 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3518 "Unsupported vector type for unpckh");
3520 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3521 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3524 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3525 // independently on 128-bit lanes.
3526 unsigned NumLanes = VT.getSizeInBits()/128;
3527 unsigned NumLaneElts = NumElts/NumLanes;
3530 unsigned End = NumLaneElts;
3531 for (unsigned l = 0; l != NumLanes; ++l) {
3532 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3533 i != End; i += 2, ++j) {
3535 int BitI1 = Mask[i+1];
3536 if (!isUndefOrEqual(BitI, j))
3539 if (isUndefOrEqual(BitI1, NumElts))
3542 if (!isUndefOrEqual(BitI1, j+NumElts))
3546 // Process the next 128 bits.
3547 Start += NumLaneElts;
3553 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3554 SmallVector<int, 8> M;
3556 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3559 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3560 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3562 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3563 int NumElems = VT.getVectorNumElements();
3564 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3567 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3568 // FIXME: Need a better way to get rid of this, there's no latency difference
3569 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3570 // the former later. We should also remove the "_undef" special mask.
3571 if (NumElems == 4 && VT.getSizeInBits() == 256)
3574 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3575 // independently on 128-bit lanes.
3576 unsigned NumLanes = VT.getSizeInBits() / 128;
3577 unsigned NumLaneElts = NumElems / NumLanes;
3579 for (unsigned s = 0; s < NumLanes; ++s) {
3580 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3581 i != NumLaneElts * (s + 1);
3584 int BitI1 = Mask[i+1];
3586 if (!isUndefOrEqual(BitI, j))
3588 if (!isUndefOrEqual(BitI1, j))
3596 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3597 SmallVector<int, 8> M;
3599 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3602 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3603 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3605 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3606 int NumElems = VT.getVectorNumElements();
3607 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3610 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3612 int BitI1 = Mask[i+1];
3613 if (!isUndefOrEqual(BitI, j))
3615 if (!isUndefOrEqual(BitI1, j))
3621 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3622 SmallVector<int, 8> M;
3624 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3627 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3628 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3629 /// MOVSD, and MOVD, i.e. setting the lowest element.
3630 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3631 if (VT.getVectorElementType().getSizeInBits() < 32)
3634 int NumElts = VT.getVectorNumElements();
3636 if (!isUndefOrEqual(Mask[0], NumElts))
3639 for (int i = 1; i < NumElts; ++i)
3640 if (!isUndefOrEqual(Mask[i], i))
3646 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3647 SmallVector<int, 8> M;
3649 return ::isMOVLMask(M, N->getValueType(0));
3652 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3653 /// as permutations between 128-bit chunks or halves. As an example: this
3655 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3656 /// The first half comes from the second half of V1 and the second half from the
3657 /// the second half of V2.
3658 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3660 if (!HasAVX || VT.getSizeInBits() != 256)
3663 // The shuffle result is divided into half A and half B. In total the two
3664 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3665 // B must come from C, D, E or F.
3666 int HalfSize = VT.getVectorNumElements()/2;
3667 bool MatchA = false, MatchB = false;
3669 // Check if A comes from one of C, D, E, F.
3670 for (int Half = 0; Half < 4; ++Half) {
3671 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3677 // Check if B comes from one of C, D, E, F.
3678 for (int Half = 0; Half < 4; ++Half) {
3679 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3685 return MatchA && MatchB;
3688 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3689 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3690 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3691 EVT VT = SVOp->getValueType(0);
3693 int HalfSize = VT.getVectorNumElements()/2;
3695 int FstHalf = 0, SndHalf = 0;
3696 for (int i = 0; i < HalfSize; ++i) {
3697 if (SVOp->getMaskElt(i) > 0) {
3698 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3702 for (int i = HalfSize; i < HalfSize*2; ++i) {
3703 if (SVOp->getMaskElt(i) > 0) {
3704 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3709 return (FstHalf | (SndHalf << 4));
3712 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3713 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3714 /// Note that VPERMIL mask matching is different depending whether theunderlying
3715 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3716 /// to the same elements of the low, but to the higher half of the source.
3717 /// In VPERMILPD the two lanes could be shuffled independently of each other
3718 /// with the same restriction that lanes can't be crossed.
3719 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3721 int NumElts = VT.getVectorNumElements();
3722 int NumLanes = VT.getSizeInBits()/128;
3727 // Only match 256-bit with 32/64-bit types
3728 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3731 int LaneSize = NumElts/NumLanes;
3732 for (int l = 0; l != NumLanes; ++l) {
3733 int LaneStart = l*LaneSize;
3734 for (int i = 0; i != LaneSize; ++i) {
3735 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3737 if (NumElts == 4 || l == 0)
3739 // VPERMILPS handling
3742 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3750 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3751 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3752 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3753 EVT VT = SVOp->getValueType(0);
3755 int NumElts = VT.getVectorNumElements();
3756 int NumLanes = VT.getSizeInBits()/128;
3757 int LaneSize = NumElts/NumLanes;
3759 // Although the mask is equal for both lanes do it twice to get the cases
3760 // where a mask will match because the same mask element is undef on the
3761 // first half but valid on the second. This would get pathological cases
3762 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3763 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3765 for (int i = 0; i != NumElts; ++i) {
3766 int MaskElt = SVOp->getMaskElt(i);
3769 MaskElt %= LaneSize;
3771 // VPERMILPSY, the mask of the first half must be equal to the second one
3772 if (NumElts == 8) Shamt %= LaneSize;
3773 Mask |= MaskElt << (Shamt*Shift);
3779 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3780 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3781 /// element of vector 2 and the other elements to come from vector 1 in order.
3782 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3783 bool V2IsSplat = false, bool V2IsUndef = false) {
3784 int NumOps = VT.getVectorNumElements();
3785 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3788 if (!isUndefOrEqual(Mask[0], 0))
3791 for (int i = 1; i < NumOps; ++i)
3792 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3793 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3794 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3800 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3801 bool V2IsUndef = false) {
3802 SmallVector<int, 8> M;
3804 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3807 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3809 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3810 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3811 const X86Subtarget *Subtarget) {
3812 if (!Subtarget->hasSSE3orAVX())
3815 // The second vector must be undef
3816 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3819 EVT VT = N->getValueType(0);
3820 unsigned NumElems = VT.getVectorNumElements();
3822 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3823 (VT.getSizeInBits() == 256 && NumElems != 8))
3826 // "i+1" is the value the indexed mask element must have
3827 for (unsigned i = 0; i < NumElems; i += 2)
3828 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3829 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3835 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3836 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3837 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3838 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3839 const X86Subtarget *Subtarget) {
3840 if (!Subtarget->hasSSE3orAVX())
3843 // The second vector must be undef
3844 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3847 EVT VT = N->getValueType(0);
3848 unsigned NumElems = VT.getVectorNumElements();
3850 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3851 (VT.getSizeInBits() == 256 && NumElems != 8))
3854 // "i" is the value the indexed mask element must have
3855 for (unsigned i = 0; i < NumElems; i += 2)
3856 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3857 !isUndefOrEqual(N->getMaskElt(i+1), i))
3863 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3864 /// specifies a shuffle of elements that is suitable for input to 256-bit
3865 /// version of MOVDDUP.
3866 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3868 int NumElts = VT.getVectorNumElements();
3870 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3873 for (int i = 0; i != NumElts/2; ++i)
3874 if (!isUndefOrEqual(Mask[i], 0))
3876 for (int i = NumElts/2; i != NumElts; ++i)
3877 if (!isUndefOrEqual(Mask[i], NumElts/2))
3882 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3883 /// specifies a shuffle of elements that is suitable for input to 128-bit
3884 /// version of MOVDDUP.
3885 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3886 EVT VT = N->getValueType(0);
3888 if (VT.getSizeInBits() != 128)
3891 int e = VT.getVectorNumElements() / 2;
3892 for (int i = 0; i < e; ++i)
3893 if (!isUndefOrEqual(N->getMaskElt(i), i))
3895 for (int i = 0; i < e; ++i)
3896 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3901 /// isVEXTRACTF128Index - Return true if the specified
3902 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3903 /// suitable for input to VEXTRACTF128.
3904 bool X86::isVEXTRACTF128Index(SDNode *N) {
3905 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3908 // The index should be aligned on a 128-bit boundary.
3910 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3912 unsigned VL = N->getValueType(0).getVectorNumElements();
3913 unsigned VBits = N->getValueType(0).getSizeInBits();
3914 unsigned ElSize = VBits / VL;
3915 bool Result = (Index * ElSize) % 128 == 0;
3920 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3921 /// operand specifies a subvector insert that is suitable for input to
3923 bool X86::isVINSERTF128Index(SDNode *N) {
3924 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3927 // The index should be aligned on a 128-bit boundary.
3929 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3931 unsigned VL = N->getValueType(0).getVectorNumElements();
3932 unsigned VBits = N->getValueType(0).getSizeInBits();
3933 unsigned ElSize = VBits / VL;
3934 bool Result = (Index * ElSize) % 128 == 0;
3939 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3940 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3941 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3942 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3943 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3945 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3947 for (int i = 0; i < NumOperands; ++i) {
3948 int Val = SVOp->getMaskElt(NumOperands-i-1);
3949 if (Val < 0) Val = 0;
3950 if (Val >= NumOperands) Val -= NumOperands;
3952 if (i != NumOperands - 1)
3958 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3959 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3960 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3961 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3963 // 8 nodes, but we only care about the last 4.
3964 for (unsigned i = 7; i >= 4; --i) {
3965 int Val = SVOp->getMaskElt(i);
3974 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3975 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3976 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3977 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3979 // 8 nodes, but we only care about the first 4.
3980 for (int i = 3; i >= 0; --i) {
3981 int Val = SVOp->getMaskElt(i);
3990 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3991 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3992 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3993 EVT VT = SVOp->getValueType(0);
3994 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3998 for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3999 Val = SVOp->getMaskElt(i);
4003 assert(Val - i > 0 && "PALIGNR imm should be positive");
4004 return (Val - i) * EltSize;
4007 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4008 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4010 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4011 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4012 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4015 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4017 EVT VecVT = N->getOperand(0).getValueType();
4018 EVT ElVT = VecVT.getVectorElementType();
4020 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4021 return Index / NumElemsPerChunk;
4024 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4025 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4027 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4028 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4029 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4032 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4034 EVT VecVT = N->getValueType(0);
4035 EVT ElVT = VecVT.getVectorElementType();
4037 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4038 return Index / NumElemsPerChunk;
4041 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4043 bool X86::isZeroNode(SDValue Elt) {
4044 return ((isa<ConstantSDNode>(Elt) &&
4045 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4046 (isa<ConstantFPSDNode>(Elt) &&
4047 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4050 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4051 /// their permute mask.
4052 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4053 SelectionDAG &DAG) {
4054 EVT VT = SVOp->getValueType(0);
4055 unsigned NumElems = VT.getVectorNumElements();
4056 SmallVector<int, 8> MaskVec;
4058 for (unsigned i = 0; i != NumElems; ++i) {
4059 int idx = SVOp->getMaskElt(i);
4061 MaskVec.push_back(idx);
4062 else if (idx < (int)NumElems)
4063 MaskVec.push_back(idx + NumElems);
4065 MaskVec.push_back(idx - NumElems);
4067 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4068 SVOp->getOperand(0), &MaskVec[0]);
4071 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4072 /// match movhlps. The lower half elements should come from upper half of
4073 /// V1 (and in order), and the upper half elements should come from the upper
4074 /// half of V2 (and in order).
4075 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4076 EVT VT = Op->getValueType(0);
4077 if (VT.getSizeInBits() != 128)
4079 if (VT.getVectorNumElements() != 4)
4081 for (unsigned i = 0, e = 2; i != e; ++i)
4082 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4084 for (unsigned i = 2; i != 4; ++i)
4085 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4090 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4091 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4093 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4094 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4096 N = N->getOperand(0).getNode();
4097 if (!ISD::isNON_EXTLoad(N))
4100 *LD = cast<LoadSDNode>(N);
4104 // Test whether the given value is a vector value which will be legalized
4106 static bool WillBeConstantPoolLoad(SDNode *N) {
4107 if (N->getOpcode() != ISD::BUILD_VECTOR)
4110 // Check for any non-constant elements.
4111 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4112 switch (N->getOperand(i).getNode()->getOpcode()) {
4114 case ISD::ConstantFP:
4121 // Vectors of all-zeros and all-ones are materialized with special
4122 // instructions rather than being loaded.
4123 return !ISD::isBuildVectorAllZeros(N) &&
4124 !ISD::isBuildVectorAllOnes(N);
4127 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4128 /// match movlp{s|d}. The lower half elements should come from lower half of
4129 /// V1 (and in order), and the upper half elements should come from the upper
4130 /// half of V2 (and in order). And since V1 will become the source of the
4131 /// MOVLP, it must be either a vector load or a scalar load to vector.
4132 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4133 ShuffleVectorSDNode *Op) {
4134 EVT VT = Op->getValueType(0);
4135 if (VT.getSizeInBits() != 128)
4138 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4140 // Is V2 is a vector load, don't do this transformation. We will try to use
4141 // load folding shufps op.
4142 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4145 unsigned NumElems = VT.getVectorNumElements();
4147 if (NumElems != 2 && NumElems != 4)
4149 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4150 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4152 for (unsigned i = NumElems/2; i != NumElems; ++i)
4153 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4158 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4160 static bool isSplatVector(SDNode *N) {
4161 if (N->getOpcode() != ISD::BUILD_VECTOR)
4164 SDValue SplatValue = N->getOperand(0);
4165 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4166 if (N->getOperand(i) != SplatValue)
4171 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4172 /// to an zero vector.
4173 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4174 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4175 SDValue V1 = N->getOperand(0);
4176 SDValue V2 = N->getOperand(1);
4177 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4178 for (unsigned i = 0; i != NumElems; ++i) {
4179 int Idx = N->getMaskElt(i);
4180 if (Idx >= (int)NumElems) {
4181 unsigned Opc = V2.getOpcode();
4182 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4184 if (Opc != ISD::BUILD_VECTOR ||
4185 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4187 } else if (Idx >= 0) {
4188 unsigned Opc = V1.getOpcode();
4189 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4191 if (Opc != ISD::BUILD_VECTOR ||
4192 !X86::isZeroNode(V1.getOperand(Idx)))
4199 /// getZeroVector - Returns a vector of specified type with all zero elements.
4201 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4203 assert(VT.isVector() && "Expected a vector type");
4205 // Always build SSE zero vectors as <4 x i32> bitcasted
4206 // to their dest type. This ensures they get CSE'd.
4208 if (VT.getSizeInBits() == 128) { // SSE
4209 if (HasXMMInt) { // SSE2
4210 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4211 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4213 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4214 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4216 } else if (VT.getSizeInBits() == 256) { // AVX
4217 // 256-bit logic and arithmetic instructions in AVX are
4218 // all floating-point, no support for integer ops. Default
4219 // to emitting fp zeroed vectors then.
4220 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4221 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4222 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4224 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4227 /// getOnesVector - Returns a vector of specified type with all bits set.
4228 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4229 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4230 /// Then bitcast to their original type, ensuring they get CSE'd.
4231 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4233 assert(VT.isVector() && "Expected a vector type");
4234 assert((VT.is128BitVector() || VT.is256BitVector())
4235 && "Expected a 128-bit or 256-bit vector type");
4237 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4239 if (VT.getSizeInBits() == 256) {
4240 if (HasAVX2) { // AVX2
4241 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4242 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4244 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4245 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4246 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4247 Vec = Insert128BitVector(InsV, Vec,
4248 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4251 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4254 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4257 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4258 /// that point to V2 points to its first element.
4259 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4260 EVT VT = SVOp->getValueType(0);
4261 unsigned NumElems = VT.getVectorNumElements();
4263 bool Changed = false;
4264 SmallVector<int, 8> MaskVec;
4265 SVOp->getMask(MaskVec);
4267 for (unsigned i = 0; i != NumElems; ++i) {
4268 if (MaskVec[i] > (int)NumElems) {
4269 MaskVec[i] = NumElems;
4274 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4275 SVOp->getOperand(1), &MaskVec[0]);
4276 return SDValue(SVOp, 0);
4279 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4280 /// operation of specified width.
4281 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4283 unsigned NumElems = VT.getVectorNumElements();
4284 SmallVector<int, 8> Mask;
4285 Mask.push_back(NumElems);
4286 for (unsigned i = 1; i != NumElems; ++i)
4288 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4291 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4292 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4294 unsigned NumElems = VT.getVectorNumElements();
4295 SmallVector<int, 8> Mask;
4296 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4298 Mask.push_back(i + NumElems);
4300 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4303 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4304 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4306 unsigned NumElems = VT.getVectorNumElements();
4307 unsigned Half = NumElems/2;
4308 SmallVector<int, 8> Mask;
4309 for (unsigned i = 0; i != Half; ++i) {
4310 Mask.push_back(i + Half);
4311 Mask.push_back(i + NumElems + Half);
4313 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4316 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4317 // a generic shuffle instruction because the target has no such instructions.
4318 // Generate shuffles which repeat i16 and i8 several times until they can be
4319 // represented by v4f32 and then be manipulated by target suported shuffles.
4320 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4321 EVT VT = V.getValueType();
4322 int NumElems = VT.getVectorNumElements();
4323 DebugLoc dl = V.getDebugLoc();
4325 while (NumElems > 4) {
4326 if (EltNo < NumElems/2) {
4327 V = getUnpackl(DAG, dl, VT, V, V);
4329 V = getUnpackh(DAG, dl, VT, V, V);
4330 EltNo -= NumElems/2;
4337 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4338 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4339 EVT VT = V.getValueType();
4340 DebugLoc dl = V.getDebugLoc();
4341 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4342 && "Vector size not supported");
4344 if (VT.getSizeInBits() == 128) {
4345 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4346 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4347 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4350 // To use VPERMILPS to splat scalars, the second half of indicies must
4351 // refer to the higher part, which is a duplication of the lower one,
4352 // because VPERMILPS can only handle in-lane permutations.
4353 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4354 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4356 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4357 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4361 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4364 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4365 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4366 EVT SrcVT = SV->getValueType(0);
4367 SDValue V1 = SV->getOperand(0);
4368 DebugLoc dl = SV->getDebugLoc();
4370 int EltNo = SV->getSplatIndex();
4371 int NumElems = SrcVT.getVectorNumElements();
4372 unsigned Size = SrcVT.getSizeInBits();
4374 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4375 "Unknown how to promote splat for type");
4377 // Extract the 128-bit part containing the splat element and update
4378 // the splat element index when it refers to the higher register.
4380 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4381 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4383 EltNo -= NumElems/2;
4386 // All i16 and i8 vector types can't be used directly by a generic shuffle
4387 // instruction because the target has no such instruction. Generate shuffles
4388 // which repeat i16 and i8 several times until they fit in i32, and then can
4389 // be manipulated by target suported shuffles.
4390 EVT EltVT = SrcVT.getVectorElementType();
4391 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4392 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4394 // Recreate the 256-bit vector and place the same 128-bit vector
4395 // into the low and high part. This is necessary because we want
4396 // to use VPERM* to shuffle the vectors
4398 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4399 DAG.getConstant(0, MVT::i32), DAG, dl);
4400 V1 = Insert128BitVector(InsV, V1,
4401 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4404 return getLegalSplat(DAG, V1, EltNo);
4407 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4408 /// vector of zero or undef vector. This produces a shuffle where the low
4409 /// element of V2 is swizzled into the zero/undef vector, landing at element
4410 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4411 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4412 bool isZero, bool HasXMMInt,
4413 SelectionDAG &DAG) {
4414 EVT VT = V2.getValueType();
4416 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4417 unsigned NumElems = VT.getVectorNumElements();
4418 SmallVector<int, 16> MaskVec;
4419 for (unsigned i = 0; i != NumElems; ++i)
4420 // If this is the insertion idx, put the low elt of V2 here.
4421 MaskVec.push_back(i == Idx ? NumElems : i);
4422 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4425 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4426 /// element of the result of the vector shuffle.
4427 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4430 return SDValue(); // Limit search depth.
4432 SDValue V = SDValue(N, 0);
4433 EVT VT = V.getValueType();
4434 unsigned Opcode = V.getOpcode();
4436 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4437 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4438 Index = SV->getMaskElt(Index);
4441 return DAG.getUNDEF(VT.getVectorElementType());
4443 int NumElems = VT.getVectorNumElements();
4444 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4445 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4448 // Recurse into target specific vector shuffles to find scalars.
4449 if (isTargetShuffle(Opcode)) {
4450 int NumElems = VT.getVectorNumElements();
4451 SmallVector<unsigned, 16> ShuffleMask;
4455 case X86ISD::SHUFPS:
4456 case X86ISD::SHUFPD:
4457 ImmN = N->getOperand(N->getNumOperands()-1);
4458 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4461 case X86ISD::UNPCKH:
4462 DecodeUNPCKHMask(VT, ShuffleMask);
4464 case X86ISD::UNPCKL:
4465 DecodeUNPCKLMask(VT, ShuffleMask);
4467 case X86ISD::MOVHLPS:
4468 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4470 case X86ISD::MOVLHPS:
4471 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4473 case X86ISD::PSHUFD:
4474 ImmN = N->getOperand(N->getNumOperands()-1);
4475 DecodePSHUFMask(NumElems,
4476 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4479 case X86ISD::PSHUFHW:
4480 ImmN = N->getOperand(N->getNumOperands()-1);
4481 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4484 case X86ISD::PSHUFLW:
4485 ImmN = N->getOperand(N->getNumOperands()-1);
4486 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4490 case X86ISD::MOVSD: {
4491 // The index 0 always comes from the first element of the second source,
4492 // this is why MOVSS and MOVSD are used in the first place. The other
4493 // elements come from the other positions of the first source vector.
4494 unsigned OpNum = (Index == 0) ? 1 : 0;
4495 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4498 case X86ISD::VPERMILP:
4499 ImmN = N->getOperand(N->getNumOperands()-1);
4500 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4503 case X86ISD::VPERM2X128:
4504 ImmN = N->getOperand(N->getNumOperands()-1);
4505 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4508 case X86ISD::MOVDDUP:
4509 case X86ISD::MOVLHPD:
4510 case X86ISD::MOVLPD:
4511 case X86ISD::MOVLPS:
4512 case X86ISD::MOVSHDUP:
4513 case X86ISD::MOVSLDUP:
4514 case X86ISD::PALIGN:
4515 return SDValue(); // Not yet implemented.
4517 assert(0 && "unknown target shuffle node");
4521 Index = ShuffleMask[Index];
4523 return DAG.getUNDEF(VT.getVectorElementType());
4525 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4526 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4530 // Actual nodes that may contain scalar elements
4531 if (Opcode == ISD::BITCAST) {
4532 V = V.getOperand(0);
4533 EVT SrcVT = V.getValueType();
4534 unsigned NumElems = VT.getVectorNumElements();
4536 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4540 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4541 return (Index == 0) ? V.getOperand(0)
4542 : DAG.getUNDEF(VT.getVectorElementType());
4544 if (V.getOpcode() == ISD::BUILD_VECTOR)
4545 return V.getOperand(Index);
4550 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4551 /// shuffle operation which come from a consecutively from a zero. The
4552 /// search can start in two different directions, from left or right.
4554 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4555 bool ZerosFromLeft, SelectionDAG &DAG) {
4558 while (i < NumElems) {
4559 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4560 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4561 if (!(Elt.getNode() &&
4562 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4570 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4571 /// MaskE correspond consecutively to elements from one of the vector operands,
4572 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4574 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4575 int OpIdx, int NumElems, unsigned &OpNum) {
4576 bool SeenV1 = false;
4577 bool SeenV2 = false;
4579 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4580 int Idx = SVOp->getMaskElt(i);
4581 // Ignore undef indicies
4590 // Only accept consecutive elements from the same vector
4591 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4595 OpNum = SeenV1 ? 0 : 1;
4599 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4600 /// logical left shift of a vector.
4601 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4602 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4603 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4604 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4605 false /* check zeros from right */, DAG);
4611 // Considering the elements in the mask that are not consecutive zeros,
4612 // check if they consecutively come from only one of the source vectors.
4614 // V1 = {X, A, B, C} 0
4616 // vector_shuffle V1, V2 <1, 2, 3, X>
4618 if (!isShuffleMaskConsecutive(SVOp,
4619 0, // Mask Start Index
4620 NumElems-NumZeros-1, // Mask End Index
4621 NumZeros, // Where to start looking in the src vector
4622 NumElems, // Number of elements in vector
4623 OpSrc)) // Which source operand ?
4628 ShVal = SVOp->getOperand(OpSrc);
4632 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4633 /// logical left shift of a vector.
4634 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4635 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4636 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4637 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4638 true /* check zeros from left */, DAG);
4644 // Considering the elements in the mask that are not consecutive zeros,
4645 // check if they consecutively come from only one of the source vectors.
4647 // 0 { A, B, X, X } = V2
4649 // vector_shuffle V1, V2 <X, X, 4, 5>
4651 if (!isShuffleMaskConsecutive(SVOp,
4652 NumZeros, // Mask Start Index
4653 NumElems-1, // Mask End Index
4654 0, // Where to start looking in the src vector
4655 NumElems, // Number of elements in vector
4656 OpSrc)) // Which source operand ?
4661 ShVal = SVOp->getOperand(OpSrc);
4665 /// isVectorShift - Returns true if the shuffle can be implemented as a
4666 /// logical left or right shift of a vector.
4667 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4668 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4669 // Although the logic below support any bitwidth size, there are no
4670 // shift instructions which handle more than 128-bit vectors.
4671 if (SVOp->getValueType(0).getSizeInBits() > 128)
4674 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4675 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4681 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4683 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4684 unsigned NumNonZero, unsigned NumZero,
4686 const TargetLowering &TLI) {
4690 DebugLoc dl = Op.getDebugLoc();
4693 for (unsigned i = 0; i < 16; ++i) {
4694 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4695 if (ThisIsNonZero && First) {
4697 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4699 V = DAG.getUNDEF(MVT::v8i16);
4704 SDValue ThisElt(0, 0), LastElt(0, 0);
4705 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4706 if (LastIsNonZero) {
4707 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4708 MVT::i16, Op.getOperand(i-1));
4710 if (ThisIsNonZero) {
4711 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4712 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4713 ThisElt, DAG.getConstant(8, MVT::i8));
4715 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4719 if (ThisElt.getNode())
4720 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4721 DAG.getIntPtrConstant(i/2));
4725 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4728 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4730 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4731 unsigned NumNonZero, unsigned NumZero,
4733 const TargetLowering &TLI) {
4737 DebugLoc dl = Op.getDebugLoc();
4740 for (unsigned i = 0; i < 8; ++i) {
4741 bool isNonZero = (NonZeros & (1 << i)) != 0;
4745 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4747 V = DAG.getUNDEF(MVT::v8i16);
4750 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4751 MVT::v8i16, V, Op.getOperand(i),
4752 DAG.getIntPtrConstant(i));
4759 /// getVShift - Return a vector logical shift node.
4761 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4762 unsigned NumBits, SelectionDAG &DAG,
4763 const TargetLowering &TLI, DebugLoc dl) {
4764 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4765 EVT ShVT = MVT::v2i64;
4766 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4767 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4768 return DAG.getNode(ISD::BITCAST, dl, VT,
4769 DAG.getNode(Opc, dl, ShVT, SrcOp,
4770 DAG.getConstant(NumBits,
4771 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4775 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4776 SelectionDAG &DAG) const {
4778 // Check if the scalar load can be widened into a vector load. And if
4779 // the address is "base + cst" see if the cst can be "absorbed" into
4780 // the shuffle mask.
4781 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4782 SDValue Ptr = LD->getBasePtr();
4783 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4785 EVT PVT = LD->getValueType(0);
4786 if (PVT != MVT::i32 && PVT != MVT::f32)
4791 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4792 FI = FINode->getIndex();
4794 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4795 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4796 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4797 Offset = Ptr.getConstantOperandVal(1);
4798 Ptr = Ptr.getOperand(0);
4803 // FIXME: 256-bit vector instructions don't require a strict alignment,
4804 // improve this code to support it better.
4805 unsigned RequiredAlign = VT.getSizeInBits()/8;
4806 SDValue Chain = LD->getChain();
4807 // Make sure the stack object alignment is at least 16 or 32.
4808 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4809 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4810 if (MFI->isFixedObjectIndex(FI)) {
4811 // Can't change the alignment. FIXME: It's possible to compute
4812 // the exact stack offset and reference FI + adjust offset instead.
4813 // If someone *really* cares about this. That's the way to implement it.
4816 MFI->setObjectAlignment(FI, RequiredAlign);
4820 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4821 // Ptr + (Offset & ~15).
4824 if ((Offset % RequiredAlign) & 3)
4826 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4828 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4829 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4831 int EltNo = (Offset - StartOffset) >> 2;
4832 int NumElems = VT.getVectorNumElements();
4834 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4835 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4836 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4837 LD->getPointerInfo().getWithOffset(StartOffset),
4838 false, false, false, 0);
4840 // Canonicalize it to a v4i32 or v8i32 shuffle.
4841 SmallVector<int, 8> Mask;
4842 for (int i = 0; i < NumElems; ++i)
4843 Mask.push_back(EltNo);
4845 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4846 return DAG.getNode(ISD::BITCAST, dl, NVT,
4847 DAG.getVectorShuffle(CanonVT, dl, V1,
4848 DAG.getUNDEF(CanonVT),&Mask[0]));
4854 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4855 /// vector of type 'VT', see if the elements can be replaced by a single large
4856 /// load which has the same value as a build_vector whose operands are 'elts'.
4858 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4860 /// FIXME: we'd also like to handle the case where the last elements are zero
4861 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4862 /// There's even a handy isZeroNode for that purpose.
4863 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4864 DebugLoc &DL, SelectionDAG &DAG) {
4865 EVT EltVT = VT.getVectorElementType();
4866 unsigned NumElems = Elts.size();
4868 LoadSDNode *LDBase = NULL;
4869 unsigned LastLoadedElt = -1U;
4871 // For each element in the initializer, see if we've found a load or an undef.
4872 // If we don't find an initial load element, or later load elements are
4873 // non-consecutive, bail out.
4874 for (unsigned i = 0; i < NumElems; ++i) {
4875 SDValue Elt = Elts[i];
4877 if (!Elt.getNode() ||
4878 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4881 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4883 LDBase = cast<LoadSDNode>(Elt.getNode());
4887 if (Elt.getOpcode() == ISD::UNDEF)
4890 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4891 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4896 // If we have found an entire vector of loads and undefs, then return a large
4897 // load of the entire vector width starting at the base pointer. If we found
4898 // consecutive loads for the low half, generate a vzext_load node.
4899 if (LastLoadedElt == NumElems - 1) {
4900 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4901 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4902 LDBase->getPointerInfo(),
4903 LDBase->isVolatile(), LDBase->isNonTemporal(),
4904 LDBase->isInvariant(), 0);
4905 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4906 LDBase->getPointerInfo(),
4907 LDBase->isVolatile(), LDBase->isNonTemporal(),
4908 LDBase->isInvariant(), LDBase->getAlignment());
4909 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4910 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4911 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4912 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4914 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4915 LDBase->getPointerInfo(),
4916 LDBase->getAlignment(),
4917 false/*isVolatile*/, true/*ReadMem*/,
4919 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4924 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4925 /// a vbroadcast node. We support two patterns:
4926 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4927 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4929 /// The scalar load node is returned when a pattern is found,
4930 /// or SDValue() otherwise.
4931 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4932 EVT VT = Op.getValueType();
4935 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4936 V = V.getOperand(0);
4938 //A suspected load to be broadcasted.
4941 switch (V.getOpcode()) {
4943 // Unknown pattern found.
4946 case ISD::BUILD_VECTOR: {
4947 // The BUILD_VECTOR node must be a splat.
4948 if (!isSplatVector(V.getNode()))
4951 Ld = V.getOperand(0);
4953 // The suspected load node has several users. Make sure that all
4954 // of its users are from the BUILD_VECTOR node.
4955 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4960 case ISD::VECTOR_SHUFFLE: {
4961 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4963 // Shuffles must have a splat mask where the first element is
4965 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4968 SDValue Sc = Op.getOperand(0);
4969 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4972 Ld = Sc.getOperand(0);
4974 // The scalar_to_vector node and the suspected
4975 // load node must have exactly one user.
4976 if (!Sc.hasOneUse() || !Ld.hasOneUse())
4982 // The scalar source must be a normal load.
4983 if (!ISD::isNormalLoad(Ld.getNode()))
4986 bool Is256 = VT.getSizeInBits() == 256;
4987 bool Is128 = VT.getSizeInBits() == 128;
4988 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4991 // VBroadcast to YMM
4992 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
4993 ScalarSize == 32 || ScalarSize == 64 ))
4996 // VBroadcast to XMM
4997 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
4998 ScalarSize == 16 || ScalarSize == 64 ))
5002 // VBroadcast to YMM
5003 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5006 // VBroadcast to XMM
5007 if (Is128 && (ScalarSize == 32))
5011 // Unsupported broadcast.
5016 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5017 DebugLoc dl = Op.getDebugLoc();
5019 EVT VT = Op.getValueType();
5020 EVT ExtVT = VT.getVectorElementType();
5021 unsigned NumElems = Op.getNumOperands();
5023 // Vectors containing all zeros can be matched by pxor and xorps later
5024 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5025 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5026 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5027 if (Op.getValueType() == MVT::v4i32 ||
5028 Op.getValueType() == MVT::v8i32)
5031 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5034 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5035 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5036 // vpcmpeqd on 256-bit vectors.
5037 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5038 if (Op.getValueType() == MVT::v4i32 ||
5039 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5042 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5045 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5046 if (Subtarget->hasAVX() && LD.getNode())
5047 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5049 unsigned EVTBits = ExtVT.getSizeInBits();
5051 unsigned NumZero = 0;
5052 unsigned NumNonZero = 0;
5053 unsigned NonZeros = 0;
5054 bool IsAllConstants = true;
5055 SmallSet<SDValue, 8> Values;
5056 for (unsigned i = 0; i < NumElems; ++i) {
5057 SDValue Elt = Op.getOperand(i);
5058 if (Elt.getOpcode() == ISD::UNDEF)
5061 if (Elt.getOpcode() != ISD::Constant &&
5062 Elt.getOpcode() != ISD::ConstantFP)
5063 IsAllConstants = false;
5064 if (X86::isZeroNode(Elt))
5067 NonZeros |= (1 << i);
5072 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5073 if (NumNonZero == 0)
5074 return DAG.getUNDEF(VT);
5076 // Special case for single non-zero, non-undef, element.
5077 if (NumNonZero == 1) {
5078 unsigned Idx = CountTrailingZeros_32(NonZeros);
5079 SDValue Item = Op.getOperand(Idx);
5081 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5082 // the value are obviously zero, truncate the value to i32 and do the
5083 // insertion that way. Only do this if the value is non-constant or if the
5084 // value is a constant being inserted into element 0. It is cheaper to do
5085 // a constant pool load than it is to do a movd + shuffle.
5086 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5087 (!IsAllConstants || Idx == 0)) {
5088 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5090 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5091 EVT VecVT = MVT::v4i32;
5092 unsigned VecElts = 4;
5094 // Truncate the value (which may itself be a constant) to i32, and
5095 // convert it to a vector with movd (S2V+shuffle to zero extend).
5096 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5097 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5098 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5099 Subtarget->hasXMMInt(), DAG);
5101 // Now we have our 32-bit value zero extended in the low element of
5102 // a vector. If Idx != 0, swizzle it into place.
5104 SmallVector<int, 4> Mask;
5105 Mask.push_back(Idx);
5106 for (unsigned i = 1; i != VecElts; ++i)
5108 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5109 DAG.getUNDEF(Item.getValueType()),
5112 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5116 // If we have a constant or non-constant insertion into the low element of
5117 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5118 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5119 // depending on what the source datatype is.
5122 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5123 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5124 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5125 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5126 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5127 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5129 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5130 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5131 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5132 EVT MiddleVT = MVT::v4i32;
5133 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5134 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5135 Subtarget->hasXMMInt(), DAG);
5136 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5140 // Is it a vector logical left shift?
5141 if (NumElems == 2 && Idx == 1 &&
5142 X86::isZeroNode(Op.getOperand(0)) &&
5143 !X86::isZeroNode(Op.getOperand(1))) {
5144 unsigned NumBits = VT.getSizeInBits();
5145 return getVShift(true, VT,
5146 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5147 VT, Op.getOperand(1)),
5148 NumBits/2, DAG, *this, dl);
5151 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5154 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5155 // is a non-constant being inserted into an element other than the low one,
5156 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5157 // movd/movss) to move this into the low element, then shuffle it into
5159 if (EVTBits == 32) {
5160 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5162 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5163 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5164 Subtarget->hasXMMInt(), DAG);
5165 SmallVector<int, 8> MaskVec;
5166 for (unsigned i = 0; i < NumElems; i++)
5167 MaskVec.push_back(i == Idx ? 0 : 1);
5168 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5172 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5173 if (Values.size() == 1) {
5174 if (EVTBits == 32) {
5175 // Instead of a shuffle like this:
5176 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5177 // Check if it's possible to issue this instead.
5178 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5179 unsigned Idx = CountTrailingZeros_32(NonZeros);
5180 SDValue Item = Op.getOperand(Idx);
5181 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5182 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5187 // A vector full of immediates; various special cases are already
5188 // handled, so this is best done with a single constant-pool load.
5192 // For AVX-length vectors, build the individual 128-bit pieces and use
5193 // shuffles to put them in place.
5194 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5195 SmallVector<SDValue, 32> V;
5196 for (unsigned i = 0; i < NumElems; ++i)
5197 V.push_back(Op.getOperand(i));
5199 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5201 // Build both the lower and upper subvector.
5202 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5203 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5206 // Recreate the wider vector with the lower and upper part.
5207 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5208 DAG.getConstant(0, MVT::i32), DAG, dl);
5209 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5213 // Let legalizer expand 2-wide build_vectors.
5214 if (EVTBits == 64) {
5215 if (NumNonZero == 1) {
5216 // One half is zero or undef.
5217 unsigned Idx = CountTrailingZeros_32(NonZeros);
5218 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5219 Op.getOperand(Idx));
5220 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5221 Subtarget->hasXMMInt(), DAG);
5226 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5227 if (EVTBits == 8 && NumElems == 16) {
5228 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5230 if (V.getNode()) return V;
5233 if (EVTBits == 16 && NumElems == 8) {
5234 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5236 if (V.getNode()) return V;
5239 // If element VT is == 32 bits, turn it into a number of shuffles.
5240 SmallVector<SDValue, 8> V;
5242 if (NumElems == 4 && NumZero > 0) {
5243 for (unsigned i = 0; i < 4; ++i) {
5244 bool isZero = !(NonZeros & (1 << i));
5246 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5248 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5251 for (unsigned i = 0; i < 2; ++i) {
5252 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5255 V[i] = V[i*2]; // Must be a zero vector.
5258 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5261 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5264 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5269 SmallVector<int, 8> MaskVec;
5270 bool Reverse = (NonZeros & 0x3) == 2;
5271 for (unsigned i = 0; i < 2; ++i)
5272 MaskVec.push_back(Reverse ? 1-i : i);
5273 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5274 for (unsigned i = 0; i < 2; ++i)
5275 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5276 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5279 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5280 // Check for a build vector of consecutive loads.
5281 for (unsigned i = 0; i < NumElems; ++i)
5282 V[i] = Op.getOperand(i);
5284 // Check for elements which are consecutive loads.
5285 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5289 // For SSE 4.1, use insertps to put the high elements into the low element.
5290 if (getSubtarget()->hasSSE41orAVX()) {
5292 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5293 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5295 Result = DAG.getUNDEF(VT);
5297 for (unsigned i = 1; i < NumElems; ++i) {
5298 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5299 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5300 Op.getOperand(i), DAG.getIntPtrConstant(i));
5305 // Otherwise, expand into a number of unpckl*, start by extending each of
5306 // our (non-undef) elements to the full vector width with the element in the
5307 // bottom slot of the vector (which generates no code for SSE).
5308 for (unsigned i = 0; i < NumElems; ++i) {
5309 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5310 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5312 V[i] = DAG.getUNDEF(VT);
5315 // Next, we iteratively mix elements, e.g. for v4f32:
5316 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5317 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5318 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5319 unsigned EltStride = NumElems >> 1;
5320 while (EltStride != 0) {
5321 for (unsigned i = 0; i < EltStride; ++i) {
5322 // If V[i+EltStride] is undef and this is the first round of mixing,
5323 // then it is safe to just drop this shuffle: V[i] is already in the
5324 // right place, the one element (since it's the first round) being
5325 // inserted as undef can be dropped. This isn't safe for successive
5326 // rounds because they will permute elements within both vectors.
5327 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5328 EltStride == NumElems/2)
5331 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5340 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5341 // them in a MMX register. This is better than doing a stack convert.
5342 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5343 DebugLoc dl = Op.getDebugLoc();
5344 EVT ResVT = Op.getValueType();
5346 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5347 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5349 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5350 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5351 InVec = Op.getOperand(1);
5352 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5353 unsigned NumElts = ResVT.getVectorNumElements();
5354 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5355 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5356 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5358 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5359 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5360 Mask[0] = 0; Mask[1] = 2;
5361 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5363 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5366 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5367 // to create 256-bit vectors from two other 128-bit ones.
5368 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5369 DebugLoc dl = Op.getDebugLoc();
5370 EVT ResVT = Op.getValueType();
5372 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5374 SDValue V1 = Op.getOperand(0);
5375 SDValue V2 = Op.getOperand(1);
5376 unsigned NumElems = ResVT.getVectorNumElements();
5378 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5379 DAG.getConstant(0, MVT::i32), DAG, dl);
5380 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5385 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5386 EVT ResVT = Op.getValueType();
5388 assert(Op.getNumOperands() == 2);
5389 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5390 "Unsupported CONCAT_VECTORS for value type");
5392 // We support concatenate two MMX registers and place them in a MMX register.
5393 // This is better than doing a stack convert.
5394 if (ResVT.is128BitVector())
5395 return LowerMMXCONCAT_VECTORS(Op, DAG);
5397 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5398 // from two other 128-bit ones.
5399 return LowerAVXCONCAT_VECTORS(Op, DAG);
5402 // v8i16 shuffles - Prefer shuffles in the following order:
5403 // 1. [all] pshuflw, pshufhw, optional move
5404 // 2. [ssse3] 1 x pshufb
5405 // 3. [ssse3] 2 x pshufb + 1 x por
5406 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5408 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5409 SelectionDAG &DAG) const {
5410 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5411 SDValue V1 = SVOp->getOperand(0);
5412 SDValue V2 = SVOp->getOperand(1);
5413 DebugLoc dl = SVOp->getDebugLoc();
5414 SmallVector<int, 8> MaskVals;
5416 // Determine if more than 1 of the words in each of the low and high quadwords
5417 // of the result come from the same quadword of one of the two inputs. Undef
5418 // mask values count as coming from any quadword, for better codegen.
5419 unsigned LoQuad[] = { 0, 0, 0, 0 };
5420 unsigned HiQuad[] = { 0, 0, 0, 0 };
5421 BitVector InputQuads(4);
5422 for (unsigned i = 0; i < 8; ++i) {
5423 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5424 int EltIdx = SVOp->getMaskElt(i);
5425 MaskVals.push_back(EltIdx);
5434 InputQuads.set(EltIdx / 4);
5437 int BestLoQuad = -1;
5438 unsigned MaxQuad = 1;
5439 for (unsigned i = 0; i < 4; ++i) {
5440 if (LoQuad[i] > MaxQuad) {
5442 MaxQuad = LoQuad[i];
5446 int BestHiQuad = -1;
5448 for (unsigned i = 0; i < 4; ++i) {
5449 if (HiQuad[i] > MaxQuad) {
5451 MaxQuad = HiQuad[i];
5455 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5456 // of the two input vectors, shuffle them into one input vector so only a
5457 // single pshufb instruction is necessary. If There are more than 2 input
5458 // quads, disable the next transformation since it does not help SSSE3.
5459 bool V1Used = InputQuads[0] || InputQuads[1];
5460 bool V2Used = InputQuads[2] || InputQuads[3];
5461 if (Subtarget->hasSSSE3orAVX()) {
5462 if (InputQuads.count() == 2 && V1Used && V2Used) {
5463 BestLoQuad = InputQuads.find_first();
5464 BestHiQuad = InputQuads.find_next(BestLoQuad);
5466 if (InputQuads.count() > 2) {
5472 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5473 // the shuffle mask. If a quad is scored as -1, that means that it contains
5474 // words from all 4 input quadwords.
5476 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5477 SmallVector<int, 8> MaskV;
5478 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5479 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5480 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5481 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5482 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5483 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5485 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5486 // source words for the shuffle, to aid later transformations.
5487 bool AllWordsInNewV = true;
5488 bool InOrder[2] = { true, true };
5489 for (unsigned i = 0; i != 8; ++i) {
5490 int idx = MaskVals[i];
5492 InOrder[i/4] = false;
5493 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5495 AllWordsInNewV = false;
5499 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5500 if (AllWordsInNewV) {
5501 for (int i = 0; i != 8; ++i) {
5502 int idx = MaskVals[i];
5505 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5506 if ((idx != i) && idx < 4)
5508 if ((idx != i) && idx > 3)
5517 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5518 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5519 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5520 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5521 unsigned TargetMask = 0;
5522 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5523 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5524 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5525 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5526 V1 = NewV.getOperand(0);
5527 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5531 // If we have SSSE3, and all words of the result are from 1 input vector,
5532 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5533 // is present, fall back to case 4.
5534 if (Subtarget->hasSSSE3orAVX()) {
5535 SmallVector<SDValue,16> pshufbMask;
5537 // If we have elements from both input vectors, set the high bit of the
5538 // shuffle mask element to zero out elements that come from V2 in the V1
5539 // mask, and elements that come from V1 in the V2 mask, so that the two
5540 // results can be OR'd together.
5541 bool TwoInputs = V1Used && V2Used;
5542 for (unsigned i = 0; i != 8; ++i) {
5543 int EltIdx = MaskVals[i] * 2;
5544 if (TwoInputs && (EltIdx >= 16)) {
5545 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5546 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5549 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5550 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5552 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5553 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5554 DAG.getNode(ISD::BUILD_VECTOR, dl,
5555 MVT::v16i8, &pshufbMask[0], 16));
5557 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5559 // Calculate the shuffle mask for the second input, shuffle it, and
5560 // OR it with the first shuffled input.
5562 for (unsigned i = 0; i != 8; ++i) {
5563 int EltIdx = MaskVals[i] * 2;
5565 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5566 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5569 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5570 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5572 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5573 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5574 DAG.getNode(ISD::BUILD_VECTOR, dl,
5575 MVT::v16i8, &pshufbMask[0], 16));
5576 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5577 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5580 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5581 // and update MaskVals with new element order.
5582 BitVector InOrder(8);
5583 if (BestLoQuad >= 0) {
5584 SmallVector<int, 8> MaskV;
5585 for (int i = 0; i != 4; ++i) {
5586 int idx = MaskVals[i];
5588 MaskV.push_back(-1);
5590 } else if ((idx / 4) == BestLoQuad) {
5591 MaskV.push_back(idx & 3);
5594 MaskV.push_back(-1);
5597 for (unsigned i = 4; i != 8; ++i)
5599 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5602 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5603 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5605 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5609 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5610 // and update MaskVals with the new element order.
5611 if (BestHiQuad >= 0) {
5612 SmallVector<int, 8> MaskV;
5613 for (unsigned i = 0; i != 4; ++i)
5615 for (unsigned i = 4; i != 8; ++i) {
5616 int idx = MaskVals[i];
5618 MaskV.push_back(-1);
5620 } else if ((idx / 4) == BestHiQuad) {
5621 MaskV.push_back((idx & 3) + 4);
5624 MaskV.push_back(-1);
5627 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5630 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5631 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5633 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5637 // In case BestHi & BestLo were both -1, which means each quadword has a word
5638 // from each of the four input quadwords, calculate the InOrder bitvector now
5639 // before falling through to the insert/extract cleanup.
5640 if (BestLoQuad == -1 && BestHiQuad == -1) {
5642 for (int i = 0; i != 8; ++i)
5643 if (MaskVals[i] < 0 || MaskVals[i] == i)
5647 // The other elements are put in the right place using pextrw and pinsrw.
5648 for (unsigned i = 0; i != 8; ++i) {
5651 int EltIdx = MaskVals[i];
5654 SDValue ExtOp = (EltIdx < 8)
5655 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5656 DAG.getIntPtrConstant(EltIdx))
5657 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5658 DAG.getIntPtrConstant(EltIdx - 8));
5659 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5660 DAG.getIntPtrConstant(i));
5665 // v16i8 shuffles - Prefer shuffles in the following order:
5666 // 1. [ssse3] 1 x pshufb
5667 // 2. [ssse3] 2 x pshufb + 1 x por
5668 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5670 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5672 const X86TargetLowering &TLI) {
5673 SDValue V1 = SVOp->getOperand(0);
5674 SDValue V2 = SVOp->getOperand(1);
5675 DebugLoc dl = SVOp->getDebugLoc();
5676 SmallVector<int, 16> MaskVals;
5677 SVOp->getMask(MaskVals);
5679 // If we have SSSE3, case 1 is generated when all result bytes come from
5680 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5681 // present, fall back to case 3.
5682 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5685 for (unsigned i = 0; i < 16; ++i) {
5686 int EltIdx = MaskVals[i];
5695 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5696 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5697 SmallVector<SDValue,16> pshufbMask;
5699 // If all result elements are from one input vector, then only translate
5700 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5702 // Otherwise, we have elements from both input vectors, and must zero out
5703 // elements that come from V2 in the first mask, and V1 in the second mask
5704 // so that we can OR them together.
5705 bool TwoInputs = !(V1Only || V2Only);
5706 for (unsigned i = 0; i != 16; ++i) {
5707 int EltIdx = MaskVals[i];
5708 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5709 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5712 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5714 // If all the elements are from V2, assign it to V1 and return after
5715 // building the first pshufb.
5718 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5719 DAG.getNode(ISD::BUILD_VECTOR, dl,
5720 MVT::v16i8, &pshufbMask[0], 16));
5724 // Calculate the shuffle mask for the second input, shuffle it, and
5725 // OR it with the first shuffled input.
5727 for (unsigned i = 0; i != 16; ++i) {
5728 int EltIdx = MaskVals[i];
5730 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5733 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5735 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5736 DAG.getNode(ISD::BUILD_VECTOR, dl,
5737 MVT::v16i8, &pshufbMask[0], 16));
5738 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5741 // No SSSE3 - Calculate in place words and then fix all out of place words
5742 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5743 // the 16 different words that comprise the two doublequadword input vectors.
5744 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5745 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5746 SDValue NewV = V2Only ? V2 : V1;
5747 for (int i = 0; i != 8; ++i) {
5748 int Elt0 = MaskVals[i*2];
5749 int Elt1 = MaskVals[i*2+1];
5751 // This word of the result is all undef, skip it.
5752 if (Elt0 < 0 && Elt1 < 0)
5755 // This word of the result is already in the correct place, skip it.
5756 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5758 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5761 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5762 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5765 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5766 // using a single extract together, load it and store it.
5767 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5768 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5769 DAG.getIntPtrConstant(Elt1 / 2));
5770 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5771 DAG.getIntPtrConstant(i));
5775 // If Elt1 is defined, extract it from the appropriate source. If the
5776 // source byte is not also odd, shift the extracted word left 8 bits
5777 // otherwise clear the bottom 8 bits if we need to do an or.
5779 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5780 DAG.getIntPtrConstant(Elt1 / 2));
5781 if ((Elt1 & 1) == 0)
5782 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5784 TLI.getShiftAmountTy(InsElt.getValueType())));
5786 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5787 DAG.getConstant(0xFF00, MVT::i16));
5789 // If Elt0 is defined, extract it from the appropriate source. If the
5790 // source byte is not also even, shift the extracted word right 8 bits. If
5791 // Elt1 was also defined, OR the extracted values together before
5792 // inserting them in the result.
5794 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5795 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5796 if ((Elt0 & 1) != 0)
5797 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5799 TLI.getShiftAmountTy(InsElt0.getValueType())));
5801 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5802 DAG.getConstant(0x00FF, MVT::i16));
5803 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5806 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5807 DAG.getIntPtrConstant(i));
5809 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5812 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5813 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5814 /// done when every pair / quad of shuffle mask elements point to elements in
5815 /// the right sequence. e.g.
5816 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5818 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5819 SelectionDAG &DAG, DebugLoc dl) {
5820 EVT VT = SVOp->getValueType(0);
5821 SDValue V1 = SVOp->getOperand(0);
5822 SDValue V2 = SVOp->getOperand(1);
5823 unsigned NumElems = VT.getVectorNumElements();
5824 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5826 switch (VT.getSimpleVT().SimpleTy) {
5827 default: assert(false && "Unexpected!");
5828 case MVT::v4f32: NewVT = MVT::v2f64; break;
5829 case MVT::v4i32: NewVT = MVT::v2i64; break;
5830 case MVT::v8i16: NewVT = MVT::v4i32; break;
5831 case MVT::v16i8: NewVT = MVT::v4i32; break;
5834 int Scale = NumElems / NewWidth;
5835 SmallVector<int, 8> MaskVec;
5836 for (unsigned i = 0; i < NumElems; i += Scale) {
5838 for (int j = 0; j < Scale; ++j) {
5839 int EltIdx = SVOp->getMaskElt(i+j);
5843 StartIdx = EltIdx - (EltIdx % Scale);
5844 if (EltIdx != StartIdx + j)
5848 MaskVec.push_back(-1);
5850 MaskVec.push_back(StartIdx / Scale);
5853 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5854 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5855 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5858 /// getVZextMovL - Return a zero-extending vector move low node.
5860 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5861 SDValue SrcOp, SelectionDAG &DAG,
5862 const X86Subtarget *Subtarget, DebugLoc dl) {
5863 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5864 LoadSDNode *LD = NULL;
5865 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5866 LD = dyn_cast<LoadSDNode>(SrcOp);
5868 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5870 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5871 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5872 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5873 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5874 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5876 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5877 return DAG.getNode(ISD::BITCAST, dl, VT,
5878 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5879 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5887 return DAG.getNode(ISD::BITCAST, dl, VT,
5888 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5889 DAG.getNode(ISD::BITCAST, dl,
5893 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5894 /// shuffle node referes to only one lane in the sources.
5895 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5896 EVT VT = SVOp->getValueType(0);
5897 int NumElems = VT.getVectorNumElements();
5898 int HalfSize = NumElems/2;
5899 SmallVector<int, 16> M;
5901 bool MatchA = false, MatchB = false;
5903 for (int l = 0; l < NumElems*2; l += HalfSize) {
5904 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5910 for (int l = 0; l < NumElems*2; l += HalfSize) {
5911 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5917 return MatchA && MatchB;
5920 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5921 /// which could not be matched by any known target speficic shuffle
5923 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5924 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5925 // If each half of a vector shuffle node referes to only one lane in the
5926 // source vectors, extract each used 128-bit lane and shuffle them using
5927 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5928 // the work to the legalizer.
5929 DebugLoc dl = SVOp->getDebugLoc();
5930 EVT VT = SVOp->getValueType(0);
5931 int NumElems = VT.getVectorNumElements();
5932 int HalfSize = NumElems/2;
5934 // Extract the reference for each half
5935 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5936 int FstVecOpNum = 0, SndVecOpNum = 0;
5937 for (int i = 0; i < HalfSize; ++i) {
5938 int Elt = SVOp->getMaskElt(i);
5939 if (SVOp->getMaskElt(i) < 0)
5941 FstVecOpNum = Elt/NumElems;
5942 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5945 for (int i = HalfSize; i < NumElems; ++i) {
5946 int Elt = SVOp->getMaskElt(i);
5947 if (SVOp->getMaskElt(i) < 0)
5949 SndVecOpNum = Elt/NumElems;
5950 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5954 // Extract the subvectors
5955 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5956 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5957 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5958 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5960 // Generate 128-bit shuffles
5961 SmallVector<int, 16> MaskV1, MaskV2;
5962 for (int i = 0; i < HalfSize; ++i) {
5963 int Elt = SVOp->getMaskElt(i);
5964 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5966 for (int i = HalfSize; i < NumElems; ++i) {
5967 int Elt = SVOp->getMaskElt(i);
5968 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5971 EVT NVT = V1.getValueType();
5972 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5973 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5975 // Concatenate the result back
5976 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5977 DAG.getConstant(0, MVT::i32), DAG, dl);
5978 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5985 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5986 /// 4 elements, and match them with several different shuffle types.
5988 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5989 SDValue V1 = SVOp->getOperand(0);
5990 SDValue V2 = SVOp->getOperand(1);
5991 DebugLoc dl = SVOp->getDebugLoc();
5992 EVT VT = SVOp->getValueType(0);
5994 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5996 SmallVector<std::pair<int, int>, 8> Locs;
5998 SmallVector<int, 8> Mask1(4U, -1);
5999 SmallVector<int, 8> PermMask;
6000 SVOp->getMask(PermMask);
6004 for (unsigned i = 0; i != 4; ++i) {
6005 int Idx = PermMask[i];
6007 Locs[i] = std::make_pair(-1, -1);
6009 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6011 Locs[i] = std::make_pair(0, NumLo);
6015 Locs[i] = std::make_pair(1, NumHi);
6017 Mask1[2+NumHi] = Idx;
6023 if (NumLo <= 2 && NumHi <= 2) {
6024 // If no more than two elements come from either vector. This can be
6025 // implemented with two shuffles. First shuffle gather the elements.
6026 // The second shuffle, which takes the first shuffle as both of its
6027 // vector operands, put the elements into the right order.
6028 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6030 SmallVector<int, 8> Mask2(4U, -1);
6032 for (unsigned i = 0; i != 4; ++i) {
6033 if (Locs[i].first == -1)
6036 unsigned Idx = (i < 2) ? 0 : 4;
6037 Idx += Locs[i].first * 2 + Locs[i].second;
6042 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6043 } else if (NumLo == 3 || NumHi == 3) {
6044 // Otherwise, we must have three elements from one vector, call it X, and
6045 // one element from the other, call it Y. First, use a shufps to build an
6046 // intermediate vector with the one element from Y and the element from X
6047 // that will be in the same half in the final destination (the indexes don't
6048 // matter). Then, use a shufps to build the final vector, taking the half
6049 // containing the element from Y from the intermediate, and the other half
6052 // Normalize it so the 3 elements come from V1.
6053 CommuteVectorShuffleMask(PermMask, 4);
6057 // Find the element from V2.
6059 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6060 int Val = PermMask[HiIndex];
6067 Mask1[0] = PermMask[HiIndex];
6069 Mask1[2] = PermMask[HiIndex^1];
6071 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6074 Mask1[0] = PermMask[0];
6075 Mask1[1] = PermMask[1];
6076 Mask1[2] = HiIndex & 1 ? 6 : 4;
6077 Mask1[3] = HiIndex & 1 ? 4 : 6;
6078 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6080 Mask1[0] = HiIndex & 1 ? 2 : 0;
6081 Mask1[1] = HiIndex & 1 ? 0 : 2;
6082 Mask1[2] = PermMask[2];
6083 Mask1[3] = PermMask[3];
6088 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6092 // Break it into (shuffle shuffle_hi, shuffle_lo).
6095 SmallVector<int,8> LoMask(4U, -1);
6096 SmallVector<int,8> HiMask(4U, -1);
6098 SmallVector<int,8> *MaskPtr = &LoMask;
6099 unsigned MaskIdx = 0;
6102 for (unsigned i = 0; i != 4; ++i) {
6109 int Idx = PermMask[i];
6111 Locs[i] = std::make_pair(-1, -1);
6112 } else if (Idx < 4) {
6113 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6114 (*MaskPtr)[LoIdx] = Idx;
6117 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6118 (*MaskPtr)[HiIdx] = Idx;
6123 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6124 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6125 SmallVector<int, 8> MaskOps;
6126 for (unsigned i = 0; i != 4; ++i) {
6127 if (Locs[i].first == -1) {
6128 MaskOps.push_back(-1);
6130 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6131 MaskOps.push_back(Idx);
6134 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6137 static bool MayFoldVectorLoad(SDValue V) {
6138 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6139 V = V.getOperand(0);
6140 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6141 V = V.getOperand(0);
6142 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6143 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6144 // BUILD_VECTOR (load), undef
6145 V = V.getOperand(0);
6151 // FIXME: the version above should always be used. Since there's
6152 // a bug where several vector shuffles can't be folded because the
6153 // DAG is not updated during lowering and a node claims to have two
6154 // uses while it only has one, use this version, and let isel match
6155 // another instruction if the load really happens to have more than
6156 // one use. Remove this version after this bug get fixed.
6157 // rdar://8434668, PR8156
6158 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6159 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6160 V = V.getOperand(0);
6161 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6162 V = V.getOperand(0);
6163 if (ISD::isNormalLoad(V.getNode()))
6168 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6169 /// a vector extract, and if both can be later optimized into a single load.
6170 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6171 /// here because otherwise a target specific shuffle node is going to be
6172 /// emitted for this shuffle, and the optimization not done.
6173 /// FIXME: This is probably not the best approach, but fix the problem
6174 /// until the right path is decided.
6176 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6177 const TargetLowering &TLI) {
6178 EVT VT = V.getValueType();
6179 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6181 // Be sure that the vector shuffle is present in a pattern like this:
6182 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6186 SDNode *N = *V.getNode()->use_begin();
6187 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6190 SDValue EltNo = N->getOperand(1);
6191 if (!isa<ConstantSDNode>(EltNo))
6194 // If the bit convert changed the number of elements, it is unsafe
6195 // to examine the mask.
6196 bool HasShuffleIntoBitcast = false;
6197 if (V.getOpcode() == ISD::BITCAST) {
6198 EVT SrcVT = V.getOperand(0).getValueType();
6199 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6201 V = V.getOperand(0);
6202 HasShuffleIntoBitcast = true;
6205 // Select the input vector, guarding against out of range extract vector.
6206 unsigned NumElems = VT.getVectorNumElements();
6207 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6208 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6209 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6211 // Skip one more bit_convert if necessary
6212 if (V.getOpcode() == ISD::BITCAST)
6213 V = V.getOperand(0);
6215 if (ISD::isNormalLoad(V.getNode())) {
6216 // Is the original load suitable?
6217 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6219 // FIXME: avoid the multi-use bug that is preventing lots of
6220 // of foldings to be detected, this is still wrong of course, but
6221 // give the temporary desired behavior, and if it happens that
6222 // the load has real more uses, during isel it will not fold, and
6223 // will generate poor code.
6224 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6227 if (!HasShuffleIntoBitcast)
6230 // If there's a bitcast before the shuffle, check if the load type and
6231 // alignment is valid.
6232 unsigned Align = LN0->getAlignment();
6234 TLI.getTargetData()->getABITypeAlignment(
6235 VT.getTypeForEVT(*DAG.getContext()));
6237 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6245 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6246 EVT VT = Op.getValueType();
6248 // Canonizalize to v2f64.
6249 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6250 return DAG.getNode(ISD::BITCAST, dl, VT,
6251 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6256 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6258 SDValue V1 = Op.getOperand(0);
6259 SDValue V2 = Op.getOperand(1);
6260 EVT VT = Op.getValueType();
6262 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6264 if (HasXMMInt && VT == MVT::v2f64)
6265 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6267 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6268 return DAG.getNode(ISD::BITCAST, dl, VT,
6269 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6270 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6271 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6275 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6276 SDValue V1 = Op.getOperand(0);
6277 SDValue V2 = Op.getOperand(1);
6278 EVT VT = Op.getValueType();
6280 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6281 "unsupported shuffle type");
6283 if (V2.getOpcode() == ISD::UNDEF)
6287 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6290 static inline unsigned getSHUFPOpcode(EVT VT) {
6291 switch(VT.getSimpleVT().SimpleTy) {
6292 case MVT::v8i32: // Use fp unit for int unpack.
6294 case MVT::v4i32: // Use fp unit for int unpack.
6295 case MVT::v4f32: return X86ISD::SHUFPS;
6296 case MVT::v4i64: // Use fp unit for int unpack.
6298 case MVT::v2i64: // Use fp unit for int unpack.
6299 case MVT::v2f64: return X86ISD::SHUFPD;
6301 llvm_unreachable("Unknown type for shufp*");
6307 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6308 SDValue V1 = Op.getOperand(0);
6309 SDValue V2 = Op.getOperand(1);
6310 EVT VT = Op.getValueType();
6311 unsigned NumElems = VT.getVectorNumElements();
6313 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6314 // operand of these instructions is only memory, so check if there's a
6315 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6317 bool CanFoldLoad = false;
6319 // Trivial case, when V2 comes from a load.
6320 if (MayFoldVectorLoad(V2))
6323 // When V1 is a load, it can be folded later into a store in isel, example:
6324 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6326 // (MOVLPSmr addr:$src1, VR128:$src2)
6327 // So, recognize this potential and also use MOVLPS or MOVLPD
6328 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6331 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6333 if (HasXMMInt && NumElems == 2)
6334 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6337 // If we don't care about the second element, procede to use movss.
6338 if (SVOp->getMaskElt(1) != -1)
6339 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6342 // movl and movlp will both match v2i64, but v2i64 is never matched by
6343 // movl earlier because we make it strict to avoid messing with the movlp load
6344 // folding logic (see the code above getMOVLP call). Match it here then,
6345 // this is horrible, but will stay like this until we move all shuffle
6346 // matching to x86 specific nodes. Note that for the 1st condition all
6347 // types are matched with movsd.
6349 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6350 // as to remove this logic from here, as much as possible
6351 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6352 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6353 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6356 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6358 // Invert the operand order and use SHUFPS to match it.
6359 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6360 X86::getShuffleSHUFImmediate(SVOp), DAG);
6364 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6365 const TargetLowering &TLI,
6366 const X86Subtarget *Subtarget) {
6367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6368 EVT VT = Op.getValueType();
6369 DebugLoc dl = Op.getDebugLoc();
6370 SDValue V1 = Op.getOperand(0);
6371 SDValue V2 = Op.getOperand(1);
6373 if (isZeroShuffle(SVOp))
6374 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6376 // Handle splat operations
6377 if (SVOp->isSplat()) {
6378 unsigned NumElem = VT.getVectorNumElements();
6379 int Size = VT.getSizeInBits();
6380 // Special case, this is the only place now where it's allowed to return
6381 // a vector_shuffle operation without using a target specific node, because
6382 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6383 // this be moved to DAGCombine instead?
6384 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6387 // Use vbroadcast whenever the splat comes from a foldable load
6388 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6389 if (Subtarget->hasAVX() && LD.getNode())
6390 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6392 // Handle splats by matching through known shuffle masks
6393 if ((Size == 128 && NumElem <= 4) ||
6394 (Size == 256 && NumElem < 8))
6397 // All remaning splats are promoted to target supported vector shuffles.
6398 return PromoteSplat(SVOp, DAG);
6401 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6403 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6404 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6405 if (NewOp.getNode())
6406 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6407 } else if ((VT == MVT::v4i32 ||
6408 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6409 // FIXME: Figure out a cleaner way to do this.
6410 // Try to make use of movq to zero out the top part.
6411 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6412 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6413 if (NewOp.getNode()) {
6414 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6415 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6416 DAG, Subtarget, dl);
6418 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6419 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6420 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6421 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6422 DAG, Subtarget, dl);
6429 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6430 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6431 SDValue V1 = Op.getOperand(0);
6432 SDValue V2 = Op.getOperand(1);
6433 EVT VT = Op.getValueType();
6434 DebugLoc dl = Op.getDebugLoc();
6435 unsigned NumElems = VT.getVectorNumElements();
6436 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6437 bool V1IsSplat = false;
6438 bool V2IsSplat = false;
6439 bool HasXMMInt = Subtarget->hasXMMInt();
6440 bool HasAVX = Subtarget->hasAVX();
6441 bool HasAVX2 = Subtarget->hasAVX2();
6442 MachineFunction &MF = DAG.getMachineFunction();
6443 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6445 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6447 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6449 // Vector shuffle lowering takes 3 steps:
6451 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6452 // narrowing and commutation of operands should be handled.
6453 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6455 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6456 // so the shuffle can be broken into other shuffles and the legalizer can
6457 // try the lowering again.
6459 // The general idea is that no vector_shuffle operation should be left to
6460 // be matched during isel, all of them must be converted to a target specific
6463 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6464 // narrowing and commutation of operands should be handled. The actual code
6465 // doesn't include all of those, work in progress...
6466 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6467 if (NewOp.getNode())
6470 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6471 // unpckh_undef). Only use pshufd if speed is more important than size.
6472 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6473 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6474 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6475 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6477 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6478 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6479 return getMOVDDup(Op, dl, V1, DAG);
6481 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6482 return getMOVHighToLow(Op, dl, DAG);
6484 // Use to match splats
6485 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6486 (VT == MVT::v2f64 || VT == MVT::v2i64))
6487 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6489 if (X86::isPSHUFDMask(SVOp)) {
6490 // The actual implementation will match the mask in the if above and then
6491 // during isel it can match several different instructions, not only pshufd
6492 // as its name says, sad but true, emulate the behavior for now...
6493 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6494 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6496 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6498 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6499 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6501 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6505 // Check if this can be converted into a logical shift.
6506 bool isLeft = false;
6509 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6510 if (isShift && ShVal.hasOneUse()) {
6511 // If the shifted value has multiple uses, it may be cheaper to use
6512 // v_set0 + movlhps or movhlps, etc.
6513 EVT EltVT = VT.getVectorElementType();
6514 ShAmt *= EltVT.getSizeInBits();
6515 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6518 if (X86::isMOVLMask(SVOp)) {
6519 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6520 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6521 if (!X86::isMOVLPMask(SVOp)) {
6522 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6523 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6525 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6526 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6530 // FIXME: fold these into legal mask.
6531 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6532 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6534 if (X86::isMOVHLPSMask(SVOp))
6535 return getMOVHighToLow(Op, dl, DAG);
6537 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6538 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6540 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6541 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6543 if (X86::isMOVLPMask(SVOp))
6544 return getMOVLP(Op, dl, DAG, HasXMMInt);
6546 if (ShouldXformToMOVHLPS(SVOp) ||
6547 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6548 return CommuteVectorShuffle(SVOp, DAG);
6551 // No better options. Use a vshl / vsrl.
6552 EVT EltVT = VT.getVectorElementType();
6553 ShAmt *= EltVT.getSizeInBits();
6554 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6557 bool Commuted = false;
6558 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6559 // 1,1,1,1 -> v8i16 though.
6560 V1IsSplat = isSplatVector(V1.getNode());
6561 V2IsSplat = isSplatVector(V2.getNode());
6563 // Canonicalize the splat or undef, if present, to be on the RHS.
6564 if (V1IsSplat && !V2IsSplat) {
6565 Op = CommuteVectorShuffle(SVOp, DAG);
6566 SVOp = cast<ShuffleVectorSDNode>(Op);
6567 V1 = SVOp->getOperand(0);
6568 V2 = SVOp->getOperand(1);
6569 std::swap(V1IsSplat, V2IsSplat);
6573 SmallVector<int, 32> M;
6576 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6577 // Shuffling low element of v1 into undef, just return v1.
6580 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6581 // the instruction selector will not match, so get a canonical MOVL with
6582 // swapped operands to undo the commute.
6583 return getMOVL(DAG, dl, VT, V2, V1);
6586 if (isUNPCKLMask(M, VT, HasAVX2))
6587 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6589 if (isUNPCKHMask(M, VT, HasAVX2))
6590 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6593 // Normalize mask so all entries that point to V2 points to its first
6594 // element then try to match unpck{h|l} again. If match, return a
6595 // new vector_shuffle with the corrected mask.
6596 SDValue NewMask = NormalizeMask(SVOp, DAG);
6597 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6598 if (NSVOp != SVOp) {
6599 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6601 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6608 // Commute is back and try unpck* again.
6609 // FIXME: this seems wrong.
6610 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6611 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6613 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6614 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6616 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6617 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6620 // Normalize the node to match x86 shuffle ops if needed
6621 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6622 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6623 return CommuteVectorShuffle(SVOp, DAG);
6625 // The checks below are all present in isShuffleMaskLegal, but they are
6626 // inlined here right now to enable us to directly emit target specific
6627 // nodes, and remove one by one until they don't return Op anymore.
6629 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6630 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6631 getShufflePALIGNRImmediate(SVOp),
6634 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6635 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6636 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6637 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6640 if (isPSHUFHWMask(M, VT))
6641 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6642 X86::getShufflePSHUFHWImmediate(SVOp),
6645 if (isPSHUFLWMask(M, VT))
6646 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6647 X86::getShufflePSHUFLWImmediate(SVOp),
6650 if (isSHUFPMask(M, VT))
6651 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6652 X86::getShuffleSHUFImmediate(SVOp), DAG);
6654 if (isUNPCKL_v_undef_Mask(M, VT))
6655 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6656 if (isUNPCKH_v_undef_Mask(M, VT))
6657 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6659 //===--------------------------------------------------------------------===//
6660 // Generate target specific nodes for 128 or 256-bit shuffles only
6661 // supported in the AVX instruction set.
6664 // Handle VMOVDDUPY permutations
6665 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6666 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6668 // Handle VPERMILPS/D* permutations
6669 if (isVPERMILPMask(M, VT, HasAVX))
6670 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6671 getShuffleVPERMILPImmediate(SVOp), DAG);
6673 // Handle VPERM2F128/VPERM2I128 permutations
6674 if (isVPERM2X128Mask(M, VT, HasAVX))
6675 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6676 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6678 // Handle VSHUFPS/DY permutations
6679 if (isVSHUFPYMask(M, VT, HasAVX))
6680 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6681 getShuffleVSHUFPYImmediate(SVOp), DAG);
6683 //===--------------------------------------------------------------------===//
6684 // Since no target specific shuffle was selected for this generic one,
6685 // lower it into other known shuffles. FIXME: this isn't true yet, but
6686 // this is the plan.
6689 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6690 if (VT == MVT::v8i16) {
6691 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6692 if (NewOp.getNode())
6696 if (VT == MVT::v16i8) {
6697 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6698 if (NewOp.getNode())
6702 // Handle all 128-bit wide vectors with 4 elements, and match them with
6703 // several different shuffle types.
6704 if (NumElems == 4 && VT.getSizeInBits() == 128)
6705 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6707 // Handle general 256-bit shuffles
6708 if (VT.is256BitVector())
6709 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6715 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6716 SelectionDAG &DAG) const {
6717 EVT VT = Op.getValueType();
6718 DebugLoc dl = Op.getDebugLoc();
6720 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6723 if (VT.getSizeInBits() == 8) {
6724 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6725 Op.getOperand(0), Op.getOperand(1));
6726 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6727 DAG.getValueType(VT));
6728 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6729 } else if (VT.getSizeInBits() == 16) {
6730 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6731 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6733 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6734 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6735 DAG.getNode(ISD::BITCAST, dl,
6739 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6740 Op.getOperand(0), Op.getOperand(1));
6741 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6742 DAG.getValueType(VT));
6743 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6744 } else if (VT == MVT::f32) {
6745 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6746 // the result back to FR32 register. It's only worth matching if the
6747 // result has a single use which is a store or a bitcast to i32. And in
6748 // the case of a store, it's not worth it if the index is a constant 0,
6749 // because a MOVSSmr can be used instead, which is smaller and faster.
6750 if (!Op.hasOneUse())
6752 SDNode *User = *Op.getNode()->use_begin();
6753 if ((User->getOpcode() != ISD::STORE ||
6754 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6755 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6756 (User->getOpcode() != ISD::BITCAST ||
6757 User->getValueType(0) != MVT::i32))
6759 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6760 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6763 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6764 } else if (VT == MVT::i32 || VT == MVT::i64) {
6765 // ExtractPS/pextrq works with constant index.
6766 if (isa<ConstantSDNode>(Op.getOperand(1)))
6774 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6775 SelectionDAG &DAG) const {
6776 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6779 SDValue Vec = Op.getOperand(0);
6780 EVT VecVT = Vec.getValueType();
6782 // If this is a 256-bit vector result, first extract the 128-bit vector and
6783 // then extract the element from the 128-bit vector.
6784 if (VecVT.getSizeInBits() == 256) {
6785 DebugLoc dl = Op.getNode()->getDebugLoc();
6786 unsigned NumElems = VecVT.getVectorNumElements();
6787 SDValue Idx = Op.getOperand(1);
6788 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6790 // Get the 128-bit vector.
6791 bool Upper = IdxVal >= NumElems/2;
6792 Vec = Extract128BitVector(Vec,
6793 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6795 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6796 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6799 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6801 if (Subtarget->hasSSE41orAVX()) {
6802 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6807 EVT VT = Op.getValueType();
6808 DebugLoc dl = Op.getDebugLoc();
6809 // TODO: handle v16i8.
6810 if (VT.getSizeInBits() == 16) {
6811 SDValue Vec = Op.getOperand(0);
6812 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6814 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6815 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6816 DAG.getNode(ISD::BITCAST, dl,
6819 // Transform it so it match pextrw which produces a 32-bit result.
6820 EVT EltVT = MVT::i32;
6821 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6822 Op.getOperand(0), Op.getOperand(1));
6823 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6824 DAG.getValueType(VT));
6825 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6826 } else if (VT.getSizeInBits() == 32) {
6827 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6831 // SHUFPS the element to the lowest double word, then movss.
6832 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6833 EVT VVT = Op.getOperand(0).getValueType();
6834 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6835 DAG.getUNDEF(VVT), Mask);
6836 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6837 DAG.getIntPtrConstant(0));
6838 } else if (VT.getSizeInBits() == 64) {
6839 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6840 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6841 // to match extract_elt for f64.
6842 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6846 // UNPCKHPD the element to the lowest double word, then movsd.
6847 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6848 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6849 int Mask[2] = { 1, -1 };
6850 EVT VVT = Op.getOperand(0).getValueType();
6851 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6852 DAG.getUNDEF(VVT), Mask);
6853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6854 DAG.getIntPtrConstant(0));
6861 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6862 SelectionDAG &DAG) const {
6863 EVT VT = Op.getValueType();
6864 EVT EltVT = VT.getVectorElementType();
6865 DebugLoc dl = Op.getDebugLoc();
6867 SDValue N0 = Op.getOperand(0);
6868 SDValue N1 = Op.getOperand(1);
6869 SDValue N2 = Op.getOperand(2);
6871 if (VT.getSizeInBits() == 256)
6874 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6875 isa<ConstantSDNode>(N2)) {
6877 if (VT == MVT::v8i16)
6878 Opc = X86ISD::PINSRW;
6879 else if (VT == MVT::v16i8)
6880 Opc = X86ISD::PINSRB;
6882 Opc = X86ISD::PINSRB;
6884 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6886 if (N1.getValueType() != MVT::i32)
6887 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6888 if (N2.getValueType() != MVT::i32)
6889 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6890 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6891 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6892 // Bits [7:6] of the constant are the source select. This will always be
6893 // zero here. The DAG Combiner may combine an extract_elt index into these
6894 // bits. For example (insert (extract, 3), 2) could be matched by putting
6895 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6896 // Bits [5:4] of the constant are the destination select. This is the
6897 // value of the incoming immediate.
6898 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6899 // combine either bitwise AND or insert of float 0.0 to set these bits.
6900 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6901 // Create this as a scalar to vector..
6902 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6903 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6904 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6905 isa<ConstantSDNode>(N2)) {
6906 // PINSR* works with constant index.
6913 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6914 EVT VT = Op.getValueType();
6915 EVT EltVT = VT.getVectorElementType();
6917 DebugLoc dl = Op.getDebugLoc();
6918 SDValue N0 = Op.getOperand(0);
6919 SDValue N1 = Op.getOperand(1);
6920 SDValue N2 = Op.getOperand(2);
6922 // If this is a 256-bit vector result, first extract the 128-bit vector,
6923 // insert the element into the extracted half and then place it back.
6924 if (VT.getSizeInBits() == 256) {
6925 if (!isa<ConstantSDNode>(N2))
6928 // Get the desired 128-bit vector half.
6929 unsigned NumElems = VT.getVectorNumElements();
6930 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6931 bool Upper = IdxVal >= NumElems/2;
6932 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6933 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6935 // Insert the element into the desired half.
6936 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6937 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6939 // Insert the changed part back to the 256-bit vector
6940 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6943 if (Subtarget->hasSSE41orAVX())
6944 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6946 if (EltVT == MVT::i8)
6949 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6950 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6951 // as its second argument.
6952 if (N1.getValueType() != MVT::i32)
6953 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6954 if (N2.getValueType() != MVT::i32)
6955 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6956 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6962 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6963 LLVMContext *Context = DAG.getContext();
6964 DebugLoc dl = Op.getDebugLoc();
6965 EVT OpVT = Op.getValueType();
6967 // If this is a 256-bit vector result, first insert into a 128-bit
6968 // vector and then insert into the 256-bit vector.
6969 if (OpVT.getSizeInBits() > 128) {
6970 // Insert into a 128-bit vector.
6971 EVT VT128 = EVT::getVectorVT(*Context,
6972 OpVT.getVectorElementType(),
6973 OpVT.getVectorNumElements() / 2);
6975 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6977 // Insert the 128-bit vector.
6978 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6979 DAG.getConstant(0, MVT::i32),
6983 if (Op.getValueType() == MVT::v1i64 &&
6984 Op.getOperand(0).getValueType() == MVT::i64)
6985 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6987 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6988 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6989 "Expected an SSE type!");
6990 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6994 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6995 // a simple subregister reference or explicit instructions to grab
6996 // upper bits of a vector.
6998 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6999 if (Subtarget->hasAVX()) {
7000 DebugLoc dl = Op.getNode()->getDebugLoc();
7001 SDValue Vec = Op.getNode()->getOperand(0);
7002 SDValue Idx = Op.getNode()->getOperand(1);
7004 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7005 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7006 return Extract128BitVector(Vec, Idx, DAG, dl);
7012 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7013 // simple superregister reference or explicit instructions to insert
7014 // the upper bits of a vector.
7016 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7017 if (Subtarget->hasAVX()) {
7018 DebugLoc dl = Op.getNode()->getDebugLoc();
7019 SDValue Vec = Op.getNode()->getOperand(0);
7020 SDValue SubVec = Op.getNode()->getOperand(1);
7021 SDValue Idx = Op.getNode()->getOperand(2);
7023 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7024 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7025 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7031 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7032 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7033 // one of the above mentioned nodes. It has to be wrapped because otherwise
7034 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7035 // be used to form addressing mode. These wrapped nodes will be selected
7038 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7039 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7041 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7043 unsigned char OpFlag = 0;
7044 unsigned WrapperKind = X86ISD::Wrapper;
7045 CodeModel::Model M = getTargetMachine().getCodeModel();
7047 if (Subtarget->isPICStyleRIPRel() &&
7048 (M == CodeModel::Small || M == CodeModel::Kernel))
7049 WrapperKind = X86ISD::WrapperRIP;
7050 else if (Subtarget->isPICStyleGOT())
7051 OpFlag = X86II::MO_GOTOFF;
7052 else if (Subtarget->isPICStyleStubPIC())
7053 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7055 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7057 CP->getOffset(), OpFlag);
7058 DebugLoc DL = CP->getDebugLoc();
7059 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7060 // With PIC, the address is actually $g + Offset.
7062 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7063 DAG.getNode(X86ISD::GlobalBaseReg,
7064 DebugLoc(), getPointerTy()),
7071 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7072 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7074 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7076 unsigned char OpFlag = 0;
7077 unsigned WrapperKind = X86ISD::Wrapper;
7078 CodeModel::Model M = getTargetMachine().getCodeModel();
7080 if (Subtarget->isPICStyleRIPRel() &&
7081 (M == CodeModel::Small || M == CodeModel::Kernel))
7082 WrapperKind = X86ISD::WrapperRIP;
7083 else if (Subtarget->isPICStyleGOT())
7084 OpFlag = X86II::MO_GOTOFF;
7085 else if (Subtarget->isPICStyleStubPIC())
7086 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7088 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7090 DebugLoc DL = JT->getDebugLoc();
7091 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7093 // With PIC, the address is actually $g + Offset.
7095 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7096 DAG.getNode(X86ISD::GlobalBaseReg,
7097 DebugLoc(), getPointerTy()),
7104 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7105 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7107 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7109 unsigned char OpFlag = 0;
7110 unsigned WrapperKind = X86ISD::Wrapper;
7111 CodeModel::Model M = getTargetMachine().getCodeModel();
7113 if (Subtarget->isPICStyleRIPRel() &&
7114 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7115 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7116 OpFlag = X86II::MO_GOTPCREL;
7117 WrapperKind = X86ISD::WrapperRIP;
7118 } else if (Subtarget->isPICStyleGOT()) {
7119 OpFlag = X86II::MO_GOT;
7120 } else if (Subtarget->isPICStyleStubPIC()) {
7121 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7122 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7123 OpFlag = X86II::MO_DARWIN_NONLAZY;
7126 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7128 DebugLoc DL = Op.getDebugLoc();
7129 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7132 // With PIC, the address is actually $g + Offset.
7133 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7134 !Subtarget->is64Bit()) {
7135 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7136 DAG.getNode(X86ISD::GlobalBaseReg,
7137 DebugLoc(), getPointerTy()),
7141 // For symbols that require a load from a stub to get the address, emit the
7143 if (isGlobalStubReference(OpFlag))
7144 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7145 MachinePointerInfo::getGOT(), false, false, false, 0);
7151 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7152 // Create the TargetBlockAddressAddress node.
7153 unsigned char OpFlags =
7154 Subtarget->ClassifyBlockAddressReference();
7155 CodeModel::Model M = getTargetMachine().getCodeModel();
7156 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7157 DebugLoc dl = Op.getDebugLoc();
7158 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7159 /*isTarget=*/true, OpFlags);
7161 if (Subtarget->isPICStyleRIPRel() &&
7162 (M == CodeModel::Small || M == CodeModel::Kernel))
7163 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7165 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7167 // With PIC, the address is actually $g + Offset.
7168 if (isGlobalRelativeToPICBase(OpFlags)) {
7169 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7170 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7178 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7180 SelectionDAG &DAG) const {
7181 // Create the TargetGlobalAddress node, folding in the constant
7182 // offset if it is legal.
7183 unsigned char OpFlags =
7184 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7185 CodeModel::Model M = getTargetMachine().getCodeModel();
7187 if (OpFlags == X86II::MO_NO_FLAG &&
7188 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7189 // A direct static reference to a global.
7190 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7193 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7196 if (Subtarget->isPICStyleRIPRel() &&
7197 (M == CodeModel::Small || M == CodeModel::Kernel))
7198 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7200 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7202 // With PIC, the address is actually $g + Offset.
7203 if (isGlobalRelativeToPICBase(OpFlags)) {
7204 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7205 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7209 // For globals that require a load from a stub to get the address, emit the
7211 if (isGlobalStubReference(OpFlags))
7212 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7213 MachinePointerInfo::getGOT(), false, false, false, 0);
7215 // If there was a non-zero offset that we didn't fold, create an explicit
7218 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7219 DAG.getConstant(Offset, getPointerTy()));
7225 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7226 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7227 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7228 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7232 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7233 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7234 unsigned char OperandFlags) {
7235 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7237 DebugLoc dl = GA->getDebugLoc();
7238 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7239 GA->getValueType(0),
7243 SDValue Ops[] = { Chain, TGA, *InFlag };
7244 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7246 SDValue Ops[] = { Chain, TGA };
7247 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7250 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7251 MFI->setAdjustsStack(true);
7253 SDValue Flag = Chain.getValue(1);
7254 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7257 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7259 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7262 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7263 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7264 DAG.getNode(X86ISD::GlobalBaseReg,
7265 DebugLoc(), PtrVT), InFlag);
7266 InFlag = Chain.getValue(1);
7268 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7271 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7273 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7275 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7276 X86::RAX, X86II::MO_TLSGD);
7279 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7280 // "local exec" model.
7281 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7282 const EVT PtrVT, TLSModel::Model model,
7284 DebugLoc dl = GA->getDebugLoc();
7286 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7287 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7288 is64Bit ? 257 : 256));
7290 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7291 DAG.getIntPtrConstant(0),
7292 MachinePointerInfo(Ptr),
7293 false, false, false, 0);
7295 unsigned char OperandFlags = 0;
7296 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7298 unsigned WrapperKind = X86ISD::Wrapper;
7299 if (model == TLSModel::LocalExec) {
7300 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7301 } else if (is64Bit) {
7302 assert(model == TLSModel::InitialExec);
7303 OperandFlags = X86II::MO_GOTTPOFF;
7304 WrapperKind = X86ISD::WrapperRIP;
7306 assert(model == TLSModel::InitialExec);
7307 OperandFlags = X86II::MO_INDNTPOFF;
7310 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7312 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7313 GA->getValueType(0),
7314 GA->getOffset(), OperandFlags);
7315 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7317 if (model == TLSModel::InitialExec)
7318 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7319 MachinePointerInfo::getGOT(), false, false, false, 0);
7321 // The address of the thread local variable is the add of the thread
7322 // pointer with the offset of the variable.
7323 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7327 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7329 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7330 const GlobalValue *GV = GA->getGlobal();
7332 if (Subtarget->isTargetELF()) {
7333 // TODO: implement the "local dynamic" model
7334 // TODO: implement the "initial exec"model for pic executables
7336 // If GV is an alias then use the aliasee for determining
7337 // thread-localness.
7338 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7339 GV = GA->resolveAliasedGlobal(false);
7341 TLSModel::Model model
7342 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7345 case TLSModel::GeneralDynamic:
7346 case TLSModel::LocalDynamic: // not implemented
7347 if (Subtarget->is64Bit())
7348 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7349 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7351 case TLSModel::InitialExec:
7352 case TLSModel::LocalExec:
7353 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7354 Subtarget->is64Bit());
7356 } else if (Subtarget->isTargetDarwin()) {
7357 // Darwin only has one model of TLS. Lower to that.
7358 unsigned char OpFlag = 0;
7359 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7360 X86ISD::WrapperRIP : X86ISD::Wrapper;
7362 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7364 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7365 !Subtarget->is64Bit();
7367 OpFlag = X86II::MO_TLVP_PIC_BASE;
7369 OpFlag = X86II::MO_TLVP;
7370 DebugLoc DL = Op.getDebugLoc();
7371 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7372 GA->getValueType(0),
7373 GA->getOffset(), OpFlag);
7374 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7376 // With PIC32, the address is actually $g + Offset.
7378 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7379 DAG.getNode(X86ISD::GlobalBaseReg,
7380 DebugLoc(), getPointerTy()),
7383 // Lowering the machine isd will make sure everything is in the right
7385 SDValue Chain = DAG.getEntryNode();
7386 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7387 SDValue Args[] = { Chain, Offset };
7388 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7390 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7391 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7392 MFI->setAdjustsStack(true);
7394 // And our return value (tls address) is in the standard call return value
7396 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7397 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7402 "TLS not implemented for this target.");
7404 llvm_unreachable("Unreachable");
7409 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7410 /// take a 2 x i32 value to shift plus a shift amount.
7411 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7412 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7413 EVT VT = Op.getValueType();
7414 unsigned VTBits = VT.getSizeInBits();
7415 DebugLoc dl = Op.getDebugLoc();
7416 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7417 SDValue ShOpLo = Op.getOperand(0);
7418 SDValue ShOpHi = Op.getOperand(1);
7419 SDValue ShAmt = Op.getOperand(2);
7420 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7421 DAG.getConstant(VTBits - 1, MVT::i8))
7422 : DAG.getConstant(0, VT);
7425 if (Op.getOpcode() == ISD::SHL_PARTS) {
7426 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7427 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7429 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7430 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7433 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7434 DAG.getConstant(VTBits, MVT::i8));
7435 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7436 AndNode, DAG.getConstant(0, MVT::i8));
7439 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7440 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7441 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7443 if (Op.getOpcode() == ISD::SHL_PARTS) {
7444 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7445 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7447 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7448 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7451 SDValue Ops[2] = { Lo, Hi };
7452 return DAG.getMergeValues(Ops, 2, dl);
7455 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7456 SelectionDAG &DAG) const {
7457 EVT SrcVT = Op.getOperand(0).getValueType();
7459 if (SrcVT.isVector())
7462 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7463 "Unknown SINT_TO_FP to lower!");
7465 // These are really Legal; return the operand so the caller accepts it as
7467 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7469 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7470 Subtarget->is64Bit()) {
7474 DebugLoc dl = Op.getDebugLoc();
7475 unsigned Size = SrcVT.getSizeInBits()/8;
7476 MachineFunction &MF = DAG.getMachineFunction();
7477 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7478 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7479 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7481 MachinePointerInfo::getFixedStack(SSFI),
7483 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7486 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7488 SelectionDAG &DAG) const {
7490 DebugLoc DL = Op.getDebugLoc();
7492 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7494 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7496 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7498 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7500 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7501 MachineMemOperand *MMO;
7503 int SSFI = FI->getIndex();
7505 DAG.getMachineFunction()
7506 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7507 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7509 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7510 StackSlot = StackSlot.getOperand(1);
7512 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7513 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7515 Tys, Ops, array_lengthof(Ops),
7519 Chain = Result.getValue(1);
7520 SDValue InFlag = Result.getValue(2);
7522 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7523 // shouldn't be necessary except that RFP cannot be live across
7524 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7525 MachineFunction &MF = DAG.getMachineFunction();
7526 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7527 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7528 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7529 Tys = DAG.getVTList(MVT::Other);
7531 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7533 MachineMemOperand *MMO =
7534 DAG.getMachineFunction()
7535 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7536 MachineMemOperand::MOStore, SSFISize, SSFISize);
7538 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7539 Ops, array_lengthof(Ops),
7540 Op.getValueType(), MMO);
7541 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7542 MachinePointerInfo::getFixedStack(SSFI),
7543 false, false, false, 0);
7549 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7550 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7551 SelectionDAG &DAG) const {
7552 // This algorithm is not obvious. Here it is in C code, more or less:
7554 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7555 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7556 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7558 // Copy ints to xmm registers.
7559 __m128i xh = _mm_cvtsi32_si128( hi );
7560 __m128i xl = _mm_cvtsi32_si128( lo );
7562 // Combine into low half of a single xmm register.
7563 __m128i x = _mm_unpacklo_epi32( xh, xl );
7567 // Merge in appropriate exponents to give the integer bits the right
7569 x = _mm_unpacklo_epi32( x, exp );
7571 // Subtract away the biases to deal with the IEEE-754 double precision
7573 d = _mm_sub_pd( (__m128d) x, bias );
7575 // All conversions up to here are exact. The correctly rounded result is
7576 // calculated using the current rounding mode using the following
7578 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7579 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7580 // store doesn't really need to be here (except
7581 // maybe to zero the other double)
7586 DebugLoc dl = Op.getDebugLoc();
7587 LLVMContext *Context = DAG.getContext();
7589 // Build some magic constants.
7590 std::vector<Constant*> CV0;
7591 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7592 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7593 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7594 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7595 Constant *C0 = ConstantVector::get(CV0);
7596 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7598 std::vector<Constant*> CV1;
7600 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7602 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7603 Constant *C1 = ConstantVector::get(CV1);
7604 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7606 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7607 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7609 DAG.getIntPtrConstant(1)));
7610 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7611 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7613 DAG.getIntPtrConstant(0)));
7614 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7615 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7616 MachinePointerInfo::getConstantPool(),
7617 false, false, false, 16);
7618 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7619 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7620 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7621 MachinePointerInfo::getConstantPool(),
7622 false, false, false, 16);
7623 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7625 // Add the halves; easiest way is to swap them into another reg first.
7626 int ShufMask[2] = { 1, -1 };
7627 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7628 DAG.getUNDEF(MVT::v2f64), ShufMask);
7629 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7630 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7631 DAG.getIntPtrConstant(0));
7634 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7635 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7636 SelectionDAG &DAG) const {
7637 DebugLoc dl = Op.getDebugLoc();
7638 // FP constant to bias correct the final result.
7639 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7642 // Load the 32-bit value into an XMM register.
7643 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7646 // Zero out the upper parts of the register.
7647 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7650 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7651 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7652 DAG.getIntPtrConstant(0));
7654 // Or the load with the bias.
7655 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7656 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7657 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7659 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7660 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7661 MVT::v2f64, Bias)));
7662 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7663 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7664 DAG.getIntPtrConstant(0));
7666 // Subtract the bias.
7667 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7669 // Handle final rounding.
7670 EVT DestVT = Op.getValueType();
7672 if (DestVT.bitsLT(MVT::f64)) {
7673 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7674 DAG.getIntPtrConstant(0));
7675 } else if (DestVT.bitsGT(MVT::f64)) {
7676 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7679 // Handle final rounding.
7683 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7684 SelectionDAG &DAG) const {
7685 SDValue N0 = Op.getOperand(0);
7686 DebugLoc dl = Op.getDebugLoc();
7688 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7689 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7690 // the optimization here.
7691 if (DAG.SignBitIsZero(N0))
7692 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7694 EVT SrcVT = N0.getValueType();
7695 EVT DstVT = Op.getValueType();
7696 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7697 return LowerUINT_TO_FP_i64(Op, DAG);
7698 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7699 return LowerUINT_TO_FP_i32(Op, DAG);
7701 // Make a 64-bit buffer, and use it to build an FILD.
7702 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7703 if (SrcVT == MVT::i32) {
7704 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7705 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7706 getPointerTy(), StackSlot, WordOff);
7707 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7708 StackSlot, MachinePointerInfo(),
7710 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7711 OffsetSlot, MachinePointerInfo(),
7713 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7717 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7718 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7719 StackSlot, MachinePointerInfo(),
7721 // For i64 source, we need to add the appropriate power of 2 if the input
7722 // was negative. This is the same as the optimization in
7723 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7724 // we must be careful to do the computation in x87 extended precision, not
7725 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7726 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7727 MachineMemOperand *MMO =
7728 DAG.getMachineFunction()
7729 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7730 MachineMemOperand::MOLoad, 8, 8);
7732 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7733 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7734 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7737 APInt FF(32, 0x5F800000ULL);
7739 // Check whether the sign bit is set.
7740 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7741 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7744 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7745 SDValue FudgePtr = DAG.getConstantPool(
7746 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7749 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7750 SDValue Zero = DAG.getIntPtrConstant(0);
7751 SDValue Four = DAG.getIntPtrConstant(4);
7752 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7754 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7756 // Load the value out, extending it from f32 to f80.
7757 // FIXME: Avoid the extend by constructing the right constant pool?
7758 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7759 FudgePtr, MachinePointerInfo::getConstantPool(),
7760 MVT::f32, false, false, 4);
7761 // Extend everything to 80 bits to force it to be done on x87.
7762 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7763 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7766 std::pair<SDValue,SDValue> X86TargetLowering::
7767 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7768 DebugLoc DL = Op.getDebugLoc();
7770 EVT DstTy = Op.getValueType();
7773 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7777 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7778 DstTy.getSimpleVT() >= MVT::i16 &&
7779 "Unknown FP_TO_SINT to lower!");
7781 // These are really Legal.
7782 if (DstTy == MVT::i32 &&
7783 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7784 return std::make_pair(SDValue(), SDValue());
7785 if (Subtarget->is64Bit() &&
7786 DstTy == MVT::i64 &&
7787 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7788 return std::make_pair(SDValue(), SDValue());
7790 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7792 MachineFunction &MF = DAG.getMachineFunction();
7793 unsigned MemSize = DstTy.getSizeInBits()/8;
7794 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7795 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7800 switch (DstTy.getSimpleVT().SimpleTy) {
7801 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7802 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7803 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7804 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7807 SDValue Chain = DAG.getEntryNode();
7808 SDValue Value = Op.getOperand(0);
7809 EVT TheVT = Op.getOperand(0).getValueType();
7810 if (isScalarFPTypeInSSEReg(TheVT)) {
7811 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7812 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7813 MachinePointerInfo::getFixedStack(SSFI),
7815 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7817 Chain, StackSlot, DAG.getValueType(TheVT)
7820 MachineMemOperand *MMO =
7821 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7822 MachineMemOperand::MOLoad, MemSize, MemSize);
7823 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7825 Chain = Value.getValue(1);
7826 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7827 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7830 MachineMemOperand *MMO =
7831 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7832 MachineMemOperand::MOStore, MemSize, MemSize);
7834 // Build the FP_TO_INT*_IN_MEM
7835 SDValue Ops[] = { Chain, Value, StackSlot };
7836 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7837 Ops, 3, DstTy, MMO);
7839 return std::make_pair(FIST, StackSlot);
7842 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7843 SelectionDAG &DAG) const {
7844 if (Op.getValueType().isVector())
7847 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7848 SDValue FIST = Vals.first, StackSlot = Vals.second;
7849 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7850 if (FIST.getNode() == 0) return Op;
7853 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7854 FIST, StackSlot, MachinePointerInfo(),
7855 false, false, false, 0);
7858 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7859 SelectionDAG &DAG) const {
7860 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7861 SDValue FIST = Vals.first, StackSlot = Vals.second;
7862 assert(FIST.getNode() && "Unexpected failure");
7865 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7866 FIST, StackSlot, MachinePointerInfo(),
7867 false, false, false, 0);
7870 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7871 SelectionDAG &DAG) const {
7872 LLVMContext *Context = DAG.getContext();
7873 DebugLoc dl = Op.getDebugLoc();
7874 EVT VT = Op.getValueType();
7877 EltVT = VT.getVectorElementType();
7878 std::vector<Constant*> CV;
7879 if (EltVT == MVT::f64) {
7880 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7884 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7890 Constant *C = ConstantVector::get(CV);
7891 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7892 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7893 MachinePointerInfo::getConstantPool(),
7894 false, false, false, 16);
7895 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7898 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7899 LLVMContext *Context = DAG.getContext();
7900 DebugLoc dl = Op.getDebugLoc();
7901 EVT VT = Op.getValueType();
7904 EltVT = VT.getVectorElementType();
7905 std::vector<Constant*> CV;
7906 if (EltVT == MVT::f64) {
7907 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7911 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7917 Constant *C = ConstantVector::get(CV);
7918 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7919 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7920 MachinePointerInfo::getConstantPool(),
7921 false, false, false, 16);
7922 if (VT.isVector()) {
7923 return DAG.getNode(ISD::BITCAST, dl, VT,
7924 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7925 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7927 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7929 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7933 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7934 LLVMContext *Context = DAG.getContext();
7935 SDValue Op0 = Op.getOperand(0);
7936 SDValue Op1 = Op.getOperand(1);
7937 DebugLoc dl = Op.getDebugLoc();
7938 EVT VT = Op.getValueType();
7939 EVT SrcVT = Op1.getValueType();
7941 // If second operand is smaller, extend it first.
7942 if (SrcVT.bitsLT(VT)) {
7943 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7946 // And if it is bigger, shrink it first.
7947 if (SrcVT.bitsGT(VT)) {
7948 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7952 // At this point the operands and the result should have the same
7953 // type, and that won't be f80 since that is not custom lowered.
7955 // First get the sign bit of second operand.
7956 std::vector<Constant*> CV;
7957 if (SrcVT == MVT::f64) {
7958 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7959 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7961 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7962 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7963 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7964 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7966 Constant *C = ConstantVector::get(CV);
7967 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7968 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7969 MachinePointerInfo::getConstantPool(),
7970 false, false, false, 16);
7971 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7973 // Shift sign bit right or left if the two operands have different types.
7974 if (SrcVT.bitsGT(VT)) {
7975 // Op0 is MVT::f32, Op1 is MVT::f64.
7976 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7977 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7978 DAG.getConstant(32, MVT::i32));
7979 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7980 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7981 DAG.getIntPtrConstant(0));
7984 // Clear first operand sign bit.
7986 if (VT == MVT::f64) {
7987 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7988 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7990 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7991 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7992 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7993 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7995 C = ConstantVector::get(CV);
7996 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7997 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7998 MachinePointerInfo::getConstantPool(),
7999 false, false, false, 16);
8000 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8002 // Or the value with the sign bit.
8003 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8006 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8007 SDValue N0 = Op.getOperand(0);
8008 DebugLoc dl = Op.getDebugLoc();
8009 EVT VT = Op.getValueType();
8011 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8012 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8013 DAG.getConstant(1, VT));
8014 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8017 /// Emit nodes that will be selected as "test Op0,Op0", or something
8019 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8020 SelectionDAG &DAG) const {
8021 DebugLoc dl = Op.getDebugLoc();
8023 // CF and OF aren't always set the way we want. Determine which
8024 // of these we need.
8025 bool NeedCF = false;
8026 bool NeedOF = false;
8029 case X86::COND_A: case X86::COND_AE:
8030 case X86::COND_B: case X86::COND_BE:
8033 case X86::COND_G: case X86::COND_GE:
8034 case X86::COND_L: case X86::COND_LE:
8035 case X86::COND_O: case X86::COND_NO:
8040 // See if we can use the EFLAGS value from the operand instead of
8041 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8042 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8043 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8044 // Emit a CMP with 0, which is the TEST pattern.
8045 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8046 DAG.getConstant(0, Op.getValueType()));
8048 unsigned Opcode = 0;
8049 unsigned NumOperands = 0;
8050 switch (Op.getNode()->getOpcode()) {
8052 // Due to an isel shortcoming, be conservative if this add is likely to be
8053 // selected as part of a load-modify-store instruction. When the root node
8054 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8055 // uses of other nodes in the match, such as the ADD in this case. This
8056 // leads to the ADD being left around and reselected, with the result being
8057 // two adds in the output. Alas, even if none our users are stores, that
8058 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8059 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8060 // climbing the DAG back to the root, and it doesn't seem to be worth the
8062 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8063 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8064 if (UI->getOpcode() != ISD::CopyToReg &&
8065 UI->getOpcode() != ISD::SETCC &&
8066 UI->getOpcode() != ISD::STORE)
8069 if (ConstantSDNode *C =
8070 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8071 // An add of one will be selected as an INC.
8072 if (C->getAPIntValue() == 1) {
8073 Opcode = X86ISD::INC;
8078 // An add of negative one (subtract of one) will be selected as a DEC.
8079 if (C->getAPIntValue().isAllOnesValue()) {
8080 Opcode = X86ISD::DEC;
8086 // Otherwise use a regular EFLAGS-setting add.
8087 Opcode = X86ISD::ADD;
8091 // If the primary and result isn't used, don't bother using X86ISD::AND,
8092 // because a TEST instruction will be better.
8093 bool NonFlagUse = false;
8094 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8095 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8097 unsigned UOpNo = UI.getOperandNo();
8098 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8099 // Look pass truncate.
8100 UOpNo = User->use_begin().getOperandNo();
8101 User = *User->use_begin();
8104 if (User->getOpcode() != ISD::BRCOND &&
8105 User->getOpcode() != ISD::SETCC &&
8106 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8119 // Due to the ISEL shortcoming noted above, be conservative if this op is
8120 // likely to be selected as part of a load-modify-store instruction.
8121 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8122 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8123 if (UI->getOpcode() == ISD::STORE)
8126 // Otherwise use a regular EFLAGS-setting instruction.
8127 switch (Op.getNode()->getOpcode()) {
8128 default: llvm_unreachable("unexpected operator!");
8129 case ISD::SUB: Opcode = X86ISD::SUB; break;
8130 case ISD::OR: Opcode = X86ISD::OR; break;
8131 case ISD::XOR: Opcode = X86ISD::XOR; break;
8132 case ISD::AND: Opcode = X86ISD::AND; break;
8144 return SDValue(Op.getNode(), 1);
8151 // Emit a CMP with 0, which is the TEST pattern.
8152 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8153 DAG.getConstant(0, Op.getValueType()));
8155 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8156 SmallVector<SDValue, 4> Ops;
8157 for (unsigned i = 0; i != NumOperands; ++i)
8158 Ops.push_back(Op.getOperand(i));
8160 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8161 DAG.ReplaceAllUsesWith(Op, New);
8162 return SDValue(New.getNode(), 1);
8165 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8167 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8168 SelectionDAG &DAG) const {
8169 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8170 if (C->getAPIntValue() == 0)
8171 return EmitTest(Op0, X86CC, DAG);
8173 DebugLoc dl = Op0.getDebugLoc();
8174 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8177 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8178 /// if it's possible.
8179 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8180 DebugLoc dl, SelectionDAG &DAG) const {
8181 SDValue Op0 = And.getOperand(0);
8182 SDValue Op1 = And.getOperand(1);
8183 if (Op0.getOpcode() == ISD::TRUNCATE)
8184 Op0 = Op0.getOperand(0);
8185 if (Op1.getOpcode() == ISD::TRUNCATE)
8186 Op1 = Op1.getOperand(0);
8189 if (Op1.getOpcode() == ISD::SHL)
8190 std::swap(Op0, Op1);
8191 if (Op0.getOpcode() == ISD::SHL) {
8192 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8193 if (And00C->getZExtValue() == 1) {
8194 // If we looked past a truncate, check that it's only truncating away
8196 unsigned BitWidth = Op0.getValueSizeInBits();
8197 unsigned AndBitWidth = And.getValueSizeInBits();
8198 if (BitWidth > AndBitWidth) {
8199 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8200 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8201 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8205 RHS = Op0.getOperand(1);
8207 } else if (Op1.getOpcode() == ISD::Constant) {
8208 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8209 uint64_t AndRHSVal = AndRHS->getZExtValue();
8210 SDValue AndLHS = Op0;
8212 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8213 LHS = AndLHS.getOperand(0);
8214 RHS = AndLHS.getOperand(1);
8217 // Use BT if the immediate can't be encoded in a TEST instruction.
8218 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8220 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8224 if (LHS.getNode()) {
8225 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8226 // instruction. Since the shift amount is in-range-or-undefined, we know
8227 // that doing a bittest on the i32 value is ok. We extend to i32 because
8228 // the encoding for the i16 version is larger than the i32 version.
8229 // Also promote i16 to i32 for performance / code size reason.
8230 if (LHS.getValueType() == MVT::i8 ||
8231 LHS.getValueType() == MVT::i16)
8232 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8234 // If the operand types disagree, extend the shift amount to match. Since
8235 // BT ignores high bits (like shifts) we can use anyextend.
8236 if (LHS.getValueType() != RHS.getValueType())
8237 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8239 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8240 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8241 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8242 DAG.getConstant(Cond, MVT::i8), BT);
8248 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8250 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8252 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8253 SDValue Op0 = Op.getOperand(0);
8254 SDValue Op1 = Op.getOperand(1);
8255 DebugLoc dl = Op.getDebugLoc();
8256 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8258 // Optimize to BT if possible.
8259 // Lower (X & (1 << N)) == 0 to BT(X, N).
8260 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8261 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8262 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8263 Op1.getOpcode() == ISD::Constant &&
8264 cast<ConstantSDNode>(Op1)->isNullValue() &&
8265 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8266 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8267 if (NewSetCC.getNode())
8271 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8273 if (Op1.getOpcode() == ISD::Constant &&
8274 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8275 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8276 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8278 // If the input is a setcc, then reuse the input setcc or use a new one with
8279 // the inverted condition.
8280 if (Op0.getOpcode() == X86ISD::SETCC) {
8281 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8282 bool Invert = (CC == ISD::SETNE) ^
8283 cast<ConstantSDNode>(Op1)->isNullValue();
8284 if (!Invert) return Op0;
8286 CCode = X86::GetOppositeBranchCondition(CCode);
8287 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8288 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8292 bool isFP = Op1.getValueType().isFloatingPoint();
8293 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8294 if (X86CC == X86::COND_INVALID)
8297 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8298 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8299 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8302 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8303 // ones, and then concatenate the result back.
8304 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8305 EVT VT = Op.getValueType();
8307 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8308 "Unsupported value type for operation");
8310 int NumElems = VT.getVectorNumElements();
8311 DebugLoc dl = Op.getDebugLoc();
8312 SDValue CC = Op.getOperand(2);
8313 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8314 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8316 // Extract the LHS vectors
8317 SDValue LHS = Op.getOperand(0);
8318 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8319 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8321 // Extract the RHS vectors
8322 SDValue RHS = Op.getOperand(1);
8323 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8324 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8326 // Issue the operation on the smaller types and concatenate the result back
8327 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8328 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8329 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8330 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8331 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8335 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8337 SDValue Op0 = Op.getOperand(0);
8338 SDValue Op1 = Op.getOperand(1);
8339 SDValue CC = Op.getOperand(2);
8340 EVT VT = Op.getValueType();
8341 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8342 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8343 DebugLoc dl = Op.getDebugLoc();
8347 EVT EltVT = Op0.getValueType().getVectorElementType();
8348 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8350 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8353 // SSE Condition code mapping:
8362 switch (SetCCOpcode) {
8365 case ISD::SETEQ: SSECC = 0; break;
8367 case ISD::SETGT: Swap = true; // Fallthrough
8369 case ISD::SETOLT: SSECC = 1; break;
8371 case ISD::SETGE: Swap = true; // Fallthrough
8373 case ISD::SETOLE: SSECC = 2; break;
8374 case ISD::SETUO: SSECC = 3; break;
8376 case ISD::SETNE: SSECC = 4; break;
8377 case ISD::SETULE: Swap = true;
8378 case ISD::SETUGE: SSECC = 5; break;
8379 case ISD::SETULT: Swap = true;
8380 case ISD::SETUGT: SSECC = 6; break;
8381 case ISD::SETO: SSECC = 7; break;
8384 std::swap(Op0, Op1);
8386 // In the two special cases we can't handle, emit two comparisons.
8388 if (SetCCOpcode == ISD::SETUEQ) {
8390 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8391 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8392 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8393 } else if (SetCCOpcode == ISD::SETONE) {
8395 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8396 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8397 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8399 llvm_unreachable("Illegal FP comparison");
8401 // Handle all other FP comparisons here.
8402 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8405 // Break 256-bit integer vector compare into smaller ones.
8406 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8407 return Lower256IntVSETCC(Op, DAG);
8409 // We are handling one of the integer comparisons here. Since SSE only has
8410 // GT and EQ comparisons for integer, swapping operands and multiple
8411 // operations may be required for some comparisons.
8412 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8413 bool Swap = false, Invert = false, FlipSigns = false;
8415 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8417 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8418 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8419 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8420 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8423 switch (SetCCOpcode) {
8425 case ISD::SETNE: Invert = true;
8426 case ISD::SETEQ: Opc = EQOpc; break;
8427 case ISD::SETLT: Swap = true;
8428 case ISD::SETGT: Opc = GTOpc; break;
8429 case ISD::SETGE: Swap = true;
8430 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8431 case ISD::SETULT: Swap = true;
8432 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8433 case ISD::SETUGE: Swap = true;
8434 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8437 std::swap(Op0, Op1);
8439 // Check that the operation in question is available (most are plain SSE2,
8440 // but PCMPGTQ and PCMPEQQ have different requirements).
8441 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8443 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8446 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8447 // bits of the inputs before performing those operations.
8449 EVT EltVT = VT.getVectorElementType();
8450 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8452 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8453 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8455 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8456 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8459 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8461 // If the logical-not of the result is required, perform that now.
8463 Result = DAG.getNOT(dl, Result, VT);
8468 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8469 static bool isX86LogicalCmp(SDValue Op) {
8470 unsigned Opc = Op.getNode()->getOpcode();
8471 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8473 if (Op.getResNo() == 1 &&
8474 (Opc == X86ISD::ADD ||
8475 Opc == X86ISD::SUB ||
8476 Opc == X86ISD::ADC ||
8477 Opc == X86ISD::SBB ||
8478 Opc == X86ISD::SMUL ||
8479 Opc == X86ISD::UMUL ||
8480 Opc == X86ISD::INC ||
8481 Opc == X86ISD::DEC ||
8482 Opc == X86ISD::OR ||
8483 Opc == X86ISD::XOR ||
8484 Opc == X86ISD::AND))
8487 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8493 static bool isZero(SDValue V) {
8494 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8495 return C && C->isNullValue();
8498 static bool isAllOnes(SDValue V) {
8499 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8500 return C && C->isAllOnesValue();
8503 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8504 bool addTest = true;
8505 SDValue Cond = Op.getOperand(0);
8506 SDValue Op1 = Op.getOperand(1);
8507 SDValue Op2 = Op.getOperand(2);
8508 DebugLoc DL = Op.getDebugLoc();
8511 if (Cond.getOpcode() == ISD::SETCC) {
8512 SDValue NewCond = LowerSETCC(Cond, DAG);
8513 if (NewCond.getNode())
8517 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8518 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8519 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8520 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8521 if (Cond.getOpcode() == X86ISD::SETCC &&
8522 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8523 isZero(Cond.getOperand(1).getOperand(1))) {
8524 SDValue Cmp = Cond.getOperand(1);
8526 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8528 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8529 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8530 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8532 SDValue CmpOp0 = Cmp.getOperand(0);
8533 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8534 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8536 SDValue Res = // Res = 0 or -1.
8537 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8538 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8540 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8541 Res = DAG.getNOT(DL, Res, Res.getValueType());
8543 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8544 if (N2C == 0 || !N2C->isNullValue())
8545 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8550 // Look past (and (setcc_carry (cmp ...)), 1).
8551 if (Cond.getOpcode() == ISD::AND &&
8552 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8553 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8554 if (C && C->getAPIntValue() == 1)
8555 Cond = Cond.getOperand(0);
8558 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8559 // setting operand in place of the X86ISD::SETCC.
8560 unsigned CondOpcode = Cond.getOpcode();
8561 if (CondOpcode == X86ISD::SETCC ||
8562 CondOpcode == X86ISD::SETCC_CARRY) {
8563 CC = Cond.getOperand(0);
8565 SDValue Cmp = Cond.getOperand(1);
8566 unsigned Opc = Cmp.getOpcode();
8567 EVT VT = Op.getValueType();
8569 bool IllegalFPCMov = false;
8570 if (VT.isFloatingPoint() && !VT.isVector() &&
8571 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8572 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8574 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8575 Opc == X86ISD::BT) { // FIXME
8579 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8580 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8581 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8582 Cond.getOperand(0).getValueType() != MVT::i8)) {
8583 SDValue LHS = Cond.getOperand(0);
8584 SDValue RHS = Cond.getOperand(1);
8588 switch (CondOpcode) {
8589 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8590 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8591 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8592 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8593 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8594 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8595 default: llvm_unreachable("unexpected overflowing operator");
8597 if (CondOpcode == ISD::UMULO)
8598 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8601 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8603 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8605 if (CondOpcode == ISD::UMULO)
8606 Cond = X86Op.getValue(2);
8608 Cond = X86Op.getValue(1);
8610 CC = DAG.getConstant(X86Cond, MVT::i8);
8615 // Look pass the truncate.
8616 if (Cond.getOpcode() == ISD::TRUNCATE)
8617 Cond = Cond.getOperand(0);
8619 // We know the result of AND is compared against zero. Try to match
8621 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8622 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8623 if (NewSetCC.getNode()) {
8624 CC = NewSetCC.getOperand(0);
8625 Cond = NewSetCC.getOperand(1);
8632 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8633 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8636 // a < b ? -1 : 0 -> RES = ~setcc_carry
8637 // a < b ? 0 : -1 -> RES = setcc_carry
8638 // a >= b ? -1 : 0 -> RES = setcc_carry
8639 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8640 if (Cond.getOpcode() == X86ISD::CMP) {
8641 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8643 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8644 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8645 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8646 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8647 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8648 return DAG.getNOT(DL, Res, Res.getValueType());
8653 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8654 // condition is true.
8655 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8656 SDValue Ops[] = { Op2, Op1, CC, Cond };
8657 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8660 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8661 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8662 // from the AND / OR.
8663 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8664 Opc = Op.getOpcode();
8665 if (Opc != ISD::OR && Opc != ISD::AND)
8667 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8668 Op.getOperand(0).hasOneUse() &&
8669 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8670 Op.getOperand(1).hasOneUse());
8673 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8674 // 1 and that the SETCC node has a single use.
8675 static bool isXor1OfSetCC(SDValue Op) {
8676 if (Op.getOpcode() != ISD::XOR)
8678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8679 if (N1C && N1C->getAPIntValue() == 1) {
8680 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8681 Op.getOperand(0).hasOneUse();
8686 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8687 bool addTest = true;
8688 SDValue Chain = Op.getOperand(0);
8689 SDValue Cond = Op.getOperand(1);
8690 SDValue Dest = Op.getOperand(2);
8691 DebugLoc dl = Op.getDebugLoc();
8693 bool Inverted = false;
8695 if (Cond.getOpcode() == ISD::SETCC) {
8696 // Check for setcc([su]{add,sub,mul}o == 0).
8697 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8698 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8699 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8700 Cond.getOperand(0).getResNo() == 1 &&
8701 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8702 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8703 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8704 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8705 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8706 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8708 Cond = Cond.getOperand(0);
8710 SDValue NewCond = LowerSETCC(Cond, DAG);
8711 if (NewCond.getNode())
8716 // FIXME: LowerXALUO doesn't handle these!!
8717 else if (Cond.getOpcode() == X86ISD::ADD ||
8718 Cond.getOpcode() == X86ISD::SUB ||
8719 Cond.getOpcode() == X86ISD::SMUL ||
8720 Cond.getOpcode() == X86ISD::UMUL)
8721 Cond = LowerXALUO(Cond, DAG);
8724 // Look pass (and (setcc_carry (cmp ...)), 1).
8725 if (Cond.getOpcode() == ISD::AND &&
8726 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8728 if (C && C->getAPIntValue() == 1)
8729 Cond = Cond.getOperand(0);
8732 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8733 // setting operand in place of the X86ISD::SETCC.
8734 unsigned CondOpcode = Cond.getOpcode();
8735 if (CondOpcode == X86ISD::SETCC ||
8736 CondOpcode == X86ISD::SETCC_CARRY) {
8737 CC = Cond.getOperand(0);
8739 SDValue Cmp = Cond.getOperand(1);
8740 unsigned Opc = Cmp.getOpcode();
8741 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8742 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8746 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8750 // These can only come from an arithmetic instruction with overflow,
8751 // e.g. SADDO, UADDO.
8752 Cond = Cond.getNode()->getOperand(1);
8758 CondOpcode = Cond.getOpcode();
8759 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8760 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8761 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8762 Cond.getOperand(0).getValueType() != MVT::i8)) {
8763 SDValue LHS = Cond.getOperand(0);
8764 SDValue RHS = Cond.getOperand(1);
8768 switch (CondOpcode) {
8769 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8770 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8771 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8772 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8773 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8774 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8775 default: llvm_unreachable("unexpected overflowing operator");
8778 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8779 if (CondOpcode == ISD::UMULO)
8780 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8783 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8785 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8787 if (CondOpcode == ISD::UMULO)
8788 Cond = X86Op.getValue(2);
8790 Cond = X86Op.getValue(1);
8792 CC = DAG.getConstant(X86Cond, MVT::i8);
8796 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8797 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8798 if (CondOpc == ISD::OR) {
8799 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8800 // two branches instead of an explicit OR instruction with a
8802 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8803 isX86LogicalCmp(Cmp)) {
8804 CC = Cond.getOperand(0).getOperand(0);
8805 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8806 Chain, Dest, CC, Cmp);
8807 CC = Cond.getOperand(1).getOperand(0);
8811 } else { // ISD::AND
8812 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8813 // two branches instead of an explicit AND instruction with a
8814 // separate test. However, we only do this if this block doesn't
8815 // have a fall-through edge, because this requires an explicit
8816 // jmp when the condition is false.
8817 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8818 isX86LogicalCmp(Cmp) &&
8819 Op.getNode()->hasOneUse()) {
8820 X86::CondCode CCode =
8821 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8822 CCode = X86::GetOppositeBranchCondition(CCode);
8823 CC = DAG.getConstant(CCode, MVT::i8);
8824 SDNode *User = *Op.getNode()->use_begin();
8825 // Look for an unconditional branch following this conditional branch.
8826 // We need this because we need to reverse the successors in order
8827 // to implement FCMP_OEQ.
8828 if (User->getOpcode() == ISD::BR) {
8829 SDValue FalseBB = User->getOperand(1);
8831 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8832 assert(NewBR == User);
8836 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8837 Chain, Dest, CC, Cmp);
8838 X86::CondCode CCode =
8839 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8840 CCode = X86::GetOppositeBranchCondition(CCode);
8841 CC = DAG.getConstant(CCode, MVT::i8);
8847 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8848 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8849 // It should be transformed during dag combiner except when the condition
8850 // is set by a arithmetics with overflow node.
8851 X86::CondCode CCode =
8852 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8853 CCode = X86::GetOppositeBranchCondition(CCode);
8854 CC = DAG.getConstant(CCode, MVT::i8);
8855 Cond = Cond.getOperand(0).getOperand(1);
8857 } else if (Cond.getOpcode() == ISD::SETCC &&
8858 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8859 // For FCMP_OEQ, we can emit
8860 // two branches instead of an explicit AND instruction with a
8861 // separate test. However, we only do this if this block doesn't
8862 // have a fall-through edge, because this requires an explicit
8863 // jmp when the condition is false.
8864 if (Op.getNode()->hasOneUse()) {
8865 SDNode *User = *Op.getNode()->use_begin();
8866 // Look for an unconditional branch following this conditional branch.
8867 // We need this because we need to reverse the successors in order
8868 // to implement FCMP_OEQ.
8869 if (User->getOpcode() == ISD::BR) {
8870 SDValue FalseBB = User->getOperand(1);
8872 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8873 assert(NewBR == User);
8877 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8878 Cond.getOperand(0), Cond.getOperand(1));
8879 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8880 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8881 Chain, Dest, CC, Cmp);
8882 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8887 } else if (Cond.getOpcode() == ISD::SETCC &&
8888 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8889 // For FCMP_UNE, we can emit
8890 // two branches instead of an explicit AND instruction with a
8891 // separate test. However, we only do this if this block doesn't
8892 // have a fall-through edge, because this requires an explicit
8893 // jmp when the condition is false.
8894 if (Op.getNode()->hasOneUse()) {
8895 SDNode *User = *Op.getNode()->use_begin();
8896 // Look for an unconditional branch following this conditional branch.
8897 // We need this because we need to reverse the successors in order
8898 // to implement FCMP_UNE.
8899 if (User->getOpcode() == ISD::BR) {
8900 SDValue FalseBB = User->getOperand(1);
8902 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8903 assert(NewBR == User);
8906 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8907 Cond.getOperand(0), Cond.getOperand(1));
8908 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8909 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8910 Chain, Dest, CC, Cmp);
8911 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8921 // Look pass the truncate.
8922 if (Cond.getOpcode() == ISD::TRUNCATE)
8923 Cond = Cond.getOperand(0);
8925 // We know the result of AND is compared against zero. Try to match
8927 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8928 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8929 if (NewSetCC.getNode()) {
8930 CC = NewSetCC.getOperand(0);
8931 Cond = NewSetCC.getOperand(1);
8938 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8939 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8941 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8942 Chain, Dest, CC, Cond);
8946 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8947 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8948 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8949 // that the guard pages used by the OS virtual memory manager are allocated in
8950 // correct sequence.
8952 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8953 SelectionDAG &DAG) const {
8954 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8955 getTargetMachine().Options.EnableSegmentedStacks) &&
8956 "This should be used only on Windows targets or when segmented stacks "
8958 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8959 DebugLoc dl = Op.getDebugLoc();
8962 SDValue Chain = Op.getOperand(0);
8963 SDValue Size = Op.getOperand(1);
8964 // FIXME: Ensure alignment here
8966 bool Is64Bit = Subtarget->is64Bit();
8967 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8969 if (getTargetMachine().Options.EnableSegmentedStacks) {
8970 MachineFunction &MF = DAG.getMachineFunction();
8971 MachineRegisterInfo &MRI = MF.getRegInfo();
8974 // The 64 bit implementation of segmented stacks needs to clobber both r10
8975 // r11. This makes it impossible to use it along with nested parameters.
8976 const Function *F = MF.getFunction();
8978 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8980 if (I->hasNestAttr())
8981 report_fatal_error("Cannot use segmented stacks with functions that "
8982 "have nested arguments.");
8985 const TargetRegisterClass *AddrRegClass =
8986 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8987 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8988 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8989 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8990 DAG.getRegister(Vreg, SPTy));
8991 SDValue Ops1[2] = { Value, Chain };
8992 return DAG.getMergeValues(Ops1, 2, dl);
8995 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8997 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8998 Flag = Chain.getValue(1);
8999 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9001 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9002 Flag = Chain.getValue(1);
9004 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9006 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9007 return DAG.getMergeValues(Ops1, 2, dl);
9011 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9012 MachineFunction &MF = DAG.getMachineFunction();
9013 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9015 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9016 DebugLoc DL = Op.getDebugLoc();
9018 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9019 // vastart just stores the address of the VarArgsFrameIndex slot into the
9020 // memory location argument.
9021 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9023 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9024 MachinePointerInfo(SV), false, false, 0);
9028 // gp_offset (0 - 6 * 8)
9029 // fp_offset (48 - 48 + 8 * 16)
9030 // overflow_arg_area (point to parameters coming in memory).
9032 SmallVector<SDValue, 8> MemOps;
9033 SDValue FIN = Op.getOperand(1);
9035 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9036 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9038 FIN, MachinePointerInfo(SV), false, false, 0);
9039 MemOps.push_back(Store);
9042 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9043 FIN, DAG.getIntPtrConstant(4));
9044 Store = DAG.getStore(Op.getOperand(0), DL,
9045 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9047 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9048 MemOps.push_back(Store);
9050 // Store ptr to overflow_arg_area
9051 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9052 FIN, DAG.getIntPtrConstant(4));
9053 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9055 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9056 MachinePointerInfo(SV, 8),
9058 MemOps.push_back(Store);
9060 // Store ptr to reg_save_area.
9061 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9062 FIN, DAG.getIntPtrConstant(8));
9063 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9065 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9066 MachinePointerInfo(SV, 16), false, false, 0);
9067 MemOps.push_back(Store);
9068 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9069 &MemOps[0], MemOps.size());
9072 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9073 assert(Subtarget->is64Bit() &&
9074 "LowerVAARG only handles 64-bit va_arg!");
9075 assert((Subtarget->isTargetLinux() ||
9076 Subtarget->isTargetDarwin()) &&
9077 "Unhandled target in LowerVAARG");
9078 assert(Op.getNode()->getNumOperands() == 4);
9079 SDValue Chain = Op.getOperand(0);
9080 SDValue SrcPtr = Op.getOperand(1);
9081 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9082 unsigned Align = Op.getConstantOperandVal(3);
9083 DebugLoc dl = Op.getDebugLoc();
9085 EVT ArgVT = Op.getNode()->getValueType(0);
9086 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9087 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9090 // Decide which area this value should be read from.
9091 // TODO: Implement the AMD64 ABI in its entirety. This simple
9092 // selection mechanism works only for the basic types.
9093 if (ArgVT == MVT::f80) {
9094 llvm_unreachable("va_arg for f80 not yet implemented");
9095 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9096 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9097 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9098 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9100 llvm_unreachable("Unhandled argument type in LowerVAARG");
9104 // Sanity Check: Make sure using fp_offset makes sense.
9105 assert(!getTargetMachine().Options.UseSoftFloat &&
9106 !(DAG.getMachineFunction()
9107 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9108 Subtarget->hasXMM());
9111 // Insert VAARG_64 node into the DAG
9112 // VAARG_64 returns two values: Variable Argument Address, Chain
9113 SmallVector<SDValue, 11> InstOps;
9114 InstOps.push_back(Chain);
9115 InstOps.push_back(SrcPtr);
9116 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9117 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9118 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9119 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9120 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9121 VTs, &InstOps[0], InstOps.size(),
9123 MachinePointerInfo(SV),
9128 Chain = VAARG.getValue(1);
9130 // Load the next argument and return it
9131 return DAG.getLoad(ArgVT, dl,
9134 MachinePointerInfo(),
9135 false, false, false, 0);
9138 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9139 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9140 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9141 SDValue Chain = Op.getOperand(0);
9142 SDValue DstPtr = Op.getOperand(1);
9143 SDValue SrcPtr = Op.getOperand(2);
9144 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9145 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9146 DebugLoc DL = Op.getDebugLoc();
9148 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9149 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9151 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9155 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9156 DebugLoc dl = Op.getDebugLoc();
9157 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9159 default: return SDValue(); // Don't custom lower most intrinsics.
9160 // Comparison intrinsics.
9161 case Intrinsic::x86_sse_comieq_ss:
9162 case Intrinsic::x86_sse_comilt_ss:
9163 case Intrinsic::x86_sse_comile_ss:
9164 case Intrinsic::x86_sse_comigt_ss:
9165 case Intrinsic::x86_sse_comige_ss:
9166 case Intrinsic::x86_sse_comineq_ss:
9167 case Intrinsic::x86_sse_ucomieq_ss:
9168 case Intrinsic::x86_sse_ucomilt_ss:
9169 case Intrinsic::x86_sse_ucomile_ss:
9170 case Intrinsic::x86_sse_ucomigt_ss:
9171 case Intrinsic::x86_sse_ucomige_ss:
9172 case Intrinsic::x86_sse_ucomineq_ss:
9173 case Intrinsic::x86_sse2_comieq_sd:
9174 case Intrinsic::x86_sse2_comilt_sd:
9175 case Intrinsic::x86_sse2_comile_sd:
9176 case Intrinsic::x86_sse2_comigt_sd:
9177 case Intrinsic::x86_sse2_comige_sd:
9178 case Intrinsic::x86_sse2_comineq_sd:
9179 case Intrinsic::x86_sse2_ucomieq_sd:
9180 case Intrinsic::x86_sse2_ucomilt_sd:
9181 case Intrinsic::x86_sse2_ucomile_sd:
9182 case Intrinsic::x86_sse2_ucomigt_sd:
9183 case Intrinsic::x86_sse2_ucomige_sd:
9184 case Intrinsic::x86_sse2_ucomineq_sd: {
9186 ISD::CondCode CC = ISD::SETCC_INVALID;
9189 case Intrinsic::x86_sse_comieq_ss:
9190 case Intrinsic::x86_sse2_comieq_sd:
9194 case Intrinsic::x86_sse_comilt_ss:
9195 case Intrinsic::x86_sse2_comilt_sd:
9199 case Intrinsic::x86_sse_comile_ss:
9200 case Intrinsic::x86_sse2_comile_sd:
9204 case Intrinsic::x86_sse_comigt_ss:
9205 case Intrinsic::x86_sse2_comigt_sd:
9209 case Intrinsic::x86_sse_comige_ss:
9210 case Intrinsic::x86_sse2_comige_sd:
9214 case Intrinsic::x86_sse_comineq_ss:
9215 case Intrinsic::x86_sse2_comineq_sd:
9219 case Intrinsic::x86_sse_ucomieq_ss:
9220 case Intrinsic::x86_sse2_ucomieq_sd:
9221 Opc = X86ISD::UCOMI;
9224 case Intrinsic::x86_sse_ucomilt_ss:
9225 case Intrinsic::x86_sse2_ucomilt_sd:
9226 Opc = X86ISD::UCOMI;
9229 case Intrinsic::x86_sse_ucomile_ss:
9230 case Intrinsic::x86_sse2_ucomile_sd:
9231 Opc = X86ISD::UCOMI;
9234 case Intrinsic::x86_sse_ucomigt_ss:
9235 case Intrinsic::x86_sse2_ucomigt_sd:
9236 Opc = X86ISD::UCOMI;
9239 case Intrinsic::x86_sse_ucomige_ss:
9240 case Intrinsic::x86_sse2_ucomige_sd:
9241 Opc = X86ISD::UCOMI;
9244 case Intrinsic::x86_sse_ucomineq_ss:
9245 case Intrinsic::x86_sse2_ucomineq_sd:
9246 Opc = X86ISD::UCOMI;
9251 SDValue LHS = Op.getOperand(1);
9252 SDValue RHS = Op.getOperand(2);
9253 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9254 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9255 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9256 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9257 DAG.getConstant(X86CC, MVT::i8), Cond);
9258 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9260 // Arithmetic intrinsics.
9261 case Intrinsic::x86_sse3_hadd_ps:
9262 case Intrinsic::x86_sse3_hadd_pd:
9263 case Intrinsic::x86_avx_hadd_ps_256:
9264 case Intrinsic::x86_avx_hadd_pd_256:
9265 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9266 Op.getOperand(1), Op.getOperand(2));
9267 case Intrinsic::x86_sse3_hsub_ps:
9268 case Intrinsic::x86_sse3_hsub_pd:
9269 case Intrinsic::x86_avx_hsub_ps_256:
9270 case Intrinsic::x86_avx_hsub_pd_256:
9271 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9272 Op.getOperand(1), Op.getOperand(2));
9273 case Intrinsic::x86_avx2_psllv_d:
9274 case Intrinsic::x86_avx2_psllv_q:
9275 case Intrinsic::x86_avx2_psllv_d_256:
9276 case Intrinsic::x86_avx2_psllv_q_256:
9277 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9278 Op.getOperand(1), Op.getOperand(2));
9279 case Intrinsic::x86_avx2_psrlv_d:
9280 case Intrinsic::x86_avx2_psrlv_q:
9281 case Intrinsic::x86_avx2_psrlv_d_256:
9282 case Intrinsic::x86_avx2_psrlv_q_256:
9283 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9284 Op.getOperand(1), Op.getOperand(2));
9285 case Intrinsic::x86_avx2_psrav_d:
9286 case Intrinsic::x86_avx2_psrav_d_256:
9287 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9288 Op.getOperand(1), Op.getOperand(2));
9290 // ptest and testp intrinsics. The intrinsic these come from are designed to
9291 // return an integer value, not just an instruction so lower it to the ptest
9292 // or testp pattern and a setcc for the result.
9293 case Intrinsic::x86_sse41_ptestz:
9294 case Intrinsic::x86_sse41_ptestc:
9295 case Intrinsic::x86_sse41_ptestnzc:
9296 case Intrinsic::x86_avx_ptestz_256:
9297 case Intrinsic::x86_avx_ptestc_256:
9298 case Intrinsic::x86_avx_ptestnzc_256:
9299 case Intrinsic::x86_avx_vtestz_ps:
9300 case Intrinsic::x86_avx_vtestc_ps:
9301 case Intrinsic::x86_avx_vtestnzc_ps:
9302 case Intrinsic::x86_avx_vtestz_pd:
9303 case Intrinsic::x86_avx_vtestc_pd:
9304 case Intrinsic::x86_avx_vtestnzc_pd:
9305 case Intrinsic::x86_avx_vtestz_ps_256:
9306 case Intrinsic::x86_avx_vtestc_ps_256:
9307 case Intrinsic::x86_avx_vtestnzc_ps_256:
9308 case Intrinsic::x86_avx_vtestz_pd_256:
9309 case Intrinsic::x86_avx_vtestc_pd_256:
9310 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9311 bool IsTestPacked = false;
9314 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9315 case Intrinsic::x86_avx_vtestz_ps:
9316 case Intrinsic::x86_avx_vtestz_pd:
9317 case Intrinsic::x86_avx_vtestz_ps_256:
9318 case Intrinsic::x86_avx_vtestz_pd_256:
9319 IsTestPacked = true; // Fallthrough
9320 case Intrinsic::x86_sse41_ptestz:
9321 case Intrinsic::x86_avx_ptestz_256:
9323 X86CC = X86::COND_E;
9325 case Intrinsic::x86_avx_vtestc_ps:
9326 case Intrinsic::x86_avx_vtestc_pd:
9327 case Intrinsic::x86_avx_vtestc_ps_256:
9328 case Intrinsic::x86_avx_vtestc_pd_256:
9329 IsTestPacked = true; // Fallthrough
9330 case Intrinsic::x86_sse41_ptestc:
9331 case Intrinsic::x86_avx_ptestc_256:
9333 X86CC = X86::COND_B;
9335 case Intrinsic::x86_avx_vtestnzc_ps:
9336 case Intrinsic::x86_avx_vtestnzc_pd:
9337 case Intrinsic::x86_avx_vtestnzc_ps_256:
9338 case Intrinsic::x86_avx_vtestnzc_pd_256:
9339 IsTestPacked = true; // Fallthrough
9340 case Intrinsic::x86_sse41_ptestnzc:
9341 case Intrinsic::x86_avx_ptestnzc_256:
9343 X86CC = X86::COND_A;
9347 SDValue LHS = Op.getOperand(1);
9348 SDValue RHS = Op.getOperand(2);
9349 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9350 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9351 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9352 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9353 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9356 // Fix vector shift instructions where the last operand is a non-immediate
9358 case Intrinsic::x86_avx2_pslli_w:
9359 case Intrinsic::x86_avx2_pslli_d:
9360 case Intrinsic::x86_avx2_pslli_q:
9361 case Intrinsic::x86_avx2_psrli_w:
9362 case Intrinsic::x86_avx2_psrli_d:
9363 case Intrinsic::x86_avx2_psrli_q:
9364 case Intrinsic::x86_avx2_psrai_w:
9365 case Intrinsic::x86_avx2_psrai_d:
9366 case Intrinsic::x86_sse2_pslli_w:
9367 case Intrinsic::x86_sse2_pslli_d:
9368 case Intrinsic::x86_sse2_pslli_q:
9369 case Intrinsic::x86_sse2_psrli_w:
9370 case Intrinsic::x86_sse2_psrli_d:
9371 case Intrinsic::x86_sse2_psrli_q:
9372 case Intrinsic::x86_sse2_psrai_w:
9373 case Intrinsic::x86_sse2_psrai_d:
9374 case Intrinsic::x86_mmx_pslli_w:
9375 case Intrinsic::x86_mmx_pslli_d:
9376 case Intrinsic::x86_mmx_pslli_q:
9377 case Intrinsic::x86_mmx_psrli_w:
9378 case Intrinsic::x86_mmx_psrli_d:
9379 case Intrinsic::x86_mmx_psrli_q:
9380 case Intrinsic::x86_mmx_psrai_w:
9381 case Intrinsic::x86_mmx_psrai_d: {
9382 SDValue ShAmt = Op.getOperand(2);
9383 if (isa<ConstantSDNode>(ShAmt))
9386 unsigned NewIntNo = 0;
9387 EVT ShAmtVT = MVT::v4i32;
9389 case Intrinsic::x86_sse2_pslli_w:
9390 NewIntNo = Intrinsic::x86_sse2_psll_w;
9392 case Intrinsic::x86_sse2_pslli_d:
9393 NewIntNo = Intrinsic::x86_sse2_psll_d;
9395 case Intrinsic::x86_sse2_pslli_q:
9396 NewIntNo = Intrinsic::x86_sse2_psll_q;
9398 case Intrinsic::x86_sse2_psrli_w:
9399 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9401 case Intrinsic::x86_sse2_psrli_d:
9402 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9404 case Intrinsic::x86_sse2_psrli_q:
9405 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9407 case Intrinsic::x86_sse2_psrai_w:
9408 NewIntNo = Intrinsic::x86_sse2_psra_w;
9410 case Intrinsic::x86_sse2_psrai_d:
9411 NewIntNo = Intrinsic::x86_sse2_psra_d;
9413 case Intrinsic::x86_avx2_pslli_w:
9414 NewIntNo = Intrinsic::x86_avx2_psll_w;
9416 case Intrinsic::x86_avx2_pslli_d:
9417 NewIntNo = Intrinsic::x86_avx2_psll_d;
9419 case Intrinsic::x86_avx2_pslli_q:
9420 NewIntNo = Intrinsic::x86_avx2_psll_q;
9422 case Intrinsic::x86_avx2_psrli_w:
9423 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9425 case Intrinsic::x86_avx2_psrli_d:
9426 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9428 case Intrinsic::x86_avx2_psrli_q:
9429 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9431 case Intrinsic::x86_avx2_psrai_w:
9432 NewIntNo = Intrinsic::x86_avx2_psra_w;
9434 case Intrinsic::x86_avx2_psrai_d:
9435 NewIntNo = Intrinsic::x86_avx2_psra_d;
9438 ShAmtVT = MVT::v2i32;
9440 case Intrinsic::x86_mmx_pslli_w:
9441 NewIntNo = Intrinsic::x86_mmx_psll_w;
9443 case Intrinsic::x86_mmx_pslli_d:
9444 NewIntNo = Intrinsic::x86_mmx_psll_d;
9446 case Intrinsic::x86_mmx_pslli_q:
9447 NewIntNo = Intrinsic::x86_mmx_psll_q;
9449 case Intrinsic::x86_mmx_psrli_w:
9450 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9452 case Intrinsic::x86_mmx_psrli_d:
9453 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9455 case Intrinsic::x86_mmx_psrli_q:
9456 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9458 case Intrinsic::x86_mmx_psrai_w:
9459 NewIntNo = Intrinsic::x86_mmx_psra_w;
9461 case Intrinsic::x86_mmx_psrai_d:
9462 NewIntNo = Intrinsic::x86_mmx_psra_d;
9464 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9470 // The vector shift intrinsics with scalars uses 32b shift amounts but
9471 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9475 ShOps[1] = DAG.getConstant(0, MVT::i32);
9476 if (ShAmtVT == MVT::v4i32) {
9477 ShOps[2] = DAG.getUNDEF(MVT::i32);
9478 ShOps[3] = DAG.getUNDEF(MVT::i32);
9479 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9481 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9482 // FIXME this must be lowered to get rid of the invalid type.
9485 EVT VT = Op.getValueType();
9486 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9487 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9488 DAG.getConstant(NewIntNo, MVT::i32),
9489 Op.getOperand(1), ShAmt);
9494 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9495 SelectionDAG &DAG) const {
9496 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9497 MFI->setReturnAddressIsTaken(true);
9499 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9500 DebugLoc dl = Op.getDebugLoc();
9503 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9505 DAG.getConstant(TD->getPointerSize(),
9506 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9507 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9508 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9510 MachinePointerInfo(), false, false, false, 0);
9513 // Just load the return address.
9514 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9515 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9516 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9519 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9520 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9521 MFI->setFrameAddressIsTaken(true);
9523 EVT VT = Op.getValueType();
9524 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9525 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9526 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9527 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9529 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9530 MachinePointerInfo(),
9531 false, false, false, 0);
9535 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9536 SelectionDAG &DAG) const {
9537 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9540 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9541 MachineFunction &MF = DAG.getMachineFunction();
9542 SDValue Chain = Op.getOperand(0);
9543 SDValue Offset = Op.getOperand(1);
9544 SDValue Handler = Op.getOperand(2);
9545 DebugLoc dl = Op.getDebugLoc();
9547 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9548 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9550 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9552 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9553 DAG.getIntPtrConstant(TD->getPointerSize()));
9554 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9555 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9557 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9558 MF.getRegInfo().addLiveOut(StoreAddrReg);
9560 return DAG.getNode(X86ISD::EH_RETURN, dl,
9562 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9565 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9566 SelectionDAG &DAG) const {
9567 return Op.getOperand(0);
9570 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9571 SelectionDAG &DAG) const {
9572 SDValue Root = Op.getOperand(0);
9573 SDValue Trmp = Op.getOperand(1); // trampoline
9574 SDValue FPtr = Op.getOperand(2); // nested function
9575 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9576 DebugLoc dl = Op.getDebugLoc();
9578 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9580 if (Subtarget->is64Bit()) {
9581 SDValue OutChains[6];
9583 // Large code-model.
9584 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9585 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9587 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9588 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9590 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9592 // Load the pointer to the nested function into R11.
9593 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9594 SDValue Addr = Trmp;
9595 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9596 Addr, MachinePointerInfo(TrmpAddr),
9599 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9600 DAG.getConstant(2, MVT::i64));
9601 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9602 MachinePointerInfo(TrmpAddr, 2),
9605 // Load the 'nest' parameter value into R10.
9606 // R10 is specified in X86CallingConv.td
9607 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9608 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9609 DAG.getConstant(10, MVT::i64));
9610 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9611 Addr, MachinePointerInfo(TrmpAddr, 10),
9614 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9615 DAG.getConstant(12, MVT::i64));
9616 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9617 MachinePointerInfo(TrmpAddr, 12),
9620 // Jump to the nested function.
9621 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9622 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9623 DAG.getConstant(20, MVT::i64));
9624 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9625 Addr, MachinePointerInfo(TrmpAddr, 20),
9628 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9629 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9630 DAG.getConstant(22, MVT::i64));
9631 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9632 MachinePointerInfo(TrmpAddr, 22),
9635 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9637 const Function *Func =
9638 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9639 CallingConv::ID CC = Func->getCallingConv();
9644 llvm_unreachable("Unsupported calling convention");
9645 case CallingConv::C:
9646 case CallingConv::X86_StdCall: {
9647 // Pass 'nest' parameter in ECX.
9648 // Must be kept in sync with X86CallingConv.td
9651 // Check that ECX wasn't needed by an 'inreg' parameter.
9652 FunctionType *FTy = Func->getFunctionType();
9653 const AttrListPtr &Attrs = Func->getAttributes();
9655 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9656 unsigned InRegCount = 0;
9659 for (FunctionType::param_iterator I = FTy->param_begin(),
9660 E = FTy->param_end(); I != E; ++I, ++Idx)
9661 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9662 // FIXME: should only count parameters that are lowered to integers.
9663 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9665 if (InRegCount > 2) {
9666 report_fatal_error("Nest register in use - reduce number of inreg"
9672 case CallingConv::X86_FastCall:
9673 case CallingConv::X86_ThisCall:
9674 case CallingConv::Fast:
9675 // Pass 'nest' parameter in EAX.
9676 // Must be kept in sync with X86CallingConv.td
9681 SDValue OutChains[4];
9684 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9685 DAG.getConstant(10, MVT::i32));
9686 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9688 // This is storing the opcode for MOV32ri.
9689 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9690 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9691 OutChains[0] = DAG.getStore(Root, dl,
9692 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9693 Trmp, MachinePointerInfo(TrmpAddr),
9696 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9697 DAG.getConstant(1, MVT::i32));
9698 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9699 MachinePointerInfo(TrmpAddr, 1),
9702 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9703 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9704 DAG.getConstant(5, MVT::i32));
9705 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9706 MachinePointerInfo(TrmpAddr, 5),
9709 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9710 DAG.getConstant(6, MVT::i32));
9711 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9712 MachinePointerInfo(TrmpAddr, 6),
9715 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9719 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9720 SelectionDAG &DAG) const {
9722 The rounding mode is in bits 11:10 of FPSR, and has the following
9729 FLT_ROUNDS, on the other hand, expects the following:
9736 To perform the conversion, we do:
9737 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9740 MachineFunction &MF = DAG.getMachineFunction();
9741 const TargetMachine &TM = MF.getTarget();
9742 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9743 unsigned StackAlignment = TFI.getStackAlignment();
9744 EVT VT = Op.getValueType();
9745 DebugLoc DL = Op.getDebugLoc();
9747 // Save FP Control Word to stack slot
9748 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9749 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9752 MachineMemOperand *MMO =
9753 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9754 MachineMemOperand::MOStore, 2, 2);
9756 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9757 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9758 DAG.getVTList(MVT::Other),
9759 Ops, 2, MVT::i16, MMO);
9761 // Load FP Control Word from stack slot
9762 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9763 MachinePointerInfo(), false, false, false, 0);
9765 // Transform as necessary
9767 DAG.getNode(ISD::SRL, DL, MVT::i16,
9768 DAG.getNode(ISD::AND, DL, MVT::i16,
9769 CWD, DAG.getConstant(0x800, MVT::i16)),
9770 DAG.getConstant(11, MVT::i8));
9772 DAG.getNode(ISD::SRL, DL, MVT::i16,
9773 DAG.getNode(ISD::AND, DL, MVT::i16,
9774 CWD, DAG.getConstant(0x400, MVT::i16)),
9775 DAG.getConstant(9, MVT::i8));
9778 DAG.getNode(ISD::AND, DL, MVT::i16,
9779 DAG.getNode(ISD::ADD, DL, MVT::i16,
9780 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9781 DAG.getConstant(1, MVT::i16)),
9782 DAG.getConstant(3, MVT::i16));
9785 return DAG.getNode((VT.getSizeInBits() < 16 ?
9786 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9789 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9790 EVT VT = Op.getValueType();
9792 unsigned NumBits = VT.getSizeInBits();
9793 DebugLoc dl = Op.getDebugLoc();
9795 Op = Op.getOperand(0);
9796 if (VT == MVT::i8) {
9797 // Zero extend to i32 since there is not an i8 bsr.
9799 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9802 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9803 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9804 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9806 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9809 DAG.getConstant(NumBits+NumBits-1, OpVT),
9810 DAG.getConstant(X86::COND_E, MVT::i8),
9813 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9815 // Finally xor with NumBits-1.
9816 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9819 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9823 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9824 EVT VT = Op.getValueType();
9826 unsigned NumBits = VT.getSizeInBits();
9827 DebugLoc dl = Op.getDebugLoc();
9829 Op = Op.getOperand(0);
9830 if (VT == MVT::i8) {
9832 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9835 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9836 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9837 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9839 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9842 DAG.getConstant(NumBits, OpVT),
9843 DAG.getConstant(X86::COND_E, MVT::i8),
9846 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9849 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9853 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9854 // ones, and then concatenate the result back.
9855 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9856 EVT VT = Op.getValueType();
9858 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9859 "Unsupported value type for operation");
9861 int NumElems = VT.getVectorNumElements();
9862 DebugLoc dl = Op.getDebugLoc();
9863 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9864 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9866 // Extract the LHS vectors
9867 SDValue LHS = Op.getOperand(0);
9868 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9869 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9871 // Extract the RHS vectors
9872 SDValue RHS = Op.getOperand(1);
9873 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9874 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9876 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9877 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9879 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9880 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9881 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9884 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9885 assert(Op.getValueType().getSizeInBits() == 256 &&
9886 Op.getValueType().isInteger() &&
9887 "Only handle AVX 256-bit vector integer operation");
9888 return Lower256IntArith(Op, DAG);
9891 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9892 assert(Op.getValueType().getSizeInBits() == 256 &&
9893 Op.getValueType().isInteger() &&
9894 "Only handle AVX 256-bit vector integer operation");
9895 return Lower256IntArith(Op, DAG);
9898 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9899 EVT VT = Op.getValueType();
9901 // Decompose 256-bit ops into smaller 128-bit ops.
9902 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9903 return Lower256IntArith(Op, DAG);
9905 DebugLoc dl = Op.getDebugLoc();
9907 SDValue A = Op.getOperand(0);
9908 SDValue B = Op.getOperand(1);
9910 if (VT == MVT::v4i64) {
9911 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9913 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9914 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9915 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9916 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9917 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9919 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9920 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9921 // return AloBlo + AloBhi + AhiBlo;
9923 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9924 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9925 A, DAG.getConstant(32, MVT::i32));
9926 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9927 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9928 B, DAG.getConstant(32, MVT::i32));
9929 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9930 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9932 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9933 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9935 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9936 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9938 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9939 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9940 AloBhi, DAG.getConstant(32, MVT::i32));
9941 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9942 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9943 AhiBlo, DAG.getConstant(32, MVT::i32));
9944 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9945 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9949 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9951 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9952 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9953 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9954 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9955 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9957 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9958 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9959 // return AloBlo + AloBhi + AhiBlo;
9961 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9962 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9963 A, DAG.getConstant(32, MVT::i32));
9964 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9965 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9966 B, DAG.getConstant(32, MVT::i32));
9967 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9968 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9970 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9971 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9973 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9974 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9976 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9977 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9978 AloBhi, DAG.getConstant(32, MVT::i32));
9979 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9980 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9981 AhiBlo, DAG.getConstant(32, MVT::i32));
9982 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9983 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9987 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9989 EVT VT = Op.getValueType();
9990 DebugLoc dl = Op.getDebugLoc();
9991 SDValue R = Op.getOperand(0);
9992 SDValue Amt = Op.getOperand(1);
9993 LLVMContext *Context = DAG.getContext();
9995 if (!Subtarget->hasXMMInt())
9998 // Optimize shl/srl/sra with constant shift amount.
9999 if (isSplatVector(Amt.getNode())) {
10000 SDValue SclrAmt = Amt->getOperand(0);
10001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10002 uint64_t ShiftAmt = C->getZExtValue();
10004 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10005 // Make a large shift.
10007 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10008 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10009 R, DAG.getConstant(ShiftAmt, MVT::i32));
10010 // Zero out the rightmost bits.
10011 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10013 return DAG.getNode(ISD::AND, dl, VT, SHL,
10014 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10017 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10018 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10019 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10020 R, DAG.getConstant(ShiftAmt, MVT::i32));
10022 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10023 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10024 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10025 R, DAG.getConstant(ShiftAmt, MVT::i32));
10027 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10028 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10029 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10030 R, DAG.getConstant(ShiftAmt, MVT::i32));
10032 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10033 // Make a large shift.
10035 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10036 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10037 R, DAG.getConstant(ShiftAmt, MVT::i32));
10038 // Zero out the leftmost bits.
10039 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10041 return DAG.getNode(ISD::AND, dl, VT, SRL,
10042 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10045 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10046 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10047 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10048 R, DAG.getConstant(ShiftAmt, MVT::i32));
10050 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10051 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10052 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10053 R, DAG.getConstant(ShiftAmt, MVT::i32));
10055 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10056 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10057 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10058 R, DAG.getConstant(ShiftAmt, MVT::i32));
10060 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10061 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10062 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10063 R, DAG.getConstant(ShiftAmt, MVT::i32));
10065 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10066 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10067 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10068 R, DAG.getConstant(ShiftAmt, MVT::i32));
10070 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10071 if (ShiftAmt == 7) {
10072 // R s>> 7 === R s< 0
10073 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10074 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10077 // R s>> a === ((R u>> a) ^ m) - m
10078 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10079 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10081 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10082 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10083 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10087 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10088 if (Op.getOpcode() == ISD::SHL) {
10089 // Make a large shift.
10091 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10092 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10093 R, DAG.getConstant(ShiftAmt, MVT::i32));
10094 // Zero out the rightmost bits.
10095 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10097 return DAG.getNode(ISD::AND, dl, VT, SHL,
10098 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10100 if (Op.getOpcode() == ISD::SRL) {
10101 // Make a large shift.
10103 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10104 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10105 R, DAG.getConstant(ShiftAmt, MVT::i32));
10106 // Zero out the leftmost bits.
10107 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10109 return DAG.getNode(ISD::AND, dl, VT, SRL,
10110 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10112 if (Op.getOpcode() == ISD::SRA) {
10113 if (ShiftAmt == 7) {
10114 // R s>> 7 === R s< 0
10115 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10116 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10119 // R s>> a === ((R u>> a) ^ m) - m
10120 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10121 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10123 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10124 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10125 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10132 // Lower SHL with variable shift amount.
10133 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10134 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10135 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10136 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10138 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10140 std::vector<Constant*> CV(4, CI);
10141 Constant *C = ConstantVector::get(CV);
10142 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10143 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10144 MachinePointerInfo::getConstantPool(),
10145 false, false, false, 16);
10147 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10148 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10149 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10150 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10152 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10154 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10155 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10156 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10158 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10159 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10161 std::vector<Constant*> CVM1(16, CM1);
10162 std::vector<Constant*> CVM2(16, CM2);
10163 Constant *C = ConstantVector::get(CVM1);
10164 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10165 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10166 MachinePointerInfo::getConstantPool(),
10167 false, false, false, 16);
10169 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10170 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10171 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10172 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10173 DAG.getConstant(4, MVT::i32));
10174 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10176 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10178 C = ConstantVector::get(CVM2);
10179 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10180 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10181 MachinePointerInfo::getConstantPool(),
10182 false, false, false, 16);
10184 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10185 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10186 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10187 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10188 DAG.getConstant(2, MVT::i32));
10189 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10191 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10193 // return pblendv(r, r+r, a);
10194 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10195 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10199 // Decompose 256-bit shifts into smaller 128-bit shifts.
10200 if (VT.getSizeInBits() == 256) {
10201 int NumElems = VT.getVectorNumElements();
10202 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10203 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10205 // Extract the two vectors
10206 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10207 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10210 // Recreate the shift amount vectors
10211 SDValue Amt1, Amt2;
10212 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10213 // Constant shift amount
10214 SmallVector<SDValue, 4> Amt1Csts;
10215 SmallVector<SDValue, 4> Amt2Csts;
10216 for (int i = 0; i < NumElems/2; ++i)
10217 Amt1Csts.push_back(Amt->getOperand(i));
10218 for (int i = NumElems/2; i < NumElems; ++i)
10219 Amt2Csts.push_back(Amt->getOperand(i));
10221 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10222 &Amt1Csts[0], NumElems/2);
10223 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10224 &Amt2Csts[0], NumElems/2);
10226 // Variable shift amount
10227 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10228 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10232 // Issue new vector shifts for the smaller types
10233 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10234 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10236 // Concatenate the result back
10237 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10243 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10244 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10245 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10246 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10247 // has only one use.
10248 SDNode *N = Op.getNode();
10249 SDValue LHS = N->getOperand(0);
10250 SDValue RHS = N->getOperand(1);
10251 unsigned BaseOp = 0;
10253 DebugLoc DL = Op.getDebugLoc();
10254 switch (Op.getOpcode()) {
10255 default: llvm_unreachable("Unknown ovf instruction!");
10257 // A subtract of one will be selected as a INC. Note that INC doesn't
10258 // set CF, so we can't do this for UADDO.
10259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10261 BaseOp = X86ISD::INC;
10262 Cond = X86::COND_O;
10265 BaseOp = X86ISD::ADD;
10266 Cond = X86::COND_O;
10269 BaseOp = X86ISD::ADD;
10270 Cond = X86::COND_B;
10273 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10274 // set CF, so we can't do this for USUBO.
10275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10277 BaseOp = X86ISD::DEC;
10278 Cond = X86::COND_O;
10281 BaseOp = X86ISD::SUB;
10282 Cond = X86::COND_O;
10285 BaseOp = X86ISD::SUB;
10286 Cond = X86::COND_B;
10289 BaseOp = X86ISD::SMUL;
10290 Cond = X86::COND_O;
10292 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10293 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10295 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10298 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10299 DAG.getConstant(X86::COND_O, MVT::i32),
10300 SDValue(Sum.getNode(), 2));
10302 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10306 // Also sets EFLAGS.
10307 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10308 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10311 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10312 DAG.getConstant(Cond, MVT::i32),
10313 SDValue(Sum.getNode(), 1));
10315 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10318 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10319 DebugLoc dl = Op.getDebugLoc();
10320 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10321 EVT VT = Op.getValueType();
10323 if (Subtarget->hasXMMInt() && VT.isVector()) {
10324 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10325 ExtraVT.getScalarType().getSizeInBits();
10326 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10328 unsigned SHLIntrinsicsID = 0;
10329 unsigned SRAIntrinsicsID = 0;
10330 switch (VT.getSimpleVT().SimpleTy) {
10334 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10335 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10338 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10339 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10343 if (!Subtarget->hasAVX())
10345 if (!Subtarget->hasAVX2()) {
10346 // needs to be split
10347 int NumElems = VT.getVectorNumElements();
10348 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10349 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10351 // Extract the LHS vectors
10352 SDValue LHS = Op.getOperand(0);
10353 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10354 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10356 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10357 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10359 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10360 int ExtraNumElems = ExtraVT.getVectorNumElements();
10361 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10363 SDValue Extra = DAG.getValueType(ExtraVT);
10365 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10366 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10368 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10370 if (VT == MVT::v8i32) {
10371 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10372 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10374 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10375 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10379 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10380 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10381 Op.getOperand(0), ShAmt);
10383 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10384 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10392 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10393 DebugLoc dl = Op.getDebugLoc();
10395 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10396 // There isn't any reason to disable it if the target processor supports it.
10397 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10398 SDValue Chain = Op.getOperand(0);
10399 SDValue Zero = DAG.getConstant(0, MVT::i32);
10401 DAG.getRegister(X86::ESP, MVT::i32), // Base
10402 DAG.getTargetConstant(1, MVT::i8), // Scale
10403 DAG.getRegister(0, MVT::i32), // Index
10404 DAG.getTargetConstant(0, MVT::i32), // Disp
10405 DAG.getRegister(0, MVT::i32), // Segment.
10410 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10411 array_lengthof(Ops));
10412 return SDValue(Res, 0);
10415 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10417 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10419 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10420 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10421 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10422 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10424 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10425 if (!Op1 && !Op2 && !Op3 && Op4)
10426 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10428 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10429 if (Op1 && !Op2 && !Op3 && !Op4)
10430 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10432 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10434 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10437 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10438 SelectionDAG &DAG) const {
10439 DebugLoc dl = Op.getDebugLoc();
10440 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10441 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10442 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10443 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10445 // The only fence that needs an instruction is a sequentially-consistent
10446 // cross-thread fence.
10447 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10448 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10449 // no-sse2). There isn't any reason to disable it if the target processor
10451 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10452 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10454 SDValue Chain = Op.getOperand(0);
10455 SDValue Zero = DAG.getConstant(0, MVT::i32);
10457 DAG.getRegister(X86::ESP, MVT::i32), // Base
10458 DAG.getTargetConstant(1, MVT::i8), // Scale
10459 DAG.getRegister(0, MVT::i32), // Index
10460 DAG.getTargetConstant(0, MVT::i32), // Disp
10461 DAG.getRegister(0, MVT::i32), // Segment.
10466 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10467 array_lengthof(Ops));
10468 return SDValue(Res, 0);
10471 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10472 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10476 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10477 EVT T = Op.getValueType();
10478 DebugLoc DL = Op.getDebugLoc();
10481 switch(T.getSimpleVT().SimpleTy) {
10483 assert(false && "Invalid value type!");
10484 case MVT::i8: Reg = X86::AL; size = 1; break;
10485 case MVT::i16: Reg = X86::AX; size = 2; break;
10486 case MVT::i32: Reg = X86::EAX; size = 4; break;
10488 assert(Subtarget->is64Bit() && "Node not type legal!");
10489 Reg = X86::RAX; size = 8;
10492 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10493 Op.getOperand(2), SDValue());
10494 SDValue Ops[] = { cpIn.getValue(0),
10497 DAG.getTargetConstant(size, MVT::i8),
10498 cpIn.getValue(1) };
10499 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10500 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10501 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10504 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10508 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10509 SelectionDAG &DAG) const {
10510 assert(Subtarget->is64Bit() && "Result not type legalized?");
10511 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10512 SDValue TheChain = Op.getOperand(0);
10513 DebugLoc dl = Op.getDebugLoc();
10514 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10515 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10516 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10518 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10519 DAG.getConstant(32, MVT::i8));
10521 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10524 return DAG.getMergeValues(Ops, 2, dl);
10527 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10528 SelectionDAG &DAG) const {
10529 EVT SrcVT = Op.getOperand(0).getValueType();
10530 EVT DstVT = Op.getValueType();
10531 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10532 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10533 assert((DstVT == MVT::i64 ||
10534 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10535 "Unexpected custom BITCAST");
10536 // i64 <=> MMX conversions are Legal.
10537 if (SrcVT==MVT::i64 && DstVT.isVector())
10539 if (DstVT==MVT::i64 && SrcVT.isVector())
10541 // MMX <=> MMX conversions are Legal.
10542 if (SrcVT.isVector() && DstVT.isVector())
10544 // All other conversions need to be expanded.
10548 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10549 SDNode *Node = Op.getNode();
10550 DebugLoc dl = Node->getDebugLoc();
10551 EVT T = Node->getValueType(0);
10552 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10553 DAG.getConstant(0, T), Node->getOperand(2));
10554 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10555 cast<AtomicSDNode>(Node)->getMemoryVT(),
10556 Node->getOperand(0),
10557 Node->getOperand(1), negOp,
10558 cast<AtomicSDNode>(Node)->getSrcValue(),
10559 cast<AtomicSDNode>(Node)->getAlignment(),
10560 cast<AtomicSDNode>(Node)->getOrdering(),
10561 cast<AtomicSDNode>(Node)->getSynchScope());
10564 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10565 SDNode *Node = Op.getNode();
10566 DebugLoc dl = Node->getDebugLoc();
10567 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10569 // Convert seq_cst store -> xchg
10570 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10571 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10572 // (The only way to get a 16-byte store is cmpxchg16b)
10573 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10574 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10575 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10576 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10577 cast<AtomicSDNode>(Node)->getMemoryVT(),
10578 Node->getOperand(0),
10579 Node->getOperand(1), Node->getOperand(2),
10580 cast<AtomicSDNode>(Node)->getMemOperand(),
10581 cast<AtomicSDNode>(Node)->getOrdering(),
10582 cast<AtomicSDNode>(Node)->getSynchScope());
10583 return Swap.getValue(1);
10585 // Other atomic stores have a simple pattern.
10589 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10590 EVT VT = Op.getNode()->getValueType(0);
10592 // Let legalize expand this if it isn't a legal type yet.
10593 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10596 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10599 bool ExtraOp = false;
10600 switch (Op.getOpcode()) {
10601 default: assert(0 && "Invalid code");
10602 case ISD::ADDC: Opc = X86ISD::ADD; break;
10603 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10604 case ISD::SUBC: Opc = X86ISD::SUB; break;
10605 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10609 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10611 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10612 Op.getOperand(1), Op.getOperand(2));
10615 /// LowerOperation - Provide custom lowering hooks for some operations.
10617 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10618 switch (Op.getOpcode()) {
10619 default: llvm_unreachable("Should not custom lower this!");
10620 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10621 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10622 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10623 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10624 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10625 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10626 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10627 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10628 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10629 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10630 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10631 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10632 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10633 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10634 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10635 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10636 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10637 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10638 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10639 case ISD::SHL_PARTS:
10640 case ISD::SRA_PARTS:
10641 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10642 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10643 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10644 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10645 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10646 case ISD::FABS: return LowerFABS(Op, DAG);
10647 case ISD::FNEG: return LowerFNEG(Op, DAG);
10648 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10649 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10650 case ISD::SETCC: return LowerSETCC(Op, DAG);
10651 case ISD::SELECT: return LowerSELECT(Op, DAG);
10652 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10653 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10654 case ISD::VASTART: return LowerVASTART(Op, DAG);
10655 case ISD::VAARG: return LowerVAARG(Op, DAG);
10656 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10657 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10658 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10659 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10660 case ISD::FRAME_TO_ARGS_OFFSET:
10661 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10662 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10663 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10664 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10665 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10666 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10667 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10668 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10669 case ISD::MUL: return LowerMUL(Op, DAG);
10672 case ISD::SHL: return LowerShift(Op, DAG);
10678 case ISD::UMULO: return LowerXALUO(Op, DAG);
10679 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10680 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10684 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10685 case ISD::ADD: return LowerADD(Op, DAG);
10686 case ISD::SUB: return LowerSUB(Op, DAG);
10690 static void ReplaceATOMIC_LOAD(SDNode *Node,
10691 SmallVectorImpl<SDValue> &Results,
10692 SelectionDAG &DAG) {
10693 DebugLoc dl = Node->getDebugLoc();
10694 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10696 // Convert wide load -> cmpxchg8b/cmpxchg16b
10697 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10698 // (The only way to get a 16-byte load is cmpxchg16b)
10699 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10700 SDValue Zero = DAG.getConstant(0, VT);
10701 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10702 Node->getOperand(0),
10703 Node->getOperand(1), Zero, Zero,
10704 cast<AtomicSDNode>(Node)->getMemOperand(),
10705 cast<AtomicSDNode>(Node)->getOrdering(),
10706 cast<AtomicSDNode>(Node)->getSynchScope());
10707 Results.push_back(Swap.getValue(0));
10708 Results.push_back(Swap.getValue(1));
10711 void X86TargetLowering::
10712 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10713 SelectionDAG &DAG, unsigned NewOp) const {
10714 DebugLoc dl = Node->getDebugLoc();
10715 assert (Node->getValueType(0) == MVT::i64 &&
10716 "Only know how to expand i64 atomics");
10718 SDValue Chain = Node->getOperand(0);
10719 SDValue In1 = Node->getOperand(1);
10720 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10721 Node->getOperand(2), DAG.getIntPtrConstant(0));
10722 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10723 Node->getOperand(2), DAG.getIntPtrConstant(1));
10724 SDValue Ops[] = { Chain, In1, In2L, In2H };
10725 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10727 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10728 cast<MemSDNode>(Node)->getMemOperand());
10729 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10730 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10731 Results.push_back(Result.getValue(2));
10734 /// ReplaceNodeResults - Replace a node with an illegal result type
10735 /// with a new node built out of custom code.
10736 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10737 SmallVectorImpl<SDValue>&Results,
10738 SelectionDAG &DAG) const {
10739 DebugLoc dl = N->getDebugLoc();
10740 switch (N->getOpcode()) {
10742 assert(false && "Do not know how to custom type legalize this operation!");
10744 case ISD::SIGN_EXTEND_INREG:
10749 // We don't want to expand or promote these.
10751 case ISD::FP_TO_SINT: {
10752 std::pair<SDValue,SDValue> Vals =
10753 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10754 SDValue FIST = Vals.first, StackSlot = Vals.second;
10755 if (FIST.getNode() != 0) {
10756 EVT VT = N->getValueType(0);
10757 // Return a load from the stack slot.
10758 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10759 MachinePointerInfo(),
10760 false, false, false, 0));
10764 case ISD::READCYCLECOUNTER: {
10765 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10766 SDValue TheChain = N->getOperand(0);
10767 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10768 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10770 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10772 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10773 SDValue Ops[] = { eax, edx };
10774 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10775 Results.push_back(edx.getValue(1));
10778 case ISD::ATOMIC_CMP_SWAP: {
10779 EVT T = N->getValueType(0);
10780 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10781 bool Regs64bit = T == MVT::i128;
10782 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10783 SDValue cpInL, cpInH;
10784 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10785 DAG.getConstant(0, HalfT));
10786 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10787 DAG.getConstant(1, HalfT));
10788 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10789 Regs64bit ? X86::RAX : X86::EAX,
10791 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10792 Regs64bit ? X86::RDX : X86::EDX,
10793 cpInH, cpInL.getValue(1));
10794 SDValue swapInL, swapInH;
10795 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10796 DAG.getConstant(0, HalfT));
10797 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10798 DAG.getConstant(1, HalfT));
10799 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10800 Regs64bit ? X86::RBX : X86::EBX,
10801 swapInL, cpInH.getValue(1));
10802 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10803 Regs64bit ? X86::RCX : X86::ECX,
10804 swapInH, swapInL.getValue(1));
10805 SDValue Ops[] = { swapInH.getValue(0),
10807 swapInH.getValue(1) };
10808 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10809 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10810 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10811 X86ISD::LCMPXCHG8_DAG;
10812 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10814 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10815 Regs64bit ? X86::RAX : X86::EAX,
10816 HalfT, Result.getValue(1));
10817 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10818 Regs64bit ? X86::RDX : X86::EDX,
10819 HalfT, cpOutL.getValue(2));
10820 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10821 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10822 Results.push_back(cpOutH.getValue(1));
10825 case ISD::ATOMIC_LOAD_ADD:
10826 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10828 case ISD::ATOMIC_LOAD_AND:
10829 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10831 case ISD::ATOMIC_LOAD_NAND:
10832 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10834 case ISD::ATOMIC_LOAD_OR:
10835 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10837 case ISD::ATOMIC_LOAD_SUB:
10838 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10840 case ISD::ATOMIC_LOAD_XOR:
10841 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10843 case ISD::ATOMIC_SWAP:
10844 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10846 case ISD::ATOMIC_LOAD:
10847 ReplaceATOMIC_LOAD(N, Results, DAG);
10851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10853 default: return NULL;
10854 case X86ISD::BSF: return "X86ISD::BSF";
10855 case X86ISD::BSR: return "X86ISD::BSR";
10856 case X86ISD::SHLD: return "X86ISD::SHLD";
10857 case X86ISD::SHRD: return "X86ISD::SHRD";
10858 case X86ISD::FAND: return "X86ISD::FAND";
10859 case X86ISD::FOR: return "X86ISD::FOR";
10860 case X86ISD::FXOR: return "X86ISD::FXOR";
10861 case X86ISD::FSRL: return "X86ISD::FSRL";
10862 case X86ISD::FILD: return "X86ISD::FILD";
10863 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10864 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10865 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10866 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10867 case X86ISD::FLD: return "X86ISD::FLD";
10868 case X86ISD::FST: return "X86ISD::FST";
10869 case X86ISD::CALL: return "X86ISD::CALL";
10870 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10871 case X86ISD::BT: return "X86ISD::BT";
10872 case X86ISD::CMP: return "X86ISD::CMP";
10873 case X86ISD::COMI: return "X86ISD::COMI";
10874 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10875 case X86ISD::SETCC: return "X86ISD::SETCC";
10876 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10877 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10878 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10879 case X86ISD::CMOV: return "X86ISD::CMOV";
10880 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10881 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10882 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10883 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10884 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10885 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10886 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10887 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10888 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10889 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10890 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10891 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10892 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10893 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10894 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10895 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10896 case X86ISD::HADD: return "X86ISD::HADD";
10897 case X86ISD::HSUB: return "X86ISD::HSUB";
10898 case X86ISD::FHADD: return "X86ISD::FHADD";
10899 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10900 case X86ISD::FMAX: return "X86ISD::FMAX";
10901 case X86ISD::FMIN: return "X86ISD::FMIN";
10902 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10903 case X86ISD::FRCP: return "X86ISD::FRCP";
10904 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10905 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10906 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10907 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10908 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10909 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10910 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10911 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10912 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10913 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10914 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10915 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10916 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10917 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10918 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10919 case X86ISD::VSHL: return "X86ISD::VSHL";
10920 case X86ISD::VSRL: return "X86ISD::VSRL";
10921 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10922 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10923 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10924 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10925 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10926 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10927 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10928 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10929 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10930 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10931 case X86ISD::ADD: return "X86ISD::ADD";
10932 case X86ISD::SUB: return "X86ISD::SUB";
10933 case X86ISD::ADC: return "X86ISD::ADC";
10934 case X86ISD::SBB: return "X86ISD::SBB";
10935 case X86ISD::SMUL: return "X86ISD::SMUL";
10936 case X86ISD::UMUL: return "X86ISD::UMUL";
10937 case X86ISD::INC: return "X86ISD::INC";
10938 case X86ISD::DEC: return "X86ISD::DEC";
10939 case X86ISD::OR: return "X86ISD::OR";
10940 case X86ISD::XOR: return "X86ISD::XOR";
10941 case X86ISD::AND: return "X86ISD::AND";
10942 case X86ISD::ANDN: return "X86ISD::ANDN";
10943 case X86ISD::BLSI: return "X86ISD::BLSI";
10944 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
10945 case X86ISD::BLSR: return "X86ISD::BLSR";
10946 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10947 case X86ISD::PTEST: return "X86ISD::PTEST";
10948 case X86ISD::TESTP: return "X86ISD::TESTP";
10949 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10950 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10951 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10952 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10953 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10954 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10955 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10956 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10957 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10958 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10959 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10960 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10961 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10962 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10963 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10964 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10965 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10966 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10967 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10968 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10969 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10970 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
10971 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
10972 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10973 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
10974 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
10975 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10976 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10977 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10978 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10979 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
10983 // isLegalAddressingMode - Return true if the addressing mode represented
10984 // by AM is legal for this target, for a load/store of the specified type.
10985 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10987 // X86 supports extremely general addressing modes.
10988 CodeModel::Model M = getTargetMachine().getCodeModel();
10989 Reloc::Model R = getTargetMachine().getRelocationModel();
10991 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10992 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10997 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10999 // If a reference to this global requires an extra load, we can't fold it.
11000 if (isGlobalStubReference(GVFlags))
11003 // If BaseGV requires a register for the PIC base, we cannot also have a
11004 // BaseReg specified.
11005 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11008 // If lower 4G is not available, then we must use rip-relative addressing.
11009 if ((M != CodeModel::Small || R != Reloc::Static) &&
11010 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11014 switch (AM.Scale) {
11020 // These scales always work.
11025 // These scales are formed with basereg+scalereg. Only accept if there is
11030 default: // Other stuff never works.
11038 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11039 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11041 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11042 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11043 if (NumBits1 <= NumBits2)
11048 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11049 if (!VT1.isInteger() || !VT2.isInteger())
11051 unsigned NumBits1 = VT1.getSizeInBits();
11052 unsigned NumBits2 = VT2.getSizeInBits();
11053 if (NumBits1 <= NumBits2)
11058 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11059 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11060 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11063 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11064 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11065 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11068 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11069 // i16 instructions are longer (0x66 prefix) and potentially slower.
11070 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11073 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11074 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11075 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11076 /// are assumed to be legal.
11078 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11080 // Very little shuffling can be done for 64-bit vectors right now.
11081 if (VT.getSizeInBits() == 64)
11084 // FIXME: pshufb, blends, shifts.
11085 return (VT.getVectorNumElements() == 2 ||
11086 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11087 isMOVLMask(M, VT) ||
11088 isSHUFPMask(M, VT) ||
11089 isPSHUFDMask(M, VT) ||
11090 isPSHUFHWMask(M, VT) ||
11091 isPSHUFLWMask(M, VT) ||
11092 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11093 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11094 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11095 isUNPCKL_v_undef_Mask(M, VT) ||
11096 isUNPCKH_v_undef_Mask(M, VT));
11100 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11102 unsigned NumElts = VT.getVectorNumElements();
11103 // FIXME: This collection of masks seems suspect.
11106 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11107 return (isMOVLMask(Mask, VT) ||
11108 isCommutedMOVLMask(Mask, VT, true) ||
11109 isSHUFPMask(Mask, VT) ||
11110 isSHUFPMask(Mask, VT, /* Commuted */ true));
11115 //===----------------------------------------------------------------------===//
11116 // X86 Scheduler Hooks
11117 //===----------------------------------------------------------------------===//
11119 // private utility function
11120 MachineBasicBlock *
11121 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11122 MachineBasicBlock *MBB,
11129 TargetRegisterClass *RC,
11130 bool invSrc) const {
11131 // For the atomic bitwise operator, we generate
11134 // ld t1 = [bitinstr.addr]
11135 // op t2 = t1, [bitinstr.val]
11137 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11139 // fallthrough -->nextMBB
11140 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11141 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11142 MachineFunction::iterator MBBIter = MBB;
11145 /// First build the CFG
11146 MachineFunction *F = MBB->getParent();
11147 MachineBasicBlock *thisMBB = MBB;
11148 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11149 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11150 F->insert(MBBIter, newMBB);
11151 F->insert(MBBIter, nextMBB);
11153 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11154 nextMBB->splice(nextMBB->begin(), thisMBB,
11155 llvm::next(MachineBasicBlock::iterator(bInstr)),
11157 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11159 // Update thisMBB to fall through to newMBB
11160 thisMBB->addSuccessor(newMBB);
11162 // newMBB jumps to itself and fall through to nextMBB
11163 newMBB->addSuccessor(nextMBB);
11164 newMBB->addSuccessor(newMBB);
11166 // Insert instructions into newMBB based on incoming instruction
11167 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11168 "unexpected number of operands");
11169 DebugLoc dl = bInstr->getDebugLoc();
11170 MachineOperand& destOper = bInstr->getOperand(0);
11171 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11172 int numArgs = bInstr->getNumOperands() - 1;
11173 for (int i=0; i < numArgs; ++i)
11174 argOpers[i] = &bInstr->getOperand(i+1);
11176 // x86 address has 4 operands: base, index, scale, and displacement
11177 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11178 int valArgIndx = lastAddrIndx + 1;
11180 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11181 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11182 for (int i=0; i <= lastAddrIndx; ++i)
11183 (*MIB).addOperand(*argOpers[i]);
11185 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11187 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11192 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11193 assert((argOpers[valArgIndx]->isReg() ||
11194 argOpers[valArgIndx]->isImm()) &&
11195 "invalid operand");
11196 if (argOpers[valArgIndx]->isReg())
11197 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11199 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11201 (*MIB).addOperand(*argOpers[valArgIndx]);
11203 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11206 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11207 for (int i=0; i <= lastAddrIndx; ++i)
11208 (*MIB).addOperand(*argOpers[i]);
11210 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11211 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11212 bInstr->memoperands_end());
11214 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11215 MIB.addReg(EAXreg);
11218 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11220 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11224 // private utility function: 64 bit atomics on 32 bit host.
11225 MachineBasicBlock *
11226 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11227 MachineBasicBlock *MBB,
11232 bool invSrc) const {
11233 // For the atomic bitwise operator, we generate
11234 // thisMBB (instructions are in pairs, except cmpxchg8b)
11235 // ld t1,t2 = [bitinstr.addr]
11237 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11238 // op t5, t6 <- out1, out2, [bitinstr.val]
11239 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11240 // mov ECX, EBX <- t5, t6
11241 // mov EAX, EDX <- t1, t2
11242 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11243 // mov t3, t4 <- EAX, EDX
11245 // result in out1, out2
11246 // fallthrough -->nextMBB
11248 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11249 const unsigned LoadOpc = X86::MOV32rm;
11250 const unsigned NotOpc = X86::NOT32r;
11251 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11252 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11253 MachineFunction::iterator MBBIter = MBB;
11256 /// First build the CFG
11257 MachineFunction *F = MBB->getParent();
11258 MachineBasicBlock *thisMBB = MBB;
11259 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11260 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11261 F->insert(MBBIter, newMBB);
11262 F->insert(MBBIter, nextMBB);
11264 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11265 nextMBB->splice(nextMBB->begin(), thisMBB,
11266 llvm::next(MachineBasicBlock::iterator(bInstr)),
11268 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11270 // Update thisMBB to fall through to newMBB
11271 thisMBB->addSuccessor(newMBB);
11273 // newMBB jumps to itself and fall through to nextMBB
11274 newMBB->addSuccessor(nextMBB);
11275 newMBB->addSuccessor(newMBB);
11277 DebugLoc dl = bInstr->getDebugLoc();
11278 // Insert instructions into newMBB based on incoming instruction
11279 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11280 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11281 "unexpected number of operands");
11282 MachineOperand& dest1Oper = bInstr->getOperand(0);
11283 MachineOperand& dest2Oper = bInstr->getOperand(1);
11284 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11285 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11286 argOpers[i] = &bInstr->getOperand(i+2);
11288 // We use some of the operands multiple times, so conservatively just
11289 // clear any kill flags that might be present.
11290 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11291 argOpers[i]->setIsKill(false);
11294 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11295 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11297 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11298 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11299 for (int i=0; i <= lastAddrIndx; ++i)
11300 (*MIB).addOperand(*argOpers[i]);
11301 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11302 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11303 // add 4 to displacement.
11304 for (int i=0; i <= lastAddrIndx-2; ++i)
11305 (*MIB).addOperand(*argOpers[i]);
11306 MachineOperand newOp3 = *(argOpers[3]);
11307 if (newOp3.isImm())
11308 newOp3.setImm(newOp3.getImm()+4);
11310 newOp3.setOffset(newOp3.getOffset()+4);
11311 (*MIB).addOperand(newOp3);
11312 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11314 // t3/4 are defined later, at the bottom of the loop
11315 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11316 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11317 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11318 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11319 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11320 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11322 // The subsequent operations should be using the destination registers of
11323 //the PHI instructions.
11325 t1 = F->getRegInfo().createVirtualRegister(RC);
11326 t2 = F->getRegInfo().createVirtualRegister(RC);
11327 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11328 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11330 t1 = dest1Oper.getReg();
11331 t2 = dest2Oper.getReg();
11334 int valArgIndx = lastAddrIndx + 1;
11335 assert((argOpers[valArgIndx]->isReg() ||
11336 argOpers[valArgIndx]->isImm()) &&
11337 "invalid operand");
11338 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11339 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11340 if (argOpers[valArgIndx]->isReg())
11341 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11343 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11344 if (regOpcL != X86::MOV32rr)
11346 (*MIB).addOperand(*argOpers[valArgIndx]);
11347 assert(argOpers[valArgIndx + 1]->isReg() ==
11348 argOpers[valArgIndx]->isReg());
11349 assert(argOpers[valArgIndx + 1]->isImm() ==
11350 argOpers[valArgIndx]->isImm());
11351 if (argOpers[valArgIndx + 1]->isReg())
11352 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11354 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11355 if (regOpcH != X86::MOV32rr)
11357 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11359 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11361 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11364 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11366 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11369 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11370 for (int i=0; i <= lastAddrIndx; ++i)
11371 (*MIB).addOperand(*argOpers[i]);
11373 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11374 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11375 bInstr->memoperands_end());
11377 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11378 MIB.addReg(X86::EAX);
11379 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11380 MIB.addReg(X86::EDX);
11383 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11385 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11389 // private utility function
11390 MachineBasicBlock *
11391 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11392 MachineBasicBlock *MBB,
11393 unsigned cmovOpc) const {
11394 // For the atomic min/max operator, we generate
11397 // ld t1 = [min/max.addr]
11398 // mov t2 = [min/max.val]
11400 // cmov[cond] t2 = t1
11402 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11404 // fallthrough -->nextMBB
11406 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11407 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11408 MachineFunction::iterator MBBIter = MBB;
11411 /// First build the CFG
11412 MachineFunction *F = MBB->getParent();
11413 MachineBasicBlock *thisMBB = MBB;
11414 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11415 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11416 F->insert(MBBIter, newMBB);
11417 F->insert(MBBIter, nextMBB);
11419 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11420 nextMBB->splice(nextMBB->begin(), thisMBB,
11421 llvm::next(MachineBasicBlock::iterator(mInstr)),
11423 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11425 // Update thisMBB to fall through to newMBB
11426 thisMBB->addSuccessor(newMBB);
11428 // newMBB jumps to newMBB and fall through to nextMBB
11429 newMBB->addSuccessor(nextMBB);
11430 newMBB->addSuccessor(newMBB);
11432 DebugLoc dl = mInstr->getDebugLoc();
11433 // Insert instructions into newMBB based on incoming instruction
11434 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11435 "unexpected number of operands");
11436 MachineOperand& destOper = mInstr->getOperand(0);
11437 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11438 int numArgs = mInstr->getNumOperands() - 1;
11439 for (int i=0; i < numArgs; ++i)
11440 argOpers[i] = &mInstr->getOperand(i+1);
11442 // x86 address has 4 operands: base, index, scale, and displacement
11443 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11444 int valArgIndx = lastAddrIndx + 1;
11446 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11447 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11448 for (int i=0; i <= lastAddrIndx; ++i)
11449 (*MIB).addOperand(*argOpers[i]);
11451 // We only support register and immediate values
11452 assert((argOpers[valArgIndx]->isReg() ||
11453 argOpers[valArgIndx]->isImm()) &&
11454 "invalid operand");
11456 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11457 if (argOpers[valArgIndx]->isReg())
11458 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11460 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11461 (*MIB).addOperand(*argOpers[valArgIndx]);
11463 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11466 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11471 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11472 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11476 // Cmp and exchange if none has modified the memory location
11477 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11478 for (int i=0; i <= lastAddrIndx; ++i)
11479 (*MIB).addOperand(*argOpers[i]);
11481 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11482 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11483 mInstr->memoperands_end());
11485 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11486 MIB.addReg(X86::EAX);
11489 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11491 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11495 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11496 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11497 // in the .td file.
11498 MachineBasicBlock *
11499 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11500 unsigned numArgs, bool memArg) const {
11501 assert(Subtarget->hasSSE42orAVX() &&
11502 "Target must have SSE4.2 or AVX features enabled");
11504 DebugLoc dl = MI->getDebugLoc();
11505 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11507 if (!Subtarget->hasAVX()) {
11509 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11511 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11514 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11516 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11519 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11520 for (unsigned i = 0; i < numArgs; ++i) {
11521 MachineOperand &Op = MI->getOperand(i+1);
11522 if (!(Op.isReg() && Op.isImplicit()))
11523 MIB.addOperand(Op);
11525 BuildMI(*BB, MI, dl,
11526 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11527 MI->getOperand(0).getReg())
11528 .addReg(X86::XMM0);
11530 MI->eraseFromParent();
11534 MachineBasicBlock *
11535 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11536 DebugLoc dl = MI->getDebugLoc();
11537 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11539 // Address into RAX/EAX, other two args into ECX, EDX.
11540 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11541 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11542 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11543 for (int i = 0; i < X86::AddrNumOperands; ++i)
11544 MIB.addOperand(MI->getOperand(i));
11546 unsigned ValOps = X86::AddrNumOperands;
11547 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11548 .addReg(MI->getOperand(ValOps).getReg());
11549 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11550 .addReg(MI->getOperand(ValOps+1).getReg());
11552 // The instruction doesn't actually take any operands though.
11553 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11555 MI->eraseFromParent(); // The pseudo is gone now.
11559 MachineBasicBlock *
11560 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11561 DebugLoc dl = MI->getDebugLoc();
11562 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11564 // First arg in ECX, the second in EAX.
11565 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11566 .addReg(MI->getOperand(0).getReg());
11567 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11568 .addReg(MI->getOperand(1).getReg());
11570 // The instruction doesn't actually take any operands though.
11571 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11573 MI->eraseFromParent(); // The pseudo is gone now.
11577 MachineBasicBlock *
11578 X86TargetLowering::EmitVAARG64WithCustomInserter(
11580 MachineBasicBlock *MBB) const {
11581 // Emit va_arg instruction on X86-64.
11583 // Operands to this pseudo-instruction:
11584 // 0 ) Output : destination address (reg)
11585 // 1-5) Input : va_list address (addr, i64mem)
11586 // 6 ) ArgSize : Size (in bytes) of vararg type
11587 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11588 // 8 ) Align : Alignment of type
11589 // 9 ) EFLAGS (implicit-def)
11591 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11592 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11594 unsigned DestReg = MI->getOperand(0).getReg();
11595 MachineOperand &Base = MI->getOperand(1);
11596 MachineOperand &Scale = MI->getOperand(2);
11597 MachineOperand &Index = MI->getOperand(3);
11598 MachineOperand &Disp = MI->getOperand(4);
11599 MachineOperand &Segment = MI->getOperand(5);
11600 unsigned ArgSize = MI->getOperand(6).getImm();
11601 unsigned ArgMode = MI->getOperand(7).getImm();
11602 unsigned Align = MI->getOperand(8).getImm();
11604 // Memory Reference
11605 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11606 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11607 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11609 // Machine Information
11610 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11611 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11612 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11613 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11614 DebugLoc DL = MI->getDebugLoc();
11616 // struct va_list {
11619 // i64 overflow_area (address)
11620 // i64 reg_save_area (address)
11622 // sizeof(va_list) = 24
11623 // alignment(va_list) = 8
11625 unsigned TotalNumIntRegs = 6;
11626 unsigned TotalNumXMMRegs = 8;
11627 bool UseGPOffset = (ArgMode == 1);
11628 bool UseFPOffset = (ArgMode == 2);
11629 unsigned MaxOffset = TotalNumIntRegs * 8 +
11630 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11632 /* Align ArgSize to a multiple of 8 */
11633 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11634 bool NeedsAlign = (Align > 8);
11636 MachineBasicBlock *thisMBB = MBB;
11637 MachineBasicBlock *overflowMBB;
11638 MachineBasicBlock *offsetMBB;
11639 MachineBasicBlock *endMBB;
11641 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11642 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11643 unsigned OffsetReg = 0;
11645 if (!UseGPOffset && !UseFPOffset) {
11646 // If we only pull from the overflow region, we don't create a branch.
11647 // We don't need to alter control flow.
11648 OffsetDestReg = 0; // unused
11649 OverflowDestReg = DestReg;
11652 overflowMBB = thisMBB;
11655 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11656 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11657 // If not, pull from overflow_area. (branch to overflowMBB)
11662 // offsetMBB overflowMBB
11667 // Registers for the PHI in endMBB
11668 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11669 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11671 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11672 MachineFunction *MF = MBB->getParent();
11673 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11674 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11675 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11677 MachineFunction::iterator MBBIter = MBB;
11680 // Insert the new basic blocks
11681 MF->insert(MBBIter, offsetMBB);
11682 MF->insert(MBBIter, overflowMBB);
11683 MF->insert(MBBIter, endMBB);
11685 // Transfer the remainder of MBB and its successor edges to endMBB.
11686 endMBB->splice(endMBB->begin(), thisMBB,
11687 llvm::next(MachineBasicBlock::iterator(MI)),
11689 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11691 // Make offsetMBB and overflowMBB successors of thisMBB
11692 thisMBB->addSuccessor(offsetMBB);
11693 thisMBB->addSuccessor(overflowMBB);
11695 // endMBB is a successor of both offsetMBB and overflowMBB
11696 offsetMBB->addSuccessor(endMBB);
11697 overflowMBB->addSuccessor(endMBB);
11699 // Load the offset value into a register
11700 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11701 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11705 .addDisp(Disp, UseFPOffset ? 4 : 0)
11706 .addOperand(Segment)
11707 .setMemRefs(MMOBegin, MMOEnd);
11709 // Check if there is enough room left to pull this argument.
11710 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11712 .addImm(MaxOffset + 8 - ArgSizeA8);
11714 // Branch to "overflowMBB" if offset >= max
11715 // Fall through to "offsetMBB" otherwise
11716 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11717 .addMBB(overflowMBB);
11720 // In offsetMBB, emit code to use the reg_save_area.
11722 assert(OffsetReg != 0);
11724 // Read the reg_save_area address.
11725 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11726 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11731 .addOperand(Segment)
11732 .setMemRefs(MMOBegin, MMOEnd);
11734 // Zero-extend the offset
11735 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11736 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11739 .addImm(X86::sub_32bit);
11741 // Add the offset to the reg_save_area to get the final address.
11742 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11743 .addReg(OffsetReg64)
11744 .addReg(RegSaveReg);
11746 // Compute the offset for the next argument
11747 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11748 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11750 .addImm(UseFPOffset ? 16 : 8);
11752 // Store it back into the va_list.
11753 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11757 .addDisp(Disp, UseFPOffset ? 4 : 0)
11758 .addOperand(Segment)
11759 .addReg(NextOffsetReg)
11760 .setMemRefs(MMOBegin, MMOEnd);
11763 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11768 // Emit code to use overflow area
11771 // Load the overflow_area address into a register.
11772 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11773 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11778 .addOperand(Segment)
11779 .setMemRefs(MMOBegin, MMOEnd);
11781 // If we need to align it, do so. Otherwise, just copy the address
11782 // to OverflowDestReg.
11784 // Align the overflow address
11785 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11786 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11788 // aligned_addr = (addr + (align-1)) & ~(align-1)
11789 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11790 .addReg(OverflowAddrReg)
11793 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11795 .addImm(~(uint64_t)(Align-1));
11797 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11798 .addReg(OverflowAddrReg);
11801 // Compute the next overflow address after this argument.
11802 // (the overflow address should be kept 8-byte aligned)
11803 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11804 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11805 .addReg(OverflowDestReg)
11806 .addImm(ArgSizeA8);
11808 // Store the new overflow address.
11809 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11814 .addOperand(Segment)
11815 .addReg(NextAddrReg)
11816 .setMemRefs(MMOBegin, MMOEnd);
11818 // If we branched, emit the PHI to the front of endMBB.
11820 BuildMI(*endMBB, endMBB->begin(), DL,
11821 TII->get(X86::PHI), DestReg)
11822 .addReg(OffsetDestReg).addMBB(offsetMBB)
11823 .addReg(OverflowDestReg).addMBB(overflowMBB);
11826 // Erase the pseudo instruction
11827 MI->eraseFromParent();
11832 MachineBasicBlock *
11833 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11835 MachineBasicBlock *MBB) const {
11836 // Emit code to save XMM registers to the stack. The ABI says that the
11837 // number of registers to save is given in %al, so it's theoretically
11838 // possible to do an indirect jump trick to avoid saving all of them,
11839 // however this code takes a simpler approach and just executes all
11840 // of the stores if %al is non-zero. It's less code, and it's probably
11841 // easier on the hardware branch predictor, and stores aren't all that
11842 // expensive anyway.
11844 // Create the new basic blocks. One block contains all the XMM stores,
11845 // and one block is the final destination regardless of whether any
11846 // stores were performed.
11847 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11848 MachineFunction *F = MBB->getParent();
11849 MachineFunction::iterator MBBIter = MBB;
11851 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11852 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11853 F->insert(MBBIter, XMMSaveMBB);
11854 F->insert(MBBIter, EndMBB);
11856 // Transfer the remainder of MBB and its successor edges to EndMBB.
11857 EndMBB->splice(EndMBB->begin(), MBB,
11858 llvm::next(MachineBasicBlock::iterator(MI)),
11860 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11862 // The original block will now fall through to the XMM save block.
11863 MBB->addSuccessor(XMMSaveMBB);
11864 // The XMMSaveMBB will fall through to the end block.
11865 XMMSaveMBB->addSuccessor(EndMBB);
11867 // Now add the instructions.
11868 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11869 DebugLoc DL = MI->getDebugLoc();
11871 unsigned CountReg = MI->getOperand(0).getReg();
11872 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11873 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11875 if (!Subtarget->isTargetWin64()) {
11876 // If %al is 0, branch around the XMM save block.
11877 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11878 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11879 MBB->addSuccessor(EndMBB);
11882 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11883 // In the XMM save block, save all the XMM argument registers.
11884 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11885 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11886 MachineMemOperand *MMO =
11887 F->getMachineMemOperand(
11888 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11889 MachineMemOperand::MOStore,
11890 /*Size=*/16, /*Align=*/16);
11891 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11892 .addFrameIndex(RegSaveFrameIndex)
11893 .addImm(/*Scale=*/1)
11894 .addReg(/*IndexReg=*/0)
11895 .addImm(/*Disp=*/Offset)
11896 .addReg(/*Segment=*/0)
11897 .addReg(MI->getOperand(i).getReg())
11898 .addMemOperand(MMO);
11901 MI->eraseFromParent(); // The pseudo instruction is gone now.
11906 MachineBasicBlock *
11907 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11908 MachineBasicBlock *BB) const {
11909 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11910 DebugLoc DL = MI->getDebugLoc();
11912 // To "insert" a SELECT_CC instruction, we actually have to insert the
11913 // diamond control-flow pattern. The incoming instruction knows the
11914 // destination vreg to set, the condition code register to branch on, the
11915 // true/false values to select between, and a branch opcode to use.
11916 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11917 MachineFunction::iterator It = BB;
11923 // cmpTY ccX, r1, r2
11925 // fallthrough --> copy0MBB
11926 MachineBasicBlock *thisMBB = BB;
11927 MachineFunction *F = BB->getParent();
11928 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11929 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11930 F->insert(It, copy0MBB);
11931 F->insert(It, sinkMBB);
11933 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11934 // live into the sink and copy blocks.
11935 if (!MI->killsRegister(X86::EFLAGS)) {
11936 copy0MBB->addLiveIn(X86::EFLAGS);
11937 sinkMBB->addLiveIn(X86::EFLAGS);
11940 // Transfer the remainder of BB and its successor edges to sinkMBB.
11941 sinkMBB->splice(sinkMBB->begin(), BB,
11942 llvm::next(MachineBasicBlock::iterator(MI)),
11944 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11946 // Add the true and fallthrough blocks as its successors.
11947 BB->addSuccessor(copy0MBB);
11948 BB->addSuccessor(sinkMBB);
11950 // Create the conditional branch instruction.
11952 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11953 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11956 // %FalseValue = ...
11957 // # fallthrough to sinkMBB
11958 copy0MBB->addSuccessor(sinkMBB);
11961 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11963 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11964 TII->get(X86::PHI), MI->getOperand(0).getReg())
11965 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11966 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11968 MI->eraseFromParent(); // The pseudo instruction is gone now.
11972 MachineBasicBlock *
11973 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11974 bool Is64Bit) const {
11975 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11976 DebugLoc DL = MI->getDebugLoc();
11977 MachineFunction *MF = BB->getParent();
11978 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11980 assert(getTargetMachine().Options.EnableSegmentedStacks);
11982 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11983 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11986 // ... [Till the alloca]
11987 // If stacklet is not large enough, jump to mallocMBB
11990 // Allocate by subtracting from RSP
11991 // Jump to continueMBB
11994 // Allocate by call to runtime
11998 // [rest of original BB]
12001 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12002 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12003 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12005 MachineRegisterInfo &MRI = MF->getRegInfo();
12006 const TargetRegisterClass *AddrRegClass =
12007 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12009 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12010 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12011 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12012 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12013 sizeVReg = MI->getOperand(1).getReg(),
12014 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12016 MachineFunction::iterator MBBIter = BB;
12019 MF->insert(MBBIter, bumpMBB);
12020 MF->insert(MBBIter, mallocMBB);
12021 MF->insert(MBBIter, continueMBB);
12023 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12024 (MachineBasicBlock::iterator(MI)), BB->end());
12025 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12027 // Add code to the main basic block to check if the stack limit has been hit,
12028 // and if so, jump to mallocMBB otherwise to bumpMBB.
12029 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12030 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12031 .addReg(tmpSPVReg).addReg(sizeVReg);
12032 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12033 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12034 .addReg(SPLimitVReg);
12035 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12037 // bumpMBB simply decreases the stack pointer, since we know the current
12038 // stacklet has enough space.
12039 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12040 .addReg(SPLimitVReg);
12041 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12042 .addReg(SPLimitVReg);
12043 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12045 // Calls into a routine in libgcc to allocate more space from the heap.
12047 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12049 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12050 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12052 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12054 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12055 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12056 .addExternalSymbol("__morestack_allocate_stack_space");
12060 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12063 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12064 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12065 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12067 // Set up the CFG correctly.
12068 BB->addSuccessor(bumpMBB);
12069 BB->addSuccessor(mallocMBB);
12070 mallocMBB->addSuccessor(continueMBB);
12071 bumpMBB->addSuccessor(continueMBB);
12073 // Take care of the PHI nodes.
12074 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12075 MI->getOperand(0).getReg())
12076 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12077 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12079 // Delete the original pseudo instruction.
12080 MI->eraseFromParent();
12083 return continueMBB;
12086 MachineBasicBlock *
12087 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12088 MachineBasicBlock *BB) const {
12089 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12090 DebugLoc DL = MI->getDebugLoc();
12092 assert(!Subtarget->isTargetEnvMacho());
12094 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12095 // non-trivial part is impdef of ESP.
12097 if (Subtarget->isTargetWin64()) {
12098 if (Subtarget->isTargetCygMing()) {
12099 // ___chkstk(Mingw64):
12100 // Clobbers R10, R11, RAX and EFLAGS.
12102 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12103 .addExternalSymbol("___chkstk")
12104 .addReg(X86::RAX, RegState::Implicit)
12105 .addReg(X86::RSP, RegState::Implicit)
12106 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12107 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12108 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12110 // __chkstk(MSVCRT): does not update stack pointer.
12111 // Clobbers R10, R11 and EFLAGS.
12112 // FIXME: RAX(allocated size) might be reused and not killed.
12113 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12114 .addExternalSymbol("__chkstk")
12115 .addReg(X86::RAX, RegState::Implicit)
12116 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12117 // RAX has the offset to subtracted from RSP.
12118 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12123 const char *StackProbeSymbol =
12124 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12126 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12127 .addExternalSymbol(StackProbeSymbol)
12128 .addReg(X86::EAX, RegState::Implicit)
12129 .addReg(X86::ESP, RegState::Implicit)
12130 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12131 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12132 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12135 MI->eraseFromParent(); // The pseudo instruction is gone now.
12139 MachineBasicBlock *
12140 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12141 MachineBasicBlock *BB) const {
12142 // This is pretty easy. We're taking the value that we received from
12143 // our load from the relocation, sticking it in either RDI (x86-64)
12144 // or EAX and doing an indirect call. The return value will then
12145 // be in the normal return register.
12146 const X86InstrInfo *TII
12147 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12148 DebugLoc DL = MI->getDebugLoc();
12149 MachineFunction *F = BB->getParent();
12151 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12152 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12154 if (Subtarget->is64Bit()) {
12155 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12156 TII->get(X86::MOV64rm), X86::RDI)
12158 .addImm(0).addReg(0)
12159 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12160 MI->getOperand(3).getTargetFlags())
12162 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12163 addDirectMem(MIB, X86::RDI);
12164 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12165 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12166 TII->get(X86::MOV32rm), X86::EAX)
12168 .addImm(0).addReg(0)
12169 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12170 MI->getOperand(3).getTargetFlags())
12172 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12173 addDirectMem(MIB, X86::EAX);
12175 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12176 TII->get(X86::MOV32rm), X86::EAX)
12177 .addReg(TII->getGlobalBaseReg(F))
12178 .addImm(0).addReg(0)
12179 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12180 MI->getOperand(3).getTargetFlags())
12182 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12183 addDirectMem(MIB, X86::EAX);
12186 MI->eraseFromParent(); // The pseudo instruction is gone now.
12190 MachineBasicBlock *
12191 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12192 MachineBasicBlock *BB) const {
12193 switch (MI->getOpcode()) {
12194 default: assert(0 && "Unexpected instr type to insert");
12195 case X86::TAILJMPd64:
12196 case X86::TAILJMPr64:
12197 case X86::TAILJMPm64:
12198 assert(0 && "TAILJMP64 would not be touched here.");
12199 case X86::TCRETURNdi64:
12200 case X86::TCRETURNri64:
12201 case X86::TCRETURNmi64:
12202 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12203 // On AMD64, additional defs should be added before register allocation.
12204 if (!Subtarget->isTargetWin64()) {
12205 MI->addRegisterDefined(X86::RSI);
12206 MI->addRegisterDefined(X86::RDI);
12207 MI->addRegisterDefined(X86::XMM6);
12208 MI->addRegisterDefined(X86::XMM7);
12209 MI->addRegisterDefined(X86::XMM8);
12210 MI->addRegisterDefined(X86::XMM9);
12211 MI->addRegisterDefined(X86::XMM10);
12212 MI->addRegisterDefined(X86::XMM11);
12213 MI->addRegisterDefined(X86::XMM12);
12214 MI->addRegisterDefined(X86::XMM13);
12215 MI->addRegisterDefined(X86::XMM14);
12216 MI->addRegisterDefined(X86::XMM15);
12219 case X86::WIN_ALLOCA:
12220 return EmitLoweredWinAlloca(MI, BB);
12221 case X86::SEG_ALLOCA_32:
12222 return EmitLoweredSegAlloca(MI, BB, false);
12223 case X86::SEG_ALLOCA_64:
12224 return EmitLoweredSegAlloca(MI, BB, true);
12225 case X86::TLSCall_32:
12226 case X86::TLSCall_64:
12227 return EmitLoweredTLSCall(MI, BB);
12228 case X86::CMOV_GR8:
12229 case X86::CMOV_FR32:
12230 case X86::CMOV_FR64:
12231 case X86::CMOV_V4F32:
12232 case X86::CMOV_V2F64:
12233 case X86::CMOV_V2I64:
12234 case X86::CMOV_V8F32:
12235 case X86::CMOV_V4F64:
12236 case X86::CMOV_V4I64:
12237 case X86::CMOV_GR16:
12238 case X86::CMOV_GR32:
12239 case X86::CMOV_RFP32:
12240 case X86::CMOV_RFP64:
12241 case X86::CMOV_RFP80:
12242 return EmitLoweredSelect(MI, BB);
12244 case X86::FP32_TO_INT16_IN_MEM:
12245 case X86::FP32_TO_INT32_IN_MEM:
12246 case X86::FP32_TO_INT64_IN_MEM:
12247 case X86::FP64_TO_INT16_IN_MEM:
12248 case X86::FP64_TO_INT32_IN_MEM:
12249 case X86::FP64_TO_INT64_IN_MEM:
12250 case X86::FP80_TO_INT16_IN_MEM:
12251 case X86::FP80_TO_INT32_IN_MEM:
12252 case X86::FP80_TO_INT64_IN_MEM: {
12253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12254 DebugLoc DL = MI->getDebugLoc();
12256 // Change the floating point control register to use "round towards zero"
12257 // mode when truncating to an integer value.
12258 MachineFunction *F = BB->getParent();
12259 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12260 addFrameReference(BuildMI(*BB, MI, DL,
12261 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12263 // Load the old value of the high byte of the control word...
12265 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12266 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12269 // Set the high part to be round to zero...
12270 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12273 // Reload the modified control word now...
12274 addFrameReference(BuildMI(*BB, MI, DL,
12275 TII->get(X86::FLDCW16m)), CWFrameIdx);
12277 // Restore the memory image of control word to original value
12278 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12281 // Get the X86 opcode to use.
12283 switch (MI->getOpcode()) {
12284 default: llvm_unreachable("illegal opcode!");
12285 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12286 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12287 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12288 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12289 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12290 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12291 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12292 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12293 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12297 MachineOperand &Op = MI->getOperand(0);
12299 AM.BaseType = X86AddressMode::RegBase;
12300 AM.Base.Reg = Op.getReg();
12302 AM.BaseType = X86AddressMode::FrameIndexBase;
12303 AM.Base.FrameIndex = Op.getIndex();
12305 Op = MI->getOperand(1);
12307 AM.Scale = Op.getImm();
12308 Op = MI->getOperand(2);
12310 AM.IndexReg = Op.getImm();
12311 Op = MI->getOperand(3);
12312 if (Op.isGlobal()) {
12313 AM.GV = Op.getGlobal();
12315 AM.Disp = Op.getImm();
12317 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12318 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12320 // Reload the original control word now.
12321 addFrameReference(BuildMI(*BB, MI, DL,
12322 TII->get(X86::FLDCW16m)), CWFrameIdx);
12324 MI->eraseFromParent(); // The pseudo instruction is gone now.
12327 // String/text processing lowering.
12328 case X86::PCMPISTRM128REG:
12329 case X86::VPCMPISTRM128REG:
12330 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12331 case X86::PCMPISTRM128MEM:
12332 case X86::VPCMPISTRM128MEM:
12333 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12334 case X86::PCMPESTRM128REG:
12335 case X86::VPCMPESTRM128REG:
12336 return EmitPCMP(MI, BB, 5, false /* in mem */);
12337 case X86::PCMPESTRM128MEM:
12338 case X86::VPCMPESTRM128MEM:
12339 return EmitPCMP(MI, BB, 5, true /* in mem */);
12341 // Thread synchronization.
12343 return EmitMonitor(MI, BB);
12345 return EmitMwait(MI, BB);
12347 // Atomic Lowering.
12348 case X86::ATOMAND32:
12349 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12350 X86::AND32ri, X86::MOV32rm,
12352 X86::NOT32r, X86::EAX,
12353 X86::GR32RegisterClass);
12354 case X86::ATOMOR32:
12355 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12356 X86::OR32ri, X86::MOV32rm,
12358 X86::NOT32r, X86::EAX,
12359 X86::GR32RegisterClass);
12360 case X86::ATOMXOR32:
12361 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12362 X86::XOR32ri, X86::MOV32rm,
12364 X86::NOT32r, X86::EAX,
12365 X86::GR32RegisterClass);
12366 case X86::ATOMNAND32:
12367 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12368 X86::AND32ri, X86::MOV32rm,
12370 X86::NOT32r, X86::EAX,
12371 X86::GR32RegisterClass, true);
12372 case X86::ATOMMIN32:
12373 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12374 case X86::ATOMMAX32:
12375 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12376 case X86::ATOMUMIN32:
12377 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12378 case X86::ATOMUMAX32:
12379 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12381 case X86::ATOMAND16:
12382 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12383 X86::AND16ri, X86::MOV16rm,
12385 X86::NOT16r, X86::AX,
12386 X86::GR16RegisterClass);
12387 case X86::ATOMOR16:
12388 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12389 X86::OR16ri, X86::MOV16rm,
12391 X86::NOT16r, X86::AX,
12392 X86::GR16RegisterClass);
12393 case X86::ATOMXOR16:
12394 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12395 X86::XOR16ri, X86::MOV16rm,
12397 X86::NOT16r, X86::AX,
12398 X86::GR16RegisterClass);
12399 case X86::ATOMNAND16:
12400 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12401 X86::AND16ri, X86::MOV16rm,
12403 X86::NOT16r, X86::AX,
12404 X86::GR16RegisterClass, true);
12405 case X86::ATOMMIN16:
12406 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12407 case X86::ATOMMAX16:
12408 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12409 case X86::ATOMUMIN16:
12410 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12411 case X86::ATOMUMAX16:
12412 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12414 case X86::ATOMAND8:
12415 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12416 X86::AND8ri, X86::MOV8rm,
12418 X86::NOT8r, X86::AL,
12419 X86::GR8RegisterClass);
12421 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12422 X86::OR8ri, X86::MOV8rm,
12424 X86::NOT8r, X86::AL,
12425 X86::GR8RegisterClass);
12426 case X86::ATOMXOR8:
12427 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12428 X86::XOR8ri, X86::MOV8rm,
12430 X86::NOT8r, X86::AL,
12431 X86::GR8RegisterClass);
12432 case X86::ATOMNAND8:
12433 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12434 X86::AND8ri, X86::MOV8rm,
12436 X86::NOT8r, X86::AL,
12437 X86::GR8RegisterClass, true);
12438 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12439 // This group is for 64-bit host.
12440 case X86::ATOMAND64:
12441 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12442 X86::AND64ri32, X86::MOV64rm,
12444 X86::NOT64r, X86::RAX,
12445 X86::GR64RegisterClass);
12446 case X86::ATOMOR64:
12447 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12448 X86::OR64ri32, X86::MOV64rm,
12450 X86::NOT64r, X86::RAX,
12451 X86::GR64RegisterClass);
12452 case X86::ATOMXOR64:
12453 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12454 X86::XOR64ri32, X86::MOV64rm,
12456 X86::NOT64r, X86::RAX,
12457 X86::GR64RegisterClass);
12458 case X86::ATOMNAND64:
12459 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12460 X86::AND64ri32, X86::MOV64rm,
12462 X86::NOT64r, X86::RAX,
12463 X86::GR64RegisterClass, true);
12464 case X86::ATOMMIN64:
12465 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12466 case X86::ATOMMAX64:
12467 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12468 case X86::ATOMUMIN64:
12469 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12470 case X86::ATOMUMAX64:
12471 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12473 // This group does 64-bit operations on a 32-bit host.
12474 case X86::ATOMAND6432:
12475 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12476 X86::AND32rr, X86::AND32rr,
12477 X86::AND32ri, X86::AND32ri,
12479 case X86::ATOMOR6432:
12480 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12481 X86::OR32rr, X86::OR32rr,
12482 X86::OR32ri, X86::OR32ri,
12484 case X86::ATOMXOR6432:
12485 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12486 X86::XOR32rr, X86::XOR32rr,
12487 X86::XOR32ri, X86::XOR32ri,
12489 case X86::ATOMNAND6432:
12490 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12491 X86::AND32rr, X86::AND32rr,
12492 X86::AND32ri, X86::AND32ri,
12494 case X86::ATOMADD6432:
12495 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12496 X86::ADD32rr, X86::ADC32rr,
12497 X86::ADD32ri, X86::ADC32ri,
12499 case X86::ATOMSUB6432:
12500 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12501 X86::SUB32rr, X86::SBB32rr,
12502 X86::SUB32ri, X86::SBB32ri,
12504 case X86::ATOMSWAP6432:
12505 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12506 X86::MOV32rr, X86::MOV32rr,
12507 X86::MOV32ri, X86::MOV32ri,
12509 case X86::VASTART_SAVE_XMM_REGS:
12510 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12512 case X86::VAARG_64:
12513 return EmitVAARG64WithCustomInserter(MI, BB);
12517 //===----------------------------------------------------------------------===//
12518 // X86 Optimization Hooks
12519 //===----------------------------------------------------------------------===//
12521 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12525 const SelectionDAG &DAG,
12526 unsigned Depth) const {
12527 unsigned Opc = Op.getOpcode();
12528 assert((Opc >= ISD::BUILTIN_OP_END ||
12529 Opc == ISD::INTRINSIC_WO_CHAIN ||
12530 Opc == ISD::INTRINSIC_W_CHAIN ||
12531 Opc == ISD::INTRINSIC_VOID) &&
12532 "Should use MaskedValueIsZero if you don't know whether Op"
12533 " is a target node!");
12535 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12549 // These nodes' second result is a boolean.
12550 if (Op.getResNo() == 0)
12553 case X86ISD::SETCC:
12554 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12555 Mask.getBitWidth() - 1);
12557 case ISD::INTRINSIC_WO_CHAIN: {
12558 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12559 unsigned NumLoBits = 0;
12562 case Intrinsic::x86_sse_movmsk_ps:
12563 case Intrinsic::x86_avx_movmsk_ps_256:
12564 case Intrinsic::x86_sse2_movmsk_pd:
12565 case Intrinsic::x86_avx_movmsk_pd_256:
12566 case Intrinsic::x86_mmx_pmovmskb:
12567 case Intrinsic::x86_sse2_pmovmskb_128: {
12568 // High bits of movmskp{s|d}, pmovmskb are known zero.
12570 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12571 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12572 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12573 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12574 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12575 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12577 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12578 Mask.getBitWidth() - NumLoBits);
12587 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12588 unsigned Depth) const {
12589 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12590 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12591 return Op.getValueType().getScalarType().getSizeInBits();
12597 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12598 /// node is a GlobalAddress + offset.
12599 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12600 const GlobalValue* &GA,
12601 int64_t &Offset) const {
12602 if (N->getOpcode() == X86ISD::Wrapper) {
12603 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12604 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12605 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12609 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12612 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12613 /// same as extracting the high 128-bit part of 256-bit vector and then
12614 /// inserting the result into the low part of a new 256-bit vector
12615 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12616 EVT VT = SVOp->getValueType(0);
12617 int NumElems = VT.getVectorNumElements();
12619 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12620 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12621 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12622 SVOp->getMaskElt(j) >= 0)
12628 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12629 /// same as extracting the low 128-bit part of 256-bit vector and then
12630 /// inserting the result into the high part of a new 256-bit vector
12631 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12632 EVT VT = SVOp->getValueType(0);
12633 int NumElems = VT.getVectorNumElements();
12635 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12636 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12637 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12638 SVOp->getMaskElt(j) >= 0)
12644 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12645 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12646 TargetLowering::DAGCombinerInfo &DCI) {
12647 DebugLoc dl = N->getDebugLoc();
12648 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12649 SDValue V1 = SVOp->getOperand(0);
12650 SDValue V2 = SVOp->getOperand(1);
12651 EVT VT = SVOp->getValueType(0);
12652 int NumElems = VT.getVectorNumElements();
12654 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12655 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12659 // V UNDEF BUILD_VECTOR UNDEF
12661 // CONCAT_VECTOR CONCAT_VECTOR
12664 // RESULT: V + zero extended
12666 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12667 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12668 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12671 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12674 // To match the shuffle mask, the first half of the mask should
12675 // be exactly the first vector, and all the rest a splat with the
12676 // first element of the second one.
12677 for (int i = 0; i < NumElems/2; ++i)
12678 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12679 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12682 // Emit a zeroed vector and insert the desired subvector on its
12684 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12685 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12686 DAG.getConstant(0, MVT::i32), DAG, dl);
12687 return DCI.CombineTo(N, InsV);
12690 //===--------------------------------------------------------------------===//
12691 // Combine some shuffles into subvector extracts and inserts:
12694 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12695 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12696 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12698 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12699 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12700 return DCI.CombineTo(N, InsV);
12703 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12704 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12705 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12706 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12707 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12708 return DCI.CombineTo(N, InsV);
12714 /// PerformShuffleCombine - Performs several different shuffle combines.
12715 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12716 TargetLowering::DAGCombinerInfo &DCI,
12717 const X86Subtarget *Subtarget) {
12718 DebugLoc dl = N->getDebugLoc();
12719 EVT VT = N->getValueType(0);
12721 // Don't create instructions with illegal types after legalize types has run.
12722 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12723 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12726 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12727 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12728 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12729 return PerformShuffleCombine256(N, DAG, DCI);
12731 // Only handle 128 wide vector from here on.
12732 if (VT.getSizeInBits() != 128)
12735 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12736 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12737 // consecutive, non-overlapping, and in the right order.
12738 SmallVector<SDValue, 16> Elts;
12739 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12740 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12742 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12745 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12746 /// generation and convert it from being a bunch of shuffles and extracts
12747 /// to a simple store and scalar loads to extract the elements.
12748 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12749 const TargetLowering &TLI) {
12750 SDValue InputVector = N->getOperand(0);
12752 // Only operate on vectors of 4 elements, where the alternative shuffling
12753 // gets to be more expensive.
12754 if (InputVector.getValueType() != MVT::v4i32)
12757 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12758 // single use which is a sign-extend or zero-extend, and all elements are
12760 SmallVector<SDNode *, 4> Uses;
12761 unsigned ExtractedElements = 0;
12762 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12763 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12764 if (UI.getUse().getResNo() != InputVector.getResNo())
12767 SDNode *Extract = *UI;
12768 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12771 if (Extract->getValueType(0) != MVT::i32)
12773 if (!Extract->hasOneUse())
12775 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12776 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12778 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12781 // Record which element was extracted.
12782 ExtractedElements |=
12783 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12785 Uses.push_back(Extract);
12788 // If not all the elements were used, this may not be worthwhile.
12789 if (ExtractedElements != 15)
12792 // Ok, we've now decided to do the transformation.
12793 DebugLoc dl = InputVector.getDebugLoc();
12795 // Store the value to a temporary stack slot.
12796 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12797 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12798 MachinePointerInfo(), false, false, 0);
12800 // Replace each use (extract) with a load of the appropriate element.
12801 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12802 UE = Uses.end(); UI != UE; ++UI) {
12803 SDNode *Extract = *UI;
12805 // cOMpute the element's address.
12806 SDValue Idx = Extract->getOperand(1);
12808 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12809 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12810 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12812 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12813 StackPtr, OffsetVal);
12815 // Load the scalar.
12816 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12817 ScalarAddr, MachinePointerInfo(),
12818 false, false, false, 0);
12820 // Replace the exact with the load.
12821 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12824 // The replacement was made in place; don't return anything.
12828 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12830 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12831 const X86Subtarget *Subtarget) {
12832 DebugLoc DL = N->getDebugLoc();
12833 SDValue Cond = N->getOperand(0);
12834 // Get the LHS/RHS of the select.
12835 SDValue LHS = N->getOperand(1);
12836 SDValue RHS = N->getOperand(2);
12837 EVT VT = LHS.getValueType();
12839 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12840 // instructions match the semantics of the common C idiom x<y?x:y but not
12841 // x<=y?x:y, because of how they handle negative zero (which can be
12842 // ignored in unsafe-math mode).
12843 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12844 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12845 (Subtarget->hasXMMInt() ||
12846 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12847 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12849 unsigned Opcode = 0;
12850 // Check for x CC y ? x : y.
12851 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12852 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12856 // Converting this to a min would handle NaNs incorrectly, and swapping
12857 // the operands would cause it to handle comparisons between positive
12858 // and negative zero incorrectly.
12859 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12860 if (!DAG.getTarget().Options.UnsafeFPMath &&
12861 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12863 std::swap(LHS, RHS);
12865 Opcode = X86ISD::FMIN;
12868 // Converting this to a min would handle comparisons between positive
12869 // and negative zero incorrectly.
12870 if (!DAG.getTarget().Options.UnsafeFPMath &&
12871 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12873 Opcode = X86ISD::FMIN;
12876 // Converting this to a min would handle both negative zeros and NaNs
12877 // incorrectly, but we can swap the operands to fix both.
12878 std::swap(LHS, RHS);
12882 Opcode = X86ISD::FMIN;
12886 // Converting this to a max would handle comparisons between positive
12887 // and negative zero incorrectly.
12888 if (!DAG.getTarget().Options.UnsafeFPMath &&
12889 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12891 Opcode = X86ISD::FMAX;
12894 // Converting this to a max would handle NaNs incorrectly, and swapping
12895 // the operands would cause it to handle comparisons between positive
12896 // and negative zero incorrectly.
12897 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12898 if (!DAG.getTarget().Options.UnsafeFPMath &&
12899 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12901 std::swap(LHS, RHS);
12903 Opcode = X86ISD::FMAX;
12906 // Converting this to a max would handle both negative zeros and NaNs
12907 // incorrectly, but we can swap the operands to fix both.
12908 std::swap(LHS, RHS);
12912 Opcode = X86ISD::FMAX;
12915 // Check for x CC y ? y : x -- a min/max with reversed arms.
12916 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12917 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12921 // Converting this to a min would handle comparisons between positive
12922 // and negative zero incorrectly, and swapping the operands would
12923 // cause it to handle NaNs incorrectly.
12924 if (!DAG.getTarget().Options.UnsafeFPMath &&
12925 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12926 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12928 std::swap(LHS, RHS);
12930 Opcode = X86ISD::FMIN;
12933 // Converting this to a min would handle NaNs incorrectly.
12934 if (!DAG.getTarget().Options.UnsafeFPMath &&
12935 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12937 Opcode = X86ISD::FMIN;
12940 // Converting this to a min would handle both negative zeros and NaNs
12941 // incorrectly, but we can swap the operands to fix both.
12942 std::swap(LHS, RHS);
12946 Opcode = X86ISD::FMIN;
12950 // Converting this to a max would handle NaNs incorrectly.
12951 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12953 Opcode = X86ISD::FMAX;
12956 // Converting this to a max would handle comparisons between positive
12957 // and negative zero incorrectly, and swapping the operands would
12958 // cause it to handle NaNs incorrectly.
12959 if (!DAG.getTarget().Options.UnsafeFPMath &&
12960 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12961 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12963 std::swap(LHS, RHS);
12965 Opcode = X86ISD::FMAX;
12968 // Converting this to a max would handle both negative zeros and NaNs
12969 // incorrectly, but we can swap the operands to fix both.
12970 std::swap(LHS, RHS);
12974 Opcode = X86ISD::FMAX;
12980 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12983 // If this is a select between two integer constants, try to do some
12985 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12986 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12987 // Don't do this for crazy integer types.
12988 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12989 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12990 // so that TrueC (the true value) is larger than FalseC.
12991 bool NeedsCondInvert = false;
12993 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12994 // Efficiently invertible.
12995 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12996 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12997 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12998 NeedsCondInvert = true;
12999 std::swap(TrueC, FalseC);
13002 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13003 if (FalseC->getAPIntValue() == 0 &&
13004 TrueC->getAPIntValue().isPowerOf2()) {
13005 if (NeedsCondInvert) // Invert the condition if needed.
13006 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13007 DAG.getConstant(1, Cond.getValueType()));
13009 // Zero extend the condition if needed.
13010 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13012 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13013 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13014 DAG.getConstant(ShAmt, MVT::i8));
13017 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13018 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13019 if (NeedsCondInvert) // Invert the condition if needed.
13020 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13021 DAG.getConstant(1, Cond.getValueType()));
13023 // Zero extend the condition if needed.
13024 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13025 FalseC->getValueType(0), Cond);
13026 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13027 SDValue(FalseC, 0));
13030 // Optimize cases that will turn into an LEA instruction. This requires
13031 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13032 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13033 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13034 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13036 bool isFastMultiplier = false;
13038 switch ((unsigned char)Diff) {
13040 case 1: // result = add base, cond
13041 case 2: // result = lea base( , cond*2)
13042 case 3: // result = lea base(cond, cond*2)
13043 case 4: // result = lea base( , cond*4)
13044 case 5: // result = lea base(cond, cond*4)
13045 case 8: // result = lea base( , cond*8)
13046 case 9: // result = lea base(cond, cond*8)
13047 isFastMultiplier = true;
13052 if (isFastMultiplier) {
13053 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13054 if (NeedsCondInvert) // Invert the condition if needed.
13055 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13056 DAG.getConstant(1, Cond.getValueType()));
13058 // Zero extend the condition if needed.
13059 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13061 // Scale the condition by the difference.
13063 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13064 DAG.getConstant(Diff, Cond.getValueType()));
13066 // Add the base if non-zero.
13067 if (FalseC->getAPIntValue() != 0)
13068 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13069 SDValue(FalseC, 0));
13079 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13080 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13081 TargetLowering::DAGCombinerInfo &DCI) {
13082 DebugLoc DL = N->getDebugLoc();
13084 // If the flag operand isn't dead, don't touch this CMOV.
13085 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13088 SDValue FalseOp = N->getOperand(0);
13089 SDValue TrueOp = N->getOperand(1);
13090 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13091 SDValue Cond = N->getOperand(3);
13092 if (CC == X86::COND_E || CC == X86::COND_NE) {
13093 switch (Cond.getOpcode()) {
13097 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13098 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13099 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13103 // If this is a select between two integer constants, try to do some
13104 // optimizations. Note that the operands are ordered the opposite of SELECT
13106 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13107 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13108 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13109 // larger than FalseC (the false value).
13110 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13111 CC = X86::GetOppositeBranchCondition(CC);
13112 std::swap(TrueC, FalseC);
13115 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13116 // This is efficient for any integer data type (including i8/i16) and
13118 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13119 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13120 DAG.getConstant(CC, MVT::i8), Cond);
13122 // Zero extend the condition if needed.
13123 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13125 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13126 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13127 DAG.getConstant(ShAmt, MVT::i8));
13128 if (N->getNumValues() == 2) // Dead flag value?
13129 return DCI.CombineTo(N, Cond, SDValue());
13133 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13134 // for any integer data type, including i8/i16.
13135 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13136 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13137 DAG.getConstant(CC, MVT::i8), Cond);
13139 // Zero extend the condition if needed.
13140 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13141 FalseC->getValueType(0), Cond);
13142 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13143 SDValue(FalseC, 0));
13145 if (N->getNumValues() == 2) // Dead flag value?
13146 return DCI.CombineTo(N, Cond, SDValue());
13150 // Optimize cases that will turn into an LEA instruction. This requires
13151 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13152 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13153 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13154 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13156 bool isFastMultiplier = false;
13158 switch ((unsigned char)Diff) {
13160 case 1: // result = add base, cond
13161 case 2: // result = lea base( , cond*2)
13162 case 3: // result = lea base(cond, cond*2)
13163 case 4: // result = lea base( , cond*4)
13164 case 5: // result = lea base(cond, cond*4)
13165 case 8: // result = lea base( , cond*8)
13166 case 9: // result = lea base(cond, cond*8)
13167 isFastMultiplier = true;
13172 if (isFastMultiplier) {
13173 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13174 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13175 DAG.getConstant(CC, MVT::i8), Cond);
13176 // Zero extend the condition if needed.
13177 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13179 // Scale the condition by the difference.
13181 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13182 DAG.getConstant(Diff, Cond.getValueType()));
13184 // Add the base if non-zero.
13185 if (FalseC->getAPIntValue() != 0)
13186 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13187 SDValue(FalseC, 0));
13188 if (N->getNumValues() == 2) // Dead flag value?
13189 return DCI.CombineTo(N, Cond, SDValue());
13199 /// PerformMulCombine - Optimize a single multiply with constant into two
13200 /// in order to implement it with two cheaper instructions, e.g.
13201 /// LEA + SHL, LEA + LEA.
13202 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13203 TargetLowering::DAGCombinerInfo &DCI) {
13204 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13207 EVT VT = N->getValueType(0);
13208 if (VT != MVT::i64)
13211 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13214 uint64_t MulAmt = C->getZExtValue();
13215 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13218 uint64_t MulAmt1 = 0;
13219 uint64_t MulAmt2 = 0;
13220 if ((MulAmt % 9) == 0) {
13222 MulAmt2 = MulAmt / 9;
13223 } else if ((MulAmt % 5) == 0) {
13225 MulAmt2 = MulAmt / 5;
13226 } else if ((MulAmt % 3) == 0) {
13228 MulAmt2 = MulAmt / 3;
13231 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13232 DebugLoc DL = N->getDebugLoc();
13234 if (isPowerOf2_64(MulAmt2) &&
13235 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13236 // If second multiplifer is pow2, issue it first. We want the multiply by
13237 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13239 std::swap(MulAmt1, MulAmt2);
13242 if (isPowerOf2_64(MulAmt1))
13243 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13244 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13246 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13247 DAG.getConstant(MulAmt1, VT));
13249 if (isPowerOf2_64(MulAmt2))
13250 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13251 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13253 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13254 DAG.getConstant(MulAmt2, VT));
13256 // Do not add new nodes to DAG combiner worklist.
13257 DCI.CombineTo(N, NewMul, false);
13262 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13263 SDValue N0 = N->getOperand(0);
13264 SDValue N1 = N->getOperand(1);
13265 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13266 EVT VT = N0.getValueType();
13268 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13269 // since the result of setcc_c is all zero's or all ones.
13270 if (VT.isInteger() && !VT.isVector() &&
13271 N1C && N0.getOpcode() == ISD::AND &&
13272 N0.getOperand(1).getOpcode() == ISD::Constant) {
13273 SDValue N00 = N0.getOperand(0);
13274 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13275 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13276 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13277 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13278 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13279 APInt ShAmt = N1C->getAPIntValue();
13280 Mask = Mask.shl(ShAmt);
13282 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13283 N00, DAG.getConstant(Mask, VT));
13288 // Hardware support for vector shifts is sparse which makes us scalarize the
13289 // vector operations in many cases. Also, on sandybridge ADD is faster than
13291 // (shl V, 1) -> add V,V
13292 if (isSplatVector(N1.getNode())) {
13293 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13294 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13295 // We shift all of the values by one. In many cases we do not have
13296 // hardware support for this operation. This is better expressed as an ADD
13298 if (N1C && (1 == N1C->getZExtValue())) {
13299 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13306 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13308 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13309 const X86Subtarget *Subtarget) {
13310 EVT VT = N->getValueType(0);
13311 if (N->getOpcode() == ISD::SHL) {
13312 SDValue V = PerformSHLCombine(N, DAG);
13313 if (V.getNode()) return V;
13316 // On X86 with SSE2 support, we can transform this to a vector shift if
13317 // all elements are shifted by the same amount. We can't do this in legalize
13318 // because the a constant vector is typically transformed to a constant pool
13319 // so we have no knowledge of the shift amount.
13320 if (!Subtarget->hasXMMInt())
13323 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13324 (!Subtarget->hasAVX2() ||
13325 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13328 SDValue ShAmtOp = N->getOperand(1);
13329 EVT EltVT = VT.getVectorElementType();
13330 DebugLoc DL = N->getDebugLoc();
13331 SDValue BaseShAmt = SDValue();
13332 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13333 unsigned NumElts = VT.getVectorNumElements();
13335 for (; i != NumElts; ++i) {
13336 SDValue Arg = ShAmtOp.getOperand(i);
13337 if (Arg.getOpcode() == ISD::UNDEF) continue;
13341 for (; i != NumElts; ++i) {
13342 SDValue Arg = ShAmtOp.getOperand(i);
13343 if (Arg.getOpcode() == ISD::UNDEF) continue;
13344 if (Arg != BaseShAmt) {
13348 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13349 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13350 SDValue InVec = ShAmtOp.getOperand(0);
13351 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13352 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13354 for (; i != NumElts; ++i) {
13355 SDValue Arg = InVec.getOperand(i);
13356 if (Arg.getOpcode() == ISD::UNDEF) continue;
13360 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13362 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13363 if (C->getZExtValue() == SplatIdx)
13364 BaseShAmt = InVec.getOperand(1);
13367 if (BaseShAmt.getNode() == 0)
13368 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13369 DAG.getIntPtrConstant(0));
13373 // The shift amount is an i32.
13374 if (EltVT.bitsGT(MVT::i32))
13375 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13376 else if (EltVT.bitsLT(MVT::i32))
13377 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13379 // The shift amount is identical so we can do a vector shift.
13380 SDValue ValOp = N->getOperand(0);
13381 switch (N->getOpcode()) {
13383 llvm_unreachable("Unknown shift opcode!");
13386 if (VT == MVT::v2i64)
13387 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13388 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13390 if (VT == MVT::v4i32)
13391 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13392 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13394 if (VT == MVT::v8i16)
13395 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13396 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13398 if (VT == MVT::v4i64)
13399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13400 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13402 if (VT == MVT::v8i32)
13403 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13404 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13406 if (VT == MVT::v16i16)
13407 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13408 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13412 if (VT == MVT::v4i32)
13413 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13414 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13416 if (VT == MVT::v8i16)
13417 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13418 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13420 if (VT == MVT::v8i32)
13421 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13422 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13424 if (VT == MVT::v16i16)
13425 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13426 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13430 if (VT == MVT::v2i64)
13431 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13432 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13434 if (VT == MVT::v4i32)
13435 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13436 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13438 if (VT == MVT::v8i16)
13439 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13440 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13442 if (VT == MVT::v4i64)
13443 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13444 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13446 if (VT == MVT::v8i32)
13447 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13448 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13450 if (VT == MVT::v16i16)
13451 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13452 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13460 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13461 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13462 // and friends. Likewise for OR -> CMPNEQSS.
13463 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13464 TargetLowering::DAGCombinerInfo &DCI,
13465 const X86Subtarget *Subtarget) {
13468 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13469 // we're requiring SSE2 for both.
13470 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13471 SDValue N0 = N->getOperand(0);
13472 SDValue N1 = N->getOperand(1);
13473 SDValue CMP0 = N0->getOperand(1);
13474 SDValue CMP1 = N1->getOperand(1);
13475 DebugLoc DL = N->getDebugLoc();
13477 // The SETCCs should both refer to the same CMP.
13478 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13481 SDValue CMP00 = CMP0->getOperand(0);
13482 SDValue CMP01 = CMP0->getOperand(1);
13483 EVT VT = CMP00.getValueType();
13485 if (VT == MVT::f32 || VT == MVT::f64) {
13486 bool ExpectingFlags = false;
13487 // Check for any users that want flags:
13488 for (SDNode::use_iterator UI = N->use_begin(),
13490 !ExpectingFlags && UI != UE; ++UI)
13491 switch (UI->getOpcode()) {
13496 ExpectingFlags = true;
13498 case ISD::CopyToReg:
13499 case ISD::SIGN_EXTEND:
13500 case ISD::ZERO_EXTEND:
13501 case ISD::ANY_EXTEND:
13505 if (!ExpectingFlags) {
13506 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13507 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13509 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13510 X86::CondCode tmp = cc0;
13515 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13516 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13517 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13518 X86ISD::NodeType NTOperator = is64BitFP ?
13519 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13520 // FIXME: need symbolic constants for these magic numbers.
13521 // See X86ATTInstPrinter.cpp:printSSECC().
13522 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13523 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13524 DAG.getConstant(x86cc, MVT::i8));
13525 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13527 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13528 DAG.getConstant(1, MVT::i32));
13529 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13530 return OneBitOfTruth;
13538 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13539 /// so it can be folded inside ANDNP.
13540 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13541 EVT VT = N->getValueType(0);
13543 // Match direct AllOnes for 128 and 256-bit vectors
13544 if (ISD::isBuildVectorAllOnes(N))
13547 // Look through a bit convert.
13548 if (N->getOpcode() == ISD::BITCAST)
13549 N = N->getOperand(0).getNode();
13551 // Sometimes the operand may come from a insert_subvector building a 256-bit
13553 if (VT.getSizeInBits() == 256 &&
13554 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13555 SDValue V1 = N->getOperand(0);
13556 SDValue V2 = N->getOperand(1);
13558 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13559 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13560 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13561 ISD::isBuildVectorAllOnes(V2.getNode()))
13568 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13569 TargetLowering::DAGCombinerInfo &DCI,
13570 const X86Subtarget *Subtarget) {
13571 if (DCI.isBeforeLegalizeOps())
13574 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13578 EVT VT = N->getValueType(0);
13580 // Create ANDN, BLSI, and BLSR instructions
13581 // BLSI is X & (-X)
13582 // BLSR is X & (X-1)
13583 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13584 SDValue N0 = N->getOperand(0);
13585 SDValue N1 = N->getOperand(1);
13586 DebugLoc DL = N->getDebugLoc();
13588 // Check LHS for not
13589 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13590 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13591 // Check RHS for not
13592 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13593 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13595 // Check LHS for neg
13596 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13597 isZero(N0.getOperand(0)))
13598 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13600 // Check RHS for neg
13601 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13602 isZero(N1.getOperand(0)))
13603 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13605 // Check LHS for X-1
13606 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13607 isAllOnes(N0.getOperand(1)))
13608 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13610 // Check RHS for X-1
13611 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13612 isAllOnes(N1.getOperand(1)))
13613 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13618 // Want to form ANDNP nodes:
13619 // 1) In the hopes of then easily combining them with OR and AND nodes
13620 // to form PBLEND/PSIGN.
13621 // 2) To match ANDN packed intrinsics
13622 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13625 SDValue N0 = N->getOperand(0);
13626 SDValue N1 = N->getOperand(1);
13627 DebugLoc DL = N->getDebugLoc();
13629 // Check LHS for vnot
13630 if (N0.getOpcode() == ISD::XOR &&
13631 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13632 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13633 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13635 // Check RHS for vnot
13636 if (N1.getOpcode() == ISD::XOR &&
13637 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13638 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13639 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13644 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13645 TargetLowering::DAGCombinerInfo &DCI,
13646 const X86Subtarget *Subtarget) {
13647 if (DCI.isBeforeLegalizeOps())
13650 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13654 EVT VT = N->getValueType(0);
13656 SDValue N0 = N->getOperand(0);
13657 SDValue N1 = N->getOperand(1);
13659 // look for psign/blend
13660 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13661 if (!Subtarget->hasSSSE3orAVX() ||
13662 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13665 // Canonicalize pandn to RHS
13666 if (N0.getOpcode() == X86ISD::ANDNP)
13668 // or (and (m, x), (pandn m, y))
13669 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13670 SDValue Mask = N1.getOperand(0);
13671 SDValue X = N1.getOperand(1);
13673 if (N0.getOperand(0) == Mask)
13674 Y = N0.getOperand(1);
13675 if (N0.getOperand(1) == Mask)
13676 Y = N0.getOperand(0);
13678 // Check to see if the mask appeared in both the AND and ANDNP and
13682 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13683 if (Mask.getOpcode() != ISD::BITCAST ||
13684 X.getOpcode() != ISD::BITCAST ||
13685 Y.getOpcode() != ISD::BITCAST)
13688 // Look through mask bitcast.
13689 Mask = Mask.getOperand(0);
13690 EVT MaskVT = Mask.getValueType();
13692 // Validate that the Mask operand is a vector sra node. The sra node
13693 // will be an intrinsic.
13694 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13697 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13698 // there is no psrai.b
13699 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13700 case Intrinsic::x86_sse2_psrai_w:
13701 case Intrinsic::x86_sse2_psrai_d:
13702 case Intrinsic::x86_avx2_psrai_w:
13703 case Intrinsic::x86_avx2_psrai_d:
13705 default: return SDValue();
13708 // Check that the SRA is all signbits.
13709 SDValue SraC = Mask.getOperand(2);
13710 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13711 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13712 if ((SraAmt + 1) != EltBits)
13715 DebugLoc DL = N->getDebugLoc();
13717 // Now we know we at least have a plendvb with the mask val. See if
13718 // we can form a psignb/w/d.
13719 // psign = x.type == y.type == mask.type && y = sub(0, x);
13720 X = X.getOperand(0);
13721 Y = Y.getOperand(0);
13722 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13723 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13724 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13725 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13726 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13727 Mask.getOperand(1));
13728 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13730 // PBLENDVB only available on SSE 4.1
13731 if (!Subtarget->hasSSE41orAVX())
13734 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13736 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13737 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13738 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13739 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13740 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13744 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13747 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13748 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13750 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13752 if (!N0.hasOneUse() || !N1.hasOneUse())
13755 SDValue ShAmt0 = N0.getOperand(1);
13756 if (ShAmt0.getValueType() != MVT::i8)
13758 SDValue ShAmt1 = N1.getOperand(1);
13759 if (ShAmt1.getValueType() != MVT::i8)
13761 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13762 ShAmt0 = ShAmt0.getOperand(0);
13763 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13764 ShAmt1 = ShAmt1.getOperand(0);
13766 DebugLoc DL = N->getDebugLoc();
13767 unsigned Opc = X86ISD::SHLD;
13768 SDValue Op0 = N0.getOperand(0);
13769 SDValue Op1 = N1.getOperand(0);
13770 if (ShAmt0.getOpcode() == ISD::SUB) {
13771 Opc = X86ISD::SHRD;
13772 std::swap(Op0, Op1);
13773 std::swap(ShAmt0, ShAmt1);
13776 unsigned Bits = VT.getSizeInBits();
13777 if (ShAmt1.getOpcode() == ISD::SUB) {
13778 SDValue Sum = ShAmt1.getOperand(0);
13779 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13780 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13781 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13782 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13783 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13784 return DAG.getNode(Opc, DL, VT,
13786 DAG.getNode(ISD::TRUNCATE, DL,
13789 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13790 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13792 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13793 return DAG.getNode(Opc, DL, VT,
13794 N0.getOperand(0), N1.getOperand(0),
13795 DAG.getNode(ISD::TRUNCATE, DL,
13802 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13803 TargetLowering::DAGCombinerInfo &DCI,
13804 const X86Subtarget *Subtarget) {
13805 if (DCI.isBeforeLegalizeOps())
13808 EVT VT = N->getValueType(0);
13810 if (VT != MVT::i32 && VT != MVT::i64)
13813 // Create BLSMSK instructions by finding X ^ (X-1)
13814 SDValue N0 = N->getOperand(0);
13815 SDValue N1 = N->getOperand(1);
13816 DebugLoc DL = N->getDebugLoc();
13818 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13819 isAllOnes(N0.getOperand(1)))
13820 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13822 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13823 isAllOnes(N1.getOperand(1)))
13824 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13829 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13830 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13831 const X86Subtarget *Subtarget) {
13832 LoadSDNode *Ld = cast<LoadSDNode>(N);
13833 EVT RegVT = Ld->getValueType(0);
13834 EVT MemVT = Ld->getMemoryVT();
13835 DebugLoc dl = Ld->getDebugLoc();
13836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13838 ISD::LoadExtType Ext = Ld->getExtensionType();
13840 // If this is a vector EXT Load then attempt to optimize it using a
13841 // shuffle. We need SSE4 for the shuffles.
13842 // TODO: It is possible to support ZExt by zeroing the undef values
13843 // during the shuffle phase or after the shuffle.
13844 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13845 assert(MemVT != RegVT && "Cannot extend to the same type");
13846 assert(MemVT.isVector() && "Must load a vector from memory");
13848 unsigned NumElems = RegVT.getVectorNumElements();
13849 unsigned RegSz = RegVT.getSizeInBits();
13850 unsigned MemSz = MemVT.getSizeInBits();
13851 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13852 // All sizes must be a power of two
13853 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13855 // Attempt to load the original value using a single load op.
13856 // Find a scalar type which is equal to the loaded word size.
13857 MVT SclrLoadTy = MVT::i8;
13858 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13859 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13860 MVT Tp = (MVT::SimpleValueType)tp;
13861 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13867 // Proceed if a load word is found.
13868 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13870 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13871 RegSz/SclrLoadTy.getSizeInBits());
13873 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13874 RegSz/MemVT.getScalarType().getSizeInBits());
13875 // Can't shuffle using an illegal type.
13876 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13878 // Perform a single load.
13879 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13881 Ld->getPointerInfo(), Ld->isVolatile(),
13882 Ld->isNonTemporal(), Ld->isInvariant(),
13883 Ld->getAlignment());
13885 // Insert the word loaded into a vector.
13886 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13887 LoadUnitVecVT, ScalarLoad);
13889 // Bitcast the loaded value to a vector of the original element type, in
13890 // the size of the target vector type.
13891 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13892 unsigned SizeRatio = RegSz/MemSz;
13894 // Redistribute the loaded elements into the different locations.
13895 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13896 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13898 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13899 DAG.getUNDEF(SlicedVec.getValueType()),
13900 ShuffleVec.data());
13902 // Bitcast to the requested type.
13903 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13904 // Replace the original load with the new sequence
13905 // and return the new chain.
13906 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13907 return SDValue(ScalarLoad.getNode(), 1);
13913 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13914 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13915 const X86Subtarget *Subtarget) {
13916 StoreSDNode *St = cast<StoreSDNode>(N);
13917 EVT VT = St->getValue().getValueType();
13918 EVT StVT = St->getMemoryVT();
13919 DebugLoc dl = St->getDebugLoc();
13920 SDValue StoredVal = St->getOperand(1);
13921 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13923 // If we are saving a concatenation of two XMM registers, perform two stores.
13924 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13925 // 128-bit ones. If in the future the cost becomes only one memory access the
13926 // first version would be better.
13927 if (VT.getSizeInBits() == 256 &&
13928 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13929 StoredVal.getNumOperands() == 2) {
13931 SDValue Value0 = StoredVal.getOperand(0);
13932 SDValue Value1 = StoredVal.getOperand(1);
13934 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13935 SDValue Ptr0 = St->getBasePtr();
13936 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13938 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13939 St->getPointerInfo(), St->isVolatile(),
13940 St->isNonTemporal(), St->getAlignment());
13941 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13942 St->getPointerInfo(), St->isVolatile(),
13943 St->isNonTemporal(), St->getAlignment());
13944 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13947 // Optimize trunc store (of multiple scalars) to shuffle and store.
13948 // First, pack all of the elements in one place. Next, store to memory
13949 // in fewer chunks.
13950 if (St->isTruncatingStore() && VT.isVector()) {
13951 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13952 unsigned NumElems = VT.getVectorNumElements();
13953 assert(StVT != VT && "Cannot truncate to the same type");
13954 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13955 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13957 // From, To sizes and ElemCount must be pow of two
13958 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13959 // We are going to use the original vector elt for storing.
13960 // Accumulated smaller vector elements must be a multiple of the store size.
13961 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13963 unsigned SizeRatio = FromSz / ToSz;
13965 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13967 // Create a type on which we perform the shuffle
13968 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13969 StVT.getScalarType(), NumElems*SizeRatio);
13971 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13973 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13974 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13975 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13977 // Can't shuffle using an illegal type
13978 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13980 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13981 DAG.getUNDEF(WideVec.getValueType()),
13982 ShuffleVec.data());
13983 // At this point all of the data is stored at the bottom of the
13984 // register. We now need to save it to mem.
13986 // Find the largest store unit
13987 MVT StoreType = MVT::i8;
13988 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13989 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13990 MVT Tp = (MVT::SimpleValueType)tp;
13991 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13995 // Bitcast the original vector into a vector of store-size units
13996 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13997 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13998 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13999 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14000 SmallVector<SDValue, 8> Chains;
14001 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14002 TLI.getPointerTy());
14003 SDValue Ptr = St->getBasePtr();
14005 // Perform one or more big stores into memory.
14006 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14007 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14008 StoreType, ShuffWide,
14009 DAG.getIntPtrConstant(i));
14010 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14011 St->getPointerInfo(), St->isVolatile(),
14012 St->isNonTemporal(), St->getAlignment());
14013 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14014 Chains.push_back(Ch);
14017 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14022 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14023 // the FP state in cases where an emms may be missing.
14024 // A preferable solution to the general problem is to figure out the right
14025 // places to insert EMMS. This qualifies as a quick hack.
14027 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14028 if (VT.getSizeInBits() != 64)
14031 const Function *F = DAG.getMachineFunction().getFunction();
14032 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14033 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14034 && Subtarget->hasXMMInt();
14035 if ((VT.isVector() ||
14036 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14037 isa<LoadSDNode>(St->getValue()) &&
14038 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14039 St->getChain().hasOneUse() && !St->isVolatile()) {
14040 SDNode* LdVal = St->getValue().getNode();
14041 LoadSDNode *Ld = 0;
14042 int TokenFactorIndex = -1;
14043 SmallVector<SDValue, 8> Ops;
14044 SDNode* ChainVal = St->getChain().getNode();
14045 // Must be a store of a load. We currently handle two cases: the load
14046 // is a direct child, and it's under an intervening TokenFactor. It is
14047 // possible to dig deeper under nested TokenFactors.
14048 if (ChainVal == LdVal)
14049 Ld = cast<LoadSDNode>(St->getChain());
14050 else if (St->getValue().hasOneUse() &&
14051 ChainVal->getOpcode() == ISD::TokenFactor) {
14052 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14053 if (ChainVal->getOperand(i).getNode() == LdVal) {
14054 TokenFactorIndex = i;
14055 Ld = cast<LoadSDNode>(St->getValue());
14057 Ops.push_back(ChainVal->getOperand(i));
14061 if (!Ld || !ISD::isNormalLoad(Ld))
14064 // If this is not the MMX case, i.e. we are just turning i64 load/store
14065 // into f64 load/store, avoid the transformation if there are multiple
14066 // uses of the loaded value.
14067 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14070 DebugLoc LdDL = Ld->getDebugLoc();
14071 DebugLoc StDL = N->getDebugLoc();
14072 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14073 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14075 if (Subtarget->is64Bit() || F64IsLegal) {
14076 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14077 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14078 Ld->getPointerInfo(), Ld->isVolatile(),
14079 Ld->isNonTemporal(), Ld->isInvariant(),
14080 Ld->getAlignment());
14081 SDValue NewChain = NewLd.getValue(1);
14082 if (TokenFactorIndex != -1) {
14083 Ops.push_back(NewChain);
14084 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14087 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14088 St->getPointerInfo(),
14089 St->isVolatile(), St->isNonTemporal(),
14090 St->getAlignment());
14093 // Otherwise, lower to two pairs of 32-bit loads / stores.
14094 SDValue LoAddr = Ld->getBasePtr();
14095 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14096 DAG.getConstant(4, MVT::i32));
14098 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14099 Ld->getPointerInfo(),
14100 Ld->isVolatile(), Ld->isNonTemporal(),
14101 Ld->isInvariant(), Ld->getAlignment());
14102 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14103 Ld->getPointerInfo().getWithOffset(4),
14104 Ld->isVolatile(), Ld->isNonTemporal(),
14106 MinAlign(Ld->getAlignment(), 4));
14108 SDValue NewChain = LoLd.getValue(1);
14109 if (TokenFactorIndex != -1) {
14110 Ops.push_back(LoLd);
14111 Ops.push_back(HiLd);
14112 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14116 LoAddr = St->getBasePtr();
14117 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14118 DAG.getConstant(4, MVT::i32));
14120 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14121 St->getPointerInfo(),
14122 St->isVolatile(), St->isNonTemporal(),
14123 St->getAlignment());
14124 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14125 St->getPointerInfo().getWithOffset(4),
14127 St->isNonTemporal(),
14128 MinAlign(St->getAlignment(), 4));
14129 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14134 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14135 /// and return the operands for the horizontal operation in LHS and RHS. A
14136 /// horizontal operation performs the binary operation on successive elements
14137 /// of its first operand, then on successive elements of its second operand,
14138 /// returning the resulting values in a vector. For example, if
14139 /// A = < float a0, float a1, float a2, float a3 >
14141 /// B = < float b0, float b1, float b2, float b3 >
14142 /// then the result of doing a horizontal operation on A and B is
14143 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14144 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14145 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14146 /// set to A, RHS to B, and the routine returns 'true'.
14147 /// Note that the binary operation should have the property that if one of the
14148 /// operands is UNDEF then the result is UNDEF.
14149 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14150 // Look for the following pattern: if
14151 // A = < float a0, float a1, float a2, float a3 >
14152 // B = < float b0, float b1, float b2, float b3 >
14154 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14155 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14156 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14157 // which is A horizontal-op B.
14159 // At least one of the operands should be a vector shuffle.
14160 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14161 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14164 EVT VT = LHS.getValueType();
14166 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14167 "Unsupported vector type for horizontal add/sub");
14169 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14170 // operate independently on 128-bit lanes.
14171 unsigned NumElts = VT.getVectorNumElements();
14172 unsigned NumLanes = VT.getSizeInBits()/128;
14173 unsigned NumLaneElts = NumElts / NumLanes;
14174 assert((NumLaneElts % 2 == 0) &&
14175 "Vector type should have an even number of elements in each lane");
14176 unsigned HalfLaneElts = NumLaneElts/2;
14178 // View LHS in the form
14179 // LHS = VECTOR_SHUFFLE A, B, LMask
14180 // If LHS is not a shuffle then pretend it is the shuffle
14181 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14182 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14185 SmallVector<int, 16> LMask(NumElts);
14186 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14187 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14188 A = LHS.getOperand(0);
14189 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14190 B = LHS.getOperand(1);
14191 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14193 if (LHS.getOpcode() != ISD::UNDEF)
14195 for (unsigned i = 0; i != NumElts; ++i)
14199 // Likewise, view RHS in the form
14200 // RHS = VECTOR_SHUFFLE C, D, RMask
14202 SmallVector<int, 16> RMask(NumElts);
14203 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14204 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14205 C = RHS.getOperand(0);
14206 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14207 D = RHS.getOperand(1);
14208 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14210 if (RHS.getOpcode() != ISD::UNDEF)
14212 for (unsigned i = 0; i != NumElts; ++i)
14216 // Check that the shuffles are both shuffling the same vectors.
14217 if (!(A == C && B == D) && !(A == D && B == C))
14220 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14221 if (!A.getNode() && !B.getNode())
14224 // If A and B occur in reverse order in RHS, then "swap" them (which means
14225 // rewriting the mask).
14227 CommuteVectorShuffleMask(RMask, NumElts);
14229 // At this point LHS and RHS are equivalent to
14230 // LHS = VECTOR_SHUFFLE A, B, LMask
14231 // RHS = VECTOR_SHUFFLE A, B, RMask
14232 // Check that the masks correspond to performing a horizontal operation.
14233 for (unsigned i = 0; i != NumElts; ++i) {
14234 int LIdx = LMask[i], RIdx = RMask[i];
14236 // Ignore any UNDEF components.
14237 if (LIdx < 0 || RIdx < 0 ||
14238 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14239 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14242 // Check that successive elements are being operated on. If not, this is
14243 // not a horizontal operation.
14244 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14245 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14246 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14247 if (!(LIdx == Index && RIdx == Index + 1) &&
14248 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14252 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14253 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14257 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14258 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14259 const X86Subtarget *Subtarget) {
14260 EVT VT = N->getValueType(0);
14261 SDValue LHS = N->getOperand(0);
14262 SDValue RHS = N->getOperand(1);
14264 // Try to synthesize horizontal adds from adds of shuffles.
14265 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14266 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14267 isHorizontalBinOp(LHS, RHS, true))
14268 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14272 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14273 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14274 const X86Subtarget *Subtarget) {
14275 EVT VT = N->getValueType(0);
14276 SDValue LHS = N->getOperand(0);
14277 SDValue RHS = N->getOperand(1);
14279 // Try to synthesize horizontal subs from subs of shuffles.
14280 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14281 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14282 isHorizontalBinOp(LHS, RHS, false))
14283 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14287 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14288 /// X86ISD::FXOR nodes.
14289 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14290 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14291 // F[X]OR(0.0, x) -> x
14292 // F[X]OR(x, 0.0) -> x
14293 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14294 if (C->getValueAPF().isPosZero())
14295 return N->getOperand(1);
14296 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14297 if (C->getValueAPF().isPosZero())
14298 return N->getOperand(0);
14302 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14303 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14304 // FAND(0.0, x) -> 0.0
14305 // FAND(x, 0.0) -> 0.0
14306 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14307 if (C->getValueAPF().isPosZero())
14308 return N->getOperand(0);
14309 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14310 if (C->getValueAPF().isPosZero())
14311 return N->getOperand(1);
14315 static SDValue PerformBTCombine(SDNode *N,
14317 TargetLowering::DAGCombinerInfo &DCI) {
14318 // BT ignores high bits in the bit index operand.
14319 SDValue Op1 = N->getOperand(1);
14320 if (Op1.hasOneUse()) {
14321 unsigned BitWidth = Op1.getValueSizeInBits();
14322 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14323 APInt KnownZero, KnownOne;
14324 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14325 !DCI.isBeforeLegalizeOps());
14326 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14327 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14328 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14329 DCI.CommitTargetLoweringOpt(TLO);
14334 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14335 SDValue Op = N->getOperand(0);
14336 if (Op.getOpcode() == ISD::BITCAST)
14337 Op = Op.getOperand(0);
14338 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14339 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14340 VT.getVectorElementType().getSizeInBits() ==
14341 OpVT.getVectorElementType().getSizeInBits()) {
14342 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14347 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14348 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14349 // (and (i32 x86isd::setcc_carry), 1)
14350 // This eliminates the zext. This transformation is necessary because
14351 // ISD::SETCC is always legalized to i8.
14352 DebugLoc dl = N->getDebugLoc();
14353 SDValue N0 = N->getOperand(0);
14354 EVT VT = N->getValueType(0);
14355 if (N0.getOpcode() == ISD::AND &&
14357 N0.getOperand(0).hasOneUse()) {
14358 SDValue N00 = N0.getOperand(0);
14359 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14361 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14362 if (!C || C->getZExtValue() != 1)
14364 return DAG.getNode(ISD::AND, dl, VT,
14365 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14366 N00.getOperand(0), N00.getOperand(1)),
14367 DAG.getConstant(1, VT));
14373 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14374 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14375 unsigned X86CC = N->getConstantOperandVal(0);
14376 SDValue EFLAG = N->getOperand(1);
14377 DebugLoc DL = N->getDebugLoc();
14379 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14380 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14382 if (X86CC == X86::COND_B)
14383 return DAG.getNode(ISD::AND, DL, MVT::i8,
14384 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14385 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14386 DAG.getConstant(1, MVT::i8));
14391 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14392 const X86TargetLowering *XTLI) {
14393 SDValue Op0 = N->getOperand(0);
14394 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14395 // a 32-bit target where SSE doesn't support i64->FP operations.
14396 if (Op0.getOpcode() == ISD::LOAD) {
14397 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14398 EVT VT = Ld->getValueType(0);
14399 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14400 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14401 !XTLI->getSubtarget()->is64Bit() &&
14402 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14403 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14404 Ld->getChain(), Op0, DAG);
14405 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14412 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14413 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14414 X86TargetLowering::DAGCombinerInfo &DCI) {
14415 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14416 // the result is either zero or one (depending on the input carry bit).
14417 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14418 if (X86::isZeroNode(N->getOperand(0)) &&
14419 X86::isZeroNode(N->getOperand(1)) &&
14420 // We don't have a good way to replace an EFLAGS use, so only do this when
14422 SDValue(N, 1).use_empty()) {
14423 DebugLoc DL = N->getDebugLoc();
14424 EVT VT = N->getValueType(0);
14425 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14426 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14427 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14428 DAG.getConstant(X86::COND_B,MVT::i8),
14430 DAG.getConstant(1, VT));
14431 return DCI.CombineTo(N, Res1, CarryOut);
14437 // fold (add Y, (sete X, 0)) -> adc 0, Y
14438 // (add Y, (setne X, 0)) -> sbb -1, Y
14439 // (sub (sete X, 0), Y) -> sbb 0, Y
14440 // (sub (setne X, 0), Y) -> adc -1, Y
14441 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14442 DebugLoc DL = N->getDebugLoc();
14444 // Look through ZExts.
14445 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14446 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14449 SDValue SetCC = Ext.getOperand(0);
14450 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14453 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14454 if (CC != X86::COND_E && CC != X86::COND_NE)
14457 SDValue Cmp = SetCC.getOperand(1);
14458 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14459 !X86::isZeroNode(Cmp.getOperand(1)) ||
14460 !Cmp.getOperand(0).getValueType().isInteger())
14463 SDValue CmpOp0 = Cmp.getOperand(0);
14464 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14465 DAG.getConstant(1, CmpOp0.getValueType()));
14467 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14468 if (CC == X86::COND_NE)
14469 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14470 DL, OtherVal.getValueType(), OtherVal,
14471 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14472 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14473 DL, OtherVal.getValueType(), OtherVal,
14474 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14477 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14478 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14479 const X86Subtarget *Subtarget) {
14480 EVT VT = N->getValueType(0);
14481 SDValue Op0 = N->getOperand(0);
14482 SDValue Op1 = N->getOperand(1);
14484 // Try to synthesize horizontal adds from adds of shuffles.
14485 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14486 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14487 isHorizontalBinOp(Op0, Op1, true))
14488 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14490 return OptimizeConditionalInDecrement(N, DAG);
14493 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14494 const X86Subtarget *Subtarget) {
14495 SDValue Op0 = N->getOperand(0);
14496 SDValue Op1 = N->getOperand(1);
14498 // X86 can't encode an immediate LHS of a sub. See if we can push the
14499 // negation into a preceding instruction.
14500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14501 // If the RHS of the sub is a XOR with one use and a constant, invert the
14502 // immediate. Then add one to the LHS of the sub so we can turn
14503 // X-Y -> X+~Y+1, saving one register.
14504 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14505 isa<ConstantSDNode>(Op1.getOperand(1))) {
14506 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14507 EVT VT = Op0.getValueType();
14508 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14510 DAG.getConstant(~XorC, VT));
14511 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14512 DAG.getConstant(C->getAPIntValue()+1, VT));
14516 // Try to synthesize horizontal adds from adds of shuffles.
14517 EVT VT = N->getValueType(0);
14518 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14519 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14520 isHorizontalBinOp(Op0, Op1, true))
14521 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14523 return OptimizeConditionalInDecrement(N, DAG);
14526 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14527 DAGCombinerInfo &DCI) const {
14528 SelectionDAG &DAG = DCI.DAG;
14529 switch (N->getOpcode()) {
14531 case ISD::EXTRACT_VECTOR_ELT:
14532 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14534 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14535 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14536 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14537 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14538 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14539 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14542 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14543 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14544 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14545 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14546 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14547 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14548 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14549 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14550 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14552 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14553 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14554 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14555 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14556 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14557 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14558 case X86ISD::SHUFPS: // Handle all target specific shuffles
14559 case X86ISD::SHUFPD:
14560 case X86ISD::PALIGN:
14561 case X86ISD::UNPCKH:
14562 case X86ISD::UNPCKL:
14563 case X86ISD::MOVHLPS:
14564 case X86ISD::MOVLHPS:
14565 case X86ISD::PSHUFD:
14566 case X86ISD::PSHUFHW:
14567 case X86ISD::PSHUFLW:
14568 case X86ISD::MOVSS:
14569 case X86ISD::MOVSD:
14570 case X86ISD::VPERMILP:
14571 case X86ISD::VPERM2X128:
14572 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14578 /// isTypeDesirableForOp - Return true if the target has native support for
14579 /// the specified value type and it is 'desirable' to use the type for the
14580 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14581 /// instruction encodings are longer and some i16 instructions are slow.
14582 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14583 if (!isTypeLegal(VT))
14585 if (VT != MVT::i16)
14592 case ISD::SIGN_EXTEND:
14593 case ISD::ZERO_EXTEND:
14594 case ISD::ANY_EXTEND:
14607 /// IsDesirableToPromoteOp - This method query the target whether it is
14608 /// beneficial for dag combiner to promote the specified node. If true, it
14609 /// should return the desired promotion type by reference.
14610 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14611 EVT VT = Op.getValueType();
14612 if (VT != MVT::i16)
14615 bool Promote = false;
14616 bool Commute = false;
14617 switch (Op.getOpcode()) {
14620 LoadSDNode *LD = cast<LoadSDNode>(Op);
14621 // If the non-extending load has a single use and it's not live out, then it
14622 // might be folded.
14623 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14624 Op.hasOneUse()*/) {
14625 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14626 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14627 // The only case where we'd want to promote LOAD (rather then it being
14628 // promoted as an operand is when it's only use is liveout.
14629 if (UI->getOpcode() != ISD::CopyToReg)
14636 case ISD::SIGN_EXTEND:
14637 case ISD::ZERO_EXTEND:
14638 case ISD::ANY_EXTEND:
14643 SDValue N0 = Op.getOperand(0);
14644 // Look out for (store (shl (load), x)).
14645 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14658 SDValue N0 = Op.getOperand(0);
14659 SDValue N1 = Op.getOperand(1);
14660 if (!Commute && MayFoldLoad(N1))
14662 // Avoid disabling potential load folding opportunities.
14663 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14665 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14675 //===----------------------------------------------------------------------===//
14676 // X86 Inline Assembly Support
14677 //===----------------------------------------------------------------------===//
14679 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14680 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14682 std::string AsmStr = IA->getAsmString();
14684 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14685 SmallVector<StringRef, 4> AsmPieces;
14686 SplitString(AsmStr, AsmPieces, ";\n");
14688 switch (AsmPieces.size()) {
14689 default: return false;
14691 AsmStr = AsmPieces[0];
14693 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14695 // FIXME: this should verify that we are targeting a 486 or better. If not,
14696 // we will turn this bswap into something that will be lowered to logical ops
14697 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14698 // so don't worry about this.
14700 if (AsmPieces.size() == 2 &&
14701 (AsmPieces[0] == "bswap" ||
14702 AsmPieces[0] == "bswapq" ||
14703 AsmPieces[0] == "bswapl") &&
14704 (AsmPieces[1] == "$0" ||
14705 AsmPieces[1] == "${0:q}")) {
14706 // No need to check constraints, nothing other than the equivalent of
14707 // "=r,0" would be valid here.
14708 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14709 if (!Ty || Ty->getBitWidth() % 16 != 0)
14711 return IntrinsicLowering::LowerToByteSwap(CI);
14713 // rorw $$8, ${0:w} --> llvm.bswap.i16
14714 if (CI->getType()->isIntegerTy(16) &&
14715 AsmPieces.size() == 3 &&
14716 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14717 AsmPieces[1] == "$$8," &&
14718 AsmPieces[2] == "${0:w}" &&
14719 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14721 const std::string &ConstraintsStr = IA->getConstraintString();
14722 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14723 std::sort(AsmPieces.begin(), AsmPieces.end());
14724 if (AsmPieces.size() == 4 &&
14725 AsmPieces[0] == "~{cc}" &&
14726 AsmPieces[1] == "~{dirflag}" &&
14727 AsmPieces[2] == "~{flags}" &&
14728 AsmPieces[3] == "~{fpsr}") {
14729 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14730 if (!Ty || Ty->getBitWidth() % 16 != 0)
14732 return IntrinsicLowering::LowerToByteSwap(CI);
14737 if (CI->getType()->isIntegerTy(32) &&
14738 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14739 SmallVector<StringRef, 4> Words;
14740 SplitString(AsmPieces[0], Words, " \t,");
14741 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14742 Words[2] == "${0:w}") {
14744 SplitString(AsmPieces[1], Words, " \t,");
14745 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14746 Words[2] == "$0") {
14748 SplitString(AsmPieces[2], Words, " \t,");
14749 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14750 Words[2] == "${0:w}") {
14752 const std::string &ConstraintsStr = IA->getConstraintString();
14753 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14754 std::sort(AsmPieces.begin(), AsmPieces.end());
14755 if (AsmPieces.size() == 4 &&
14756 AsmPieces[0] == "~{cc}" &&
14757 AsmPieces[1] == "~{dirflag}" &&
14758 AsmPieces[2] == "~{flags}" &&
14759 AsmPieces[3] == "~{fpsr}") {
14760 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14761 if (!Ty || Ty->getBitWidth() % 16 != 0)
14763 return IntrinsicLowering::LowerToByteSwap(CI);
14770 if (CI->getType()->isIntegerTy(64)) {
14771 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14772 if (Constraints.size() >= 2 &&
14773 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14774 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14775 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14776 SmallVector<StringRef, 4> Words;
14777 SplitString(AsmPieces[0], Words, " \t");
14778 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14780 SplitString(AsmPieces[1], Words, " \t");
14781 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14783 SplitString(AsmPieces[2], Words, " \t,");
14784 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14785 Words[2] == "%edx") {
14786 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14787 if (!Ty || Ty->getBitWidth() % 16 != 0)
14789 return IntrinsicLowering::LowerToByteSwap(CI);
14802 /// getConstraintType - Given a constraint letter, return the type of
14803 /// constraint it is for this target.
14804 X86TargetLowering::ConstraintType
14805 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14806 if (Constraint.size() == 1) {
14807 switch (Constraint[0]) {
14818 return C_RegisterClass;
14842 return TargetLowering::getConstraintType(Constraint);
14845 /// Examine constraint type and operand type and determine a weight value.
14846 /// This object must already have been set up with the operand type
14847 /// and the current alternative constraint selected.
14848 TargetLowering::ConstraintWeight
14849 X86TargetLowering::getSingleConstraintMatchWeight(
14850 AsmOperandInfo &info, const char *constraint) const {
14851 ConstraintWeight weight = CW_Invalid;
14852 Value *CallOperandVal = info.CallOperandVal;
14853 // If we don't have a value, we can't do a match,
14854 // but allow it at the lowest weight.
14855 if (CallOperandVal == NULL)
14857 Type *type = CallOperandVal->getType();
14858 // Look at the constraint type.
14859 switch (*constraint) {
14861 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14872 if (CallOperandVal->getType()->isIntegerTy())
14873 weight = CW_SpecificReg;
14878 if (type->isFloatingPointTy())
14879 weight = CW_SpecificReg;
14882 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14883 weight = CW_SpecificReg;
14887 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14888 weight = CW_Register;
14891 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14892 if (C->getZExtValue() <= 31)
14893 weight = CW_Constant;
14897 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14898 if (C->getZExtValue() <= 63)
14899 weight = CW_Constant;
14903 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14904 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14905 weight = CW_Constant;
14909 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14910 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14911 weight = CW_Constant;
14915 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14916 if (C->getZExtValue() <= 3)
14917 weight = CW_Constant;
14921 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14922 if (C->getZExtValue() <= 0xff)
14923 weight = CW_Constant;
14928 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14929 weight = CW_Constant;
14933 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14934 if ((C->getSExtValue() >= -0x80000000LL) &&
14935 (C->getSExtValue() <= 0x7fffffffLL))
14936 weight = CW_Constant;
14940 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14941 if (C->getZExtValue() <= 0xffffffff)
14942 weight = CW_Constant;
14949 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14950 /// with another that has more specific requirements based on the type of the
14951 /// corresponding operand.
14952 const char *X86TargetLowering::
14953 LowerXConstraint(EVT ConstraintVT) const {
14954 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14955 // 'f' like normal targets.
14956 if (ConstraintVT.isFloatingPoint()) {
14957 if (Subtarget->hasXMMInt())
14959 if (Subtarget->hasXMM())
14963 return TargetLowering::LowerXConstraint(ConstraintVT);
14966 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14967 /// vector. If it is invalid, don't add anything to Ops.
14968 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14969 std::string &Constraint,
14970 std::vector<SDValue>&Ops,
14971 SelectionDAG &DAG) const {
14972 SDValue Result(0, 0);
14974 // Only support length 1 constraints for now.
14975 if (Constraint.length() > 1) return;
14977 char ConstraintLetter = Constraint[0];
14978 switch (ConstraintLetter) {
14981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14982 if (C->getZExtValue() <= 31) {
14983 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14990 if (C->getZExtValue() <= 63) {
14991 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14998 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14999 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15005 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15006 if (C->getZExtValue() <= 255) {
15007 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15013 // 32-bit signed value
15014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15015 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15016 C->getSExtValue())) {
15017 // Widen to 64 bits here to get it sign extended.
15018 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15021 // FIXME gcc accepts some relocatable values here too, but only in certain
15022 // memory models; it's complicated.
15027 // 32-bit unsigned value
15028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15029 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15030 C->getZExtValue())) {
15031 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15035 // FIXME gcc accepts some relocatable values here too, but only in certain
15036 // memory models; it's complicated.
15040 // Literal immediates are always ok.
15041 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15042 // Widen to 64 bits here to get it sign extended.
15043 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15047 // In any sort of PIC mode addresses need to be computed at runtime by
15048 // adding in a register or some sort of table lookup. These can't
15049 // be used as immediates.
15050 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15053 // If we are in non-pic codegen mode, we allow the address of a global (with
15054 // an optional displacement) to be used with 'i'.
15055 GlobalAddressSDNode *GA = 0;
15056 int64_t Offset = 0;
15058 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15060 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15061 Offset += GA->getOffset();
15063 } else if (Op.getOpcode() == ISD::ADD) {
15064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15065 Offset += C->getZExtValue();
15066 Op = Op.getOperand(0);
15069 } else if (Op.getOpcode() == ISD::SUB) {
15070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15071 Offset += -C->getZExtValue();
15072 Op = Op.getOperand(0);
15077 // Otherwise, this isn't something we can handle, reject it.
15081 const GlobalValue *GV = GA->getGlobal();
15082 // If we require an extra load to get this address, as in PIC mode, we
15083 // can't accept it.
15084 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15085 getTargetMachine())))
15088 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15089 GA->getValueType(0), Offset);
15094 if (Result.getNode()) {
15095 Ops.push_back(Result);
15098 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15101 std::pair<unsigned, const TargetRegisterClass*>
15102 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15104 // First, see if this is a constraint that directly corresponds to an LLVM
15106 if (Constraint.size() == 1) {
15107 // GCC Constraint Letters
15108 switch (Constraint[0]) {
15110 // TODO: Slight differences here in allocation order and leaving
15111 // RIP in the class. Do they matter any more here than they do
15112 // in the normal allocation?
15113 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15114 if (Subtarget->is64Bit()) {
15115 if (VT == MVT::i32 || VT == MVT::f32)
15116 return std::make_pair(0U, X86::GR32RegisterClass);
15117 else if (VT == MVT::i16)
15118 return std::make_pair(0U, X86::GR16RegisterClass);
15119 else if (VT == MVT::i8 || VT == MVT::i1)
15120 return std::make_pair(0U, X86::GR8RegisterClass);
15121 else if (VT == MVT::i64 || VT == MVT::f64)
15122 return std::make_pair(0U, X86::GR64RegisterClass);
15125 // 32-bit fallthrough
15126 case 'Q': // Q_REGS
15127 if (VT == MVT::i32 || VT == MVT::f32)
15128 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15129 else if (VT == MVT::i16)
15130 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15131 else if (VT == MVT::i8 || VT == MVT::i1)
15132 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15133 else if (VT == MVT::i64)
15134 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15136 case 'r': // GENERAL_REGS
15137 case 'l': // INDEX_REGS
15138 if (VT == MVT::i8 || VT == MVT::i1)
15139 return std::make_pair(0U, X86::GR8RegisterClass);
15140 if (VT == MVT::i16)
15141 return std::make_pair(0U, X86::GR16RegisterClass);
15142 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15143 return std::make_pair(0U, X86::GR32RegisterClass);
15144 return std::make_pair(0U, X86::GR64RegisterClass);
15145 case 'R': // LEGACY_REGS
15146 if (VT == MVT::i8 || VT == MVT::i1)
15147 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15148 if (VT == MVT::i16)
15149 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15150 if (VT == MVT::i32 || !Subtarget->is64Bit())
15151 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15152 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15153 case 'f': // FP Stack registers.
15154 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15155 // value to the correct fpstack register class.
15156 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15157 return std::make_pair(0U, X86::RFP32RegisterClass);
15158 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15159 return std::make_pair(0U, X86::RFP64RegisterClass);
15160 return std::make_pair(0U, X86::RFP80RegisterClass);
15161 case 'y': // MMX_REGS if MMX allowed.
15162 if (!Subtarget->hasMMX()) break;
15163 return std::make_pair(0U, X86::VR64RegisterClass);
15164 case 'Y': // SSE_REGS if SSE2 allowed
15165 if (!Subtarget->hasXMMInt()) break;
15167 case 'x': // SSE_REGS if SSE1 allowed
15168 if (!Subtarget->hasXMM()) break;
15170 switch (VT.getSimpleVT().SimpleTy) {
15172 // Scalar SSE types.
15175 return std::make_pair(0U, X86::FR32RegisterClass);
15178 return std::make_pair(0U, X86::FR64RegisterClass);
15186 return std::make_pair(0U, X86::VR128RegisterClass);
15192 // Use the default implementation in TargetLowering to convert the register
15193 // constraint into a member of a register class.
15194 std::pair<unsigned, const TargetRegisterClass*> Res;
15195 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15197 // Not found as a standard register?
15198 if (Res.second == 0) {
15199 // Map st(0) -> st(7) -> ST0
15200 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15201 tolower(Constraint[1]) == 's' &&
15202 tolower(Constraint[2]) == 't' &&
15203 Constraint[3] == '(' &&
15204 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15205 Constraint[5] == ')' &&
15206 Constraint[6] == '}') {
15208 Res.first = X86::ST0+Constraint[4]-'0';
15209 Res.second = X86::RFP80RegisterClass;
15213 // GCC allows "st(0)" to be called just plain "st".
15214 if (StringRef("{st}").equals_lower(Constraint)) {
15215 Res.first = X86::ST0;
15216 Res.second = X86::RFP80RegisterClass;
15221 if (StringRef("{flags}").equals_lower(Constraint)) {
15222 Res.first = X86::EFLAGS;
15223 Res.second = X86::CCRRegisterClass;
15227 // 'A' means EAX + EDX.
15228 if (Constraint == "A") {
15229 Res.first = X86::EAX;
15230 Res.second = X86::GR32_ADRegisterClass;
15236 // Otherwise, check to see if this is a register class of the wrong value
15237 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15238 // turn into {ax},{dx}.
15239 if (Res.second->hasType(VT))
15240 return Res; // Correct type already, nothing to do.
15242 // All of the single-register GCC register classes map their values onto
15243 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15244 // really want an 8-bit or 32-bit register, map to the appropriate register
15245 // class and return the appropriate register.
15246 if (Res.second == X86::GR16RegisterClass) {
15247 if (VT == MVT::i8) {
15248 unsigned DestReg = 0;
15249 switch (Res.first) {
15251 case X86::AX: DestReg = X86::AL; break;
15252 case X86::DX: DestReg = X86::DL; break;
15253 case X86::CX: DestReg = X86::CL; break;
15254 case X86::BX: DestReg = X86::BL; break;
15257 Res.first = DestReg;
15258 Res.second = X86::GR8RegisterClass;
15260 } else if (VT == MVT::i32) {
15261 unsigned DestReg = 0;
15262 switch (Res.first) {
15264 case X86::AX: DestReg = X86::EAX; break;
15265 case X86::DX: DestReg = X86::EDX; break;
15266 case X86::CX: DestReg = X86::ECX; break;
15267 case X86::BX: DestReg = X86::EBX; break;
15268 case X86::SI: DestReg = X86::ESI; break;
15269 case X86::DI: DestReg = X86::EDI; break;
15270 case X86::BP: DestReg = X86::EBP; break;
15271 case X86::SP: DestReg = X86::ESP; break;
15274 Res.first = DestReg;
15275 Res.second = X86::GR32RegisterClass;
15277 } else if (VT == MVT::i64) {
15278 unsigned DestReg = 0;
15279 switch (Res.first) {
15281 case X86::AX: DestReg = X86::RAX; break;
15282 case X86::DX: DestReg = X86::RDX; break;
15283 case X86::CX: DestReg = X86::RCX; break;
15284 case X86::BX: DestReg = X86::RBX; break;
15285 case X86::SI: DestReg = X86::RSI; break;
15286 case X86::DI: DestReg = X86::RDI; break;
15287 case X86::BP: DestReg = X86::RBP; break;
15288 case X86::SP: DestReg = X86::RSP; break;
15291 Res.first = DestReg;
15292 Res.second = X86::GR64RegisterClass;
15295 } else if (Res.second == X86::FR32RegisterClass ||
15296 Res.second == X86::FR64RegisterClass ||
15297 Res.second == X86::VR128RegisterClass) {
15298 // Handle references to XMM physical registers that got mapped into the
15299 // wrong class. This can happen with constraints like {xmm0} where the
15300 // target independent register mapper will just pick the first match it can
15301 // find, ignoring the required type.
15302 if (VT == MVT::f32)
15303 Res.second = X86::FR32RegisterClass;
15304 else if (VT == MVT::f64)
15305 Res.second = X86::FR64RegisterClass;
15306 else if (X86::VR128RegisterClass->hasType(VT))
15307 Res.second = X86::VR128RegisterClass;