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::FMA, MVT::f80, Expand);
669 // Always use a library call for pow.
670 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
674 setOperationAction(ISD::FLOG, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 // First set operation action for all vector types to either promote
681 // (for widening) or expand (for scalarization). Then we will selectively
682 // turn on ones that can be effectively codegen'd.
683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742 setTruncStoreAction((MVT::SimpleValueType)VT,
743 (MVT::SimpleValueType)InnerVT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750 // with -msoft-float, disable use of MMX as well.
751 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753 // No operations on x86mmx supported, everything uses intrinsics.
756 // MMX-sized vectors (other than x86mmx) are expected to be expanded
757 // into smaller operations.
758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
762 setOperationAction(ISD::AND, MVT::v8i8, Expand);
763 setOperationAction(ISD::AND, MVT::v4i16, Expand);
764 setOperationAction(ISD::AND, MVT::v2i32, Expand);
765 setOperationAction(ISD::AND, MVT::v1i64, Expand);
766 setOperationAction(ISD::OR, MVT::v8i8, Expand);
767 setOperationAction(ISD::OR, MVT::v4i16, Expand);
768 setOperationAction(ISD::OR, MVT::v2i32, Expand);
769 setOperationAction(ISD::OR, MVT::v1i64, Expand);
770 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
771 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
772 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
773 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
788 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
805 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809 // registers cannot be used even for integer operations.
810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
816 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
817 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
818 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851 EVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR,
859 VT.getSimpleVT().SimpleTy, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE,
861 VT.getSimpleVT().SimpleTy, Custom);
862 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863 VT.getSimpleVT().SimpleTy, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873 if (Subtarget->is64Bit()) {
874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
883 // Do not attempt to promote non-128-bit vectors
884 if (!VT.is128BitVector())
887 setOperationAction(ISD::AND, SVT, Promote);
888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
889 setOperationAction(ISD::OR, SVT, Promote);
890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
891 setOperationAction(ISD::XOR, SVT, Promote);
892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
893 setOperationAction(ISD::LOAD, SVT, Promote);
894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
895 setOperationAction(ISD::SELECT, SVT, Promote);
896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
899 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901 // Custom lower v2i64 and v2f64 selects.
902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
911 if (Subtarget->hasSSE41orAVX()) {
912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915 setOperationAction(ISD::FRINT, MVT::f32, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923 // FIXME: Do we need to handle scalar-to-vector here?
924 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
932 // i8 and i16 vectors are custom , because the source register and source
933 // source memory operand types are not the same width. f32 vectors are
934 // custom since the immediate controlling the insert encodes additional
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946 // FIXME: these should be Legal but thats only for the case where
947 // the index is constant. For now custom expand to deal with that
948 if (Subtarget->is64Bit()) {
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
954 if (Subtarget->hasXMMInt()) {
955 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
956 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
959 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
962 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
964 if (Subtarget->hasAVX2()) {
965 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
966 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
968 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
969 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
971 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
973 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
974 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
976 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
977 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
979 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
983 if (Subtarget->hasSSE42orAVX())
984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
986 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
998 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1046 if (Subtarget->hasAVX2()) {
1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1060 // Don't lower v32i8 because there is no 128-bit byte mul
1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1085 // Don't lower v32i8 because there is no 128-bit byte mul
1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1096 // Custom lower several nodes for 256-bit types.
1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1102 // Extract subvector is special because the value type
1103 // (result) is 128-bit but the source is 256-bit wide.
1104 if (VT.is128BitVector())
1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1107 // Do not attempt to custom lower other non-256-bit vectors
1108 if (!VT.is256BitVector())
1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1124 // Do not attempt to promote non-256-bit vectors
1125 if (!VT.is256BitVector())
1128 setOperationAction(ISD::AND, SVT, Promote);
1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1130 setOperationAction(ISD::OR, SVT, Promote);
1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1132 setOperationAction(ISD::XOR, SVT, Promote);
1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1134 setOperationAction(ISD::LOAD, SVT, Promote);
1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1136 setOperationAction(ISD::SELECT, SVT, Promote);
1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142 // of this type with custom code.
1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1148 // We want to custom lower some of our intrinsics.
1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153 // handle type legalization for these operations here.
1155 // FIXME: We really should do custom legalization for addition and
1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1157 // than generic legalization for 64-bit multiplication-with-overflow, though.
1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159 // Add/Sub/Mul with overflow operations are custom lowered.
1161 setOperationAction(ISD::SADDO, VT, Custom);
1162 setOperationAction(ISD::UADDO, VT, Custom);
1163 setOperationAction(ISD::SSUBO, VT, Custom);
1164 setOperationAction(ISD::USUBO, VT, Custom);
1165 setOperationAction(ISD::SMULO, VT, Custom);
1166 setOperationAction(ISD::UMULO, VT, Custom);
1169 // There are no 8-bit 3-address imul/mul instructions
1170 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1173 if (!Subtarget->is64Bit()) {
1174 // These libcalls are not available in 32-bit.
1175 setLibcallName(RTLIB::SHL_I128, 0);
1176 setLibcallName(RTLIB::SRL_I128, 0);
1177 setLibcallName(RTLIB::SRA_I128, 0);
1180 // We have target-specific dag combine patterns for the following nodes:
1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183 setTargetDAGCombine(ISD::BUILD_VECTOR);
1184 setTargetDAGCombine(ISD::VSELECT);
1185 setTargetDAGCombine(ISD::SELECT);
1186 setTargetDAGCombine(ISD::SHL);
1187 setTargetDAGCombine(ISD::SRA);
1188 setTargetDAGCombine(ISD::SRL);
1189 setTargetDAGCombine(ISD::OR);
1190 setTargetDAGCombine(ISD::AND);
1191 setTargetDAGCombine(ISD::ADD);
1192 setTargetDAGCombine(ISD::FADD);
1193 setTargetDAGCombine(ISD::FSUB);
1194 setTargetDAGCombine(ISD::SUB);
1195 setTargetDAGCombine(ISD::LOAD);
1196 setTargetDAGCombine(ISD::STORE);
1197 setTargetDAGCombine(ISD::ZERO_EXTEND);
1198 setTargetDAGCombine(ISD::SINT_TO_FP);
1199 if (Subtarget->is64Bit())
1200 setTargetDAGCombine(ISD::MUL);
1201 if (Subtarget->hasBMI())
1202 setTargetDAGCombine(ISD::XOR);
1204 computeRegisterProperties();
1206 // On Darwin, -Os means optimize for size without hurting performance,
1207 // do not reduce the limit.
1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214 setPrefLoopAlignment(4); // 2^4 bytes.
1215 benefitFromCodePlacementOpt = true;
1217 setPrefFunctionAlignment(4); // 2^4 bytes.
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222 if (!VT.isVector()) return MVT::i8;
1223 return VT.changeVectorElementTypeToInteger();
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233 if (VTy->getBitWidth() == 128)
1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236 unsigned EltAlign = 0;
1237 getMaxByValAlign(ATy->getElementType(), EltAlign);
1238 if (EltAlign > MaxAlign)
1239 MaxAlign = EltAlign;
1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242 unsigned EltAlign = 0;
1243 getMaxByValAlign(STy->getElementType(i), EltAlign);
1244 if (EltAlign > MaxAlign)
1245 MaxAlign = EltAlign;
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258 if (Subtarget->is64Bit()) {
1259 // Max of 8 and alignment of type.
1260 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1267 if (Subtarget->hasXMM())
1268 getMaxByValAlign(Ty, Align);
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286 unsigned DstAlign, unsigned SrcAlign,
1289 MachineFunction &MF) const {
1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291 // linux. This is because the stack realignment code can't handle certain
1292 // cases like PR2962. This should be removed when PR2962 is fixed.
1293 const Function *F = MF.getFunction();
1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1297 (Subtarget->isUnalignedMemAccessFast() ||
1298 ((DstAlign == 0 || DstAlign >= 16) &&
1299 (SrcAlign == 0 || SrcAlign >= 16))) &&
1300 Subtarget->getStackAlignment() >= 16) {
1301 if (Subtarget->hasAVX() &&
1302 Subtarget->getStackAlignment() >= 32)
1304 if (Subtarget->hasXMMInt())
1306 if (Subtarget->hasXMM())
1308 } else if (!MemcpyStrSrc && Size >= 8 &&
1309 !Subtarget->is64Bit() &&
1310 Subtarget->getStackAlignment() >= 8 &&
1311 Subtarget->hasXMMInt()) {
1312 // Do not use f64 to lower memcpy if source is string constant. It's
1313 // better to use i32 to avoid the loads.
1317 if (Subtarget->is64Bit() && Size >= 8)
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function. The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329 Subtarget->isPICStyleGOT())
1330 return MachineJumpTableInfo::EK_Custom32;
1332 // Otherwise, use the normal jump table encoding heuristics.
1333 return TargetLowering::getJumpTableEncoding();
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338 const MachineBasicBlock *MBB,
1339 unsigned uid,MCContext &Ctx) const{
1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341 Subtarget->isPICStyleGOT());
1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1344 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351 SelectionDAG &DAG) const {
1352 if (!Subtarget->is64Bit())
1353 // This doesn't have DebugLoc associated with it, but is not really the
1354 // same as a Register.
1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364 MCContext &Ctx) const {
1365 // X86-64 uses RIP relative addressing based on the jump table label.
1366 if (Subtarget->isPICStyleRIPRel())
1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1369 // Otherwise, the reference is relative to the PIC base.
1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376 const TargetRegisterClass *RRC = 0;
1378 switch (VT.getSimpleVT().SimpleTy) {
1380 return TargetLowering::findRepresentativeClass(VT);
1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382 RRC = (Subtarget->is64Bit()
1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1386 RRC = X86::VR64RegisterClass;
1388 case MVT::f32: case MVT::f64:
1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390 case MVT::v4f32: case MVT::v2f64:
1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1393 RRC = X86::VR128RegisterClass;
1396 return std::make_pair(RRC, Cost);
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400 unsigned &Offset) const {
1401 if (!Subtarget->isTargetLinux())
1404 if (Subtarget->is64Bit()) {
1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1420 //===----------------------------------------------------------------------===//
1421 // Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1424 #include "X86GenCallingConv.inc"
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428 MachineFunction &MF, bool isVarArg,
1429 const SmallVectorImpl<ISD::OutputArg> &Outs,
1430 LLVMContext &Context) const {
1431 SmallVector<CCValAssign, 16> RVLocs;
1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1434 return CCInfo.CheckReturn(Outs, RetCC_X86);
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439 CallingConv::ID CallConv, bool isVarArg,
1440 const SmallVectorImpl<ISD::OutputArg> &Outs,
1441 const SmallVectorImpl<SDValue> &OutVals,
1442 DebugLoc dl, SelectionDAG &DAG) const {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448 RVLocs, *DAG.getContext());
1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1451 // Add the regs to the liveout set for the function.
1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453 for (unsigned i = 0; i != RVLocs.size(); ++i)
1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455 MRI.addLiveOut(RVLocs[i].getLocReg());
1459 SmallVector<SDValue, 6> RetOps;
1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461 // Operand #1 = Bytes To Pop
1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1465 // Copy the result values into the output registers.
1466 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467 CCValAssign &VA = RVLocs[i];
1468 assert(VA.isRegLoc() && "Can only return in registers!");
1469 SDValue ValToCopy = OutVals[i];
1470 EVT ValVT = ValToCopy.getValueType();
1472 // If this is x86-64, and we disabled SSE, we can't return FP values,
1473 // or SSE or MMX vectors.
1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477 report_fatal_error("SSE register return with SSE disabled");
1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1480 // llvm-gcc has never done it right and no one has noticed, so this
1481 // should be OK for now.
1482 if (ValVT == MVT::f64 &&
1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484 report_fatal_error("SSE2 register return with SSE2 disabled");
1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487 // the RET instruction and handled by the FP Stackifier.
1488 if (VA.getLocReg() == X86::ST0 ||
1489 VA.getLocReg() == X86::ST1) {
1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491 // change the value to the FP stack register class.
1492 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494 RetOps.push_back(ValToCopy);
1495 // Don't emit a copytoreg.
1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500 // which is returned in RAX / RDX.
1501 if (Subtarget->is64Bit()) {
1502 if (ValVT == MVT::x86mmx) {
1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1507 // If we don't have SSE2 available, convert to v4f32 so the generated
1508 // register is legal.
1509 if (!Subtarget->hasXMMInt())
1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516 Flag = Chain.getValue(1);
1519 // The x86-64 ABI for returning structs by value requires that we copy
1520 // the sret argument into %rax for the return. We saved the argument into
1521 // a virtual register in the entry block, so now we copy the value out
1523 if (Subtarget->is64Bit() &&
1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525 MachineFunction &MF = DAG.getMachineFunction();
1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527 unsigned Reg = FuncInfo->getSRetReturnReg();
1529 "SRetReturnReg should have been set in LowerFormalArguments().");
1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533 Flag = Chain.getValue(1);
1535 // RAX now acts like a return value.
1536 MRI.addLiveOut(X86::RAX);
1539 RetOps[0] = Chain; // Update chain.
1541 // Add the flag if we have it.
1543 RetOps.push_back(Flag);
1545 return DAG.getNode(X86ISD::RET_FLAG, dl,
1546 MVT::Other, &RetOps[0], RetOps.size());
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550 if (N->getNumValues() != 1)
1552 if (!N->hasNUsesOfValue(1, 0))
1555 SDNode *Copy = *N->use_begin();
1556 if (Copy->getOpcode() != ISD::CopyToReg &&
1557 Copy->getOpcode() != ISD::FP_EXTEND)
1560 bool HasRet = false;
1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1563 if (UI->getOpcode() != X86ISD::RET_FLAG)
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573 ISD::NodeType ExtendKind) const {
1575 // TODO: Is this also valid on 32-bit?
1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577 ReturnMVT = MVT::i8;
1579 ReturnMVT = MVT::i32;
1581 EVT MinVT = getRegisterType(Context, ReturnMVT);
1582 return VT.bitsLT(MinVT) ? MinVT : VT;
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590 CallingConv::ID CallConv, bool isVarArg,
1591 const SmallVectorImpl<ISD::InputArg> &Ins,
1592 DebugLoc dl, SelectionDAG &DAG,
1593 SmallVectorImpl<SDValue> &InVals) const {
1595 // Assign locations to each value returned by this call.
1596 SmallVector<CCValAssign, 16> RVLocs;
1597 bool Is64Bit = Subtarget->is64Bit();
1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599 getTargetMachine(), RVLocs, *DAG.getContext());
1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1602 // Copy all of the result registers out of their specified physreg.
1603 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604 CCValAssign &VA = RVLocs[i];
1605 EVT CopyVT = VA.getValVT();
1607 // If this is x86-64, and we disabled SSE, we can't return FP values
1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610 report_fatal_error("SSE register return with SSE disabled");
1615 // If this is a call to a function that returns an fp value on the floating
1616 // point stack, we must guarantee the the value is popped from the stack, so
1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618 // if the return value is not used. We use the FpPOP_RETVAL instruction
1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621 // If we prefer to use the value in xmm registers, copy it out as f80 and
1622 // use a truncate to move it from fp stack reg to xmm reg.
1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624 SDValue Ops[] = { Chain, InFlag };
1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626 MVT::Other, MVT::Glue, Ops, 2), 1);
1627 Val = Chain.getValue(0);
1629 // Round the f80 to the right size, which also moves it to the appropriate
1631 if (CopyVT != VA.getValVT())
1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633 // This truncation won't change the value.
1634 DAG.getIntPtrConstant(1));
1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637 CopyVT, InFlag).getValue(1);
1638 Val = Chain.getValue(0);
1640 InFlag = Chain.getValue(2);
1641 InVals.push_back(Val);
1648 //===----------------------------------------------------------------------===//
1649 // C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 // StdCall calling convention seems to be standard for many Windows' API
1652 // routines and around. It differs from C calling convention just a little:
1653 // callee should clean up the stack, not caller. Symbols should be also
1654 // decorated in some fancy way :) It doesn't support any vector arguments.
1655 // For info on fast calling convention see Fast Calling Convention (tail call)
1656 // implementation LowerX86_32FastCCCallTo.
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1664 return Outs[0].Flags.isSRet();
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1674 return Ins[0].Flags.isSRet();
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688 /*isVolatile*/false, /*AlwaysInline=*/true,
1689 MachinePointerInfo(), MachinePointerInfo());
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699 if (!CI->isTailCall())
1703 CallingConv::ID CalleeCC = CS.getCallingConv();
1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1713 bool GuaranteedTailCallOpt) {
1714 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1718 X86TargetLowering::LowerMemArgument(SDValue Chain,
1719 CallingConv::ID CallConv,
1720 const SmallVectorImpl<ISD::InputArg> &Ins,
1721 DebugLoc dl, SelectionDAG &DAG,
1722 const CCValAssign &VA,
1723 MachineFrameInfo *MFI,
1725 // Create the nodes corresponding to a load from this parameter slot.
1726 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1727 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1728 getTargetMachine().Options.GuaranteedTailCallOpt);
1729 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1732 // If value is passed by pointer we have address passed instead of the value
1734 if (VA.getLocInfo() == CCValAssign::Indirect)
1735 ValVT = VA.getLocVT();
1737 ValVT = VA.getValVT();
1739 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1740 // changed with more analysis.
1741 // In case of tail call optimization mark all arguments mutable. Since they
1742 // could be overwritten by lowering of arguments in case of a tail call.
1743 if (Flags.isByVal()) {
1744 unsigned Bytes = Flags.getByValSize();
1745 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1746 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1747 return DAG.getFrameIndex(FI, getPointerTy());
1749 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1750 VA.getLocMemOffset(), isImmutable);
1751 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1752 return DAG.getLoad(ValVT, dl, Chain, FIN,
1753 MachinePointerInfo::getFixedStack(FI),
1754 false, false, false, 0);
1759 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1760 CallingConv::ID CallConv,
1762 const SmallVectorImpl<ISD::InputArg> &Ins,
1765 SmallVectorImpl<SDValue> &InVals)
1767 MachineFunction &MF = DAG.getMachineFunction();
1768 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1770 const Function* Fn = MF.getFunction();
1771 if (Fn->hasExternalLinkage() &&
1772 Subtarget->isTargetCygMing() &&
1773 Fn->getName() == "main")
1774 FuncInfo->setForceFramePointer(true);
1776 MachineFrameInfo *MFI = MF.getFrameInfo();
1777 bool Is64Bit = Subtarget->is64Bit();
1778 bool IsWin64 = Subtarget->isTargetWin64();
1780 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1781 "Var args not supported with calling convention fastcc or ghc");
1783 // Assign locations to all of the incoming arguments.
1784 SmallVector<CCValAssign, 16> ArgLocs;
1785 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1786 ArgLocs, *DAG.getContext());
1788 // Allocate shadow area for Win64
1790 CCInfo.AllocateStack(32, 8);
1793 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1795 unsigned LastVal = ~0U;
1797 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1798 CCValAssign &VA = ArgLocs[i];
1799 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1801 assert(VA.getValNo() != LastVal &&
1802 "Don't support value assigned to multiple locs yet");
1804 LastVal = VA.getValNo();
1806 if (VA.isRegLoc()) {
1807 EVT RegVT = VA.getLocVT();
1808 TargetRegisterClass *RC = NULL;
1809 if (RegVT == MVT::i32)
1810 RC = X86::GR32RegisterClass;
1811 else if (Is64Bit && RegVT == MVT::i64)
1812 RC = X86::GR64RegisterClass;
1813 else if (RegVT == MVT::f32)
1814 RC = X86::FR32RegisterClass;
1815 else if (RegVT == MVT::f64)
1816 RC = X86::FR64RegisterClass;
1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1818 RC = X86::VR256RegisterClass;
1819 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1820 RC = X86::VR128RegisterClass;
1821 else if (RegVT == MVT::x86mmx)
1822 RC = X86::VR64RegisterClass;
1824 llvm_unreachable("Unknown argument type!");
1826 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1827 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1829 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1830 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1832 if (VA.getLocInfo() == CCValAssign::SExt)
1833 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1834 DAG.getValueType(VA.getValVT()));
1835 else if (VA.getLocInfo() == CCValAssign::ZExt)
1836 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1837 DAG.getValueType(VA.getValVT()));
1838 else if (VA.getLocInfo() == CCValAssign::BCvt)
1839 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1841 if (VA.isExtInLoc()) {
1842 // Handle MMX values passed in XMM regs.
1843 if (RegVT.isVector()) {
1844 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1847 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1850 assert(VA.isMemLoc());
1851 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1854 // If value is passed via pointer - do a load.
1855 if (VA.getLocInfo() == CCValAssign::Indirect)
1856 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1857 MachinePointerInfo(), false, false, false, 0);
1859 InVals.push_back(ArgValue);
1862 // The x86-64 ABI for returning structs by value requires that we copy
1863 // the sret argument into %rax for the return. Save the argument into
1864 // a virtual register so that we can access it from the return points.
1865 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1866 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1867 unsigned Reg = FuncInfo->getSRetReturnReg();
1869 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1870 FuncInfo->setSRetReturnReg(Reg);
1872 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1876 unsigned StackSize = CCInfo.getNextStackOffset();
1877 // Align stack specially for tail calls.
1878 if (FuncIsMadeTailCallSafe(CallConv,
1879 MF.getTarget().Options.GuaranteedTailCallOpt))
1880 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1882 // If the function takes variable number of arguments, make a frame index for
1883 // the start of the first vararg value... for expansion of llvm.va_start.
1885 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1886 CallConv != CallingConv::X86_ThisCall)) {
1887 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1890 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1892 // FIXME: We should really autogenerate these arrays
1893 static const unsigned GPR64ArgRegsWin64[] = {
1894 X86::RCX, X86::RDX, X86::R8, X86::R9
1896 static const unsigned GPR64ArgRegs64Bit[] = {
1897 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1899 static const unsigned XMMArgRegs64Bit[] = {
1900 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1901 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1903 const unsigned *GPR64ArgRegs;
1904 unsigned NumXMMRegs = 0;
1907 // The XMM registers which might contain var arg parameters are shadowed
1908 // in their paired GPR. So we only need to save the GPR to their home
1910 TotalNumIntRegs = 4;
1911 GPR64ArgRegs = GPR64ArgRegsWin64;
1913 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1914 GPR64ArgRegs = GPR64ArgRegs64Bit;
1916 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1918 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1921 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1922 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1923 "SSE register cannot be used when SSE is disabled!");
1924 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1925 NoImplicitFloatOps) &&
1926 "SSE register cannot be used when SSE is disabled!");
1927 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1928 !Subtarget->hasXMM())
1929 // Kernel mode asks for SSE to be disabled, so don't push them
1931 TotalNumXMMRegs = 0;
1934 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1935 // Get to the caller-allocated home save location. Add 8 to account
1936 // for the return address.
1937 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1938 FuncInfo->setRegSaveFrameIndex(
1939 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1940 // Fixup to set vararg frame on shadow area (4 x i64).
1942 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1944 // For X86-64, if there are vararg parameters that are passed via
1945 // registers, then we must store them to their spots on the stack so they
1946 // may be loaded by deferencing the result of va_next.
1947 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1948 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1949 FuncInfo->setRegSaveFrameIndex(
1950 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1954 // Store the integer parameter registers.
1955 SmallVector<SDValue, 8> MemOps;
1956 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1958 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1959 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1960 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1961 DAG.getIntPtrConstant(Offset));
1962 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1963 X86::GR64RegisterClass);
1964 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1966 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1967 MachinePointerInfo::getFixedStack(
1968 FuncInfo->getRegSaveFrameIndex(), Offset),
1970 MemOps.push_back(Store);
1974 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1975 // Now store the XMM (fp + vector) parameter registers.
1976 SmallVector<SDValue, 11> SaveXMMOps;
1977 SaveXMMOps.push_back(Chain);
1979 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1980 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1981 SaveXMMOps.push_back(ALVal);
1983 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1984 FuncInfo->getRegSaveFrameIndex()));
1985 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1986 FuncInfo->getVarArgsFPOffset()));
1988 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1989 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1990 X86::VR128RegisterClass);
1991 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1992 SaveXMMOps.push_back(Val);
1994 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1996 &SaveXMMOps[0], SaveXMMOps.size()));
1999 if (!MemOps.empty())
2000 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2001 &MemOps[0], MemOps.size());
2005 // Some CCs need callee pop.
2006 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2007 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2008 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2010 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2011 // If this is an sret function, the return should pop the hidden pointer.
2012 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2013 FuncInfo->setBytesToPopOnReturn(4);
2017 // RegSaveFrameIndex is X86-64 only.
2018 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2019 if (CallConv == CallingConv::X86_FastCall ||
2020 CallConv == CallingConv::X86_ThisCall)
2021 // fastcc functions can't have varargs.
2022 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2025 FuncInfo->setArgumentStackSize(StackSize);
2031 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2032 SDValue StackPtr, SDValue Arg,
2033 DebugLoc dl, SelectionDAG &DAG,
2034 const CCValAssign &VA,
2035 ISD::ArgFlagsTy Flags) const {
2036 unsigned LocMemOffset = VA.getLocMemOffset();
2037 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2038 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2039 if (Flags.isByVal())
2040 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2042 return DAG.getStore(Chain, dl, Arg, PtrOff,
2043 MachinePointerInfo::getStack(LocMemOffset),
2047 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2048 /// optimization is performed and it is required.
2050 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2051 SDValue &OutRetAddr, SDValue Chain,
2052 bool IsTailCall, bool Is64Bit,
2053 int FPDiff, DebugLoc dl) const {
2054 // Adjust the Return address stack slot.
2055 EVT VT = getPointerTy();
2056 OutRetAddr = getReturnAddressFrameIndex(DAG);
2058 // Load the "old" Return address.
2059 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2060 false, false, false, 0);
2061 return SDValue(OutRetAddr.getNode(), 1);
2064 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2065 /// optimization is performed and it is required (FPDiff!=0).
2067 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2068 SDValue Chain, SDValue RetAddrFrIdx,
2069 bool Is64Bit, int FPDiff, DebugLoc dl) {
2070 // Store the return address to the appropriate stack slot.
2071 if (!FPDiff) return Chain;
2072 // Calculate the new stack slot for the return address.
2073 int SlotSize = Is64Bit ? 8 : 4;
2074 int NewReturnAddrFI =
2075 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2076 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2077 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2078 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2079 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2085 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2086 CallingConv::ID CallConv, bool isVarArg,
2088 const SmallVectorImpl<ISD::OutputArg> &Outs,
2089 const SmallVectorImpl<SDValue> &OutVals,
2090 const SmallVectorImpl<ISD::InputArg> &Ins,
2091 DebugLoc dl, SelectionDAG &DAG,
2092 SmallVectorImpl<SDValue> &InVals) const {
2093 MachineFunction &MF = DAG.getMachineFunction();
2094 bool Is64Bit = Subtarget->is64Bit();
2095 bool IsWin64 = Subtarget->isTargetWin64();
2096 bool IsStructRet = CallIsStructReturn(Outs);
2097 bool IsSibcall = false;
2100 // Check if it's really possible to do a tail call.
2101 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2102 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2103 Outs, OutVals, Ins, DAG);
2105 // Sibcalls are automatically detected tailcalls which do not require
2107 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2114 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2115 "Var args not supported with calling convention fastcc or ghc");
2117 // Analyze operands of the call, assigning locations to each operand.
2118 SmallVector<CCValAssign, 16> ArgLocs;
2119 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2120 ArgLocs, *DAG.getContext());
2122 // Allocate shadow area for Win64
2124 CCInfo.AllocateStack(32, 8);
2127 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2129 // Get a count of how many bytes are to be pushed on the stack.
2130 unsigned NumBytes = CCInfo.getNextStackOffset();
2132 // This is a sibcall. The memory operands are available in caller's
2133 // own caller's stack.
2135 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2136 IsTailCallConvention(CallConv))
2137 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2140 if (isTailCall && !IsSibcall) {
2141 // Lower arguments at fp - stackoffset + fpdiff.
2142 unsigned NumBytesCallerPushed =
2143 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2144 FPDiff = NumBytesCallerPushed - NumBytes;
2146 // Set the delta of movement of the returnaddr stackslot.
2147 // But only set if delta is greater than previous delta.
2148 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2149 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2153 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2155 SDValue RetAddrFrIdx;
2156 // Load return address for tail calls.
2157 if (isTailCall && FPDiff)
2158 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2159 Is64Bit, FPDiff, dl);
2161 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2162 SmallVector<SDValue, 8> MemOpChains;
2165 // Walk the register/memloc assignments, inserting copies/loads. In the case
2166 // of tail call optimization arguments are handle later.
2167 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2168 CCValAssign &VA = ArgLocs[i];
2169 EVT RegVT = VA.getLocVT();
2170 SDValue Arg = OutVals[i];
2171 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2172 bool isByVal = Flags.isByVal();
2174 // Promote the value if needed.
2175 switch (VA.getLocInfo()) {
2176 default: llvm_unreachable("Unknown loc info!");
2177 case CCValAssign::Full: break;
2178 case CCValAssign::SExt:
2179 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2181 case CCValAssign::ZExt:
2182 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2184 case CCValAssign::AExt:
2185 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2186 // Special case: passing MMX values in XMM registers.
2187 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2188 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2189 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2191 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2193 case CCValAssign::BCvt:
2194 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2196 case CCValAssign::Indirect: {
2197 // Store the argument.
2198 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2199 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2200 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2201 MachinePointerInfo::getFixedStack(FI),
2208 if (VA.isRegLoc()) {
2209 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2210 if (isVarArg && IsWin64) {
2211 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2212 // shadow reg if callee is a varargs function.
2213 unsigned ShadowReg = 0;
2214 switch (VA.getLocReg()) {
2215 case X86::XMM0: ShadowReg = X86::RCX; break;
2216 case X86::XMM1: ShadowReg = X86::RDX; break;
2217 case X86::XMM2: ShadowReg = X86::R8; break;
2218 case X86::XMM3: ShadowReg = X86::R9; break;
2221 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2223 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2224 assert(VA.isMemLoc());
2225 if (StackPtr.getNode() == 0)
2226 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2227 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2228 dl, DAG, VA, Flags));
2232 if (!MemOpChains.empty())
2233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2234 &MemOpChains[0], MemOpChains.size());
2236 // Build a sequence of copy-to-reg nodes chained together with token chain
2237 // and flag operands which copy the outgoing args into registers.
2239 // Tail call byval lowering might overwrite argument registers so in case of
2240 // tail call optimization the copies to registers are lowered later.
2242 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2243 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2244 RegsToPass[i].second, InFlag);
2245 InFlag = Chain.getValue(1);
2248 if (Subtarget->isPICStyleGOT()) {
2249 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2252 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2253 DAG.getNode(X86ISD::GlobalBaseReg,
2254 DebugLoc(), getPointerTy()),
2256 InFlag = Chain.getValue(1);
2258 // If we are tail calling and generating PIC/GOT style code load the
2259 // address of the callee into ECX. The value in ecx is used as target of
2260 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2261 // for tail calls on PIC/GOT architectures. Normally we would just put the
2262 // address of GOT into ebx and then call target@PLT. But for tail calls
2263 // ebx would be restored (since ebx is callee saved) before jumping to the
2266 // Note: The actual moving to ECX is done further down.
2267 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2268 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2269 !G->getGlobal()->hasProtectedVisibility())
2270 Callee = LowerGlobalAddress(Callee, DAG);
2271 else if (isa<ExternalSymbolSDNode>(Callee))
2272 Callee = LowerExternalSymbol(Callee, DAG);
2276 if (Is64Bit && isVarArg && !IsWin64) {
2277 // From AMD64 ABI document:
2278 // For calls that may call functions that use varargs or stdargs
2279 // (prototype-less calls or calls to functions containing ellipsis (...) in
2280 // the declaration) %al is used as hidden argument to specify the number
2281 // of SSE registers used. The contents of %al do not need to match exactly
2282 // the number of registers, but must be an ubound on the number of SSE
2283 // registers used and is in the range 0 - 8 inclusive.
2285 // Count the number of XMM registers allocated.
2286 static const unsigned XMMArgRegs[] = {
2287 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2288 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2290 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2291 assert((Subtarget->hasXMM() || !NumXMMRegs)
2292 && "SSE registers cannot be used when SSE is disabled");
2294 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2295 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2296 InFlag = Chain.getValue(1);
2300 // For tail calls lower the arguments to the 'real' stack slot.
2302 // Force all the incoming stack arguments to be loaded from the stack
2303 // before any new outgoing arguments are stored to the stack, because the
2304 // outgoing stack slots may alias the incoming argument stack slots, and
2305 // the alias isn't otherwise explicit. This is slightly more conservative
2306 // than necessary, because it means that each store effectively depends
2307 // on every argument instead of just those arguments it would clobber.
2308 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2310 SmallVector<SDValue, 8> MemOpChains2;
2313 // Do not flag preceding copytoreg stuff together with the following stuff.
2315 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2317 CCValAssign &VA = ArgLocs[i];
2320 assert(VA.isMemLoc());
2321 SDValue Arg = OutVals[i];
2322 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2323 // Create frame index.
2324 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2325 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2326 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2327 FIN = DAG.getFrameIndex(FI, getPointerTy());
2329 if (Flags.isByVal()) {
2330 // Copy relative to framepointer.
2331 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2332 if (StackPtr.getNode() == 0)
2333 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2335 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2337 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2341 // Store relative to framepointer.
2342 MemOpChains2.push_back(
2343 DAG.getStore(ArgChain, dl, Arg, FIN,
2344 MachinePointerInfo::getFixedStack(FI),
2350 if (!MemOpChains2.empty())
2351 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2352 &MemOpChains2[0], MemOpChains2.size());
2354 // Copy arguments to their registers.
2355 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2356 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2357 RegsToPass[i].second, InFlag);
2358 InFlag = Chain.getValue(1);
2362 // Store the return address to the appropriate stack slot.
2363 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2367 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2368 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2369 // In the 64-bit large code model, we have to make all calls
2370 // through a register, since the call instruction's 32-bit
2371 // pc-relative offset may not be large enough to hold the whole
2373 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2374 // If the callee is a GlobalAddress node (quite common, every direct call
2375 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2378 // We should use extra load for direct calls to dllimported functions in
2380 const GlobalValue *GV = G->getGlobal();
2381 if (!GV->hasDLLImportLinkage()) {
2382 unsigned char OpFlags = 0;
2383 bool ExtraLoad = false;
2384 unsigned WrapperKind = ISD::DELETED_NODE;
2386 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2387 // external symbols most go through the PLT in PIC mode. If the symbol
2388 // has hidden or protected visibility, or if it is static or local, then
2389 // we don't need to use the PLT - we can directly call it.
2390 if (Subtarget->isTargetELF() &&
2391 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2392 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2393 OpFlags = X86II::MO_PLT;
2394 } else if (Subtarget->isPICStyleStubAny() &&
2395 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2396 (!Subtarget->getTargetTriple().isMacOSX() ||
2397 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2398 // PC-relative references to external symbols should go through $stub,
2399 // unless we're building with the leopard linker or later, which
2400 // automatically synthesizes these stubs.
2401 OpFlags = X86II::MO_DARWIN_STUB;
2402 } else if (Subtarget->isPICStyleRIPRel() &&
2403 isa<Function>(GV) &&
2404 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2405 // If the function is marked as non-lazy, generate an indirect call
2406 // which loads from the GOT directly. This avoids runtime overhead
2407 // at the cost of eager binding (and one extra byte of encoding).
2408 OpFlags = X86II::MO_GOTPCREL;
2409 WrapperKind = X86ISD::WrapperRIP;
2413 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2414 G->getOffset(), OpFlags);
2416 // Add a wrapper if needed.
2417 if (WrapperKind != ISD::DELETED_NODE)
2418 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2419 // Add extra indirection if needed.
2421 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2422 MachinePointerInfo::getGOT(),
2423 false, false, false, 0);
2425 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2426 unsigned char OpFlags = 0;
2428 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2429 // external symbols should go through the PLT.
2430 if (Subtarget->isTargetELF() &&
2431 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2432 OpFlags = X86II::MO_PLT;
2433 } else if (Subtarget->isPICStyleStubAny() &&
2434 (!Subtarget->getTargetTriple().isMacOSX() ||
2435 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2436 // PC-relative references to external symbols should go through $stub,
2437 // unless we're building with the leopard linker or later, which
2438 // automatically synthesizes these stubs.
2439 OpFlags = X86II::MO_DARWIN_STUB;
2442 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2446 // Returns a chain & a flag for retval copy to use.
2447 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2448 SmallVector<SDValue, 8> Ops;
2450 if (!IsSibcall && isTailCall) {
2451 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2452 DAG.getIntPtrConstant(0, true), InFlag);
2453 InFlag = Chain.getValue(1);
2456 Ops.push_back(Chain);
2457 Ops.push_back(Callee);
2460 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2462 // Add argument registers to the end of the list so that they are known live
2464 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2465 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2466 RegsToPass[i].second.getValueType()));
2468 // Add an implicit use GOT pointer in EBX.
2469 if (!isTailCall && Subtarget->isPICStyleGOT())
2470 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2472 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2473 if (Is64Bit && isVarArg && !IsWin64)
2474 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2476 if (InFlag.getNode())
2477 Ops.push_back(InFlag);
2481 //// If this is the first return lowered for this function, add the regs
2482 //// to the liveout set for the function.
2483 // This isn't right, although it's probably harmless on x86; liveouts
2484 // should be computed from returns not tail calls. Consider a void
2485 // function making a tail call to a function returning int.
2486 return DAG.getNode(X86ISD::TC_RETURN, dl,
2487 NodeTys, &Ops[0], Ops.size());
2490 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2491 InFlag = Chain.getValue(1);
2493 // Create the CALLSEQ_END node.
2494 unsigned NumBytesForCalleeToPush;
2495 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2496 getTargetMachine().Options.GuaranteedTailCallOpt))
2497 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2498 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2499 // If this is a call to a struct-return function, the callee
2500 // pops the hidden struct pointer, so we have to push it back.
2501 // This is common for Darwin/X86, Linux & Mingw32 targets.
2502 NumBytesForCalleeToPush = 4;
2504 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2506 // Returns a flag for retval copy to use.
2508 Chain = DAG.getCALLSEQ_END(Chain,
2509 DAG.getIntPtrConstant(NumBytes, true),
2510 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2513 InFlag = Chain.getValue(1);
2516 // Handle result values, copying them out of physregs into vregs that we
2518 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2519 Ins, dl, DAG, InVals);
2523 //===----------------------------------------------------------------------===//
2524 // Fast Calling Convention (tail call) implementation
2525 //===----------------------------------------------------------------------===//
2527 // Like std call, callee cleans arguments, convention except that ECX is
2528 // reserved for storing the tail called function address. Only 2 registers are
2529 // free for argument passing (inreg). Tail call optimization is performed
2531 // * tailcallopt is enabled
2532 // * caller/callee are fastcc
2533 // On X86_64 architecture with GOT-style position independent code only local
2534 // (within module) calls are supported at the moment.
2535 // To keep the stack aligned according to platform abi the function
2536 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2537 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2538 // If a tail called function callee has more arguments than the caller the
2539 // caller needs to make sure that there is room to move the RETADDR to. This is
2540 // achieved by reserving an area the size of the argument delta right after the
2541 // original REtADDR, but before the saved framepointer or the spilled registers
2542 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2554 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2555 /// for a 16 byte align requirement.
2557 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2558 SelectionDAG& DAG) const {
2559 MachineFunction &MF = DAG.getMachineFunction();
2560 const TargetMachine &TM = MF.getTarget();
2561 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2562 unsigned StackAlignment = TFI.getStackAlignment();
2563 uint64_t AlignMask = StackAlignment - 1;
2564 int64_t Offset = StackSize;
2565 uint64_t SlotSize = TD->getPointerSize();
2566 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2567 // Number smaller than 12 so just add the difference.
2568 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2570 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2571 Offset = ((~AlignMask) & Offset) + StackAlignment +
2572 (StackAlignment-SlotSize);
2577 /// MatchingStackOffset - Return true if the given stack call argument is
2578 /// already available in the same position (relatively) of the caller's
2579 /// incoming argument stack.
2581 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2582 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2583 const X86InstrInfo *TII) {
2584 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2586 if (Arg.getOpcode() == ISD::CopyFromReg) {
2587 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2588 if (!TargetRegisterInfo::isVirtualRegister(VR))
2590 MachineInstr *Def = MRI->getVRegDef(VR);
2593 if (!Flags.isByVal()) {
2594 if (!TII->isLoadFromStackSlot(Def, FI))
2597 unsigned Opcode = Def->getOpcode();
2598 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2599 Def->getOperand(1).isFI()) {
2600 FI = Def->getOperand(1).getIndex();
2601 Bytes = Flags.getByValSize();
2605 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2606 if (Flags.isByVal())
2607 // ByVal argument is passed in as a pointer but it's now being
2608 // dereferenced. e.g.
2609 // define @foo(%struct.X* %A) {
2610 // tail call @bar(%struct.X* byval %A)
2613 SDValue Ptr = Ld->getBasePtr();
2614 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2617 FI = FINode->getIndex();
2618 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2619 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2620 FI = FINode->getIndex();
2621 Bytes = Flags.getByValSize();
2625 assert(FI != INT_MAX);
2626 if (!MFI->isFixedObjectIndex(FI))
2628 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2631 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2632 /// for tail call optimization. Targets which want to do tail call
2633 /// optimization should implement this function.
2635 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2636 CallingConv::ID CalleeCC,
2638 bool isCalleeStructRet,
2639 bool isCallerStructRet,
2640 const SmallVectorImpl<ISD::OutputArg> &Outs,
2641 const SmallVectorImpl<SDValue> &OutVals,
2642 const SmallVectorImpl<ISD::InputArg> &Ins,
2643 SelectionDAG& DAG) const {
2644 if (!IsTailCallConvention(CalleeCC) &&
2645 CalleeCC != CallingConv::C)
2648 // If -tailcallopt is specified, make fastcc functions tail-callable.
2649 const MachineFunction &MF = DAG.getMachineFunction();
2650 const Function *CallerF = DAG.getMachineFunction().getFunction();
2651 CallingConv::ID CallerCC = CallerF->getCallingConv();
2652 bool CCMatch = CallerCC == CalleeCC;
2654 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2655 if (IsTailCallConvention(CalleeCC) && CCMatch)
2660 // Look for obvious safe cases to perform tail call optimization that do not
2661 // require ABI changes. This is what gcc calls sibcall.
2663 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2664 // emit a special epilogue.
2665 if (RegInfo->needsStackRealignment(MF))
2668 // Also avoid sibcall optimization if either caller or callee uses struct
2669 // return semantics.
2670 if (isCalleeStructRet || isCallerStructRet)
2673 // An stdcall caller is expected to clean up its arguments; the callee
2674 // isn't going to do that.
2675 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2678 // Do not sibcall optimize vararg calls unless all arguments are passed via
2680 if (isVarArg && !Outs.empty()) {
2682 // Optimizing for varargs on Win64 is unlikely to be safe without
2683 // additional testing.
2684 if (Subtarget->isTargetWin64())
2687 SmallVector<CCValAssign, 16> ArgLocs;
2688 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2689 getTargetMachine(), ArgLocs, *DAG.getContext());
2691 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2692 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2693 if (!ArgLocs[i].isRegLoc())
2697 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2698 // Therefore if it's not used by the call it is not safe to optimize this into
2700 bool Unused = false;
2701 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2708 SmallVector<CCValAssign, 16> RVLocs;
2709 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2710 getTargetMachine(), RVLocs, *DAG.getContext());
2711 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2712 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2713 CCValAssign &VA = RVLocs[i];
2714 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2719 // If the calling conventions do not match, then we'd better make sure the
2720 // results are returned in the same way as what the caller expects.
2722 SmallVector<CCValAssign, 16> RVLocs1;
2723 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2724 getTargetMachine(), RVLocs1, *DAG.getContext());
2725 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2727 SmallVector<CCValAssign, 16> RVLocs2;
2728 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2729 getTargetMachine(), RVLocs2, *DAG.getContext());
2730 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2732 if (RVLocs1.size() != RVLocs2.size())
2734 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2735 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2737 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2739 if (RVLocs1[i].isRegLoc()) {
2740 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2743 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2749 // If the callee takes no arguments then go on to check the results of the
2751 if (!Outs.empty()) {
2752 // Check if stack adjustment is needed. For now, do not do this if any
2753 // argument is passed on the stack.
2754 SmallVector<CCValAssign, 16> ArgLocs;
2755 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2756 getTargetMachine(), ArgLocs, *DAG.getContext());
2758 // Allocate shadow area for Win64
2759 if (Subtarget->isTargetWin64()) {
2760 CCInfo.AllocateStack(32, 8);
2763 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2764 if (CCInfo.getNextStackOffset()) {
2765 MachineFunction &MF = DAG.getMachineFunction();
2766 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2769 // Check if the arguments are already laid out in the right way as
2770 // the caller's fixed stack objects.
2771 MachineFrameInfo *MFI = MF.getFrameInfo();
2772 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2773 const X86InstrInfo *TII =
2774 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2775 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2776 CCValAssign &VA = ArgLocs[i];
2777 SDValue Arg = OutVals[i];
2778 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2779 if (VA.getLocInfo() == CCValAssign::Indirect)
2781 if (!VA.isRegLoc()) {
2782 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2789 // If the tailcall address may be in a register, then make sure it's
2790 // possible to register allocate for it. In 32-bit, the call address can
2791 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2792 // callee-saved registers are restored. These happen to be the same
2793 // registers used to pass 'inreg' arguments so watch out for those.
2794 if (!Subtarget->is64Bit() &&
2795 !isa<GlobalAddressSDNode>(Callee) &&
2796 !isa<ExternalSymbolSDNode>(Callee)) {
2797 unsigned NumInRegs = 0;
2798 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2799 CCValAssign &VA = ArgLocs[i];
2802 unsigned Reg = VA.getLocReg();
2805 case X86::EAX: case X86::EDX: case X86::ECX:
2806 if (++NumInRegs == 3)
2818 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2819 return X86::createFastISel(funcInfo);
2823 //===----------------------------------------------------------------------===//
2824 // Other Lowering Hooks
2825 //===----------------------------------------------------------------------===//
2827 static bool MayFoldLoad(SDValue Op) {
2828 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2831 static bool MayFoldIntoStore(SDValue Op) {
2832 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2835 static bool isTargetShuffle(unsigned Opcode) {
2837 default: return false;
2838 case X86ISD::PSHUFD:
2839 case X86ISD::PSHUFHW:
2840 case X86ISD::PSHUFLW:
2841 case X86ISD::SHUFPD:
2842 case X86ISD::PALIGN:
2843 case X86ISD::SHUFPS:
2844 case X86ISD::MOVLHPS:
2845 case X86ISD::MOVLHPD:
2846 case X86ISD::MOVHLPS:
2847 case X86ISD::MOVLPS:
2848 case X86ISD::MOVLPD:
2849 case X86ISD::MOVSHDUP:
2850 case X86ISD::MOVSLDUP:
2851 case X86ISD::MOVDDUP:
2854 case X86ISD::UNPCKL:
2855 case X86ISD::UNPCKH:
2856 case X86ISD::VPERMILP:
2857 case X86ISD::VPERM2X128:
2863 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2864 SDValue V1, SelectionDAG &DAG) {
2866 default: llvm_unreachable("Unknown x86 shuffle node");
2867 case X86ISD::MOVSHDUP:
2868 case X86ISD::MOVSLDUP:
2869 case X86ISD::MOVDDUP:
2870 return DAG.getNode(Opc, dl, VT, V1);
2876 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2877 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2879 default: llvm_unreachable("Unknown x86 shuffle node");
2880 case X86ISD::PSHUFD:
2881 case X86ISD::PSHUFHW:
2882 case X86ISD::PSHUFLW:
2883 case X86ISD::VPERMILP:
2884 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2890 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2891 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2893 default: llvm_unreachable("Unknown x86 shuffle node");
2894 case X86ISD::PALIGN:
2895 case X86ISD::SHUFPD:
2896 case X86ISD::SHUFPS:
2897 case X86ISD::VPERM2X128:
2898 return DAG.getNode(Opc, dl, VT, V1, V2,
2899 DAG.getConstant(TargetMask, MVT::i8));
2904 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2905 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2907 default: llvm_unreachable("Unknown x86 shuffle node");
2908 case X86ISD::MOVLHPS:
2909 case X86ISD::MOVLHPD:
2910 case X86ISD::MOVHLPS:
2911 case X86ISD::MOVLPS:
2912 case X86ISD::MOVLPD:
2915 case X86ISD::UNPCKL:
2916 case X86ISD::UNPCKH:
2917 return DAG.getNode(Opc, dl, VT, V1, V2);
2922 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2923 MachineFunction &MF = DAG.getMachineFunction();
2924 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2925 int ReturnAddrIndex = FuncInfo->getRAIndex();
2927 if (ReturnAddrIndex == 0) {
2928 // Set up a frame object for the return address.
2929 uint64_t SlotSize = TD->getPointerSize();
2930 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2932 FuncInfo->setRAIndex(ReturnAddrIndex);
2935 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2939 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2940 bool hasSymbolicDisplacement) {
2941 // Offset should fit into 32 bit immediate field.
2942 if (!isInt<32>(Offset))
2945 // If we don't have a symbolic displacement - we don't have any extra
2947 if (!hasSymbolicDisplacement)
2950 // FIXME: Some tweaks might be needed for medium code model.
2951 if (M != CodeModel::Small && M != CodeModel::Kernel)
2954 // For small code model we assume that latest object is 16MB before end of 31
2955 // bits boundary. We may also accept pretty large negative constants knowing
2956 // that all objects are in the positive half of address space.
2957 if (M == CodeModel::Small && Offset < 16*1024*1024)
2960 // For kernel code model we know that all object resist in the negative half
2961 // of 32bits address space. We may not accept negative offsets, since they may
2962 // be just off and we may accept pretty large positive ones.
2963 if (M == CodeModel::Kernel && Offset > 0)
2969 /// isCalleePop - Determines whether the callee is required to pop its
2970 /// own arguments. Callee pop is necessary to support tail calls.
2971 bool X86::isCalleePop(CallingConv::ID CallingConv,
2972 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2976 switch (CallingConv) {
2979 case CallingConv::X86_StdCall:
2981 case CallingConv::X86_FastCall:
2983 case CallingConv::X86_ThisCall:
2985 case CallingConv::Fast:
2987 case CallingConv::GHC:
2992 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2993 /// specific condition code, returning the condition code and the LHS/RHS of the
2994 /// comparison to make.
2995 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2996 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2998 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2999 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3000 // X > -1 -> X == 0, jump !sign.
3001 RHS = DAG.getConstant(0, RHS.getValueType());
3002 return X86::COND_NS;
3003 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3004 // X < 0 -> X == 0, jump on sign.
3006 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3008 RHS = DAG.getConstant(0, RHS.getValueType());
3009 return X86::COND_LE;
3013 switch (SetCCOpcode) {
3014 default: llvm_unreachable("Invalid integer condition!");
3015 case ISD::SETEQ: return X86::COND_E;
3016 case ISD::SETGT: return X86::COND_G;
3017 case ISD::SETGE: return X86::COND_GE;
3018 case ISD::SETLT: return X86::COND_L;
3019 case ISD::SETLE: return X86::COND_LE;
3020 case ISD::SETNE: return X86::COND_NE;
3021 case ISD::SETULT: return X86::COND_B;
3022 case ISD::SETUGT: return X86::COND_A;
3023 case ISD::SETULE: return X86::COND_BE;
3024 case ISD::SETUGE: return X86::COND_AE;
3028 // First determine if it is required or is profitable to flip the operands.
3030 // If LHS is a foldable load, but RHS is not, flip the condition.
3031 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3032 !ISD::isNON_EXTLoad(RHS.getNode())) {
3033 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3034 std::swap(LHS, RHS);
3037 switch (SetCCOpcode) {
3043 std::swap(LHS, RHS);
3047 // On a floating point condition, the flags are set as follows:
3049 // 0 | 0 | 0 | X > Y
3050 // 0 | 0 | 1 | X < Y
3051 // 1 | 0 | 0 | X == Y
3052 // 1 | 1 | 1 | unordered
3053 switch (SetCCOpcode) {
3054 default: llvm_unreachable("Condcode should be pre-legalized away");
3056 case ISD::SETEQ: return X86::COND_E;
3057 case ISD::SETOLT: // flipped
3059 case ISD::SETGT: return X86::COND_A;
3060 case ISD::SETOLE: // flipped
3062 case ISD::SETGE: return X86::COND_AE;
3063 case ISD::SETUGT: // flipped
3065 case ISD::SETLT: return X86::COND_B;
3066 case ISD::SETUGE: // flipped
3068 case ISD::SETLE: return X86::COND_BE;
3070 case ISD::SETNE: return X86::COND_NE;
3071 case ISD::SETUO: return X86::COND_P;
3072 case ISD::SETO: return X86::COND_NP;
3074 case ISD::SETUNE: return X86::COND_INVALID;
3078 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3079 /// code. Current x86 isa includes the following FP cmov instructions:
3080 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3081 static bool hasFPCMov(unsigned X86CC) {
3097 /// isFPImmLegal - Returns true if the target can instruction select the
3098 /// specified FP immediate natively. If false, the legalizer will
3099 /// materialize the FP immediate as a load from a constant pool.
3100 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3101 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3102 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3108 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3109 /// the specified range (L, H].
3110 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3111 return (Val < 0) || (Val >= Low && Val < Hi);
3114 /// isUndefOrInRange - Return true if every element in Mask, begining
3115 /// from position Pos and ending in Pos+Size, falls within the specified
3116 /// range (L, L+Pos]. or is undef.
3117 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3118 int Pos, int Size, int Low, int Hi) {
3119 for (int i = Pos, e = Pos+Size; i != e; ++i)
3120 if (!isUndefOrInRange(Mask[i], Low, Hi))
3125 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3126 /// specified value.
3127 static bool isUndefOrEqual(int Val, int CmpVal) {
3128 if (Val < 0 || Val == CmpVal)
3133 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3134 /// from position Pos and ending in Pos+Size, falls within the specified
3135 /// sequential range (L, L+Pos]. or is undef.
3136 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3137 int Pos, int Size, int Low) {
3138 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3139 if (!isUndefOrEqual(Mask[i], Low))
3144 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3145 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3146 /// the second operand.
3147 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3149 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3150 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3151 return (Mask[0] < 2 && Mask[1] < 2);
3155 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3156 SmallVector<int, 8> M;
3158 return ::isPSHUFDMask(M, N->getValueType(0));
3161 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3162 /// is suitable for input to PSHUFHW.
3163 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3164 if (VT != MVT::v8i16)
3167 // Lower quadword copied in order or undef.
3168 for (int i = 0; i != 4; ++i)
3169 if (Mask[i] >= 0 && Mask[i] != i)
3172 // Upper quadword shuffled.
3173 for (int i = 4; i != 8; ++i)
3174 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3180 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3181 SmallVector<int, 8> M;
3183 return ::isPSHUFHWMask(M, N->getValueType(0));
3186 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFLW.
3188 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3189 if (VT != MVT::v8i16)
3192 // Upper quadword copied in order.
3193 for (int i = 4; i != 8; ++i)
3194 if (Mask[i] >= 0 && Mask[i] != i)
3197 // Lower quadword shuffled.
3198 for (int i = 0; i != 4; ++i)
3205 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3206 SmallVector<int, 8> M;
3208 return ::isPSHUFLWMask(M, N->getValueType(0));
3211 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3212 /// is suitable for input to PALIGNR.
3213 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3214 bool hasSSSE3OrAVX) {
3215 int i, e = VT.getVectorNumElements();
3216 if (VT.getSizeInBits() != 128)
3219 // Do not handle v2i64 / v2f64 shuffles with palignr.
3220 if (e < 4 || !hasSSSE3OrAVX)
3223 for (i = 0; i != e; ++i)
3227 // All undef, not a palignr.
3231 // Make sure we're shifting in the right direction.
3235 int s = Mask[i] - i;
3237 // Check the rest of the elements to see if they are consecutive.
3238 for (++i; i != e; ++i) {
3240 if (m >= 0 && m != s+i)
3246 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to 256-bit
3249 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3250 bool HasAVX, bool Commuted = false) {
3251 int NumElems = VT.getVectorNumElements();
3253 if (!HasAVX || VT.getSizeInBits() != 256)
3256 if (NumElems != 4 && NumElems != 8)
3259 // VSHUFPSY divides the resulting vector into 4 chunks.
3260 // The sources are also splitted into 4 chunks, and each destination
3261 // chunk must come from a different source chunk.
3263 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3264 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3266 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3267 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3269 // VSHUFPDY divides the resulting vector into 4 chunks.
3270 // The sources are also splitted into 4 chunks, and each destination
3271 // chunk must come from a different source chunk.
3273 // SRC1 => X3 X2 X1 X0
3274 // SRC2 => Y3 Y2 Y1 Y0
3276 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3278 unsigned QuarterSize = NumElems/4;
3279 unsigned HalfSize = QuarterSize*2;
3280 for (unsigned l = 0; l != 2; ++l) {
3281 unsigned LaneStart = l*HalfSize;
3282 for (unsigned s = 0; s != 2; ++s) {
3283 unsigned QuarterStart = s*QuarterSize;
3284 unsigned Src = (Commuted) ? (1-s) : s;
3285 unsigned SrcStart = Src*NumElems + LaneStart;
3286 for (unsigned i = 0; i != QuarterSize; ++i) {
3287 int Idx = Mask[i+QuarterStart+LaneStart];
3288 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3290 // For VSHUFPSY, the mask of the second half must be the same as the first
3291 // but with the appropriate offsets. This works in the same way as
3292 // VPERMILPS works with masks.
3293 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3295 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3304 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3305 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3306 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3308 EVT VT = SVOp->getValueType(0);
3309 int NumElems = VT.getVectorNumElements();
3311 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3312 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3314 int HalfSize = NumElems/2;
3315 unsigned Mul = (NumElems == 8) ? 2 : 1;
3317 for (int i = 0; i != NumElems; ++i) {
3318 int Elt = SVOp->getMaskElt(i);
3323 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3324 if (NumElems == 8) Shamt %= HalfSize;
3325 Mask |= Elt << (Shamt*Mul);
3331 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3332 /// the two vector operands have swapped position.
3333 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3334 unsigned NumElems) {
3335 for (unsigned i = 0; i != NumElems; ++i) {
3339 else if (idx < (int)NumElems)
3340 Mask[i] = idx + NumElems;
3342 Mask[i] = idx - NumElems;
3346 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3347 /// specifies a shuffle of elements that is suitable for input to 128-bit
3348 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3349 /// reverse of what x86 shuffles want.
3350 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3351 bool Commuted = false) {
3352 unsigned NumElems = VT.getVectorNumElements();
3354 if (VT.getSizeInBits() != 128)
3357 if (NumElems != 2 && NumElems != 4)
3360 unsigned Half = NumElems / 2;
3361 unsigned SrcStart = Commuted ? NumElems : 0;
3362 for (unsigned i = 0; i != Half; ++i)
3363 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3365 SrcStart = Commuted ? 0 : NumElems;
3366 for (unsigned i = Half; i != NumElems; ++i)
3367 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3373 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3374 SmallVector<int, 8> M;
3376 return ::isSHUFPMask(M, N->getValueType(0));
3379 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3380 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3381 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3382 EVT VT = N->getValueType(0);
3383 unsigned NumElems = VT.getVectorNumElements();
3385 if (VT.getSizeInBits() != 128)
3391 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3392 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3393 isUndefOrEqual(N->getMaskElt(1), 7) &&
3394 isUndefOrEqual(N->getMaskElt(2), 2) &&
3395 isUndefOrEqual(N->getMaskElt(3), 3);
3398 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3399 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3401 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3402 EVT VT = N->getValueType(0);
3403 unsigned NumElems = VT.getVectorNumElements();
3405 if (VT.getSizeInBits() != 128)
3411 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3412 isUndefOrEqual(N->getMaskElt(1), 3) &&
3413 isUndefOrEqual(N->getMaskElt(2), 2) &&
3414 isUndefOrEqual(N->getMaskElt(3), 3);
3417 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3418 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3419 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3420 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3422 if (NumElems != 2 && NumElems != 4)
3425 for (unsigned i = 0; i < NumElems/2; ++i)
3426 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3429 for (unsigned i = NumElems/2; i < NumElems; ++i)
3430 if (!isUndefOrEqual(N->getMaskElt(i), i))
3436 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3437 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3438 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3439 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3441 if ((NumElems != 2 && NumElems != 4)
3442 || N->getValueType(0).getSizeInBits() > 128)
3445 for (unsigned i = 0; i < NumElems/2; ++i)
3446 if (!isUndefOrEqual(N->getMaskElt(i), i))
3449 for (unsigned i = 0; i < NumElems/2; ++i)
3450 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3456 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3457 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3458 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3459 bool HasAVX2, bool V2IsSplat = false) {
3460 int NumElts = VT.getVectorNumElements();
3462 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3463 "Unsupported vector type for unpckh");
3465 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3466 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3469 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3470 // independently on 128-bit lanes.
3471 unsigned NumLanes = VT.getSizeInBits()/128;
3472 unsigned NumLaneElts = NumElts/NumLanes;
3475 unsigned End = NumLaneElts;
3476 for (unsigned s = 0; s < NumLanes; ++s) {
3477 for (unsigned i = Start, j = s * NumLaneElts;
3481 int BitI1 = Mask[i+1];
3482 if (!isUndefOrEqual(BitI, j))
3485 if (!isUndefOrEqual(BitI1, NumElts))
3488 if (!isUndefOrEqual(BitI1, j + NumElts))
3492 // Process the next 128 bits.
3493 Start += NumLaneElts;
3500 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3501 SmallVector<int, 8> M;
3503 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3506 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3507 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3508 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3509 bool HasAVX2, bool V2IsSplat = false) {
3510 int NumElts = VT.getVectorNumElements();
3512 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3513 "Unsupported vector type for unpckh");
3515 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3516 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3519 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3520 // independently on 128-bit lanes.
3521 unsigned NumLanes = VT.getSizeInBits()/128;
3522 unsigned NumLaneElts = NumElts/NumLanes;
3525 unsigned End = NumLaneElts;
3526 for (unsigned l = 0; l != NumLanes; ++l) {
3527 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3528 i != End; i += 2, ++j) {
3530 int BitI1 = Mask[i+1];
3531 if (!isUndefOrEqual(BitI, j))
3534 if (isUndefOrEqual(BitI1, NumElts))
3537 if (!isUndefOrEqual(BitI1, j+NumElts))
3541 // Process the next 128 bits.
3542 Start += NumLaneElts;
3548 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3549 SmallVector<int, 8> M;
3551 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3554 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3555 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3557 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3558 int NumElems = VT.getVectorNumElements();
3559 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3562 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3563 // FIXME: Need a better way to get rid of this, there's no latency difference
3564 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3565 // the former later. We should also remove the "_undef" special mask.
3566 if (NumElems == 4 && VT.getSizeInBits() == 256)
3569 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3570 // independently on 128-bit lanes.
3571 unsigned NumLanes = VT.getSizeInBits() / 128;
3572 unsigned NumLaneElts = NumElems / NumLanes;
3574 for (unsigned s = 0; s < NumLanes; ++s) {
3575 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3576 i != NumLaneElts * (s + 1);
3579 int BitI1 = Mask[i+1];
3581 if (!isUndefOrEqual(BitI, j))
3583 if (!isUndefOrEqual(BitI1, j))
3591 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3592 SmallVector<int, 8> M;
3594 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3597 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3598 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3600 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3601 int NumElems = VT.getVectorNumElements();
3602 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3605 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3607 int BitI1 = Mask[i+1];
3608 if (!isUndefOrEqual(BitI, j))
3610 if (!isUndefOrEqual(BitI1, j))
3616 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3617 SmallVector<int, 8> M;
3619 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3622 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3623 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3624 /// MOVSD, and MOVD, i.e. setting the lowest element.
3625 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3626 if (VT.getVectorElementType().getSizeInBits() < 32)
3629 int NumElts = VT.getVectorNumElements();
3631 if (!isUndefOrEqual(Mask[0], NumElts))
3634 for (int i = 1; i < NumElts; ++i)
3635 if (!isUndefOrEqual(Mask[i], i))
3641 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3642 SmallVector<int, 8> M;
3644 return ::isMOVLMask(M, N->getValueType(0));
3647 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3648 /// as permutations between 128-bit chunks or halves. As an example: this
3650 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3651 /// The first half comes from the second half of V1 and the second half from the
3652 /// the second half of V2.
3653 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3655 if (!HasAVX || VT.getSizeInBits() != 256)
3658 // The shuffle result is divided into half A and half B. In total the two
3659 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3660 // B must come from C, D, E or F.
3661 int HalfSize = VT.getVectorNumElements()/2;
3662 bool MatchA = false, MatchB = false;
3664 // Check if A comes from one of C, D, E, F.
3665 for (int Half = 0; Half < 4; ++Half) {
3666 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3672 // Check if B comes from one of C, D, E, F.
3673 for (int Half = 0; Half < 4; ++Half) {
3674 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3680 return MatchA && MatchB;
3683 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3684 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3685 static unsigned getShuffleVPERM2X128Immediate(SDNode *N) {
3686 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3687 EVT VT = SVOp->getValueType(0);
3689 int HalfSize = VT.getVectorNumElements()/2;
3691 int FstHalf = 0, SndHalf = 0;
3692 for (int i = 0; i < HalfSize; ++i) {
3693 if (SVOp->getMaskElt(i) > 0) {
3694 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3698 for (int i = HalfSize; i < HalfSize*2; ++i) {
3699 if (SVOp->getMaskElt(i) > 0) {
3700 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3705 return (FstHalf | (SndHalf << 4));
3708 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3709 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3710 /// Note that VPERMIL mask matching is different depending whether theunderlying
3711 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3712 /// to the same elements of the low, but to the higher half of the source.
3713 /// In VPERMILPD the two lanes could be shuffled independently of each other
3714 /// with the same restriction that lanes can't be crossed.
3715 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3717 int NumElts = VT.getVectorNumElements();
3718 int NumLanes = VT.getSizeInBits()/128;
3723 // Only match 256-bit with 32/64-bit types
3724 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3727 int LaneSize = NumElts/NumLanes;
3728 for (int l = 0; l != NumLanes; ++l) {
3729 int LaneStart = l*LaneSize;
3730 for (int i = 0; i != LaneSize; ++i) {
3731 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3733 if (NumElts == 4 || l == 0)
3735 // VPERMILPS handling
3738 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3746 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3747 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3748 static unsigned getShuffleVPERMILPImmediate(SDNode *N) {
3749 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3750 EVT VT = SVOp->getValueType(0);
3752 int NumElts = VT.getVectorNumElements();
3753 int NumLanes = VT.getSizeInBits()/128;
3754 int LaneSize = NumElts/NumLanes;
3756 // Although the mask is equal for both lanes do it twice to get the cases
3757 // where a mask will match because the same mask element is undef on the
3758 // first half but valid on the second. This would get pathological cases
3759 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3760 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3762 for (int i = 0; i != NumElts; ++i) {
3763 int MaskElt = SVOp->getMaskElt(i);
3766 MaskElt %= LaneSize;
3768 // VPERMILPSY, the mask of the first half must be equal to the second one
3769 if (NumElts == 8) Shamt %= LaneSize;
3770 Mask |= MaskElt << (Shamt*Shift);
3776 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3777 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3778 /// element of vector 2 and the other elements to come from vector 1 in order.
3779 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3780 bool V2IsSplat = false, bool V2IsUndef = false) {
3781 int NumOps = VT.getVectorNumElements();
3782 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3785 if (!isUndefOrEqual(Mask[0], 0))
3788 for (int i = 1; i < NumOps; ++i)
3789 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3790 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3791 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3797 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3798 bool V2IsUndef = false) {
3799 SmallVector<int, 8> M;
3801 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3804 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3805 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3806 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3807 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3808 const X86Subtarget *Subtarget) {
3809 if (!Subtarget->hasSSE3orAVX())
3812 // The second vector must be undef
3813 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3816 EVT VT = N->getValueType(0);
3817 unsigned NumElems = VT.getVectorNumElements();
3819 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3820 (VT.getSizeInBits() == 256 && NumElems != 8))
3823 // "i+1" is the value the indexed mask element must have
3824 for (unsigned i = 0; i < NumElems; i += 2)
3825 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3826 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3832 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3833 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3834 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3835 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3836 const X86Subtarget *Subtarget) {
3837 if (!Subtarget->hasSSE3orAVX())
3840 // The second vector must be undef
3841 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3844 EVT VT = N->getValueType(0);
3845 unsigned NumElems = VT.getVectorNumElements();
3847 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3848 (VT.getSizeInBits() == 256 && NumElems != 8))
3851 // "i" is the value the indexed mask element must have
3852 for (unsigned i = 0; i < NumElems; i += 2)
3853 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3854 !isUndefOrEqual(N->getMaskElt(i+1), i))
3860 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3861 /// specifies a shuffle of elements that is suitable for input to 256-bit
3862 /// version of MOVDDUP.
3863 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3865 int NumElts = VT.getVectorNumElements();
3867 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3870 for (int i = 0; i != NumElts/2; ++i)
3871 if (!isUndefOrEqual(Mask[i], 0))
3873 for (int i = NumElts/2; i != NumElts; ++i)
3874 if (!isUndefOrEqual(Mask[i], NumElts/2))
3879 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3880 /// specifies a shuffle of elements that is suitable for input to 128-bit
3881 /// version of MOVDDUP.
3882 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3883 EVT VT = N->getValueType(0);
3885 if (VT.getSizeInBits() != 128)
3888 int e = VT.getVectorNumElements() / 2;
3889 for (int i = 0; i < e; ++i)
3890 if (!isUndefOrEqual(N->getMaskElt(i), i))
3892 for (int i = 0; i < e; ++i)
3893 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3898 /// isVEXTRACTF128Index - Return true if the specified
3899 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3900 /// suitable for input to VEXTRACTF128.
3901 bool X86::isVEXTRACTF128Index(SDNode *N) {
3902 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3905 // The index should be aligned on a 128-bit boundary.
3907 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3909 unsigned VL = N->getValueType(0).getVectorNumElements();
3910 unsigned VBits = N->getValueType(0).getSizeInBits();
3911 unsigned ElSize = VBits / VL;
3912 bool Result = (Index * ElSize) % 128 == 0;
3917 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3918 /// operand specifies a subvector insert that is suitable for input to
3920 bool X86::isVINSERTF128Index(SDNode *N) {
3921 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3924 // The index should be aligned on a 128-bit boundary.
3926 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3928 unsigned VL = N->getValueType(0).getVectorNumElements();
3929 unsigned VBits = N->getValueType(0).getSizeInBits();
3930 unsigned ElSize = VBits / VL;
3931 bool Result = (Index * ElSize) % 128 == 0;
3936 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3937 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3938 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3939 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3940 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3942 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3944 for (int i = 0; i < NumOperands; ++i) {
3945 int Val = SVOp->getMaskElt(NumOperands-i-1);
3946 if (Val < 0) Val = 0;
3947 if (Val >= NumOperands) Val -= NumOperands;
3949 if (i != NumOperands - 1)
3955 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3956 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3957 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3958 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3960 // 8 nodes, but we only care about the last 4.
3961 for (unsigned i = 7; i >= 4; --i) {
3962 int Val = SVOp->getMaskElt(i);
3971 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3972 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3973 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3974 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3976 // 8 nodes, but we only care about the first 4.
3977 for (int i = 3; i >= 0; --i) {
3978 int Val = SVOp->getMaskElt(i);
3987 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3988 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3989 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3990 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3991 EVT VVT = N->getValueType(0);
3992 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3996 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3997 Val = SVOp->getMaskElt(i);
4001 assert(Val - i > 0 && "PALIGNR imm should be positive");
4002 return (Val - i) * EltSize;
4005 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4006 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4009 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4010 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4013 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4015 EVT VecVT = N->getOperand(0).getValueType();
4016 EVT ElVT = VecVT.getVectorElementType();
4018 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4019 return Index / NumElemsPerChunk;
4022 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4023 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4025 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4026 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4027 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4030 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4032 EVT VecVT = N->getValueType(0);
4033 EVT ElVT = VecVT.getVectorElementType();
4035 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4036 return Index / NumElemsPerChunk;
4039 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4041 bool X86::isZeroNode(SDValue Elt) {
4042 return ((isa<ConstantSDNode>(Elt) &&
4043 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4044 (isa<ConstantFPSDNode>(Elt) &&
4045 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4048 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4049 /// their permute mask.
4050 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4051 SelectionDAG &DAG) {
4052 EVT VT = SVOp->getValueType(0);
4053 unsigned NumElems = VT.getVectorNumElements();
4054 SmallVector<int, 8> MaskVec;
4056 for (unsigned i = 0; i != NumElems; ++i) {
4057 int idx = SVOp->getMaskElt(i);
4059 MaskVec.push_back(idx);
4060 else if (idx < (int)NumElems)
4061 MaskVec.push_back(idx + NumElems);
4063 MaskVec.push_back(idx - NumElems);
4065 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4066 SVOp->getOperand(0), &MaskVec[0]);
4069 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4070 /// match movhlps. The lower half elements should come from upper half of
4071 /// V1 (and in order), and the upper half elements should come from the upper
4072 /// half of V2 (and in order).
4073 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4074 EVT VT = Op->getValueType(0);
4075 if (VT.getSizeInBits() != 128)
4077 if (VT.getVectorNumElements() != 4)
4079 for (unsigned i = 0, e = 2; i != e; ++i)
4080 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4082 for (unsigned i = 2; i != 4; ++i)
4083 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4088 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4089 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4091 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4092 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4094 N = N->getOperand(0).getNode();
4095 if (!ISD::isNON_EXTLoad(N))
4098 *LD = cast<LoadSDNode>(N);
4102 // Test whether the given value is a vector value which will be legalized
4104 static bool WillBeConstantPoolLoad(SDNode *N) {
4105 if (N->getOpcode() != ISD::BUILD_VECTOR)
4108 // Check for any non-constant elements.
4109 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4110 switch (N->getOperand(i).getNode()->getOpcode()) {
4112 case ISD::ConstantFP:
4119 // Vectors of all-zeros and all-ones are materialized with special
4120 // instructions rather than being loaded.
4121 return !ISD::isBuildVectorAllZeros(N) &&
4122 !ISD::isBuildVectorAllOnes(N);
4125 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4126 /// match movlp{s|d}. The lower half elements should come from lower half of
4127 /// V1 (and in order), and the upper half elements should come from the upper
4128 /// half of V2 (and in order). And since V1 will become the source of the
4129 /// MOVLP, it must be either a vector load or a scalar load to vector.
4130 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4131 ShuffleVectorSDNode *Op) {
4132 EVT VT = Op->getValueType(0);
4133 if (VT.getSizeInBits() != 128)
4136 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4138 // Is V2 is a vector load, don't do this transformation. We will try to use
4139 // load folding shufps op.
4140 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4143 unsigned NumElems = VT.getVectorNumElements();
4145 if (NumElems != 2 && NumElems != 4)
4147 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4148 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4150 for (unsigned i = NumElems/2; i != NumElems; ++i)
4151 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4156 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4158 static bool isSplatVector(SDNode *N) {
4159 if (N->getOpcode() != ISD::BUILD_VECTOR)
4162 SDValue SplatValue = N->getOperand(0);
4163 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4164 if (N->getOperand(i) != SplatValue)
4169 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4170 /// to an zero vector.
4171 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4172 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4173 SDValue V1 = N->getOperand(0);
4174 SDValue V2 = N->getOperand(1);
4175 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4176 for (unsigned i = 0; i != NumElems; ++i) {
4177 int Idx = N->getMaskElt(i);
4178 if (Idx >= (int)NumElems) {
4179 unsigned Opc = V2.getOpcode();
4180 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4182 if (Opc != ISD::BUILD_VECTOR ||
4183 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4185 } else if (Idx >= 0) {
4186 unsigned Opc = V1.getOpcode();
4187 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4189 if (Opc != ISD::BUILD_VECTOR ||
4190 !X86::isZeroNode(V1.getOperand(Idx)))
4197 /// getZeroVector - Returns a vector of specified type with all zero elements.
4199 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4201 assert(VT.isVector() && "Expected a vector type");
4203 // Always build SSE zero vectors as <4 x i32> bitcasted
4204 // to their dest type. This ensures they get CSE'd.
4206 if (VT.getSizeInBits() == 128) { // SSE
4207 if (HasXMMInt) { // SSE2
4208 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4209 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4211 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4212 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4214 } else if (VT.getSizeInBits() == 256) { // AVX
4215 // 256-bit logic and arithmetic instructions in AVX are
4216 // all floating-point, no support for integer ops. Default
4217 // to emitting fp zeroed vectors then.
4218 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4219 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4220 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4222 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4225 /// getOnesVector - Returns a vector of specified type with all bits set.
4226 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4227 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4228 /// Then bitcast to their original type, ensuring they get CSE'd.
4229 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4231 assert(VT.isVector() && "Expected a vector type");
4232 assert((VT.is128BitVector() || VT.is256BitVector())
4233 && "Expected a 128-bit or 256-bit vector type");
4235 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4237 if (VT.getSizeInBits() == 256) {
4238 if (HasAVX2) { // AVX2
4239 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4240 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4242 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4243 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4244 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4245 Vec = Insert128BitVector(InsV, Vec,
4246 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4249 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4252 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4255 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4256 /// that point to V2 points to its first element.
4257 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4258 EVT VT = SVOp->getValueType(0);
4259 unsigned NumElems = VT.getVectorNumElements();
4261 bool Changed = false;
4262 SmallVector<int, 8> MaskVec;
4263 SVOp->getMask(MaskVec);
4265 for (unsigned i = 0; i != NumElems; ++i) {
4266 if (MaskVec[i] > (int)NumElems) {
4267 MaskVec[i] = NumElems;
4272 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4273 SVOp->getOperand(1), &MaskVec[0]);
4274 return SDValue(SVOp, 0);
4277 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4278 /// operation of specified width.
4279 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4281 unsigned NumElems = VT.getVectorNumElements();
4282 SmallVector<int, 8> Mask;
4283 Mask.push_back(NumElems);
4284 for (unsigned i = 1; i != NumElems; ++i)
4286 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4289 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4290 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4292 unsigned NumElems = VT.getVectorNumElements();
4293 SmallVector<int, 8> Mask;
4294 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4296 Mask.push_back(i + NumElems);
4298 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4301 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4302 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4304 unsigned NumElems = VT.getVectorNumElements();
4305 unsigned Half = NumElems/2;
4306 SmallVector<int, 8> Mask;
4307 for (unsigned i = 0; i != Half; ++i) {
4308 Mask.push_back(i + Half);
4309 Mask.push_back(i + NumElems + Half);
4311 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4314 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4315 // a generic shuffle instruction because the target has no such instructions.
4316 // Generate shuffles which repeat i16 and i8 several times until they can be
4317 // represented by v4f32 and then be manipulated by target suported shuffles.
4318 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4319 EVT VT = V.getValueType();
4320 int NumElems = VT.getVectorNumElements();
4321 DebugLoc dl = V.getDebugLoc();
4323 while (NumElems > 4) {
4324 if (EltNo < NumElems/2) {
4325 V = getUnpackl(DAG, dl, VT, V, V);
4327 V = getUnpackh(DAG, dl, VT, V, V);
4328 EltNo -= NumElems/2;
4335 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4336 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4337 EVT VT = V.getValueType();
4338 DebugLoc dl = V.getDebugLoc();
4339 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4340 && "Vector size not supported");
4342 if (VT.getSizeInBits() == 128) {
4343 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4344 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4345 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4348 // To use VPERMILPS to splat scalars, the second half of indicies must
4349 // refer to the higher part, which is a duplication of the lower one,
4350 // because VPERMILPS can only handle in-lane permutations.
4351 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4352 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4354 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4355 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4359 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4362 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4363 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4364 EVT SrcVT = SV->getValueType(0);
4365 SDValue V1 = SV->getOperand(0);
4366 DebugLoc dl = SV->getDebugLoc();
4368 int EltNo = SV->getSplatIndex();
4369 int NumElems = SrcVT.getVectorNumElements();
4370 unsigned Size = SrcVT.getSizeInBits();
4372 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4373 "Unknown how to promote splat for type");
4375 // Extract the 128-bit part containing the splat element and update
4376 // the splat element index when it refers to the higher register.
4378 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4379 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4381 EltNo -= NumElems/2;
4384 // All i16 and i8 vector types can't be used directly by a generic shuffle
4385 // instruction because the target has no such instruction. Generate shuffles
4386 // which repeat i16 and i8 several times until they fit in i32, and then can
4387 // be manipulated by target suported shuffles.
4388 EVT EltVT = SrcVT.getVectorElementType();
4389 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4390 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4392 // Recreate the 256-bit vector and place the same 128-bit vector
4393 // into the low and high part. This is necessary because we want
4394 // to use VPERM* to shuffle the vectors
4396 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4397 DAG.getConstant(0, MVT::i32), DAG, dl);
4398 V1 = Insert128BitVector(InsV, V1,
4399 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4402 return getLegalSplat(DAG, V1, EltNo);
4405 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4406 /// vector of zero or undef vector. This produces a shuffle where the low
4407 /// element of V2 is swizzled into the zero/undef vector, landing at element
4408 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4409 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4410 bool isZero, bool HasXMMInt,
4411 SelectionDAG &DAG) {
4412 EVT VT = V2.getValueType();
4414 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4415 unsigned NumElems = VT.getVectorNumElements();
4416 SmallVector<int, 16> MaskVec;
4417 for (unsigned i = 0; i != NumElems; ++i)
4418 // If this is the insertion idx, put the low elt of V2 here.
4419 MaskVec.push_back(i == Idx ? NumElems : i);
4420 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4423 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4424 /// element of the result of the vector shuffle.
4425 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4428 return SDValue(); // Limit search depth.
4430 SDValue V = SDValue(N, 0);
4431 EVT VT = V.getValueType();
4432 unsigned Opcode = V.getOpcode();
4434 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4435 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4436 Index = SV->getMaskElt(Index);
4439 return DAG.getUNDEF(VT.getVectorElementType());
4441 int NumElems = VT.getVectorNumElements();
4442 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4443 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4446 // Recurse into target specific vector shuffles to find scalars.
4447 if (isTargetShuffle(Opcode)) {
4448 int NumElems = VT.getVectorNumElements();
4449 SmallVector<unsigned, 16> ShuffleMask;
4453 case X86ISD::SHUFPS:
4454 case X86ISD::SHUFPD:
4455 ImmN = N->getOperand(N->getNumOperands()-1);
4456 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4459 case X86ISD::UNPCKH:
4460 DecodeUNPCKHMask(VT, ShuffleMask);
4462 case X86ISD::UNPCKL:
4463 DecodeUNPCKLMask(VT, ShuffleMask);
4465 case X86ISD::MOVHLPS:
4466 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4468 case X86ISD::MOVLHPS:
4469 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4471 case X86ISD::PSHUFD:
4472 ImmN = N->getOperand(N->getNumOperands()-1);
4473 DecodePSHUFMask(NumElems,
4474 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4477 case X86ISD::PSHUFHW:
4478 ImmN = N->getOperand(N->getNumOperands()-1);
4479 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4482 case X86ISD::PSHUFLW:
4483 ImmN = N->getOperand(N->getNumOperands()-1);
4484 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4488 case X86ISD::MOVSD: {
4489 // The index 0 always comes from the first element of the second source,
4490 // this is why MOVSS and MOVSD are used in the first place. The other
4491 // elements come from the other positions of the first source vector.
4492 unsigned OpNum = (Index == 0) ? 1 : 0;
4493 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4496 case X86ISD::VPERMILP:
4497 ImmN = N->getOperand(N->getNumOperands()-1);
4498 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4501 case X86ISD::VPERM2X128:
4502 ImmN = N->getOperand(N->getNumOperands()-1);
4503 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4506 case X86ISD::MOVDDUP:
4507 case X86ISD::MOVLHPD:
4508 case X86ISD::MOVLPD:
4509 case X86ISD::MOVLPS:
4510 case X86ISD::MOVSHDUP:
4511 case X86ISD::MOVSLDUP:
4512 case X86ISD::PALIGN:
4513 return SDValue(); // Not yet implemented.
4515 assert(0 && "unknown target shuffle node");
4519 Index = ShuffleMask[Index];
4521 return DAG.getUNDEF(VT.getVectorElementType());
4523 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4524 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4528 // Actual nodes that may contain scalar elements
4529 if (Opcode == ISD::BITCAST) {
4530 V = V.getOperand(0);
4531 EVT SrcVT = V.getValueType();
4532 unsigned NumElems = VT.getVectorNumElements();
4534 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4538 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4539 return (Index == 0) ? V.getOperand(0)
4540 : DAG.getUNDEF(VT.getVectorElementType());
4542 if (V.getOpcode() == ISD::BUILD_VECTOR)
4543 return V.getOperand(Index);
4548 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4549 /// shuffle operation which come from a consecutively from a zero. The
4550 /// search can start in two different directions, from left or right.
4552 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4553 bool ZerosFromLeft, SelectionDAG &DAG) {
4556 while (i < NumElems) {
4557 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4558 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4559 if (!(Elt.getNode() &&
4560 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4568 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4569 /// MaskE correspond consecutively to elements from one of the vector operands,
4570 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4572 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4573 int OpIdx, int NumElems, unsigned &OpNum) {
4574 bool SeenV1 = false;
4575 bool SeenV2 = false;
4577 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4578 int Idx = SVOp->getMaskElt(i);
4579 // Ignore undef indicies
4588 // Only accept consecutive elements from the same vector
4589 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4593 OpNum = SeenV1 ? 0 : 1;
4597 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4598 /// logical left shift of a vector.
4599 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4600 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4601 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4602 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4603 false /* check zeros from right */, DAG);
4609 // Considering the elements in the mask that are not consecutive zeros,
4610 // check if they consecutively come from only one of the source vectors.
4612 // V1 = {X, A, B, C} 0
4614 // vector_shuffle V1, V2 <1, 2, 3, X>
4616 if (!isShuffleMaskConsecutive(SVOp,
4617 0, // Mask Start Index
4618 NumElems-NumZeros-1, // Mask End Index
4619 NumZeros, // Where to start looking in the src vector
4620 NumElems, // Number of elements in vector
4621 OpSrc)) // Which source operand ?
4626 ShVal = SVOp->getOperand(OpSrc);
4630 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4631 /// logical left shift of a vector.
4632 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4633 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4634 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4635 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4636 true /* check zeros from left */, DAG);
4642 // Considering the elements in the mask that are not consecutive zeros,
4643 // check if they consecutively come from only one of the source vectors.
4645 // 0 { A, B, X, X } = V2
4647 // vector_shuffle V1, V2 <X, X, 4, 5>
4649 if (!isShuffleMaskConsecutive(SVOp,
4650 NumZeros, // Mask Start Index
4651 NumElems-1, // Mask End Index
4652 0, // Where to start looking in the src vector
4653 NumElems, // Number of elements in vector
4654 OpSrc)) // Which source operand ?
4659 ShVal = SVOp->getOperand(OpSrc);
4663 /// isVectorShift - Returns true if the shuffle can be implemented as a
4664 /// logical left or right shift of a vector.
4665 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4666 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4667 // Although the logic below support any bitwidth size, there are no
4668 // shift instructions which handle more than 128-bit vectors.
4669 if (SVOp->getValueType(0).getSizeInBits() > 128)
4672 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4673 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4679 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4681 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4682 unsigned NumNonZero, unsigned NumZero,
4684 const TargetLowering &TLI) {
4688 DebugLoc dl = Op.getDebugLoc();
4691 for (unsigned i = 0; i < 16; ++i) {
4692 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4693 if (ThisIsNonZero && First) {
4695 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4697 V = DAG.getUNDEF(MVT::v8i16);
4702 SDValue ThisElt(0, 0), LastElt(0, 0);
4703 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4704 if (LastIsNonZero) {
4705 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4706 MVT::i16, Op.getOperand(i-1));
4708 if (ThisIsNonZero) {
4709 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4710 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4711 ThisElt, DAG.getConstant(8, MVT::i8));
4713 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4717 if (ThisElt.getNode())
4718 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4719 DAG.getIntPtrConstant(i/2));
4723 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4726 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4728 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4729 unsigned NumNonZero, unsigned NumZero,
4731 const TargetLowering &TLI) {
4735 DebugLoc dl = Op.getDebugLoc();
4738 for (unsigned i = 0; i < 8; ++i) {
4739 bool isNonZero = (NonZeros & (1 << i)) != 0;
4743 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4745 V = DAG.getUNDEF(MVT::v8i16);
4748 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4749 MVT::v8i16, V, Op.getOperand(i),
4750 DAG.getIntPtrConstant(i));
4757 /// getVShift - Return a vector logical shift node.
4759 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4760 unsigned NumBits, SelectionDAG &DAG,
4761 const TargetLowering &TLI, DebugLoc dl) {
4762 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4763 EVT ShVT = MVT::v2i64;
4764 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4765 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4766 return DAG.getNode(ISD::BITCAST, dl, VT,
4767 DAG.getNode(Opc, dl, ShVT, SrcOp,
4768 DAG.getConstant(NumBits,
4769 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4773 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4774 SelectionDAG &DAG) const {
4776 // Check if the scalar load can be widened into a vector load. And if
4777 // the address is "base + cst" see if the cst can be "absorbed" into
4778 // the shuffle mask.
4779 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4780 SDValue Ptr = LD->getBasePtr();
4781 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4783 EVT PVT = LD->getValueType(0);
4784 if (PVT != MVT::i32 && PVT != MVT::f32)
4789 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4790 FI = FINode->getIndex();
4792 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4793 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4794 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4795 Offset = Ptr.getConstantOperandVal(1);
4796 Ptr = Ptr.getOperand(0);
4801 // FIXME: 256-bit vector instructions don't require a strict alignment,
4802 // improve this code to support it better.
4803 unsigned RequiredAlign = VT.getSizeInBits()/8;
4804 SDValue Chain = LD->getChain();
4805 // Make sure the stack object alignment is at least 16 or 32.
4806 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4807 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4808 if (MFI->isFixedObjectIndex(FI)) {
4809 // Can't change the alignment. FIXME: It's possible to compute
4810 // the exact stack offset and reference FI + adjust offset instead.
4811 // If someone *really* cares about this. That's the way to implement it.
4814 MFI->setObjectAlignment(FI, RequiredAlign);
4818 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4819 // Ptr + (Offset & ~15).
4822 if ((Offset % RequiredAlign) & 3)
4824 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4826 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4827 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4829 int EltNo = (Offset - StartOffset) >> 2;
4830 int NumElems = VT.getVectorNumElements();
4832 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4833 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4834 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4835 LD->getPointerInfo().getWithOffset(StartOffset),
4836 false, false, false, 0);
4838 // Canonicalize it to a v4i32 or v8i32 shuffle.
4839 SmallVector<int, 8> Mask;
4840 for (int i = 0; i < NumElems; ++i)
4841 Mask.push_back(EltNo);
4843 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4844 return DAG.getNode(ISD::BITCAST, dl, NVT,
4845 DAG.getVectorShuffle(CanonVT, dl, V1,
4846 DAG.getUNDEF(CanonVT),&Mask[0]));
4852 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4853 /// vector of type 'VT', see if the elements can be replaced by a single large
4854 /// load which has the same value as a build_vector whose operands are 'elts'.
4856 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4858 /// FIXME: we'd also like to handle the case where the last elements are zero
4859 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4860 /// There's even a handy isZeroNode for that purpose.
4861 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4862 DebugLoc &DL, SelectionDAG &DAG) {
4863 EVT EltVT = VT.getVectorElementType();
4864 unsigned NumElems = Elts.size();
4866 LoadSDNode *LDBase = NULL;
4867 unsigned LastLoadedElt = -1U;
4869 // For each element in the initializer, see if we've found a load or an undef.
4870 // If we don't find an initial load element, or later load elements are
4871 // non-consecutive, bail out.
4872 for (unsigned i = 0; i < NumElems; ++i) {
4873 SDValue Elt = Elts[i];
4875 if (!Elt.getNode() ||
4876 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4879 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4881 LDBase = cast<LoadSDNode>(Elt.getNode());
4885 if (Elt.getOpcode() == ISD::UNDEF)
4888 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4889 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4894 // If we have found an entire vector of loads and undefs, then return a large
4895 // load of the entire vector width starting at the base pointer. If we found
4896 // consecutive loads for the low half, generate a vzext_load node.
4897 if (LastLoadedElt == NumElems - 1) {
4898 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4899 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4900 LDBase->getPointerInfo(),
4901 LDBase->isVolatile(), LDBase->isNonTemporal(),
4902 LDBase->isInvariant(), 0);
4903 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4904 LDBase->getPointerInfo(),
4905 LDBase->isVolatile(), LDBase->isNonTemporal(),
4906 LDBase->isInvariant(), LDBase->getAlignment());
4907 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4908 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4909 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4910 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4912 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4913 LDBase->getPointerInfo(),
4914 LDBase->getAlignment(),
4915 false/*isVolatile*/, true/*ReadMem*/,
4917 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4922 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4923 /// a vbroadcast node. We support two patterns:
4924 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4925 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4927 /// The scalar load node is returned when a pattern is found,
4928 /// or SDValue() otherwise.
4929 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4930 EVT VT = Op.getValueType();
4933 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4934 V = V.getOperand(0);
4936 //A suspected load to be broadcasted.
4939 switch (V.getOpcode()) {
4941 // Unknown pattern found.
4944 case ISD::BUILD_VECTOR: {
4945 // The BUILD_VECTOR node must be a splat.
4946 if (!isSplatVector(V.getNode()))
4949 Ld = V.getOperand(0);
4951 // The suspected load node has several users. Make sure that all
4952 // of its users are from the BUILD_VECTOR node.
4953 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4958 case ISD::VECTOR_SHUFFLE: {
4959 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4961 // Shuffles must have a splat mask where the first element is
4963 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4966 SDValue Sc = Op.getOperand(0);
4967 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4970 Ld = Sc.getOperand(0);
4972 // The scalar_to_vector node and the suspected
4973 // load node must have exactly one user.
4974 if (!Sc.hasOneUse() || !Ld.hasOneUse())
4980 // The scalar source must be a normal load.
4981 if (!ISD::isNormalLoad(Ld.getNode()))
4984 bool Is256 = VT.getSizeInBits() == 256;
4985 bool Is128 = VT.getSizeInBits() == 128;
4986 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4989 // VBroadcast to YMM
4990 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
4991 ScalarSize == 32 || ScalarSize == 64 ))
4994 // VBroadcast to XMM
4995 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
4996 ScalarSize == 16 || ScalarSize == 64 ))
5000 // VBroadcast to YMM
5001 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5004 // VBroadcast to XMM
5005 if (Is128 && (ScalarSize == 32))
5009 // Unsupported broadcast.
5014 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5015 DebugLoc dl = Op.getDebugLoc();
5017 EVT VT = Op.getValueType();
5018 EVT ExtVT = VT.getVectorElementType();
5019 unsigned NumElems = Op.getNumOperands();
5021 // Vectors containing all zeros can be matched by pxor and xorps later
5022 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5023 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5024 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5025 if (Op.getValueType() == MVT::v4i32 ||
5026 Op.getValueType() == MVT::v8i32)
5029 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5032 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5033 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5034 // vpcmpeqd on 256-bit vectors.
5035 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5036 if (Op.getValueType() == MVT::v4i32 ||
5037 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5040 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5043 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5044 if (Subtarget->hasAVX() && LD.getNode())
5045 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5047 unsigned EVTBits = ExtVT.getSizeInBits();
5049 unsigned NumZero = 0;
5050 unsigned NumNonZero = 0;
5051 unsigned NonZeros = 0;
5052 bool IsAllConstants = true;
5053 SmallSet<SDValue, 8> Values;
5054 for (unsigned i = 0; i < NumElems; ++i) {
5055 SDValue Elt = Op.getOperand(i);
5056 if (Elt.getOpcode() == ISD::UNDEF)
5059 if (Elt.getOpcode() != ISD::Constant &&
5060 Elt.getOpcode() != ISD::ConstantFP)
5061 IsAllConstants = false;
5062 if (X86::isZeroNode(Elt))
5065 NonZeros |= (1 << i);
5070 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5071 if (NumNonZero == 0)
5072 return DAG.getUNDEF(VT);
5074 // Special case for single non-zero, non-undef, element.
5075 if (NumNonZero == 1) {
5076 unsigned Idx = CountTrailingZeros_32(NonZeros);
5077 SDValue Item = Op.getOperand(Idx);
5079 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5080 // the value are obviously zero, truncate the value to i32 and do the
5081 // insertion that way. Only do this if the value is non-constant or if the
5082 // value is a constant being inserted into element 0. It is cheaper to do
5083 // a constant pool load than it is to do a movd + shuffle.
5084 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5085 (!IsAllConstants || Idx == 0)) {
5086 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5088 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5089 EVT VecVT = MVT::v4i32;
5090 unsigned VecElts = 4;
5092 // Truncate the value (which may itself be a constant) to i32, and
5093 // convert it to a vector with movd (S2V+shuffle to zero extend).
5094 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5095 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5096 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5097 Subtarget->hasXMMInt(), DAG);
5099 // Now we have our 32-bit value zero extended in the low element of
5100 // a vector. If Idx != 0, swizzle it into place.
5102 SmallVector<int, 4> Mask;
5103 Mask.push_back(Idx);
5104 for (unsigned i = 1; i != VecElts; ++i)
5106 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5107 DAG.getUNDEF(Item.getValueType()),
5110 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5114 // If we have a constant or non-constant insertion into the low element of
5115 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5116 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5117 // depending on what the source datatype is.
5120 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5121 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5122 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5123 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5124 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5125 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5127 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5128 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5129 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5130 EVT MiddleVT = MVT::v4i32;
5131 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5132 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5133 Subtarget->hasXMMInt(), DAG);
5134 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5138 // Is it a vector logical left shift?
5139 if (NumElems == 2 && Idx == 1 &&
5140 X86::isZeroNode(Op.getOperand(0)) &&
5141 !X86::isZeroNode(Op.getOperand(1))) {
5142 unsigned NumBits = VT.getSizeInBits();
5143 return getVShift(true, VT,
5144 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5145 VT, Op.getOperand(1)),
5146 NumBits/2, DAG, *this, dl);
5149 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5152 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5153 // is a non-constant being inserted into an element other than the low one,
5154 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5155 // movd/movss) to move this into the low element, then shuffle it into
5157 if (EVTBits == 32) {
5158 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5160 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5161 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5162 Subtarget->hasXMMInt(), DAG);
5163 SmallVector<int, 8> MaskVec;
5164 for (unsigned i = 0; i < NumElems; i++)
5165 MaskVec.push_back(i == Idx ? 0 : 1);
5166 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5170 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5171 if (Values.size() == 1) {
5172 if (EVTBits == 32) {
5173 // Instead of a shuffle like this:
5174 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5175 // Check if it's possible to issue this instead.
5176 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5177 unsigned Idx = CountTrailingZeros_32(NonZeros);
5178 SDValue Item = Op.getOperand(Idx);
5179 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5180 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5185 // A vector full of immediates; various special cases are already
5186 // handled, so this is best done with a single constant-pool load.
5190 // For AVX-length vectors, build the individual 128-bit pieces and use
5191 // shuffles to put them in place.
5192 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5193 SmallVector<SDValue, 32> V;
5194 for (unsigned i = 0; i < NumElems; ++i)
5195 V.push_back(Op.getOperand(i));
5197 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5199 // Build both the lower and upper subvector.
5200 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5201 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5204 // Recreate the wider vector with the lower and upper part.
5205 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5206 DAG.getConstant(0, MVT::i32), DAG, dl);
5207 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5211 // Let legalizer expand 2-wide build_vectors.
5212 if (EVTBits == 64) {
5213 if (NumNonZero == 1) {
5214 // One half is zero or undef.
5215 unsigned Idx = CountTrailingZeros_32(NonZeros);
5216 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5217 Op.getOperand(Idx));
5218 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5219 Subtarget->hasXMMInt(), DAG);
5224 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5225 if (EVTBits == 8 && NumElems == 16) {
5226 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5228 if (V.getNode()) return V;
5231 if (EVTBits == 16 && NumElems == 8) {
5232 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5234 if (V.getNode()) return V;
5237 // If element VT is == 32 bits, turn it into a number of shuffles.
5238 SmallVector<SDValue, 8> V;
5240 if (NumElems == 4 && NumZero > 0) {
5241 for (unsigned i = 0; i < 4; ++i) {
5242 bool isZero = !(NonZeros & (1 << i));
5244 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5246 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5249 for (unsigned i = 0; i < 2; ++i) {
5250 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5253 V[i] = V[i*2]; // Must be a zero vector.
5256 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5259 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5262 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5267 SmallVector<int, 8> MaskVec;
5268 bool Reverse = (NonZeros & 0x3) == 2;
5269 for (unsigned i = 0; i < 2; ++i)
5270 MaskVec.push_back(Reverse ? 1-i : i);
5271 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5272 for (unsigned i = 0; i < 2; ++i)
5273 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5274 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5277 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5278 // Check for a build vector of consecutive loads.
5279 for (unsigned i = 0; i < NumElems; ++i)
5280 V[i] = Op.getOperand(i);
5282 // Check for elements which are consecutive loads.
5283 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5287 // For SSE 4.1, use insertps to put the high elements into the low element.
5288 if (getSubtarget()->hasSSE41orAVX()) {
5290 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5291 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5293 Result = DAG.getUNDEF(VT);
5295 for (unsigned i = 1; i < NumElems; ++i) {
5296 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5297 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5298 Op.getOperand(i), DAG.getIntPtrConstant(i));
5303 // Otherwise, expand into a number of unpckl*, start by extending each of
5304 // our (non-undef) elements to the full vector width with the element in the
5305 // bottom slot of the vector (which generates no code for SSE).
5306 for (unsigned i = 0; i < NumElems; ++i) {
5307 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5308 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5310 V[i] = DAG.getUNDEF(VT);
5313 // Next, we iteratively mix elements, e.g. for v4f32:
5314 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5315 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5316 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5317 unsigned EltStride = NumElems >> 1;
5318 while (EltStride != 0) {
5319 for (unsigned i = 0; i < EltStride; ++i) {
5320 // If V[i+EltStride] is undef and this is the first round of mixing,
5321 // then it is safe to just drop this shuffle: V[i] is already in the
5322 // right place, the one element (since it's the first round) being
5323 // inserted as undef can be dropped. This isn't safe for successive
5324 // rounds because they will permute elements within both vectors.
5325 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5326 EltStride == NumElems/2)
5329 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5338 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5339 // them in a MMX register. This is better than doing a stack convert.
5340 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5341 DebugLoc dl = Op.getDebugLoc();
5342 EVT ResVT = Op.getValueType();
5344 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5345 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5347 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5348 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5349 InVec = Op.getOperand(1);
5350 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5351 unsigned NumElts = ResVT.getVectorNumElements();
5352 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5353 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5354 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5356 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5357 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5358 Mask[0] = 0; Mask[1] = 2;
5359 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5361 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5364 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5365 // to create 256-bit vectors from two other 128-bit ones.
5366 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5367 DebugLoc dl = Op.getDebugLoc();
5368 EVT ResVT = Op.getValueType();
5370 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5372 SDValue V1 = Op.getOperand(0);
5373 SDValue V2 = Op.getOperand(1);
5374 unsigned NumElems = ResVT.getVectorNumElements();
5376 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5377 DAG.getConstant(0, MVT::i32), DAG, dl);
5378 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5383 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5384 EVT ResVT = Op.getValueType();
5386 assert(Op.getNumOperands() == 2);
5387 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5388 "Unsupported CONCAT_VECTORS for value type");
5390 // We support concatenate two MMX registers and place them in a MMX register.
5391 // This is better than doing a stack convert.
5392 if (ResVT.is128BitVector())
5393 return LowerMMXCONCAT_VECTORS(Op, DAG);
5395 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5396 // from two other 128-bit ones.
5397 return LowerAVXCONCAT_VECTORS(Op, DAG);
5400 // v8i16 shuffles - Prefer shuffles in the following order:
5401 // 1. [all] pshuflw, pshufhw, optional move
5402 // 2. [ssse3] 1 x pshufb
5403 // 3. [ssse3] 2 x pshufb + 1 x por
5404 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5406 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5407 SelectionDAG &DAG) const {
5408 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5409 SDValue V1 = SVOp->getOperand(0);
5410 SDValue V2 = SVOp->getOperand(1);
5411 DebugLoc dl = SVOp->getDebugLoc();
5412 SmallVector<int, 8> MaskVals;
5414 // Determine if more than 1 of the words in each of the low and high quadwords
5415 // of the result come from the same quadword of one of the two inputs. Undef
5416 // mask values count as coming from any quadword, for better codegen.
5417 unsigned LoQuad[] = { 0, 0, 0, 0 };
5418 unsigned HiQuad[] = { 0, 0, 0, 0 };
5419 BitVector InputQuads(4);
5420 for (unsigned i = 0; i < 8; ++i) {
5421 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5422 int EltIdx = SVOp->getMaskElt(i);
5423 MaskVals.push_back(EltIdx);
5432 InputQuads.set(EltIdx / 4);
5435 int BestLoQuad = -1;
5436 unsigned MaxQuad = 1;
5437 for (unsigned i = 0; i < 4; ++i) {
5438 if (LoQuad[i] > MaxQuad) {
5440 MaxQuad = LoQuad[i];
5444 int BestHiQuad = -1;
5446 for (unsigned i = 0; i < 4; ++i) {
5447 if (HiQuad[i] > MaxQuad) {
5449 MaxQuad = HiQuad[i];
5453 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5454 // of the two input vectors, shuffle them into one input vector so only a
5455 // single pshufb instruction is necessary. If There are more than 2 input
5456 // quads, disable the next transformation since it does not help SSSE3.
5457 bool V1Used = InputQuads[0] || InputQuads[1];
5458 bool V2Used = InputQuads[2] || InputQuads[3];
5459 if (Subtarget->hasSSSE3orAVX()) {
5460 if (InputQuads.count() == 2 && V1Used && V2Used) {
5461 BestLoQuad = InputQuads.find_first();
5462 BestHiQuad = InputQuads.find_next(BestLoQuad);
5464 if (InputQuads.count() > 2) {
5470 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5471 // the shuffle mask. If a quad is scored as -1, that means that it contains
5472 // words from all 4 input quadwords.
5474 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5475 SmallVector<int, 8> MaskV;
5476 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5477 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5478 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5479 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5480 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5481 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5483 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5484 // source words for the shuffle, to aid later transformations.
5485 bool AllWordsInNewV = true;
5486 bool InOrder[2] = { true, true };
5487 for (unsigned i = 0; i != 8; ++i) {
5488 int idx = MaskVals[i];
5490 InOrder[i/4] = false;
5491 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5493 AllWordsInNewV = false;
5497 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5498 if (AllWordsInNewV) {
5499 for (int i = 0; i != 8; ++i) {
5500 int idx = MaskVals[i];
5503 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5504 if ((idx != i) && idx < 4)
5506 if ((idx != i) && idx > 3)
5515 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5516 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5517 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5518 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5519 unsigned TargetMask = 0;
5520 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5521 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5522 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5523 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5524 V1 = NewV.getOperand(0);
5525 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5529 // If we have SSSE3, and all words of the result are from 1 input vector,
5530 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5531 // is present, fall back to case 4.
5532 if (Subtarget->hasSSSE3orAVX()) {
5533 SmallVector<SDValue,16> pshufbMask;
5535 // If we have elements from both input vectors, set the high bit of the
5536 // shuffle mask element to zero out elements that come from V2 in the V1
5537 // mask, and elements that come from V1 in the V2 mask, so that the two
5538 // results can be OR'd together.
5539 bool TwoInputs = V1Used && V2Used;
5540 for (unsigned i = 0; i != 8; ++i) {
5541 int EltIdx = MaskVals[i] * 2;
5542 if (TwoInputs && (EltIdx >= 16)) {
5543 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5544 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5547 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5548 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5550 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5551 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5552 DAG.getNode(ISD::BUILD_VECTOR, dl,
5553 MVT::v16i8, &pshufbMask[0], 16));
5555 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5557 // Calculate the shuffle mask for the second input, shuffle it, and
5558 // OR it with the first shuffled input.
5560 for (unsigned i = 0; i != 8; ++i) {
5561 int EltIdx = MaskVals[i] * 2;
5563 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5564 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5567 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5568 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5570 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5571 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5572 DAG.getNode(ISD::BUILD_VECTOR, dl,
5573 MVT::v16i8, &pshufbMask[0], 16));
5574 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5575 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5578 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5579 // and update MaskVals with new element order.
5580 BitVector InOrder(8);
5581 if (BestLoQuad >= 0) {
5582 SmallVector<int, 8> MaskV;
5583 for (int i = 0; i != 4; ++i) {
5584 int idx = MaskVals[i];
5586 MaskV.push_back(-1);
5588 } else if ((idx / 4) == BestLoQuad) {
5589 MaskV.push_back(idx & 3);
5592 MaskV.push_back(-1);
5595 for (unsigned i = 4; i != 8; ++i)
5597 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5600 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5601 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5603 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5607 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5608 // and update MaskVals with the new element order.
5609 if (BestHiQuad >= 0) {
5610 SmallVector<int, 8> MaskV;
5611 for (unsigned i = 0; i != 4; ++i)
5613 for (unsigned i = 4; i != 8; ++i) {
5614 int idx = MaskVals[i];
5616 MaskV.push_back(-1);
5618 } else if ((idx / 4) == BestHiQuad) {
5619 MaskV.push_back((idx & 3) + 4);
5622 MaskV.push_back(-1);
5625 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5628 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5629 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5631 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5635 // In case BestHi & BestLo were both -1, which means each quadword has a word
5636 // from each of the four input quadwords, calculate the InOrder bitvector now
5637 // before falling through to the insert/extract cleanup.
5638 if (BestLoQuad == -1 && BestHiQuad == -1) {
5640 for (int i = 0; i != 8; ++i)
5641 if (MaskVals[i] < 0 || MaskVals[i] == i)
5645 // The other elements are put in the right place using pextrw and pinsrw.
5646 for (unsigned i = 0; i != 8; ++i) {
5649 int EltIdx = MaskVals[i];
5652 SDValue ExtOp = (EltIdx < 8)
5653 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5654 DAG.getIntPtrConstant(EltIdx))
5655 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5656 DAG.getIntPtrConstant(EltIdx - 8));
5657 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5658 DAG.getIntPtrConstant(i));
5663 // v16i8 shuffles - Prefer shuffles in the following order:
5664 // 1. [ssse3] 1 x pshufb
5665 // 2. [ssse3] 2 x pshufb + 1 x por
5666 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5668 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5670 const X86TargetLowering &TLI) {
5671 SDValue V1 = SVOp->getOperand(0);
5672 SDValue V2 = SVOp->getOperand(1);
5673 DebugLoc dl = SVOp->getDebugLoc();
5674 SmallVector<int, 16> MaskVals;
5675 SVOp->getMask(MaskVals);
5677 // If we have SSSE3, case 1 is generated when all result bytes come from
5678 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5679 // present, fall back to case 3.
5680 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5683 for (unsigned i = 0; i < 16; ++i) {
5684 int EltIdx = MaskVals[i];
5693 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5694 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5695 SmallVector<SDValue,16> pshufbMask;
5697 // If all result elements are from one input vector, then only translate
5698 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5700 // Otherwise, we have elements from both input vectors, and must zero out
5701 // elements that come from V2 in the first mask, and V1 in the second mask
5702 // so that we can OR them together.
5703 bool TwoInputs = !(V1Only || V2Only);
5704 for (unsigned i = 0; i != 16; ++i) {
5705 int EltIdx = MaskVals[i];
5706 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5707 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5710 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5712 // If all the elements are from V2, assign it to V1 and return after
5713 // building the first pshufb.
5716 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5717 DAG.getNode(ISD::BUILD_VECTOR, dl,
5718 MVT::v16i8, &pshufbMask[0], 16));
5722 // Calculate the shuffle mask for the second input, shuffle it, and
5723 // OR it with the first shuffled input.
5725 for (unsigned i = 0; i != 16; ++i) {
5726 int EltIdx = MaskVals[i];
5728 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5731 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5733 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5734 DAG.getNode(ISD::BUILD_VECTOR, dl,
5735 MVT::v16i8, &pshufbMask[0], 16));
5736 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5739 // No SSSE3 - Calculate in place words and then fix all out of place words
5740 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5741 // the 16 different words that comprise the two doublequadword input vectors.
5742 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5743 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5744 SDValue NewV = V2Only ? V2 : V1;
5745 for (int i = 0; i != 8; ++i) {
5746 int Elt0 = MaskVals[i*2];
5747 int Elt1 = MaskVals[i*2+1];
5749 // This word of the result is all undef, skip it.
5750 if (Elt0 < 0 && Elt1 < 0)
5753 // This word of the result is already in the correct place, skip it.
5754 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5756 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5759 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5760 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5763 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5764 // using a single extract together, load it and store it.
5765 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5766 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5767 DAG.getIntPtrConstant(Elt1 / 2));
5768 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5769 DAG.getIntPtrConstant(i));
5773 // If Elt1 is defined, extract it from the appropriate source. If the
5774 // source byte is not also odd, shift the extracted word left 8 bits
5775 // otherwise clear the bottom 8 bits if we need to do an or.
5777 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5778 DAG.getIntPtrConstant(Elt1 / 2));
5779 if ((Elt1 & 1) == 0)
5780 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5782 TLI.getShiftAmountTy(InsElt.getValueType())));
5784 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5785 DAG.getConstant(0xFF00, MVT::i16));
5787 // If Elt0 is defined, extract it from the appropriate source. If the
5788 // source byte is not also even, shift the extracted word right 8 bits. If
5789 // Elt1 was also defined, OR the extracted values together before
5790 // inserting them in the result.
5792 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5793 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5794 if ((Elt0 & 1) != 0)
5795 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5797 TLI.getShiftAmountTy(InsElt0.getValueType())));
5799 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5800 DAG.getConstant(0x00FF, MVT::i16));
5801 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5804 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5805 DAG.getIntPtrConstant(i));
5807 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5810 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5811 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5812 /// done when every pair / quad of shuffle mask elements point to elements in
5813 /// the right sequence. e.g.
5814 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5816 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5817 SelectionDAG &DAG, DebugLoc dl) {
5818 EVT VT = SVOp->getValueType(0);
5819 SDValue V1 = SVOp->getOperand(0);
5820 SDValue V2 = SVOp->getOperand(1);
5821 unsigned NumElems = VT.getVectorNumElements();
5822 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5824 switch (VT.getSimpleVT().SimpleTy) {
5825 default: assert(false && "Unexpected!");
5826 case MVT::v4f32: NewVT = MVT::v2f64; break;
5827 case MVT::v4i32: NewVT = MVT::v2i64; break;
5828 case MVT::v8i16: NewVT = MVT::v4i32; break;
5829 case MVT::v16i8: NewVT = MVT::v4i32; break;
5832 int Scale = NumElems / NewWidth;
5833 SmallVector<int, 8> MaskVec;
5834 for (unsigned i = 0; i < NumElems; i += Scale) {
5836 for (int j = 0; j < Scale; ++j) {
5837 int EltIdx = SVOp->getMaskElt(i+j);
5841 StartIdx = EltIdx - (EltIdx % Scale);
5842 if (EltIdx != StartIdx + j)
5846 MaskVec.push_back(-1);
5848 MaskVec.push_back(StartIdx / Scale);
5851 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5852 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5853 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5856 /// getVZextMovL - Return a zero-extending vector move low node.
5858 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5859 SDValue SrcOp, SelectionDAG &DAG,
5860 const X86Subtarget *Subtarget, DebugLoc dl) {
5861 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5862 LoadSDNode *LD = NULL;
5863 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5864 LD = dyn_cast<LoadSDNode>(SrcOp);
5866 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5868 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5869 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5870 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5871 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5872 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5874 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5875 return DAG.getNode(ISD::BITCAST, dl, VT,
5876 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5877 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5885 return DAG.getNode(ISD::BITCAST, dl, VT,
5886 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5887 DAG.getNode(ISD::BITCAST, dl,
5891 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5892 /// shuffle node referes to only one lane in the sources.
5893 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5894 EVT VT = SVOp->getValueType(0);
5895 int NumElems = VT.getVectorNumElements();
5896 int HalfSize = NumElems/2;
5897 SmallVector<int, 16> M;
5899 bool MatchA = false, MatchB = false;
5901 for (int l = 0; l < NumElems*2; l += HalfSize) {
5902 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5908 for (int l = 0; l < NumElems*2; l += HalfSize) {
5909 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5915 return MatchA && MatchB;
5918 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5919 /// which could not be matched by any known target speficic shuffle
5921 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5922 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5923 // If each half of a vector shuffle node referes to only one lane in the
5924 // source vectors, extract each used 128-bit lane and shuffle them using
5925 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5926 // the work to the legalizer.
5927 DebugLoc dl = SVOp->getDebugLoc();
5928 EVT VT = SVOp->getValueType(0);
5929 int NumElems = VT.getVectorNumElements();
5930 int HalfSize = NumElems/2;
5932 // Extract the reference for each half
5933 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5934 int FstVecOpNum = 0, SndVecOpNum = 0;
5935 for (int i = 0; i < HalfSize; ++i) {
5936 int Elt = SVOp->getMaskElt(i);
5937 if (SVOp->getMaskElt(i) < 0)
5939 FstVecOpNum = Elt/NumElems;
5940 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5943 for (int i = HalfSize; i < NumElems; ++i) {
5944 int Elt = SVOp->getMaskElt(i);
5945 if (SVOp->getMaskElt(i) < 0)
5947 SndVecOpNum = Elt/NumElems;
5948 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5952 // Extract the subvectors
5953 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5954 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5955 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5956 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5958 // Generate 128-bit shuffles
5959 SmallVector<int, 16> MaskV1, MaskV2;
5960 for (int i = 0; i < HalfSize; ++i) {
5961 int Elt = SVOp->getMaskElt(i);
5962 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5964 for (int i = HalfSize; i < NumElems; ++i) {
5965 int Elt = SVOp->getMaskElt(i);
5966 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5969 EVT NVT = V1.getValueType();
5970 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5971 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5973 // Concatenate the result back
5974 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5975 DAG.getConstant(0, MVT::i32), DAG, dl);
5976 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5983 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5984 /// 4 elements, and match them with several different shuffle types.
5986 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5987 SDValue V1 = SVOp->getOperand(0);
5988 SDValue V2 = SVOp->getOperand(1);
5989 DebugLoc dl = SVOp->getDebugLoc();
5990 EVT VT = SVOp->getValueType(0);
5992 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5994 SmallVector<std::pair<int, int>, 8> Locs;
5996 SmallVector<int, 8> Mask1(4U, -1);
5997 SmallVector<int, 8> PermMask;
5998 SVOp->getMask(PermMask);
6002 for (unsigned i = 0; i != 4; ++i) {
6003 int Idx = PermMask[i];
6005 Locs[i] = std::make_pair(-1, -1);
6007 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6009 Locs[i] = std::make_pair(0, NumLo);
6013 Locs[i] = std::make_pair(1, NumHi);
6015 Mask1[2+NumHi] = Idx;
6021 if (NumLo <= 2 && NumHi <= 2) {
6022 // If no more than two elements come from either vector. This can be
6023 // implemented with two shuffles. First shuffle gather the elements.
6024 // The second shuffle, which takes the first shuffle as both of its
6025 // vector operands, put the elements into the right order.
6026 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6028 SmallVector<int, 8> Mask2(4U, -1);
6030 for (unsigned i = 0; i != 4; ++i) {
6031 if (Locs[i].first == -1)
6034 unsigned Idx = (i < 2) ? 0 : 4;
6035 Idx += Locs[i].first * 2 + Locs[i].second;
6040 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6041 } else if (NumLo == 3 || NumHi == 3) {
6042 // Otherwise, we must have three elements from one vector, call it X, and
6043 // one element from the other, call it Y. First, use a shufps to build an
6044 // intermediate vector with the one element from Y and the element from X
6045 // that will be in the same half in the final destination (the indexes don't
6046 // matter). Then, use a shufps to build the final vector, taking the half
6047 // containing the element from Y from the intermediate, and the other half
6050 // Normalize it so the 3 elements come from V1.
6051 CommuteVectorShuffleMask(PermMask, 4);
6055 // Find the element from V2.
6057 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6058 int Val = PermMask[HiIndex];
6065 Mask1[0] = PermMask[HiIndex];
6067 Mask1[2] = PermMask[HiIndex^1];
6069 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6072 Mask1[0] = PermMask[0];
6073 Mask1[1] = PermMask[1];
6074 Mask1[2] = HiIndex & 1 ? 6 : 4;
6075 Mask1[3] = HiIndex & 1 ? 4 : 6;
6076 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6078 Mask1[0] = HiIndex & 1 ? 2 : 0;
6079 Mask1[1] = HiIndex & 1 ? 0 : 2;
6080 Mask1[2] = PermMask[2];
6081 Mask1[3] = PermMask[3];
6086 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6090 // Break it into (shuffle shuffle_hi, shuffle_lo).
6093 SmallVector<int,8> LoMask(4U, -1);
6094 SmallVector<int,8> HiMask(4U, -1);
6096 SmallVector<int,8> *MaskPtr = &LoMask;
6097 unsigned MaskIdx = 0;
6100 for (unsigned i = 0; i != 4; ++i) {
6107 int Idx = PermMask[i];
6109 Locs[i] = std::make_pair(-1, -1);
6110 } else if (Idx < 4) {
6111 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6112 (*MaskPtr)[LoIdx] = Idx;
6115 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6116 (*MaskPtr)[HiIdx] = Idx;
6121 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6122 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6123 SmallVector<int, 8> MaskOps;
6124 for (unsigned i = 0; i != 4; ++i) {
6125 if (Locs[i].first == -1) {
6126 MaskOps.push_back(-1);
6128 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6129 MaskOps.push_back(Idx);
6132 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6135 static bool MayFoldVectorLoad(SDValue V) {
6136 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6137 V = V.getOperand(0);
6138 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6139 V = V.getOperand(0);
6140 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6141 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6142 // BUILD_VECTOR (load), undef
6143 V = V.getOperand(0);
6149 // FIXME: the version above should always be used. Since there's
6150 // a bug where several vector shuffles can't be folded because the
6151 // DAG is not updated during lowering and a node claims to have two
6152 // uses while it only has one, use this version, and let isel match
6153 // another instruction if the load really happens to have more than
6154 // one use. Remove this version after this bug get fixed.
6155 // rdar://8434668, PR8156
6156 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6157 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6158 V = V.getOperand(0);
6159 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6160 V = V.getOperand(0);
6161 if (ISD::isNormalLoad(V.getNode()))
6166 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6167 /// a vector extract, and if both can be later optimized into a single load.
6168 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6169 /// here because otherwise a target specific shuffle node is going to be
6170 /// emitted for this shuffle, and the optimization not done.
6171 /// FIXME: This is probably not the best approach, but fix the problem
6172 /// until the right path is decided.
6174 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6175 const TargetLowering &TLI) {
6176 EVT VT = V.getValueType();
6177 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6179 // Be sure that the vector shuffle is present in a pattern like this:
6180 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6184 SDNode *N = *V.getNode()->use_begin();
6185 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6188 SDValue EltNo = N->getOperand(1);
6189 if (!isa<ConstantSDNode>(EltNo))
6192 // If the bit convert changed the number of elements, it is unsafe
6193 // to examine the mask.
6194 bool HasShuffleIntoBitcast = false;
6195 if (V.getOpcode() == ISD::BITCAST) {
6196 EVT SrcVT = V.getOperand(0).getValueType();
6197 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6199 V = V.getOperand(0);
6200 HasShuffleIntoBitcast = true;
6203 // Select the input vector, guarding against out of range extract vector.
6204 unsigned NumElems = VT.getVectorNumElements();
6205 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6206 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6207 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6209 // Skip one more bit_convert if necessary
6210 if (V.getOpcode() == ISD::BITCAST)
6211 V = V.getOperand(0);
6213 if (ISD::isNormalLoad(V.getNode())) {
6214 // Is the original load suitable?
6215 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6217 // FIXME: avoid the multi-use bug that is preventing lots of
6218 // of foldings to be detected, this is still wrong of course, but
6219 // give the temporary desired behavior, and if it happens that
6220 // the load has real more uses, during isel it will not fold, and
6221 // will generate poor code.
6222 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6225 if (!HasShuffleIntoBitcast)
6228 // If there's a bitcast before the shuffle, check if the load type and
6229 // alignment is valid.
6230 unsigned Align = LN0->getAlignment();
6232 TLI.getTargetData()->getABITypeAlignment(
6233 VT.getTypeForEVT(*DAG.getContext()));
6235 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6243 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6244 EVT VT = Op.getValueType();
6246 // Canonizalize to v2f64.
6247 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6248 return DAG.getNode(ISD::BITCAST, dl, VT,
6249 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6254 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6256 SDValue V1 = Op.getOperand(0);
6257 SDValue V2 = Op.getOperand(1);
6258 EVT VT = Op.getValueType();
6260 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6262 if (HasXMMInt && VT == MVT::v2f64)
6263 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6265 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6266 return DAG.getNode(ISD::BITCAST, dl, VT,
6267 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6268 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6269 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6273 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6274 SDValue V1 = Op.getOperand(0);
6275 SDValue V2 = Op.getOperand(1);
6276 EVT VT = Op.getValueType();
6278 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6279 "unsupported shuffle type");
6281 if (V2.getOpcode() == ISD::UNDEF)
6285 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6288 static inline unsigned getSHUFPOpcode(EVT VT) {
6289 switch(VT.getSimpleVT().SimpleTy) {
6290 case MVT::v8i32: // Use fp unit for int unpack.
6292 case MVT::v4i32: // Use fp unit for int unpack.
6293 case MVT::v4f32: return X86ISD::SHUFPS;
6294 case MVT::v4i64: // Use fp unit for int unpack.
6296 case MVT::v2i64: // Use fp unit for int unpack.
6297 case MVT::v2f64: return X86ISD::SHUFPD;
6299 llvm_unreachable("Unknown type for shufp*");
6305 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6306 SDValue V1 = Op.getOperand(0);
6307 SDValue V2 = Op.getOperand(1);
6308 EVT VT = Op.getValueType();
6309 unsigned NumElems = VT.getVectorNumElements();
6311 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6312 // operand of these instructions is only memory, so check if there's a
6313 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6315 bool CanFoldLoad = false;
6317 // Trivial case, when V2 comes from a load.
6318 if (MayFoldVectorLoad(V2))
6321 // When V1 is a load, it can be folded later into a store in isel, example:
6322 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6324 // (MOVLPSmr addr:$src1, VR128:$src2)
6325 // So, recognize this potential and also use MOVLPS or MOVLPD
6326 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6331 if (HasXMMInt && NumElems == 2)
6332 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6335 // If we don't care about the second element, procede to use movss.
6336 if (SVOp->getMaskElt(1) != -1)
6337 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6340 // movl and movlp will both match v2i64, but v2i64 is never matched by
6341 // movl earlier because we make it strict to avoid messing with the movlp load
6342 // folding logic (see the code above getMOVLP call). Match it here then,
6343 // this is horrible, but will stay like this until we move all shuffle
6344 // matching to x86 specific nodes. Note that for the 1st condition all
6345 // types are matched with movsd.
6347 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6348 // as to remove this logic from here, as much as possible
6349 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6350 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6351 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6354 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6356 // Invert the operand order and use SHUFPS to match it.
6357 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6358 X86::getShuffleSHUFImmediate(SVOp), DAG);
6362 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6363 const TargetLowering &TLI,
6364 const X86Subtarget *Subtarget) {
6365 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6366 EVT VT = Op.getValueType();
6367 DebugLoc dl = Op.getDebugLoc();
6368 SDValue V1 = Op.getOperand(0);
6369 SDValue V2 = Op.getOperand(1);
6371 if (isZeroShuffle(SVOp))
6372 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6374 // Handle splat operations
6375 if (SVOp->isSplat()) {
6376 unsigned NumElem = VT.getVectorNumElements();
6377 int Size = VT.getSizeInBits();
6378 // Special case, this is the only place now where it's allowed to return
6379 // a vector_shuffle operation without using a target specific node, because
6380 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6381 // this be moved to DAGCombine instead?
6382 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6385 // Use vbroadcast whenever the splat comes from a foldable load
6386 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6387 if (Subtarget->hasAVX() && LD.getNode())
6388 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6390 // Handle splats by matching through known shuffle masks
6391 if ((Size == 128 && NumElem <= 4) ||
6392 (Size == 256 && NumElem < 8))
6395 // All remaning splats are promoted to target supported vector shuffles.
6396 return PromoteSplat(SVOp, DAG);
6399 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6401 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6402 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6403 if (NewOp.getNode())
6404 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6405 } else if ((VT == MVT::v4i32 ||
6406 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6407 // FIXME: Figure out a cleaner way to do this.
6408 // Try to make use of movq to zero out the top part.
6409 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6410 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6411 if (NewOp.getNode()) {
6412 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6413 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6414 DAG, Subtarget, dl);
6416 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6417 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6418 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6419 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6420 DAG, Subtarget, dl);
6427 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6428 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6429 SDValue V1 = Op.getOperand(0);
6430 SDValue V2 = Op.getOperand(1);
6431 EVT VT = Op.getValueType();
6432 DebugLoc dl = Op.getDebugLoc();
6433 unsigned NumElems = VT.getVectorNumElements();
6434 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6435 bool V1IsSplat = false;
6436 bool V2IsSplat = false;
6437 bool HasXMMInt = Subtarget->hasXMMInt();
6438 bool HasAVX = Subtarget->hasAVX();
6439 bool HasAVX2 = Subtarget->hasAVX2();
6440 MachineFunction &MF = DAG.getMachineFunction();
6441 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6443 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6445 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6447 // Vector shuffle lowering takes 3 steps:
6449 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6450 // narrowing and commutation of operands should be handled.
6451 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6453 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6454 // so the shuffle can be broken into other shuffles and the legalizer can
6455 // try the lowering again.
6457 // The general idea is that no vector_shuffle operation should be left to
6458 // be matched during isel, all of them must be converted to a target specific
6461 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6462 // narrowing and commutation of operands should be handled. The actual code
6463 // doesn't include all of those, work in progress...
6464 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6465 if (NewOp.getNode())
6468 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6469 // unpckh_undef). Only use pshufd if speed is more important than size.
6470 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6471 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6472 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6473 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6475 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6476 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6477 return getMOVDDup(Op, dl, V1, DAG);
6479 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6480 return getMOVHighToLow(Op, dl, DAG);
6482 // Use to match splats
6483 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6484 (VT == MVT::v2f64 || VT == MVT::v2i64))
6485 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6487 if (X86::isPSHUFDMask(SVOp)) {
6488 // The actual implementation will match the mask in the if above and then
6489 // during isel it can match several different instructions, not only pshufd
6490 // as its name says, sad but true, emulate the behavior for now...
6491 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6492 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6494 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6496 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6497 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6499 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6503 // Check if this can be converted into a logical shift.
6504 bool isLeft = false;
6507 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6508 if (isShift && ShVal.hasOneUse()) {
6509 // If the shifted value has multiple uses, it may be cheaper to use
6510 // v_set0 + movlhps or movhlps, etc.
6511 EVT EltVT = VT.getVectorElementType();
6512 ShAmt *= EltVT.getSizeInBits();
6513 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6516 if (X86::isMOVLMask(SVOp)) {
6517 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6518 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6519 if (!X86::isMOVLPMask(SVOp)) {
6520 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6521 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6523 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6524 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6528 // FIXME: fold these into legal mask.
6529 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6530 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6532 if (X86::isMOVHLPSMask(SVOp))
6533 return getMOVHighToLow(Op, dl, DAG);
6535 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6536 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6538 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6539 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6541 if (X86::isMOVLPMask(SVOp))
6542 return getMOVLP(Op, dl, DAG, HasXMMInt);
6544 if (ShouldXformToMOVHLPS(SVOp) ||
6545 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6546 return CommuteVectorShuffle(SVOp, DAG);
6549 // No better options. Use a vshl / vsrl.
6550 EVT EltVT = VT.getVectorElementType();
6551 ShAmt *= EltVT.getSizeInBits();
6552 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6555 bool Commuted = false;
6556 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6557 // 1,1,1,1 -> v8i16 though.
6558 V1IsSplat = isSplatVector(V1.getNode());
6559 V2IsSplat = isSplatVector(V2.getNode());
6561 // Canonicalize the splat or undef, if present, to be on the RHS.
6562 if (V1IsSplat && !V2IsSplat) {
6563 Op = CommuteVectorShuffle(SVOp, DAG);
6564 SVOp = cast<ShuffleVectorSDNode>(Op);
6565 V1 = SVOp->getOperand(0);
6566 V2 = SVOp->getOperand(1);
6567 std::swap(V1IsSplat, V2IsSplat);
6571 SmallVector<int, 32> M;
6574 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6575 // Shuffling low element of v1 into undef, just return v1.
6578 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6579 // the instruction selector will not match, so get a canonical MOVL with
6580 // swapped operands to undo the commute.
6581 return getMOVL(DAG, dl, VT, V2, V1);
6584 if (isUNPCKLMask(M, VT, HasAVX2))
6585 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6587 if (isUNPCKHMask(M, VT, HasAVX2))
6588 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6591 // Normalize mask so all entries that point to V2 points to its first
6592 // element then try to match unpck{h|l} again. If match, return a
6593 // new vector_shuffle with the corrected mask.
6594 SDValue NewMask = NormalizeMask(SVOp, DAG);
6595 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6596 if (NSVOp != SVOp) {
6597 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6599 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6606 // Commute is back and try unpck* again.
6607 // FIXME: this seems wrong.
6608 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6609 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6611 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6612 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6614 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6615 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6618 // Normalize the node to match x86 shuffle ops if needed
6619 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6620 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6621 return CommuteVectorShuffle(SVOp, DAG);
6623 // The checks below are all present in isShuffleMaskLegal, but they are
6624 // inlined here right now to enable us to directly emit target specific
6625 // nodes, and remove one by one until they don't return Op anymore.
6627 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6628 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6629 X86::getShufflePALIGNRImmediate(SVOp),
6632 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6633 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6634 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6635 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6638 if (isPSHUFHWMask(M, VT))
6639 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6640 X86::getShufflePSHUFHWImmediate(SVOp),
6643 if (isPSHUFLWMask(M, VT))
6644 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6645 X86::getShufflePSHUFLWImmediate(SVOp),
6648 if (isSHUFPMask(M, VT))
6649 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6650 X86::getShuffleSHUFImmediate(SVOp), DAG);
6652 if (isUNPCKL_v_undef_Mask(M, VT))
6653 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6654 if (isUNPCKH_v_undef_Mask(M, VT))
6655 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6657 //===--------------------------------------------------------------------===//
6658 // Generate target specific nodes for 128 or 256-bit shuffles only
6659 // supported in the AVX instruction set.
6662 // Handle VMOVDDUPY permutations
6663 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6664 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6666 // Handle VPERMILPS/D* permutations
6667 if (isVPERMILPMask(M, VT, HasAVX))
6668 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6669 getShuffleVPERMILPImmediate(SVOp), DAG);
6671 // Handle VPERM2F128/VPERM2I128 permutations
6672 if (isVPERM2X128Mask(M, VT, HasAVX))
6673 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6674 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6676 // Handle VSHUFPS/DY permutations
6677 if (isVSHUFPYMask(M, VT, HasAVX))
6678 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6679 getShuffleVSHUFPYImmediate(SVOp), DAG);
6681 //===--------------------------------------------------------------------===//
6682 // Since no target specific shuffle was selected for this generic one,
6683 // lower it into other known shuffles. FIXME: this isn't true yet, but
6684 // this is the plan.
6687 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6688 if (VT == MVT::v8i16) {
6689 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6690 if (NewOp.getNode())
6694 if (VT == MVT::v16i8) {
6695 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6696 if (NewOp.getNode())
6700 // Handle all 128-bit wide vectors with 4 elements, and match them with
6701 // several different shuffle types.
6702 if (NumElems == 4 && VT.getSizeInBits() == 128)
6703 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6705 // Handle general 256-bit shuffles
6706 if (VT.is256BitVector())
6707 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6713 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6714 SelectionDAG &DAG) const {
6715 EVT VT = Op.getValueType();
6716 DebugLoc dl = Op.getDebugLoc();
6718 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6721 if (VT.getSizeInBits() == 8) {
6722 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6723 Op.getOperand(0), Op.getOperand(1));
6724 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6725 DAG.getValueType(VT));
6726 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6727 } else if (VT.getSizeInBits() == 16) {
6728 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6729 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6731 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6732 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6733 DAG.getNode(ISD::BITCAST, dl,
6737 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6738 Op.getOperand(0), Op.getOperand(1));
6739 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6740 DAG.getValueType(VT));
6741 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6742 } else if (VT == MVT::f32) {
6743 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6744 // the result back to FR32 register. It's only worth matching if the
6745 // result has a single use which is a store or a bitcast to i32. And in
6746 // the case of a store, it's not worth it if the index is a constant 0,
6747 // because a MOVSSmr can be used instead, which is smaller and faster.
6748 if (!Op.hasOneUse())
6750 SDNode *User = *Op.getNode()->use_begin();
6751 if ((User->getOpcode() != ISD::STORE ||
6752 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6753 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6754 (User->getOpcode() != ISD::BITCAST ||
6755 User->getValueType(0) != MVT::i32))
6757 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6758 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6761 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6762 } else if (VT == MVT::i32 || VT == MVT::i64) {
6763 // ExtractPS/pextrq works with constant index.
6764 if (isa<ConstantSDNode>(Op.getOperand(1)))
6772 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6773 SelectionDAG &DAG) const {
6774 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6777 SDValue Vec = Op.getOperand(0);
6778 EVT VecVT = Vec.getValueType();
6780 // If this is a 256-bit vector result, first extract the 128-bit vector and
6781 // then extract the element from the 128-bit vector.
6782 if (VecVT.getSizeInBits() == 256) {
6783 DebugLoc dl = Op.getNode()->getDebugLoc();
6784 unsigned NumElems = VecVT.getVectorNumElements();
6785 SDValue Idx = Op.getOperand(1);
6786 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6788 // Get the 128-bit vector.
6789 bool Upper = IdxVal >= NumElems/2;
6790 Vec = Extract128BitVector(Vec,
6791 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6793 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6794 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6797 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6799 if (Subtarget->hasSSE41orAVX()) {
6800 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6805 EVT VT = Op.getValueType();
6806 DebugLoc dl = Op.getDebugLoc();
6807 // TODO: handle v16i8.
6808 if (VT.getSizeInBits() == 16) {
6809 SDValue Vec = Op.getOperand(0);
6810 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6812 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6813 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6814 DAG.getNode(ISD::BITCAST, dl,
6817 // Transform it so it match pextrw which produces a 32-bit result.
6818 EVT EltVT = MVT::i32;
6819 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6820 Op.getOperand(0), Op.getOperand(1));
6821 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6822 DAG.getValueType(VT));
6823 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6824 } else if (VT.getSizeInBits() == 32) {
6825 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6829 // SHUFPS the element to the lowest double word, then movss.
6830 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6831 EVT VVT = Op.getOperand(0).getValueType();
6832 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6833 DAG.getUNDEF(VVT), Mask);
6834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6835 DAG.getIntPtrConstant(0));
6836 } else if (VT.getSizeInBits() == 64) {
6837 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6838 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6839 // to match extract_elt for f64.
6840 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6844 // UNPCKHPD the element to the lowest double word, then movsd.
6845 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6846 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6847 int Mask[2] = { 1, -1 };
6848 EVT VVT = Op.getOperand(0).getValueType();
6849 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6850 DAG.getUNDEF(VVT), Mask);
6851 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6852 DAG.getIntPtrConstant(0));
6859 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6860 SelectionDAG &DAG) const {
6861 EVT VT = Op.getValueType();
6862 EVT EltVT = VT.getVectorElementType();
6863 DebugLoc dl = Op.getDebugLoc();
6865 SDValue N0 = Op.getOperand(0);
6866 SDValue N1 = Op.getOperand(1);
6867 SDValue N2 = Op.getOperand(2);
6869 if (VT.getSizeInBits() == 256)
6872 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6873 isa<ConstantSDNode>(N2)) {
6875 if (VT == MVT::v8i16)
6876 Opc = X86ISD::PINSRW;
6877 else if (VT == MVT::v16i8)
6878 Opc = X86ISD::PINSRB;
6880 Opc = X86ISD::PINSRB;
6882 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6884 if (N1.getValueType() != MVT::i32)
6885 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6886 if (N2.getValueType() != MVT::i32)
6887 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6888 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6889 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6890 // Bits [7:6] of the constant are the source select. This will always be
6891 // zero here. The DAG Combiner may combine an extract_elt index into these
6892 // bits. For example (insert (extract, 3), 2) could be matched by putting
6893 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6894 // Bits [5:4] of the constant are the destination select. This is the
6895 // value of the incoming immediate.
6896 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6897 // combine either bitwise AND or insert of float 0.0 to set these bits.
6898 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6899 // Create this as a scalar to vector..
6900 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6901 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6902 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6903 isa<ConstantSDNode>(N2)) {
6904 // PINSR* works with constant index.
6911 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6912 EVT VT = Op.getValueType();
6913 EVT EltVT = VT.getVectorElementType();
6915 DebugLoc dl = Op.getDebugLoc();
6916 SDValue N0 = Op.getOperand(0);
6917 SDValue N1 = Op.getOperand(1);
6918 SDValue N2 = Op.getOperand(2);
6920 // If this is a 256-bit vector result, first extract the 128-bit vector,
6921 // insert the element into the extracted half and then place it back.
6922 if (VT.getSizeInBits() == 256) {
6923 if (!isa<ConstantSDNode>(N2))
6926 // Get the desired 128-bit vector half.
6927 unsigned NumElems = VT.getVectorNumElements();
6928 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6929 bool Upper = IdxVal >= NumElems/2;
6930 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6931 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6933 // Insert the element into the desired half.
6934 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6935 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6937 // Insert the changed part back to the 256-bit vector
6938 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6941 if (Subtarget->hasSSE41orAVX())
6942 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6944 if (EltVT == MVT::i8)
6947 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6948 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6949 // as its second argument.
6950 if (N1.getValueType() != MVT::i32)
6951 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6952 if (N2.getValueType() != MVT::i32)
6953 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6954 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6960 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6961 LLVMContext *Context = DAG.getContext();
6962 DebugLoc dl = Op.getDebugLoc();
6963 EVT OpVT = Op.getValueType();
6965 // If this is a 256-bit vector result, first insert into a 128-bit
6966 // vector and then insert into the 256-bit vector.
6967 if (OpVT.getSizeInBits() > 128) {
6968 // Insert into a 128-bit vector.
6969 EVT VT128 = EVT::getVectorVT(*Context,
6970 OpVT.getVectorElementType(),
6971 OpVT.getVectorNumElements() / 2);
6973 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6975 // Insert the 128-bit vector.
6976 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6977 DAG.getConstant(0, MVT::i32),
6981 if (Op.getValueType() == MVT::v1i64 &&
6982 Op.getOperand(0).getValueType() == MVT::i64)
6983 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6985 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6986 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6987 "Expected an SSE type!");
6988 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6989 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6992 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6993 // a simple subregister reference or explicit instructions to grab
6994 // upper bits of a vector.
6996 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6997 if (Subtarget->hasAVX()) {
6998 DebugLoc dl = Op.getNode()->getDebugLoc();
6999 SDValue Vec = Op.getNode()->getOperand(0);
7000 SDValue Idx = Op.getNode()->getOperand(1);
7002 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7003 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7004 return Extract128BitVector(Vec, Idx, DAG, dl);
7010 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7011 // simple superregister reference or explicit instructions to insert
7012 // the upper bits of a vector.
7014 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7015 if (Subtarget->hasAVX()) {
7016 DebugLoc dl = Op.getNode()->getDebugLoc();
7017 SDValue Vec = Op.getNode()->getOperand(0);
7018 SDValue SubVec = Op.getNode()->getOperand(1);
7019 SDValue Idx = Op.getNode()->getOperand(2);
7021 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7022 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7023 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7029 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7030 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7031 // one of the above mentioned nodes. It has to be wrapped because otherwise
7032 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7033 // be used to form addressing mode. These wrapped nodes will be selected
7036 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7037 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7039 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7041 unsigned char OpFlag = 0;
7042 unsigned WrapperKind = X86ISD::Wrapper;
7043 CodeModel::Model M = getTargetMachine().getCodeModel();
7045 if (Subtarget->isPICStyleRIPRel() &&
7046 (M == CodeModel::Small || M == CodeModel::Kernel))
7047 WrapperKind = X86ISD::WrapperRIP;
7048 else if (Subtarget->isPICStyleGOT())
7049 OpFlag = X86II::MO_GOTOFF;
7050 else if (Subtarget->isPICStyleStubPIC())
7051 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7053 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7055 CP->getOffset(), OpFlag);
7056 DebugLoc DL = CP->getDebugLoc();
7057 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7058 // With PIC, the address is actually $g + Offset.
7060 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7061 DAG.getNode(X86ISD::GlobalBaseReg,
7062 DebugLoc(), getPointerTy()),
7069 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7070 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7072 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7074 unsigned char OpFlag = 0;
7075 unsigned WrapperKind = X86ISD::Wrapper;
7076 CodeModel::Model M = getTargetMachine().getCodeModel();
7078 if (Subtarget->isPICStyleRIPRel() &&
7079 (M == CodeModel::Small || M == CodeModel::Kernel))
7080 WrapperKind = X86ISD::WrapperRIP;
7081 else if (Subtarget->isPICStyleGOT())
7082 OpFlag = X86II::MO_GOTOFF;
7083 else if (Subtarget->isPICStyleStubPIC())
7084 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7086 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7088 DebugLoc DL = JT->getDebugLoc();
7089 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7091 // With PIC, the address is actually $g + Offset.
7093 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7094 DAG.getNode(X86ISD::GlobalBaseReg,
7095 DebugLoc(), getPointerTy()),
7102 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7103 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7105 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7107 unsigned char OpFlag = 0;
7108 unsigned WrapperKind = X86ISD::Wrapper;
7109 CodeModel::Model M = getTargetMachine().getCodeModel();
7111 if (Subtarget->isPICStyleRIPRel() &&
7112 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7113 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7114 OpFlag = X86II::MO_GOTPCREL;
7115 WrapperKind = X86ISD::WrapperRIP;
7116 } else if (Subtarget->isPICStyleGOT()) {
7117 OpFlag = X86II::MO_GOT;
7118 } else if (Subtarget->isPICStyleStubPIC()) {
7119 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7120 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7121 OpFlag = X86II::MO_DARWIN_NONLAZY;
7124 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7126 DebugLoc DL = Op.getDebugLoc();
7127 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7130 // With PIC, the address is actually $g + Offset.
7131 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7132 !Subtarget->is64Bit()) {
7133 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7134 DAG.getNode(X86ISD::GlobalBaseReg,
7135 DebugLoc(), getPointerTy()),
7139 // For symbols that require a load from a stub to get the address, emit the
7141 if (isGlobalStubReference(OpFlag))
7142 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7143 MachinePointerInfo::getGOT(), false, false, false, 0);
7149 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7150 // Create the TargetBlockAddressAddress node.
7151 unsigned char OpFlags =
7152 Subtarget->ClassifyBlockAddressReference();
7153 CodeModel::Model M = getTargetMachine().getCodeModel();
7154 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7155 DebugLoc dl = Op.getDebugLoc();
7156 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7157 /*isTarget=*/true, OpFlags);
7159 if (Subtarget->isPICStyleRIPRel() &&
7160 (M == CodeModel::Small || M == CodeModel::Kernel))
7161 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7163 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7165 // With PIC, the address is actually $g + Offset.
7166 if (isGlobalRelativeToPICBase(OpFlags)) {
7167 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7168 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7176 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7178 SelectionDAG &DAG) const {
7179 // Create the TargetGlobalAddress node, folding in the constant
7180 // offset if it is legal.
7181 unsigned char OpFlags =
7182 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7183 CodeModel::Model M = getTargetMachine().getCodeModel();
7185 if (OpFlags == X86II::MO_NO_FLAG &&
7186 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7187 // A direct static reference to a global.
7188 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7191 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7194 if (Subtarget->isPICStyleRIPRel() &&
7195 (M == CodeModel::Small || M == CodeModel::Kernel))
7196 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7198 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7200 // With PIC, the address is actually $g + Offset.
7201 if (isGlobalRelativeToPICBase(OpFlags)) {
7202 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7203 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7207 // For globals that require a load from a stub to get the address, emit the
7209 if (isGlobalStubReference(OpFlags))
7210 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7211 MachinePointerInfo::getGOT(), false, false, false, 0);
7213 // If there was a non-zero offset that we didn't fold, create an explicit
7216 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7217 DAG.getConstant(Offset, getPointerTy()));
7223 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7224 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7225 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7226 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7230 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7231 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7232 unsigned char OperandFlags) {
7233 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7234 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7235 DebugLoc dl = GA->getDebugLoc();
7236 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7237 GA->getValueType(0),
7241 SDValue Ops[] = { Chain, TGA, *InFlag };
7242 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7244 SDValue Ops[] = { Chain, TGA };
7245 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7248 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7249 MFI->setAdjustsStack(true);
7251 SDValue Flag = Chain.getValue(1);
7252 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7255 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7257 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7260 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7261 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7262 DAG.getNode(X86ISD::GlobalBaseReg,
7263 DebugLoc(), PtrVT), InFlag);
7264 InFlag = Chain.getValue(1);
7266 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7269 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7271 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7273 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7274 X86::RAX, X86II::MO_TLSGD);
7277 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7278 // "local exec" model.
7279 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7280 const EVT PtrVT, TLSModel::Model model,
7282 DebugLoc dl = GA->getDebugLoc();
7284 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7285 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7286 is64Bit ? 257 : 256));
7288 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7289 DAG.getIntPtrConstant(0),
7290 MachinePointerInfo(Ptr),
7291 false, false, false, 0);
7293 unsigned char OperandFlags = 0;
7294 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7296 unsigned WrapperKind = X86ISD::Wrapper;
7297 if (model == TLSModel::LocalExec) {
7298 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7299 } else if (is64Bit) {
7300 assert(model == TLSModel::InitialExec);
7301 OperandFlags = X86II::MO_GOTTPOFF;
7302 WrapperKind = X86ISD::WrapperRIP;
7304 assert(model == TLSModel::InitialExec);
7305 OperandFlags = X86II::MO_INDNTPOFF;
7308 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7310 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7311 GA->getValueType(0),
7312 GA->getOffset(), OperandFlags);
7313 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7315 if (model == TLSModel::InitialExec)
7316 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7317 MachinePointerInfo::getGOT(), false, false, false, 0);
7319 // The address of the thread local variable is the add of the thread
7320 // pointer with the offset of the variable.
7321 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7325 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7327 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7328 const GlobalValue *GV = GA->getGlobal();
7330 if (Subtarget->isTargetELF()) {
7331 // TODO: implement the "local dynamic" model
7332 // TODO: implement the "initial exec"model for pic executables
7334 // If GV is an alias then use the aliasee for determining
7335 // thread-localness.
7336 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7337 GV = GA->resolveAliasedGlobal(false);
7339 TLSModel::Model model
7340 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7343 case TLSModel::GeneralDynamic:
7344 case TLSModel::LocalDynamic: // not implemented
7345 if (Subtarget->is64Bit())
7346 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7347 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7349 case TLSModel::InitialExec:
7350 case TLSModel::LocalExec:
7351 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7352 Subtarget->is64Bit());
7354 } else if (Subtarget->isTargetDarwin()) {
7355 // Darwin only has one model of TLS. Lower to that.
7356 unsigned char OpFlag = 0;
7357 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7358 X86ISD::WrapperRIP : X86ISD::Wrapper;
7360 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7362 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7363 !Subtarget->is64Bit();
7365 OpFlag = X86II::MO_TLVP_PIC_BASE;
7367 OpFlag = X86II::MO_TLVP;
7368 DebugLoc DL = Op.getDebugLoc();
7369 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7370 GA->getValueType(0),
7371 GA->getOffset(), OpFlag);
7372 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7374 // With PIC32, the address is actually $g + Offset.
7376 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7377 DAG.getNode(X86ISD::GlobalBaseReg,
7378 DebugLoc(), getPointerTy()),
7381 // Lowering the machine isd will make sure everything is in the right
7383 SDValue Chain = DAG.getEntryNode();
7384 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7385 SDValue Args[] = { Chain, Offset };
7386 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7388 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7389 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7390 MFI->setAdjustsStack(true);
7392 // And our return value (tls address) is in the standard call return value
7394 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7395 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7400 "TLS not implemented for this target.");
7402 llvm_unreachable("Unreachable");
7407 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7408 /// take a 2 x i32 value to shift plus a shift amount.
7409 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7410 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7411 EVT VT = Op.getValueType();
7412 unsigned VTBits = VT.getSizeInBits();
7413 DebugLoc dl = Op.getDebugLoc();
7414 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7415 SDValue ShOpLo = Op.getOperand(0);
7416 SDValue ShOpHi = Op.getOperand(1);
7417 SDValue ShAmt = Op.getOperand(2);
7418 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7419 DAG.getConstant(VTBits - 1, MVT::i8))
7420 : DAG.getConstant(0, VT);
7423 if (Op.getOpcode() == ISD::SHL_PARTS) {
7424 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7425 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7427 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7428 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7431 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7432 DAG.getConstant(VTBits, MVT::i8));
7433 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7434 AndNode, DAG.getConstant(0, MVT::i8));
7437 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7438 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7439 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7441 if (Op.getOpcode() == ISD::SHL_PARTS) {
7442 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7443 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7445 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7446 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7449 SDValue Ops[2] = { Lo, Hi };
7450 return DAG.getMergeValues(Ops, 2, dl);
7453 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7454 SelectionDAG &DAG) const {
7455 EVT SrcVT = Op.getOperand(0).getValueType();
7457 if (SrcVT.isVector())
7460 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7461 "Unknown SINT_TO_FP to lower!");
7463 // These are really Legal; return the operand so the caller accepts it as
7465 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7467 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7468 Subtarget->is64Bit()) {
7472 DebugLoc dl = Op.getDebugLoc();
7473 unsigned Size = SrcVT.getSizeInBits()/8;
7474 MachineFunction &MF = DAG.getMachineFunction();
7475 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7476 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7477 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7479 MachinePointerInfo::getFixedStack(SSFI),
7481 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7484 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7486 SelectionDAG &DAG) const {
7488 DebugLoc DL = Op.getDebugLoc();
7490 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7492 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7494 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7496 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7498 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7499 MachineMemOperand *MMO;
7501 int SSFI = FI->getIndex();
7503 DAG.getMachineFunction()
7504 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7505 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7507 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7508 StackSlot = StackSlot.getOperand(1);
7510 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7511 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7513 Tys, Ops, array_lengthof(Ops),
7517 Chain = Result.getValue(1);
7518 SDValue InFlag = Result.getValue(2);
7520 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7521 // shouldn't be necessary except that RFP cannot be live across
7522 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7523 MachineFunction &MF = DAG.getMachineFunction();
7524 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7525 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7526 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7527 Tys = DAG.getVTList(MVT::Other);
7529 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7531 MachineMemOperand *MMO =
7532 DAG.getMachineFunction()
7533 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7534 MachineMemOperand::MOStore, SSFISize, SSFISize);
7536 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7537 Ops, array_lengthof(Ops),
7538 Op.getValueType(), MMO);
7539 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7540 MachinePointerInfo::getFixedStack(SSFI),
7541 false, false, false, 0);
7547 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7548 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7549 SelectionDAG &DAG) const {
7550 // This algorithm is not obvious. Here it is in C code, more or less:
7552 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7553 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7554 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7556 // Copy ints to xmm registers.
7557 __m128i xh = _mm_cvtsi32_si128( hi );
7558 __m128i xl = _mm_cvtsi32_si128( lo );
7560 // Combine into low half of a single xmm register.
7561 __m128i x = _mm_unpacklo_epi32( xh, xl );
7565 // Merge in appropriate exponents to give the integer bits the right
7567 x = _mm_unpacklo_epi32( x, exp );
7569 // Subtract away the biases to deal with the IEEE-754 double precision
7571 d = _mm_sub_pd( (__m128d) x, bias );
7573 // All conversions up to here are exact. The correctly rounded result is
7574 // calculated using the current rounding mode using the following
7576 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7577 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7578 // store doesn't really need to be here (except
7579 // maybe to zero the other double)
7584 DebugLoc dl = Op.getDebugLoc();
7585 LLVMContext *Context = DAG.getContext();
7587 // Build some magic constants.
7588 std::vector<Constant*> CV0;
7589 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7590 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7591 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7592 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7593 Constant *C0 = ConstantVector::get(CV0);
7594 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7596 std::vector<Constant*> CV1;
7598 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7600 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7601 Constant *C1 = ConstantVector::get(CV1);
7602 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7604 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7605 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7607 DAG.getIntPtrConstant(1)));
7608 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7609 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7611 DAG.getIntPtrConstant(0)));
7612 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7613 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7614 MachinePointerInfo::getConstantPool(),
7615 false, false, false, 16);
7616 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7617 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7618 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7619 MachinePointerInfo::getConstantPool(),
7620 false, false, false, 16);
7621 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7623 // Add the halves; easiest way is to swap them into another reg first.
7624 int ShufMask[2] = { 1, -1 };
7625 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7626 DAG.getUNDEF(MVT::v2f64), ShufMask);
7627 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7629 DAG.getIntPtrConstant(0));
7632 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7633 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7634 SelectionDAG &DAG) const {
7635 DebugLoc dl = Op.getDebugLoc();
7636 // FP constant to bias correct the final result.
7637 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7640 // Load the 32-bit value into an XMM register.
7641 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7644 // Zero out the upper parts of the register.
7645 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7648 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7649 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7650 DAG.getIntPtrConstant(0));
7652 // Or the load with the bias.
7653 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7654 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7655 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7657 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7658 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7659 MVT::v2f64, Bias)));
7660 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7661 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7662 DAG.getIntPtrConstant(0));
7664 // Subtract the bias.
7665 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7667 // Handle final rounding.
7668 EVT DestVT = Op.getValueType();
7670 if (DestVT.bitsLT(MVT::f64)) {
7671 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7672 DAG.getIntPtrConstant(0));
7673 } else if (DestVT.bitsGT(MVT::f64)) {
7674 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7677 // Handle final rounding.
7681 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7682 SelectionDAG &DAG) const {
7683 SDValue N0 = Op.getOperand(0);
7684 DebugLoc dl = Op.getDebugLoc();
7686 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7687 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7688 // the optimization here.
7689 if (DAG.SignBitIsZero(N0))
7690 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7692 EVT SrcVT = N0.getValueType();
7693 EVT DstVT = Op.getValueType();
7694 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7695 return LowerUINT_TO_FP_i64(Op, DAG);
7696 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7697 return LowerUINT_TO_FP_i32(Op, DAG);
7699 // Make a 64-bit buffer, and use it to build an FILD.
7700 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7701 if (SrcVT == MVT::i32) {
7702 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7703 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7704 getPointerTy(), StackSlot, WordOff);
7705 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7706 StackSlot, MachinePointerInfo(),
7708 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7709 OffsetSlot, MachinePointerInfo(),
7711 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7715 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7716 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7717 StackSlot, MachinePointerInfo(),
7719 // For i64 source, we need to add the appropriate power of 2 if the input
7720 // was negative. This is the same as the optimization in
7721 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7722 // we must be careful to do the computation in x87 extended precision, not
7723 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7724 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7725 MachineMemOperand *MMO =
7726 DAG.getMachineFunction()
7727 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7728 MachineMemOperand::MOLoad, 8, 8);
7730 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7731 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7732 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7735 APInt FF(32, 0x5F800000ULL);
7737 // Check whether the sign bit is set.
7738 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7739 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7742 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7743 SDValue FudgePtr = DAG.getConstantPool(
7744 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7747 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7748 SDValue Zero = DAG.getIntPtrConstant(0);
7749 SDValue Four = DAG.getIntPtrConstant(4);
7750 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7752 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7754 // Load the value out, extending it from f32 to f80.
7755 // FIXME: Avoid the extend by constructing the right constant pool?
7756 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7757 FudgePtr, MachinePointerInfo::getConstantPool(),
7758 MVT::f32, false, false, 4);
7759 // Extend everything to 80 bits to force it to be done on x87.
7760 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7761 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7764 std::pair<SDValue,SDValue> X86TargetLowering::
7765 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7766 DebugLoc DL = Op.getDebugLoc();
7768 EVT DstTy = Op.getValueType();
7771 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7775 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7776 DstTy.getSimpleVT() >= MVT::i16 &&
7777 "Unknown FP_TO_SINT to lower!");
7779 // These are really Legal.
7780 if (DstTy == MVT::i32 &&
7781 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7782 return std::make_pair(SDValue(), SDValue());
7783 if (Subtarget->is64Bit() &&
7784 DstTy == MVT::i64 &&
7785 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7786 return std::make_pair(SDValue(), SDValue());
7788 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7790 MachineFunction &MF = DAG.getMachineFunction();
7791 unsigned MemSize = DstTy.getSizeInBits()/8;
7792 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7793 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7798 switch (DstTy.getSimpleVT().SimpleTy) {
7799 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7800 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7801 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7802 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7805 SDValue Chain = DAG.getEntryNode();
7806 SDValue Value = Op.getOperand(0);
7807 EVT TheVT = Op.getOperand(0).getValueType();
7808 if (isScalarFPTypeInSSEReg(TheVT)) {
7809 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7810 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7811 MachinePointerInfo::getFixedStack(SSFI),
7813 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7815 Chain, StackSlot, DAG.getValueType(TheVT)
7818 MachineMemOperand *MMO =
7819 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7820 MachineMemOperand::MOLoad, MemSize, MemSize);
7821 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7823 Chain = Value.getValue(1);
7824 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7825 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7828 MachineMemOperand *MMO =
7829 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7830 MachineMemOperand::MOStore, MemSize, MemSize);
7832 // Build the FP_TO_INT*_IN_MEM
7833 SDValue Ops[] = { Chain, Value, StackSlot };
7834 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7835 Ops, 3, DstTy, MMO);
7837 return std::make_pair(FIST, StackSlot);
7840 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7841 SelectionDAG &DAG) const {
7842 if (Op.getValueType().isVector())
7845 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7846 SDValue FIST = Vals.first, StackSlot = Vals.second;
7847 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7848 if (FIST.getNode() == 0) return Op;
7851 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7852 FIST, StackSlot, MachinePointerInfo(),
7853 false, false, false, 0);
7856 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7857 SelectionDAG &DAG) const {
7858 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7859 SDValue FIST = Vals.first, StackSlot = Vals.second;
7860 assert(FIST.getNode() && "Unexpected failure");
7863 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7864 FIST, StackSlot, MachinePointerInfo(),
7865 false, false, false, 0);
7868 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7869 SelectionDAG &DAG) const {
7870 LLVMContext *Context = DAG.getContext();
7871 DebugLoc dl = Op.getDebugLoc();
7872 EVT VT = Op.getValueType();
7875 EltVT = VT.getVectorElementType();
7876 std::vector<Constant*> CV;
7877 if (EltVT == MVT::f64) {
7878 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7882 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7888 Constant *C = ConstantVector::get(CV);
7889 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7890 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7891 MachinePointerInfo::getConstantPool(),
7892 false, false, false, 16);
7893 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7896 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7897 LLVMContext *Context = DAG.getContext();
7898 DebugLoc dl = Op.getDebugLoc();
7899 EVT VT = Op.getValueType();
7902 EltVT = VT.getVectorElementType();
7903 std::vector<Constant*> CV;
7904 if (EltVT == MVT::f64) {
7905 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7909 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7915 Constant *C = ConstantVector::get(CV);
7916 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7917 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7918 MachinePointerInfo::getConstantPool(),
7919 false, false, false, 16);
7920 if (VT.isVector()) {
7921 return DAG.getNode(ISD::BITCAST, dl, VT,
7922 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7923 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7925 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7927 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7931 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7932 LLVMContext *Context = DAG.getContext();
7933 SDValue Op0 = Op.getOperand(0);
7934 SDValue Op1 = Op.getOperand(1);
7935 DebugLoc dl = Op.getDebugLoc();
7936 EVT VT = Op.getValueType();
7937 EVT SrcVT = Op1.getValueType();
7939 // If second operand is smaller, extend it first.
7940 if (SrcVT.bitsLT(VT)) {
7941 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7944 // And if it is bigger, shrink it first.
7945 if (SrcVT.bitsGT(VT)) {
7946 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7950 // At this point the operands and the result should have the same
7951 // type, and that won't be f80 since that is not custom lowered.
7953 // First get the sign bit of second operand.
7954 std::vector<Constant*> CV;
7955 if (SrcVT == MVT::f64) {
7956 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7957 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7959 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7960 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7961 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7962 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7964 Constant *C = ConstantVector::get(CV);
7965 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7966 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7967 MachinePointerInfo::getConstantPool(),
7968 false, false, false, 16);
7969 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7971 // Shift sign bit right or left if the two operands have different types.
7972 if (SrcVT.bitsGT(VT)) {
7973 // Op0 is MVT::f32, Op1 is MVT::f64.
7974 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7975 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7976 DAG.getConstant(32, MVT::i32));
7977 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7978 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7979 DAG.getIntPtrConstant(0));
7982 // Clear first operand sign bit.
7984 if (VT == MVT::f64) {
7985 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7986 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7988 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7989 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7990 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7991 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7993 C = ConstantVector::get(CV);
7994 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7995 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7996 MachinePointerInfo::getConstantPool(),
7997 false, false, false, 16);
7998 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8000 // Or the value with the sign bit.
8001 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8004 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8005 SDValue N0 = Op.getOperand(0);
8006 DebugLoc dl = Op.getDebugLoc();
8007 EVT VT = Op.getValueType();
8009 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8010 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8011 DAG.getConstant(1, VT));
8012 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8015 /// Emit nodes that will be selected as "test Op0,Op0", or something
8017 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8018 SelectionDAG &DAG) const {
8019 DebugLoc dl = Op.getDebugLoc();
8021 // CF and OF aren't always set the way we want. Determine which
8022 // of these we need.
8023 bool NeedCF = false;
8024 bool NeedOF = false;
8027 case X86::COND_A: case X86::COND_AE:
8028 case X86::COND_B: case X86::COND_BE:
8031 case X86::COND_G: case X86::COND_GE:
8032 case X86::COND_L: case X86::COND_LE:
8033 case X86::COND_O: case X86::COND_NO:
8038 // See if we can use the EFLAGS value from the operand instead of
8039 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8040 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8041 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8042 // Emit a CMP with 0, which is the TEST pattern.
8043 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8044 DAG.getConstant(0, Op.getValueType()));
8046 unsigned Opcode = 0;
8047 unsigned NumOperands = 0;
8048 switch (Op.getNode()->getOpcode()) {
8050 // Due to an isel shortcoming, be conservative if this add is likely to be
8051 // selected as part of a load-modify-store instruction. When the root node
8052 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8053 // uses of other nodes in the match, such as the ADD in this case. This
8054 // leads to the ADD being left around and reselected, with the result being
8055 // two adds in the output. Alas, even if none our users are stores, that
8056 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8057 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8058 // climbing the DAG back to the root, and it doesn't seem to be worth the
8060 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8061 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8062 if (UI->getOpcode() != ISD::CopyToReg &&
8063 UI->getOpcode() != ISD::SETCC &&
8064 UI->getOpcode() != ISD::STORE)
8067 if (ConstantSDNode *C =
8068 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8069 // An add of one will be selected as an INC.
8070 if (C->getAPIntValue() == 1) {
8071 Opcode = X86ISD::INC;
8076 // An add of negative one (subtract of one) will be selected as a DEC.
8077 if (C->getAPIntValue().isAllOnesValue()) {
8078 Opcode = X86ISD::DEC;
8084 // Otherwise use a regular EFLAGS-setting add.
8085 Opcode = X86ISD::ADD;
8089 // If the primary and result isn't used, don't bother using X86ISD::AND,
8090 // because a TEST instruction will be better.
8091 bool NonFlagUse = false;
8092 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8093 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8095 unsigned UOpNo = UI.getOperandNo();
8096 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8097 // Look pass truncate.
8098 UOpNo = User->use_begin().getOperandNo();
8099 User = *User->use_begin();
8102 if (User->getOpcode() != ISD::BRCOND &&
8103 User->getOpcode() != ISD::SETCC &&
8104 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8117 // Due to the ISEL shortcoming noted above, be conservative if this op is
8118 // likely to be selected as part of a load-modify-store instruction.
8119 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8120 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8121 if (UI->getOpcode() == ISD::STORE)
8124 // Otherwise use a regular EFLAGS-setting instruction.
8125 switch (Op.getNode()->getOpcode()) {
8126 default: llvm_unreachable("unexpected operator!");
8127 case ISD::SUB: Opcode = X86ISD::SUB; break;
8128 case ISD::OR: Opcode = X86ISD::OR; break;
8129 case ISD::XOR: Opcode = X86ISD::XOR; break;
8130 case ISD::AND: Opcode = X86ISD::AND; break;
8142 return SDValue(Op.getNode(), 1);
8149 // Emit a CMP with 0, which is the TEST pattern.
8150 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8151 DAG.getConstant(0, Op.getValueType()));
8153 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8154 SmallVector<SDValue, 4> Ops;
8155 for (unsigned i = 0; i != NumOperands; ++i)
8156 Ops.push_back(Op.getOperand(i));
8158 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8159 DAG.ReplaceAllUsesWith(Op, New);
8160 return SDValue(New.getNode(), 1);
8163 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8165 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8166 SelectionDAG &DAG) const {
8167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8168 if (C->getAPIntValue() == 0)
8169 return EmitTest(Op0, X86CC, DAG);
8171 DebugLoc dl = Op0.getDebugLoc();
8172 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8175 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8176 /// if it's possible.
8177 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8178 DebugLoc dl, SelectionDAG &DAG) const {
8179 SDValue Op0 = And.getOperand(0);
8180 SDValue Op1 = And.getOperand(1);
8181 if (Op0.getOpcode() == ISD::TRUNCATE)
8182 Op0 = Op0.getOperand(0);
8183 if (Op1.getOpcode() == ISD::TRUNCATE)
8184 Op1 = Op1.getOperand(0);
8187 if (Op1.getOpcode() == ISD::SHL)
8188 std::swap(Op0, Op1);
8189 if (Op0.getOpcode() == ISD::SHL) {
8190 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8191 if (And00C->getZExtValue() == 1) {
8192 // If we looked past a truncate, check that it's only truncating away
8194 unsigned BitWidth = Op0.getValueSizeInBits();
8195 unsigned AndBitWidth = And.getValueSizeInBits();
8196 if (BitWidth > AndBitWidth) {
8197 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8198 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8199 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8203 RHS = Op0.getOperand(1);
8205 } else if (Op1.getOpcode() == ISD::Constant) {
8206 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8207 uint64_t AndRHSVal = AndRHS->getZExtValue();
8208 SDValue AndLHS = Op0;
8210 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8211 LHS = AndLHS.getOperand(0);
8212 RHS = AndLHS.getOperand(1);
8215 // Use BT if the immediate can't be encoded in a TEST instruction.
8216 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8218 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8222 if (LHS.getNode()) {
8223 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8224 // instruction. Since the shift amount is in-range-or-undefined, we know
8225 // that doing a bittest on the i32 value is ok. We extend to i32 because
8226 // the encoding for the i16 version is larger than the i32 version.
8227 // Also promote i16 to i32 for performance / code size reason.
8228 if (LHS.getValueType() == MVT::i8 ||
8229 LHS.getValueType() == MVT::i16)
8230 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8232 // If the operand types disagree, extend the shift amount to match. Since
8233 // BT ignores high bits (like shifts) we can use anyextend.
8234 if (LHS.getValueType() != RHS.getValueType())
8235 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8237 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8238 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8239 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8240 DAG.getConstant(Cond, MVT::i8), BT);
8246 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8248 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8250 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8251 SDValue Op0 = Op.getOperand(0);
8252 SDValue Op1 = Op.getOperand(1);
8253 DebugLoc dl = Op.getDebugLoc();
8254 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8256 // Optimize to BT if possible.
8257 // Lower (X & (1 << N)) == 0 to BT(X, N).
8258 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8259 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8260 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8261 Op1.getOpcode() == ISD::Constant &&
8262 cast<ConstantSDNode>(Op1)->isNullValue() &&
8263 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8264 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8265 if (NewSetCC.getNode())
8269 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8271 if (Op1.getOpcode() == ISD::Constant &&
8272 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8273 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8274 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8276 // If the input is a setcc, then reuse the input setcc or use a new one with
8277 // the inverted condition.
8278 if (Op0.getOpcode() == X86ISD::SETCC) {
8279 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8280 bool Invert = (CC == ISD::SETNE) ^
8281 cast<ConstantSDNode>(Op1)->isNullValue();
8282 if (!Invert) return Op0;
8284 CCode = X86::GetOppositeBranchCondition(CCode);
8285 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8286 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8290 bool isFP = Op1.getValueType().isFloatingPoint();
8291 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8292 if (X86CC == X86::COND_INVALID)
8295 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8296 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8297 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8300 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8301 // ones, and then concatenate the result back.
8302 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8303 EVT VT = Op.getValueType();
8305 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8306 "Unsupported value type for operation");
8308 int NumElems = VT.getVectorNumElements();
8309 DebugLoc dl = Op.getDebugLoc();
8310 SDValue CC = Op.getOperand(2);
8311 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8312 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8314 // Extract the LHS vectors
8315 SDValue LHS = Op.getOperand(0);
8316 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8317 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8319 // Extract the RHS vectors
8320 SDValue RHS = Op.getOperand(1);
8321 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8322 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8324 // Issue the operation on the smaller types and concatenate the result back
8325 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8326 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8327 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8328 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8329 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8333 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8335 SDValue Op0 = Op.getOperand(0);
8336 SDValue Op1 = Op.getOperand(1);
8337 SDValue CC = Op.getOperand(2);
8338 EVT VT = Op.getValueType();
8339 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8340 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8341 DebugLoc dl = Op.getDebugLoc();
8345 EVT EltVT = Op0.getValueType().getVectorElementType();
8346 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8348 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8351 // SSE Condition code mapping:
8360 switch (SetCCOpcode) {
8363 case ISD::SETEQ: SSECC = 0; break;
8365 case ISD::SETGT: Swap = true; // Fallthrough
8367 case ISD::SETOLT: SSECC = 1; break;
8369 case ISD::SETGE: Swap = true; // Fallthrough
8371 case ISD::SETOLE: SSECC = 2; break;
8372 case ISD::SETUO: SSECC = 3; break;
8374 case ISD::SETNE: SSECC = 4; break;
8375 case ISD::SETULE: Swap = true;
8376 case ISD::SETUGE: SSECC = 5; break;
8377 case ISD::SETULT: Swap = true;
8378 case ISD::SETUGT: SSECC = 6; break;
8379 case ISD::SETO: SSECC = 7; break;
8382 std::swap(Op0, Op1);
8384 // In the two special cases we can't handle, emit two comparisons.
8386 if (SetCCOpcode == ISD::SETUEQ) {
8388 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8389 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8390 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8391 } else if (SetCCOpcode == ISD::SETONE) {
8393 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8394 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8395 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8397 llvm_unreachable("Illegal FP comparison");
8399 // Handle all other FP comparisons here.
8400 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8403 // Break 256-bit integer vector compare into smaller ones.
8404 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8405 return Lower256IntVSETCC(Op, DAG);
8407 // We are handling one of the integer comparisons here. Since SSE only has
8408 // GT and EQ comparisons for integer, swapping operands and multiple
8409 // operations may be required for some comparisons.
8410 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8411 bool Swap = false, Invert = false, FlipSigns = false;
8413 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8415 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8416 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8417 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8418 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8421 switch (SetCCOpcode) {
8423 case ISD::SETNE: Invert = true;
8424 case ISD::SETEQ: Opc = EQOpc; break;
8425 case ISD::SETLT: Swap = true;
8426 case ISD::SETGT: Opc = GTOpc; break;
8427 case ISD::SETGE: Swap = true;
8428 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8429 case ISD::SETULT: Swap = true;
8430 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8431 case ISD::SETUGE: Swap = true;
8432 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8435 std::swap(Op0, Op1);
8437 // Check that the operation in question is available (most are plain SSE2,
8438 // but PCMPGTQ and PCMPEQQ have different requirements).
8439 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8441 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8444 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8445 // bits of the inputs before performing those operations.
8447 EVT EltVT = VT.getVectorElementType();
8448 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8450 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8451 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8453 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8454 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8457 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8459 // If the logical-not of the result is required, perform that now.
8461 Result = DAG.getNOT(dl, Result, VT);
8466 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8467 static bool isX86LogicalCmp(SDValue Op) {
8468 unsigned Opc = Op.getNode()->getOpcode();
8469 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8471 if (Op.getResNo() == 1 &&
8472 (Opc == X86ISD::ADD ||
8473 Opc == X86ISD::SUB ||
8474 Opc == X86ISD::ADC ||
8475 Opc == X86ISD::SBB ||
8476 Opc == X86ISD::SMUL ||
8477 Opc == X86ISD::UMUL ||
8478 Opc == X86ISD::INC ||
8479 Opc == X86ISD::DEC ||
8480 Opc == X86ISD::OR ||
8481 Opc == X86ISD::XOR ||
8482 Opc == X86ISD::AND))
8485 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8491 static bool isZero(SDValue V) {
8492 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8493 return C && C->isNullValue();
8496 static bool isAllOnes(SDValue V) {
8497 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8498 return C && C->isAllOnesValue();
8501 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8502 bool addTest = true;
8503 SDValue Cond = Op.getOperand(0);
8504 SDValue Op1 = Op.getOperand(1);
8505 SDValue Op2 = Op.getOperand(2);
8506 DebugLoc DL = Op.getDebugLoc();
8509 if (Cond.getOpcode() == ISD::SETCC) {
8510 SDValue NewCond = LowerSETCC(Cond, DAG);
8511 if (NewCond.getNode())
8515 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8516 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8517 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8518 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8519 if (Cond.getOpcode() == X86ISD::SETCC &&
8520 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8521 isZero(Cond.getOperand(1).getOperand(1))) {
8522 SDValue Cmp = Cond.getOperand(1);
8524 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8526 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8527 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8528 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8530 SDValue CmpOp0 = Cmp.getOperand(0);
8531 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8532 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8534 SDValue Res = // Res = 0 or -1.
8535 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8536 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8538 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8539 Res = DAG.getNOT(DL, Res, Res.getValueType());
8541 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8542 if (N2C == 0 || !N2C->isNullValue())
8543 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8548 // Look past (and (setcc_carry (cmp ...)), 1).
8549 if (Cond.getOpcode() == ISD::AND &&
8550 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8551 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8552 if (C && C->getAPIntValue() == 1)
8553 Cond = Cond.getOperand(0);
8556 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8557 // setting operand in place of the X86ISD::SETCC.
8558 unsigned CondOpcode = Cond.getOpcode();
8559 if (CondOpcode == X86ISD::SETCC ||
8560 CondOpcode == X86ISD::SETCC_CARRY) {
8561 CC = Cond.getOperand(0);
8563 SDValue Cmp = Cond.getOperand(1);
8564 unsigned Opc = Cmp.getOpcode();
8565 EVT VT = Op.getValueType();
8567 bool IllegalFPCMov = false;
8568 if (VT.isFloatingPoint() && !VT.isVector() &&
8569 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8570 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8572 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8573 Opc == X86ISD::BT) { // FIXME
8577 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8578 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8579 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8580 Cond.getOperand(0).getValueType() != MVT::i8)) {
8581 SDValue LHS = Cond.getOperand(0);
8582 SDValue RHS = Cond.getOperand(1);
8586 switch (CondOpcode) {
8587 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8588 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8589 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8590 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8591 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8592 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8593 default: llvm_unreachable("unexpected overflowing operator");
8595 if (CondOpcode == ISD::UMULO)
8596 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8599 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8601 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8603 if (CondOpcode == ISD::UMULO)
8604 Cond = X86Op.getValue(2);
8606 Cond = X86Op.getValue(1);
8608 CC = DAG.getConstant(X86Cond, MVT::i8);
8613 // Look pass the truncate.
8614 if (Cond.getOpcode() == ISD::TRUNCATE)
8615 Cond = Cond.getOperand(0);
8617 // We know the result of AND is compared against zero. Try to match
8619 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8620 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8621 if (NewSetCC.getNode()) {
8622 CC = NewSetCC.getOperand(0);
8623 Cond = NewSetCC.getOperand(1);
8630 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8631 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8634 // a < b ? -1 : 0 -> RES = ~setcc_carry
8635 // a < b ? 0 : -1 -> RES = setcc_carry
8636 // a >= b ? -1 : 0 -> RES = setcc_carry
8637 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8638 if (Cond.getOpcode() == X86ISD::CMP) {
8639 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8641 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8642 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8643 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8644 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8645 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8646 return DAG.getNOT(DL, Res, Res.getValueType());
8651 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8652 // condition is true.
8653 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8654 SDValue Ops[] = { Op2, Op1, CC, Cond };
8655 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8658 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8659 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8660 // from the AND / OR.
8661 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8662 Opc = Op.getOpcode();
8663 if (Opc != ISD::OR && Opc != ISD::AND)
8665 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8666 Op.getOperand(0).hasOneUse() &&
8667 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8668 Op.getOperand(1).hasOneUse());
8671 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8672 // 1 and that the SETCC node has a single use.
8673 static bool isXor1OfSetCC(SDValue Op) {
8674 if (Op.getOpcode() != ISD::XOR)
8676 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8677 if (N1C && N1C->getAPIntValue() == 1) {
8678 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8679 Op.getOperand(0).hasOneUse();
8684 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8685 bool addTest = true;
8686 SDValue Chain = Op.getOperand(0);
8687 SDValue Cond = Op.getOperand(1);
8688 SDValue Dest = Op.getOperand(2);
8689 DebugLoc dl = Op.getDebugLoc();
8691 bool Inverted = false;
8693 if (Cond.getOpcode() == ISD::SETCC) {
8694 // Check for setcc([su]{add,sub,mul}o == 0).
8695 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8696 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8697 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8698 Cond.getOperand(0).getResNo() == 1 &&
8699 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8700 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8701 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8702 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8703 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8704 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8706 Cond = Cond.getOperand(0);
8708 SDValue NewCond = LowerSETCC(Cond, DAG);
8709 if (NewCond.getNode())
8714 // FIXME: LowerXALUO doesn't handle these!!
8715 else if (Cond.getOpcode() == X86ISD::ADD ||
8716 Cond.getOpcode() == X86ISD::SUB ||
8717 Cond.getOpcode() == X86ISD::SMUL ||
8718 Cond.getOpcode() == X86ISD::UMUL)
8719 Cond = LowerXALUO(Cond, DAG);
8722 // Look pass (and (setcc_carry (cmp ...)), 1).
8723 if (Cond.getOpcode() == ISD::AND &&
8724 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8726 if (C && C->getAPIntValue() == 1)
8727 Cond = Cond.getOperand(0);
8730 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8731 // setting operand in place of the X86ISD::SETCC.
8732 unsigned CondOpcode = Cond.getOpcode();
8733 if (CondOpcode == X86ISD::SETCC ||
8734 CondOpcode == X86ISD::SETCC_CARRY) {
8735 CC = Cond.getOperand(0);
8737 SDValue Cmp = Cond.getOperand(1);
8738 unsigned Opc = Cmp.getOpcode();
8739 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8740 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8744 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8748 // These can only come from an arithmetic instruction with overflow,
8749 // e.g. SADDO, UADDO.
8750 Cond = Cond.getNode()->getOperand(1);
8756 CondOpcode = Cond.getOpcode();
8757 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8758 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8759 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8760 Cond.getOperand(0).getValueType() != MVT::i8)) {
8761 SDValue LHS = Cond.getOperand(0);
8762 SDValue RHS = Cond.getOperand(1);
8766 switch (CondOpcode) {
8767 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8768 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8769 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8770 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8771 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8772 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8773 default: llvm_unreachable("unexpected overflowing operator");
8776 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8777 if (CondOpcode == ISD::UMULO)
8778 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8781 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8783 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8785 if (CondOpcode == ISD::UMULO)
8786 Cond = X86Op.getValue(2);
8788 Cond = X86Op.getValue(1);
8790 CC = DAG.getConstant(X86Cond, MVT::i8);
8794 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8795 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8796 if (CondOpc == ISD::OR) {
8797 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8798 // two branches instead of an explicit OR instruction with a
8800 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8801 isX86LogicalCmp(Cmp)) {
8802 CC = Cond.getOperand(0).getOperand(0);
8803 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8804 Chain, Dest, CC, Cmp);
8805 CC = Cond.getOperand(1).getOperand(0);
8809 } else { // ISD::AND
8810 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8811 // two branches instead of an explicit AND instruction with a
8812 // separate test. However, we only do this if this block doesn't
8813 // have a fall-through edge, because this requires an explicit
8814 // jmp when the condition is false.
8815 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8816 isX86LogicalCmp(Cmp) &&
8817 Op.getNode()->hasOneUse()) {
8818 X86::CondCode CCode =
8819 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8820 CCode = X86::GetOppositeBranchCondition(CCode);
8821 CC = DAG.getConstant(CCode, MVT::i8);
8822 SDNode *User = *Op.getNode()->use_begin();
8823 // Look for an unconditional branch following this conditional branch.
8824 // We need this because we need to reverse the successors in order
8825 // to implement FCMP_OEQ.
8826 if (User->getOpcode() == ISD::BR) {
8827 SDValue FalseBB = User->getOperand(1);
8829 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8830 assert(NewBR == User);
8834 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8835 Chain, Dest, CC, Cmp);
8836 X86::CondCode CCode =
8837 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8838 CCode = X86::GetOppositeBranchCondition(CCode);
8839 CC = DAG.getConstant(CCode, MVT::i8);
8845 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8846 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8847 // It should be transformed during dag combiner except when the condition
8848 // is set by a arithmetics with overflow node.
8849 X86::CondCode CCode =
8850 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8851 CCode = X86::GetOppositeBranchCondition(CCode);
8852 CC = DAG.getConstant(CCode, MVT::i8);
8853 Cond = Cond.getOperand(0).getOperand(1);
8855 } else if (Cond.getOpcode() == ISD::SETCC &&
8856 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8857 // For FCMP_OEQ, we can emit
8858 // two branches instead of an explicit AND instruction with a
8859 // separate test. However, we only do this if this block doesn't
8860 // have a fall-through edge, because this requires an explicit
8861 // jmp when the condition is false.
8862 if (Op.getNode()->hasOneUse()) {
8863 SDNode *User = *Op.getNode()->use_begin();
8864 // Look for an unconditional branch following this conditional branch.
8865 // We need this because we need to reverse the successors in order
8866 // to implement FCMP_OEQ.
8867 if (User->getOpcode() == ISD::BR) {
8868 SDValue FalseBB = User->getOperand(1);
8870 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8871 assert(NewBR == User);
8875 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8876 Cond.getOperand(0), Cond.getOperand(1));
8877 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8878 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8879 Chain, Dest, CC, Cmp);
8880 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8885 } else if (Cond.getOpcode() == ISD::SETCC &&
8886 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8887 // For FCMP_UNE, we can emit
8888 // two branches instead of an explicit AND instruction with a
8889 // separate test. However, we only do this if this block doesn't
8890 // have a fall-through edge, because this requires an explicit
8891 // jmp when the condition is false.
8892 if (Op.getNode()->hasOneUse()) {
8893 SDNode *User = *Op.getNode()->use_begin();
8894 // Look for an unconditional branch following this conditional branch.
8895 // We need this because we need to reverse the successors in order
8896 // to implement FCMP_UNE.
8897 if (User->getOpcode() == ISD::BR) {
8898 SDValue FalseBB = User->getOperand(1);
8900 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8901 assert(NewBR == User);
8904 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8905 Cond.getOperand(0), Cond.getOperand(1));
8906 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8907 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8908 Chain, Dest, CC, Cmp);
8909 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8919 // Look pass the truncate.
8920 if (Cond.getOpcode() == ISD::TRUNCATE)
8921 Cond = Cond.getOperand(0);
8923 // We know the result of AND is compared against zero. Try to match
8925 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8926 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8927 if (NewSetCC.getNode()) {
8928 CC = NewSetCC.getOperand(0);
8929 Cond = NewSetCC.getOperand(1);
8936 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8937 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8939 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8940 Chain, Dest, CC, Cond);
8944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8945 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8947 // that the guard pages used by the OS virtual memory manager are allocated in
8948 // correct sequence.
8950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8951 SelectionDAG &DAG) const {
8952 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8953 getTargetMachine().Options.EnableSegmentedStacks) &&
8954 "This should be used only on Windows targets or when segmented stacks "
8956 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8957 DebugLoc dl = Op.getDebugLoc();
8960 SDValue Chain = Op.getOperand(0);
8961 SDValue Size = Op.getOperand(1);
8962 // FIXME: Ensure alignment here
8964 bool Is64Bit = Subtarget->is64Bit();
8965 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8967 if (getTargetMachine().Options.EnableSegmentedStacks) {
8968 MachineFunction &MF = DAG.getMachineFunction();
8969 MachineRegisterInfo &MRI = MF.getRegInfo();
8972 // The 64 bit implementation of segmented stacks needs to clobber both r10
8973 // r11. This makes it impossible to use it along with nested parameters.
8974 const Function *F = MF.getFunction();
8976 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8978 if (I->hasNestAttr())
8979 report_fatal_error("Cannot use segmented stacks with functions that "
8980 "have nested arguments.");
8983 const TargetRegisterClass *AddrRegClass =
8984 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8985 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8986 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8987 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8988 DAG.getRegister(Vreg, SPTy));
8989 SDValue Ops1[2] = { Value, Chain };
8990 return DAG.getMergeValues(Ops1, 2, dl);
8993 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8995 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8996 Flag = Chain.getValue(1);
8997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8999 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9000 Flag = Chain.getValue(1);
9002 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9004 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9005 return DAG.getMergeValues(Ops1, 2, dl);
9009 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9010 MachineFunction &MF = DAG.getMachineFunction();
9011 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9013 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9014 DebugLoc DL = Op.getDebugLoc();
9016 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9017 // vastart just stores the address of the VarArgsFrameIndex slot into the
9018 // memory location argument.
9019 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9021 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9022 MachinePointerInfo(SV), false, false, 0);
9026 // gp_offset (0 - 6 * 8)
9027 // fp_offset (48 - 48 + 8 * 16)
9028 // overflow_arg_area (point to parameters coming in memory).
9030 SmallVector<SDValue, 8> MemOps;
9031 SDValue FIN = Op.getOperand(1);
9033 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9034 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9036 FIN, MachinePointerInfo(SV), false, false, 0);
9037 MemOps.push_back(Store);
9040 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9041 FIN, DAG.getIntPtrConstant(4));
9042 Store = DAG.getStore(Op.getOperand(0), DL,
9043 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9045 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9046 MemOps.push_back(Store);
9048 // Store ptr to overflow_arg_area
9049 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9050 FIN, DAG.getIntPtrConstant(4));
9051 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9053 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9054 MachinePointerInfo(SV, 8),
9056 MemOps.push_back(Store);
9058 // Store ptr to reg_save_area.
9059 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9060 FIN, DAG.getIntPtrConstant(8));
9061 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9063 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9064 MachinePointerInfo(SV, 16), false, false, 0);
9065 MemOps.push_back(Store);
9066 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9067 &MemOps[0], MemOps.size());
9070 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9071 assert(Subtarget->is64Bit() &&
9072 "LowerVAARG only handles 64-bit va_arg!");
9073 assert((Subtarget->isTargetLinux() ||
9074 Subtarget->isTargetDarwin()) &&
9075 "Unhandled target in LowerVAARG");
9076 assert(Op.getNode()->getNumOperands() == 4);
9077 SDValue Chain = Op.getOperand(0);
9078 SDValue SrcPtr = Op.getOperand(1);
9079 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9080 unsigned Align = Op.getConstantOperandVal(3);
9081 DebugLoc dl = Op.getDebugLoc();
9083 EVT ArgVT = Op.getNode()->getValueType(0);
9084 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9085 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9088 // Decide which area this value should be read from.
9089 // TODO: Implement the AMD64 ABI in its entirety. This simple
9090 // selection mechanism works only for the basic types.
9091 if (ArgVT == MVT::f80) {
9092 llvm_unreachable("va_arg for f80 not yet implemented");
9093 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9094 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9095 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9096 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9098 llvm_unreachable("Unhandled argument type in LowerVAARG");
9102 // Sanity Check: Make sure using fp_offset makes sense.
9103 assert(!getTargetMachine().Options.UseSoftFloat &&
9104 !(DAG.getMachineFunction()
9105 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9106 Subtarget->hasXMM());
9109 // Insert VAARG_64 node into the DAG
9110 // VAARG_64 returns two values: Variable Argument Address, Chain
9111 SmallVector<SDValue, 11> InstOps;
9112 InstOps.push_back(Chain);
9113 InstOps.push_back(SrcPtr);
9114 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9115 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9116 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9117 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9118 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9119 VTs, &InstOps[0], InstOps.size(),
9121 MachinePointerInfo(SV),
9126 Chain = VAARG.getValue(1);
9128 // Load the next argument and return it
9129 return DAG.getLoad(ArgVT, dl,
9132 MachinePointerInfo(),
9133 false, false, false, 0);
9136 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9137 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9138 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9139 SDValue Chain = Op.getOperand(0);
9140 SDValue DstPtr = Op.getOperand(1);
9141 SDValue SrcPtr = Op.getOperand(2);
9142 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9143 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9144 DebugLoc DL = Op.getDebugLoc();
9146 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9147 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9149 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9153 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9154 DebugLoc dl = Op.getDebugLoc();
9155 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9157 default: return SDValue(); // Don't custom lower most intrinsics.
9158 // Comparison intrinsics.
9159 case Intrinsic::x86_sse_comieq_ss:
9160 case Intrinsic::x86_sse_comilt_ss:
9161 case Intrinsic::x86_sse_comile_ss:
9162 case Intrinsic::x86_sse_comigt_ss:
9163 case Intrinsic::x86_sse_comige_ss:
9164 case Intrinsic::x86_sse_comineq_ss:
9165 case Intrinsic::x86_sse_ucomieq_ss:
9166 case Intrinsic::x86_sse_ucomilt_ss:
9167 case Intrinsic::x86_sse_ucomile_ss:
9168 case Intrinsic::x86_sse_ucomigt_ss:
9169 case Intrinsic::x86_sse_ucomige_ss:
9170 case Intrinsic::x86_sse_ucomineq_ss:
9171 case Intrinsic::x86_sse2_comieq_sd:
9172 case Intrinsic::x86_sse2_comilt_sd:
9173 case Intrinsic::x86_sse2_comile_sd:
9174 case Intrinsic::x86_sse2_comigt_sd:
9175 case Intrinsic::x86_sse2_comige_sd:
9176 case Intrinsic::x86_sse2_comineq_sd:
9177 case Intrinsic::x86_sse2_ucomieq_sd:
9178 case Intrinsic::x86_sse2_ucomilt_sd:
9179 case Intrinsic::x86_sse2_ucomile_sd:
9180 case Intrinsic::x86_sse2_ucomigt_sd:
9181 case Intrinsic::x86_sse2_ucomige_sd:
9182 case Intrinsic::x86_sse2_ucomineq_sd: {
9184 ISD::CondCode CC = ISD::SETCC_INVALID;
9187 case Intrinsic::x86_sse_comieq_ss:
9188 case Intrinsic::x86_sse2_comieq_sd:
9192 case Intrinsic::x86_sse_comilt_ss:
9193 case Intrinsic::x86_sse2_comilt_sd:
9197 case Intrinsic::x86_sse_comile_ss:
9198 case Intrinsic::x86_sse2_comile_sd:
9202 case Intrinsic::x86_sse_comigt_ss:
9203 case Intrinsic::x86_sse2_comigt_sd:
9207 case Intrinsic::x86_sse_comige_ss:
9208 case Intrinsic::x86_sse2_comige_sd:
9212 case Intrinsic::x86_sse_comineq_ss:
9213 case Intrinsic::x86_sse2_comineq_sd:
9217 case Intrinsic::x86_sse_ucomieq_ss:
9218 case Intrinsic::x86_sse2_ucomieq_sd:
9219 Opc = X86ISD::UCOMI;
9222 case Intrinsic::x86_sse_ucomilt_ss:
9223 case Intrinsic::x86_sse2_ucomilt_sd:
9224 Opc = X86ISD::UCOMI;
9227 case Intrinsic::x86_sse_ucomile_ss:
9228 case Intrinsic::x86_sse2_ucomile_sd:
9229 Opc = X86ISD::UCOMI;
9232 case Intrinsic::x86_sse_ucomigt_ss:
9233 case Intrinsic::x86_sse2_ucomigt_sd:
9234 Opc = X86ISD::UCOMI;
9237 case Intrinsic::x86_sse_ucomige_ss:
9238 case Intrinsic::x86_sse2_ucomige_sd:
9239 Opc = X86ISD::UCOMI;
9242 case Intrinsic::x86_sse_ucomineq_ss:
9243 case Intrinsic::x86_sse2_ucomineq_sd:
9244 Opc = X86ISD::UCOMI;
9249 SDValue LHS = Op.getOperand(1);
9250 SDValue RHS = Op.getOperand(2);
9251 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9252 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9253 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9254 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9255 DAG.getConstant(X86CC, MVT::i8), Cond);
9256 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9258 // Arithmetic intrinsics.
9259 case Intrinsic::x86_sse3_hadd_ps:
9260 case Intrinsic::x86_sse3_hadd_pd:
9261 case Intrinsic::x86_avx_hadd_ps_256:
9262 case Intrinsic::x86_avx_hadd_pd_256:
9263 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9264 Op.getOperand(1), Op.getOperand(2));
9265 case Intrinsic::x86_sse3_hsub_ps:
9266 case Intrinsic::x86_sse3_hsub_pd:
9267 case Intrinsic::x86_avx_hsub_ps_256:
9268 case Intrinsic::x86_avx_hsub_pd_256:
9269 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9270 Op.getOperand(1), Op.getOperand(2));
9271 case Intrinsic::x86_avx2_psllv_d:
9272 case Intrinsic::x86_avx2_psllv_q:
9273 case Intrinsic::x86_avx2_psllv_d_256:
9274 case Intrinsic::x86_avx2_psllv_q_256:
9275 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9276 Op.getOperand(1), Op.getOperand(2));
9277 case Intrinsic::x86_avx2_psrlv_d:
9278 case Intrinsic::x86_avx2_psrlv_q:
9279 case Intrinsic::x86_avx2_psrlv_d_256:
9280 case Intrinsic::x86_avx2_psrlv_q_256:
9281 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9282 Op.getOperand(1), Op.getOperand(2));
9283 case Intrinsic::x86_avx2_psrav_d:
9284 case Intrinsic::x86_avx2_psrav_d_256:
9285 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9286 Op.getOperand(1), Op.getOperand(2));
9288 // ptest and testp intrinsics. The intrinsic these come from are designed to
9289 // return an integer value, not just an instruction so lower it to the ptest
9290 // or testp pattern and a setcc for the result.
9291 case Intrinsic::x86_sse41_ptestz:
9292 case Intrinsic::x86_sse41_ptestc:
9293 case Intrinsic::x86_sse41_ptestnzc:
9294 case Intrinsic::x86_avx_ptestz_256:
9295 case Intrinsic::x86_avx_ptestc_256:
9296 case Intrinsic::x86_avx_ptestnzc_256:
9297 case Intrinsic::x86_avx_vtestz_ps:
9298 case Intrinsic::x86_avx_vtestc_ps:
9299 case Intrinsic::x86_avx_vtestnzc_ps:
9300 case Intrinsic::x86_avx_vtestz_pd:
9301 case Intrinsic::x86_avx_vtestc_pd:
9302 case Intrinsic::x86_avx_vtestnzc_pd:
9303 case Intrinsic::x86_avx_vtestz_ps_256:
9304 case Intrinsic::x86_avx_vtestc_ps_256:
9305 case Intrinsic::x86_avx_vtestnzc_ps_256:
9306 case Intrinsic::x86_avx_vtestz_pd_256:
9307 case Intrinsic::x86_avx_vtestc_pd_256:
9308 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9309 bool IsTestPacked = false;
9312 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9313 case Intrinsic::x86_avx_vtestz_ps:
9314 case Intrinsic::x86_avx_vtestz_pd:
9315 case Intrinsic::x86_avx_vtestz_ps_256:
9316 case Intrinsic::x86_avx_vtestz_pd_256:
9317 IsTestPacked = true; // Fallthrough
9318 case Intrinsic::x86_sse41_ptestz:
9319 case Intrinsic::x86_avx_ptestz_256:
9321 X86CC = X86::COND_E;
9323 case Intrinsic::x86_avx_vtestc_ps:
9324 case Intrinsic::x86_avx_vtestc_pd:
9325 case Intrinsic::x86_avx_vtestc_ps_256:
9326 case Intrinsic::x86_avx_vtestc_pd_256:
9327 IsTestPacked = true; // Fallthrough
9328 case Intrinsic::x86_sse41_ptestc:
9329 case Intrinsic::x86_avx_ptestc_256:
9331 X86CC = X86::COND_B;
9333 case Intrinsic::x86_avx_vtestnzc_ps:
9334 case Intrinsic::x86_avx_vtestnzc_pd:
9335 case Intrinsic::x86_avx_vtestnzc_ps_256:
9336 case Intrinsic::x86_avx_vtestnzc_pd_256:
9337 IsTestPacked = true; // Fallthrough
9338 case Intrinsic::x86_sse41_ptestnzc:
9339 case Intrinsic::x86_avx_ptestnzc_256:
9341 X86CC = X86::COND_A;
9345 SDValue LHS = Op.getOperand(1);
9346 SDValue RHS = Op.getOperand(2);
9347 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9348 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9349 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9350 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9351 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9354 // Fix vector shift instructions where the last operand is a non-immediate
9356 case Intrinsic::x86_avx2_pslli_w:
9357 case Intrinsic::x86_avx2_pslli_d:
9358 case Intrinsic::x86_avx2_pslli_q:
9359 case Intrinsic::x86_avx2_psrli_w:
9360 case Intrinsic::x86_avx2_psrli_d:
9361 case Intrinsic::x86_avx2_psrli_q:
9362 case Intrinsic::x86_avx2_psrai_w:
9363 case Intrinsic::x86_avx2_psrai_d:
9364 case Intrinsic::x86_sse2_pslli_w:
9365 case Intrinsic::x86_sse2_pslli_d:
9366 case Intrinsic::x86_sse2_pslli_q:
9367 case Intrinsic::x86_sse2_psrli_w:
9368 case Intrinsic::x86_sse2_psrli_d:
9369 case Intrinsic::x86_sse2_psrli_q:
9370 case Intrinsic::x86_sse2_psrai_w:
9371 case Intrinsic::x86_sse2_psrai_d:
9372 case Intrinsic::x86_mmx_pslli_w:
9373 case Intrinsic::x86_mmx_pslli_d:
9374 case Intrinsic::x86_mmx_pslli_q:
9375 case Intrinsic::x86_mmx_psrli_w:
9376 case Intrinsic::x86_mmx_psrli_d:
9377 case Intrinsic::x86_mmx_psrli_q:
9378 case Intrinsic::x86_mmx_psrai_w:
9379 case Intrinsic::x86_mmx_psrai_d: {
9380 SDValue ShAmt = Op.getOperand(2);
9381 if (isa<ConstantSDNode>(ShAmt))
9384 unsigned NewIntNo = 0;
9385 EVT ShAmtVT = MVT::v4i32;
9387 case Intrinsic::x86_sse2_pslli_w:
9388 NewIntNo = Intrinsic::x86_sse2_psll_w;
9390 case Intrinsic::x86_sse2_pslli_d:
9391 NewIntNo = Intrinsic::x86_sse2_psll_d;
9393 case Intrinsic::x86_sse2_pslli_q:
9394 NewIntNo = Intrinsic::x86_sse2_psll_q;
9396 case Intrinsic::x86_sse2_psrli_w:
9397 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9399 case Intrinsic::x86_sse2_psrli_d:
9400 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9402 case Intrinsic::x86_sse2_psrli_q:
9403 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9405 case Intrinsic::x86_sse2_psrai_w:
9406 NewIntNo = Intrinsic::x86_sse2_psra_w;
9408 case Intrinsic::x86_sse2_psrai_d:
9409 NewIntNo = Intrinsic::x86_sse2_psra_d;
9411 case Intrinsic::x86_avx2_pslli_w:
9412 NewIntNo = Intrinsic::x86_avx2_psll_w;
9414 case Intrinsic::x86_avx2_pslli_d:
9415 NewIntNo = Intrinsic::x86_avx2_psll_d;
9417 case Intrinsic::x86_avx2_pslli_q:
9418 NewIntNo = Intrinsic::x86_avx2_psll_q;
9420 case Intrinsic::x86_avx2_psrli_w:
9421 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9423 case Intrinsic::x86_avx2_psrli_d:
9424 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9426 case Intrinsic::x86_avx2_psrli_q:
9427 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9429 case Intrinsic::x86_avx2_psrai_w:
9430 NewIntNo = Intrinsic::x86_avx2_psra_w;
9432 case Intrinsic::x86_avx2_psrai_d:
9433 NewIntNo = Intrinsic::x86_avx2_psra_d;
9436 ShAmtVT = MVT::v2i32;
9438 case Intrinsic::x86_mmx_pslli_w:
9439 NewIntNo = Intrinsic::x86_mmx_psll_w;
9441 case Intrinsic::x86_mmx_pslli_d:
9442 NewIntNo = Intrinsic::x86_mmx_psll_d;
9444 case Intrinsic::x86_mmx_pslli_q:
9445 NewIntNo = Intrinsic::x86_mmx_psll_q;
9447 case Intrinsic::x86_mmx_psrli_w:
9448 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9450 case Intrinsic::x86_mmx_psrli_d:
9451 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9453 case Intrinsic::x86_mmx_psrli_q:
9454 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9456 case Intrinsic::x86_mmx_psrai_w:
9457 NewIntNo = Intrinsic::x86_mmx_psra_w;
9459 case Intrinsic::x86_mmx_psrai_d:
9460 NewIntNo = Intrinsic::x86_mmx_psra_d;
9462 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9468 // The vector shift intrinsics with scalars uses 32b shift amounts but
9469 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9473 ShOps[1] = DAG.getConstant(0, MVT::i32);
9474 if (ShAmtVT == MVT::v4i32) {
9475 ShOps[2] = DAG.getUNDEF(MVT::i32);
9476 ShOps[3] = DAG.getUNDEF(MVT::i32);
9477 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9479 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9480 // FIXME this must be lowered to get rid of the invalid type.
9483 EVT VT = Op.getValueType();
9484 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9485 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9486 DAG.getConstant(NewIntNo, MVT::i32),
9487 Op.getOperand(1), ShAmt);
9492 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9493 SelectionDAG &DAG) const {
9494 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9495 MFI->setReturnAddressIsTaken(true);
9497 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9498 DebugLoc dl = Op.getDebugLoc();
9501 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9503 DAG.getConstant(TD->getPointerSize(),
9504 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9505 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9506 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9508 MachinePointerInfo(), false, false, false, 0);
9511 // Just load the return address.
9512 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9513 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9514 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9517 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9518 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9519 MFI->setFrameAddressIsTaken(true);
9521 EVT VT = Op.getValueType();
9522 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9523 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9524 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9525 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9527 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9528 MachinePointerInfo(),
9529 false, false, false, 0);
9533 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9534 SelectionDAG &DAG) const {
9535 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9538 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9539 MachineFunction &MF = DAG.getMachineFunction();
9540 SDValue Chain = Op.getOperand(0);
9541 SDValue Offset = Op.getOperand(1);
9542 SDValue Handler = Op.getOperand(2);
9543 DebugLoc dl = Op.getDebugLoc();
9545 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9546 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9548 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9550 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9551 DAG.getIntPtrConstant(TD->getPointerSize()));
9552 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9553 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9555 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9556 MF.getRegInfo().addLiveOut(StoreAddrReg);
9558 return DAG.getNode(X86ISD::EH_RETURN, dl,
9560 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9563 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9564 SelectionDAG &DAG) const {
9565 return Op.getOperand(0);
9568 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9569 SelectionDAG &DAG) const {
9570 SDValue Root = Op.getOperand(0);
9571 SDValue Trmp = Op.getOperand(1); // trampoline
9572 SDValue FPtr = Op.getOperand(2); // nested function
9573 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9574 DebugLoc dl = Op.getDebugLoc();
9576 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9578 if (Subtarget->is64Bit()) {
9579 SDValue OutChains[6];
9581 // Large code-model.
9582 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9583 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9585 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9586 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9588 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9590 // Load the pointer to the nested function into R11.
9591 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9592 SDValue Addr = Trmp;
9593 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9594 Addr, MachinePointerInfo(TrmpAddr),
9597 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9598 DAG.getConstant(2, MVT::i64));
9599 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9600 MachinePointerInfo(TrmpAddr, 2),
9603 // Load the 'nest' parameter value into R10.
9604 // R10 is specified in X86CallingConv.td
9605 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9606 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9607 DAG.getConstant(10, MVT::i64));
9608 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9609 Addr, MachinePointerInfo(TrmpAddr, 10),
9612 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9613 DAG.getConstant(12, MVT::i64));
9614 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9615 MachinePointerInfo(TrmpAddr, 12),
9618 // Jump to the nested function.
9619 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9621 DAG.getConstant(20, MVT::i64));
9622 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9623 Addr, MachinePointerInfo(TrmpAddr, 20),
9626 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9627 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9628 DAG.getConstant(22, MVT::i64));
9629 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9630 MachinePointerInfo(TrmpAddr, 22),
9633 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9635 const Function *Func =
9636 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9637 CallingConv::ID CC = Func->getCallingConv();
9642 llvm_unreachable("Unsupported calling convention");
9643 case CallingConv::C:
9644 case CallingConv::X86_StdCall: {
9645 // Pass 'nest' parameter in ECX.
9646 // Must be kept in sync with X86CallingConv.td
9649 // Check that ECX wasn't needed by an 'inreg' parameter.
9650 FunctionType *FTy = Func->getFunctionType();
9651 const AttrListPtr &Attrs = Func->getAttributes();
9653 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9654 unsigned InRegCount = 0;
9657 for (FunctionType::param_iterator I = FTy->param_begin(),
9658 E = FTy->param_end(); I != E; ++I, ++Idx)
9659 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9660 // FIXME: should only count parameters that are lowered to integers.
9661 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9663 if (InRegCount > 2) {
9664 report_fatal_error("Nest register in use - reduce number of inreg"
9670 case CallingConv::X86_FastCall:
9671 case CallingConv::X86_ThisCall:
9672 case CallingConv::Fast:
9673 // Pass 'nest' parameter in EAX.
9674 // Must be kept in sync with X86CallingConv.td
9679 SDValue OutChains[4];
9682 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9683 DAG.getConstant(10, MVT::i32));
9684 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9686 // This is storing the opcode for MOV32ri.
9687 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9688 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9689 OutChains[0] = DAG.getStore(Root, dl,
9690 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9691 Trmp, MachinePointerInfo(TrmpAddr),
9694 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9695 DAG.getConstant(1, MVT::i32));
9696 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9697 MachinePointerInfo(TrmpAddr, 1),
9700 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9701 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9702 DAG.getConstant(5, MVT::i32));
9703 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9704 MachinePointerInfo(TrmpAddr, 5),
9707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9708 DAG.getConstant(6, MVT::i32));
9709 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9710 MachinePointerInfo(TrmpAddr, 6),
9713 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9717 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9718 SelectionDAG &DAG) const {
9720 The rounding mode is in bits 11:10 of FPSR, and has the following
9727 FLT_ROUNDS, on the other hand, expects the following:
9734 To perform the conversion, we do:
9735 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9738 MachineFunction &MF = DAG.getMachineFunction();
9739 const TargetMachine &TM = MF.getTarget();
9740 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9741 unsigned StackAlignment = TFI.getStackAlignment();
9742 EVT VT = Op.getValueType();
9743 DebugLoc DL = Op.getDebugLoc();
9745 // Save FP Control Word to stack slot
9746 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9747 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9750 MachineMemOperand *MMO =
9751 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9752 MachineMemOperand::MOStore, 2, 2);
9754 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9755 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9756 DAG.getVTList(MVT::Other),
9757 Ops, 2, MVT::i16, MMO);
9759 // Load FP Control Word from stack slot
9760 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9761 MachinePointerInfo(), false, false, false, 0);
9763 // Transform as necessary
9765 DAG.getNode(ISD::SRL, DL, MVT::i16,
9766 DAG.getNode(ISD::AND, DL, MVT::i16,
9767 CWD, DAG.getConstant(0x800, MVT::i16)),
9768 DAG.getConstant(11, MVT::i8));
9770 DAG.getNode(ISD::SRL, DL, MVT::i16,
9771 DAG.getNode(ISD::AND, DL, MVT::i16,
9772 CWD, DAG.getConstant(0x400, MVT::i16)),
9773 DAG.getConstant(9, MVT::i8));
9776 DAG.getNode(ISD::AND, DL, MVT::i16,
9777 DAG.getNode(ISD::ADD, DL, MVT::i16,
9778 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9779 DAG.getConstant(1, MVT::i16)),
9780 DAG.getConstant(3, MVT::i16));
9783 return DAG.getNode((VT.getSizeInBits() < 16 ?
9784 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9787 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9788 EVT VT = Op.getValueType();
9790 unsigned NumBits = VT.getSizeInBits();
9791 DebugLoc dl = Op.getDebugLoc();
9793 Op = Op.getOperand(0);
9794 if (VT == MVT::i8) {
9795 // Zero extend to i32 since there is not an i8 bsr.
9797 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9800 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9801 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9802 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9804 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9807 DAG.getConstant(NumBits+NumBits-1, OpVT),
9808 DAG.getConstant(X86::COND_E, MVT::i8),
9811 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9813 // Finally xor with NumBits-1.
9814 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9817 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9821 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9822 EVT VT = Op.getValueType();
9824 unsigned NumBits = VT.getSizeInBits();
9825 DebugLoc dl = Op.getDebugLoc();
9827 Op = Op.getOperand(0);
9828 if (VT == MVT::i8) {
9830 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9833 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9834 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9835 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9837 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9840 DAG.getConstant(NumBits, OpVT),
9841 DAG.getConstant(X86::COND_E, MVT::i8),
9844 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9847 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9851 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9852 // ones, and then concatenate the result back.
9853 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9854 EVT VT = Op.getValueType();
9856 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9857 "Unsupported value type for operation");
9859 int NumElems = VT.getVectorNumElements();
9860 DebugLoc dl = Op.getDebugLoc();
9861 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9862 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9864 // Extract the LHS vectors
9865 SDValue LHS = Op.getOperand(0);
9866 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9867 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9869 // Extract the RHS vectors
9870 SDValue RHS = Op.getOperand(1);
9871 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9872 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9874 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9875 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9877 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9878 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9879 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9882 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9883 assert(Op.getValueType().getSizeInBits() == 256 &&
9884 Op.getValueType().isInteger() &&
9885 "Only handle AVX 256-bit vector integer operation");
9886 return Lower256IntArith(Op, DAG);
9889 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9890 assert(Op.getValueType().getSizeInBits() == 256 &&
9891 Op.getValueType().isInteger() &&
9892 "Only handle AVX 256-bit vector integer operation");
9893 return Lower256IntArith(Op, DAG);
9896 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9897 EVT VT = Op.getValueType();
9899 // Decompose 256-bit ops into smaller 128-bit ops.
9900 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9901 return Lower256IntArith(Op, DAG);
9903 DebugLoc dl = Op.getDebugLoc();
9905 SDValue A = Op.getOperand(0);
9906 SDValue B = Op.getOperand(1);
9908 if (VT == MVT::v4i64) {
9909 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9911 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9912 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9913 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9914 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9915 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9917 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9918 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9919 // return AloBlo + AloBhi + AhiBlo;
9921 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9922 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9923 A, DAG.getConstant(32, MVT::i32));
9924 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9925 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9926 B, DAG.getConstant(32, MVT::i32));
9927 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9928 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9930 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9931 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9933 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9934 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9936 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9937 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9938 AloBhi, DAG.getConstant(32, MVT::i32));
9939 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9940 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9941 AhiBlo, DAG.getConstant(32, MVT::i32));
9942 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9943 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9947 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9949 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9950 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9951 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9952 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9953 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9955 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9956 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9957 // return AloBlo + AloBhi + AhiBlo;
9959 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9960 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9961 A, DAG.getConstant(32, MVT::i32));
9962 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9963 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9964 B, DAG.getConstant(32, MVT::i32));
9965 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9966 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9968 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9969 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9971 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9972 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9974 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9975 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9976 AloBhi, DAG.getConstant(32, MVT::i32));
9977 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9978 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9979 AhiBlo, DAG.getConstant(32, MVT::i32));
9980 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9981 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9985 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9987 EVT VT = Op.getValueType();
9988 DebugLoc dl = Op.getDebugLoc();
9989 SDValue R = Op.getOperand(0);
9990 SDValue Amt = Op.getOperand(1);
9991 LLVMContext *Context = DAG.getContext();
9993 if (!Subtarget->hasXMMInt())
9996 // Optimize shl/srl/sra with constant shift amount.
9997 if (isSplatVector(Amt.getNode())) {
9998 SDValue SclrAmt = Amt->getOperand(0);
9999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10000 uint64_t ShiftAmt = C->getZExtValue();
10002 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10003 // Make a large shift.
10005 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10006 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10007 R, DAG.getConstant(ShiftAmt, MVT::i32));
10008 // Zero out the rightmost bits.
10009 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10011 return DAG.getNode(ISD::AND, dl, VT, SHL,
10012 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10015 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10016 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10017 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10018 R, DAG.getConstant(ShiftAmt, MVT::i32));
10020 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10021 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10022 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10023 R, DAG.getConstant(ShiftAmt, MVT::i32));
10025 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10026 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10027 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10028 R, DAG.getConstant(ShiftAmt, MVT::i32));
10030 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10031 // Make a large shift.
10033 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10034 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10035 R, DAG.getConstant(ShiftAmt, MVT::i32));
10036 // Zero out the leftmost bits.
10037 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10039 return DAG.getNode(ISD::AND, dl, VT, SRL,
10040 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10043 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10044 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10045 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10046 R, DAG.getConstant(ShiftAmt, MVT::i32));
10048 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10049 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10050 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10051 R, DAG.getConstant(ShiftAmt, MVT::i32));
10053 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10054 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10055 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10056 R, DAG.getConstant(ShiftAmt, MVT::i32));
10058 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10059 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10060 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10061 R, DAG.getConstant(ShiftAmt, MVT::i32));
10063 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10064 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10066 R, DAG.getConstant(ShiftAmt, MVT::i32));
10068 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10069 if (ShiftAmt == 7) {
10070 // R s>> 7 === R s< 0
10071 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10072 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10075 // R s>> a === ((R u>> a) ^ m) - m
10076 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10077 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10079 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10080 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10081 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10085 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10086 if (Op.getOpcode() == ISD::SHL) {
10087 // Make a large shift.
10089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10090 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10091 R, DAG.getConstant(ShiftAmt, MVT::i32));
10092 // Zero out the rightmost bits.
10093 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10095 return DAG.getNode(ISD::AND, dl, VT, SHL,
10096 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10098 if (Op.getOpcode() == ISD::SRL) {
10099 // Make a large shift.
10101 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10102 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10103 R, DAG.getConstant(ShiftAmt, MVT::i32));
10104 // Zero out the leftmost bits.
10105 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10107 return DAG.getNode(ISD::AND, dl, VT, SRL,
10108 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10110 if (Op.getOpcode() == ISD::SRA) {
10111 if (ShiftAmt == 7) {
10112 // R s>> 7 === R s< 0
10113 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10114 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10117 // R s>> a === ((R u>> a) ^ m) - m
10118 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10119 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10121 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10122 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10123 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10130 // Lower SHL with variable shift amount.
10131 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10132 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10133 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10134 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10136 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10138 std::vector<Constant*> CV(4, CI);
10139 Constant *C = ConstantVector::get(CV);
10140 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10141 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10142 MachinePointerInfo::getConstantPool(),
10143 false, false, false, 16);
10145 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10146 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10147 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10148 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10150 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10152 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10153 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10154 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10156 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10157 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10159 std::vector<Constant*> CVM1(16, CM1);
10160 std::vector<Constant*> CVM2(16, CM2);
10161 Constant *C = ConstantVector::get(CVM1);
10162 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10163 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10164 MachinePointerInfo::getConstantPool(),
10165 false, false, false, 16);
10167 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10168 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10169 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10170 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10171 DAG.getConstant(4, MVT::i32));
10172 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10174 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10176 C = ConstantVector::get(CVM2);
10177 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10178 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10179 MachinePointerInfo::getConstantPool(),
10180 false, false, false, 16);
10182 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10183 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10184 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10185 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10186 DAG.getConstant(2, MVT::i32));
10187 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10189 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10191 // return pblendv(r, r+r, a);
10192 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10193 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10197 // Decompose 256-bit shifts into smaller 128-bit shifts.
10198 if (VT.getSizeInBits() == 256) {
10199 int NumElems = VT.getVectorNumElements();
10200 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10201 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10203 // Extract the two vectors
10204 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10205 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10208 // Recreate the shift amount vectors
10209 SDValue Amt1, Amt2;
10210 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10211 // Constant shift amount
10212 SmallVector<SDValue, 4> Amt1Csts;
10213 SmallVector<SDValue, 4> Amt2Csts;
10214 for (int i = 0; i < NumElems/2; ++i)
10215 Amt1Csts.push_back(Amt->getOperand(i));
10216 for (int i = NumElems/2; i < NumElems; ++i)
10217 Amt2Csts.push_back(Amt->getOperand(i));
10219 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10220 &Amt1Csts[0], NumElems/2);
10221 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10222 &Amt2Csts[0], NumElems/2);
10224 // Variable shift amount
10225 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10226 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10230 // Issue new vector shifts for the smaller types
10231 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10232 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10234 // Concatenate the result back
10235 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10241 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10242 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10243 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10244 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10245 // has only one use.
10246 SDNode *N = Op.getNode();
10247 SDValue LHS = N->getOperand(0);
10248 SDValue RHS = N->getOperand(1);
10249 unsigned BaseOp = 0;
10251 DebugLoc DL = Op.getDebugLoc();
10252 switch (Op.getOpcode()) {
10253 default: llvm_unreachable("Unknown ovf instruction!");
10255 // A subtract of one will be selected as a INC. Note that INC doesn't
10256 // set CF, so we can't do this for UADDO.
10257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10259 BaseOp = X86ISD::INC;
10260 Cond = X86::COND_O;
10263 BaseOp = X86ISD::ADD;
10264 Cond = X86::COND_O;
10267 BaseOp = X86ISD::ADD;
10268 Cond = X86::COND_B;
10271 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10272 // set CF, so we can't do this for USUBO.
10273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10275 BaseOp = X86ISD::DEC;
10276 Cond = X86::COND_O;
10279 BaseOp = X86ISD::SUB;
10280 Cond = X86::COND_O;
10283 BaseOp = X86ISD::SUB;
10284 Cond = X86::COND_B;
10287 BaseOp = X86ISD::SMUL;
10288 Cond = X86::COND_O;
10290 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10291 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10293 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10296 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10297 DAG.getConstant(X86::COND_O, MVT::i32),
10298 SDValue(Sum.getNode(), 2));
10300 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10304 // Also sets EFLAGS.
10305 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10306 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10309 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10310 DAG.getConstant(Cond, MVT::i32),
10311 SDValue(Sum.getNode(), 1));
10313 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10316 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10317 DebugLoc dl = Op.getDebugLoc();
10318 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10319 EVT VT = Op.getValueType();
10321 if (Subtarget->hasXMMInt() && VT.isVector()) {
10322 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10323 ExtraVT.getScalarType().getSizeInBits();
10324 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10326 unsigned SHLIntrinsicsID = 0;
10327 unsigned SRAIntrinsicsID = 0;
10328 switch (VT.getSimpleVT().SimpleTy) {
10332 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10333 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10336 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10337 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10341 if (!Subtarget->hasAVX())
10343 if (!Subtarget->hasAVX2()) {
10344 // needs to be split
10345 int NumElems = VT.getVectorNumElements();
10346 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10347 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10349 // Extract the LHS vectors
10350 SDValue LHS = Op.getOperand(0);
10351 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10352 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10354 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10355 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10357 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10358 int ExtraNumElems = ExtraVT.getVectorNumElements();
10359 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10361 SDValue Extra = DAG.getValueType(ExtraVT);
10363 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10364 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10366 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10368 if (VT == MVT::v8i32) {
10369 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10370 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10372 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10373 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10377 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10378 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10379 Op.getOperand(0), ShAmt);
10381 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10382 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10390 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10391 DebugLoc dl = Op.getDebugLoc();
10393 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10394 // There isn't any reason to disable it if the target processor supports it.
10395 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10396 SDValue Chain = Op.getOperand(0);
10397 SDValue Zero = DAG.getConstant(0, MVT::i32);
10399 DAG.getRegister(X86::ESP, MVT::i32), // Base
10400 DAG.getTargetConstant(1, MVT::i8), // Scale
10401 DAG.getRegister(0, MVT::i32), // Index
10402 DAG.getTargetConstant(0, MVT::i32), // Disp
10403 DAG.getRegister(0, MVT::i32), // Segment.
10408 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10409 array_lengthof(Ops));
10410 return SDValue(Res, 0);
10413 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10415 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10417 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10418 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10419 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10420 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10422 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10423 if (!Op1 && !Op2 && !Op3 && Op4)
10424 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10426 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10427 if (Op1 && !Op2 && !Op3 && !Op4)
10428 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10430 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10432 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10435 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10436 SelectionDAG &DAG) const {
10437 DebugLoc dl = Op.getDebugLoc();
10438 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10439 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10440 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10441 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10443 // The only fence that needs an instruction is a sequentially-consistent
10444 // cross-thread fence.
10445 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10446 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10447 // no-sse2). There isn't any reason to disable it if the target processor
10449 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10450 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10452 SDValue Chain = Op.getOperand(0);
10453 SDValue Zero = DAG.getConstant(0, MVT::i32);
10455 DAG.getRegister(X86::ESP, MVT::i32), // Base
10456 DAG.getTargetConstant(1, MVT::i8), // Scale
10457 DAG.getRegister(0, MVT::i32), // Index
10458 DAG.getTargetConstant(0, MVT::i32), // Disp
10459 DAG.getRegister(0, MVT::i32), // Segment.
10464 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10465 array_lengthof(Ops));
10466 return SDValue(Res, 0);
10469 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10470 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10474 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10475 EVT T = Op.getValueType();
10476 DebugLoc DL = Op.getDebugLoc();
10479 switch(T.getSimpleVT().SimpleTy) {
10481 assert(false && "Invalid value type!");
10482 case MVT::i8: Reg = X86::AL; size = 1; break;
10483 case MVT::i16: Reg = X86::AX; size = 2; break;
10484 case MVT::i32: Reg = X86::EAX; size = 4; break;
10486 assert(Subtarget->is64Bit() && "Node not type legal!");
10487 Reg = X86::RAX; size = 8;
10490 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10491 Op.getOperand(2), SDValue());
10492 SDValue Ops[] = { cpIn.getValue(0),
10495 DAG.getTargetConstant(size, MVT::i8),
10496 cpIn.getValue(1) };
10497 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10498 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10499 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10502 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10506 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10507 SelectionDAG &DAG) const {
10508 assert(Subtarget->is64Bit() && "Result not type legalized?");
10509 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10510 SDValue TheChain = Op.getOperand(0);
10511 DebugLoc dl = Op.getDebugLoc();
10512 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10513 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10514 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10516 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10517 DAG.getConstant(32, MVT::i8));
10519 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10522 return DAG.getMergeValues(Ops, 2, dl);
10525 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10526 SelectionDAG &DAG) const {
10527 EVT SrcVT = Op.getOperand(0).getValueType();
10528 EVT DstVT = Op.getValueType();
10529 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10530 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10531 assert((DstVT == MVT::i64 ||
10532 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10533 "Unexpected custom BITCAST");
10534 // i64 <=> MMX conversions are Legal.
10535 if (SrcVT==MVT::i64 && DstVT.isVector())
10537 if (DstVT==MVT::i64 && SrcVT.isVector())
10539 // MMX <=> MMX conversions are Legal.
10540 if (SrcVT.isVector() && DstVT.isVector())
10542 // All other conversions need to be expanded.
10546 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10547 SDNode *Node = Op.getNode();
10548 DebugLoc dl = Node->getDebugLoc();
10549 EVT T = Node->getValueType(0);
10550 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10551 DAG.getConstant(0, T), Node->getOperand(2));
10552 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10553 cast<AtomicSDNode>(Node)->getMemoryVT(),
10554 Node->getOperand(0),
10555 Node->getOperand(1), negOp,
10556 cast<AtomicSDNode>(Node)->getSrcValue(),
10557 cast<AtomicSDNode>(Node)->getAlignment(),
10558 cast<AtomicSDNode>(Node)->getOrdering(),
10559 cast<AtomicSDNode>(Node)->getSynchScope());
10562 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10563 SDNode *Node = Op.getNode();
10564 DebugLoc dl = Node->getDebugLoc();
10565 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10567 // Convert seq_cst store -> xchg
10568 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10569 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10570 // (The only way to get a 16-byte store is cmpxchg16b)
10571 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10572 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10573 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10574 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10575 cast<AtomicSDNode>(Node)->getMemoryVT(),
10576 Node->getOperand(0),
10577 Node->getOperand(1), Node->getOperand(2),
10578 cast<AtomicSDNode>(Node)->getMemOperand(),
10579 cast<AtomicSDNode>(Node)->getOrdering(),
10580 cast<AtomicSDNode>(Node)->getSynchScope());
10581 return Swap.getValue(1);
10583 // Other atomic stores have a simple pattern.
10587 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10588 EVT VT = Op.getNode()->getValueType(0);
10590 // Let legalize expand this if it isn't a legal type yet.
10591 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10594 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10597 bool ExtraOp = false;
10598 switch (Op.getOpcode()) {
10599 default: assert(0 && "Invalid code");
10600 case ISD::ADDC: Opc = X86ISD::ADD; break;
10601 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10602 case ISD::SUBC: Opc = X86ISD::SUB; break;
10603 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10607 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10609 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10610 Op.getOperand(1), Op.getOperand(2));
10613 /// LowerOperation - Provide custom lowering hooks for some operations.
10615 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10616 switch (Op.getOpcode()) {
10617 default: llvm_unreachable("Should not custom lower this!");
10618 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10619 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10620 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10621 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10622 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10623 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10624 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10625 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10626 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10627 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10628 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10629 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10630 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10631 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10632 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10633 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10634 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10635 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10636 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10637 case ISD::SHL_PARTS:
10638 case ISD::SRA_PARTS:
10639 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10640 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10641 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10642 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10643 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10644 case ISD::FABS: return LowerFABS(Op, DAG);
10645 case ISD::FNEG: return LowerFNEG(Op, DAG);
10646 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10647 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10648 case ISD::SETCC: return LowerSETCC(Op, DAG);
10649 case ISD::SELECT: return LowerSELECT(Op, DAG);
10650 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10651 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10652 case ISD::VASTART: return LowerVASTART(Op, DAG);
10653 case ISD::VAARG: return LowerVAARG(Op, DAG);
10654 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10655 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10656 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10657 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10658 case ISD::FRAME_TO_ARGS_OFFSET:
10659 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10660 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10661 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10662 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10663 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10664 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10665 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10666 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10667 case ISD::MUL: return LowerMUL(Op, DAG);
10670 case ISD::SHL: return LowerShift(Op, DAG);
10676 case ISD::UMULO: return LowerXALUO(Op, DAG);
10677 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10678 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10682 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10683 case ISD::ADD: return LowerADD(Op, DAG);
10684 case ISD::SUB: return LowerSUB(Op, DAG);
10688 static void ReplaceATOMIC_LOAD(SDNode *Node,
10689 SmallVectorImpl<SDValue> &Results,
10690 SelectionDAG &DAG) {
10691 DebugLoc dl = Node->getDebugLoc();
10692 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10694 // Convert wide load -> cmpxchg8b/cmpxchg16b
10695 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10696 // (The only way to get a 16-byte load is cmpxchg16b)
10697 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10698 SDValue Zero = DAG.getConstant(0, VT);
10699 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10700 Node->getOperand(0),
10701 Node->getOperand(1), Zero, Zero,
10702 cast<AtomicSDNode>(Node)->getMemOperand(),
10703 cast<AtomicSDNode>(Node)->getOrdering(),
10704 cast<AtomicSDNode>(Node)->getSynchScope());
10705 Results.push_back(Swap.getValue(0));
10706 Results.push_back(Swap.getValue(1));
10709 void X86TargetLowering::
10710 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10711 SelectionDAG &DAG, unsigned NewOp) const {
10712 DebugLoc dl = Node->getDebugLoc();
10713 assert (Node->getValueType(0) == MVT::i64 &&
10714 "Only know how to expand i64 atomics");
10716 SDValue Chain = Node->getOperand(0);
10717 SDValue In1 = Node->getOperand(1);
10718 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10719 Node->getOperand(2), DAG.getIntPtrConstant(0));
10720 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10721 Node->getOperand(2), DAG.getIntPtrConstant(1));
10722 SDValue Ops[] = { Chain, In1, In2L, In2H };
10723 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10725 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10726 cast<MemSDNode>(Node)->getMemOperand());
10727 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10728 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10729 Results.push_back(Result.getValue(2));
10732 /// ReplaceNodeResults - Replace a node with an illegal result type
10733 /// with a new node built out of custom code.
10734 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10735 SmallVectorImpl<SDValue>&Results,
10736 SelectionDAG &DAG) const {
10737 DebugLoc dl = N->getDebugLoc();
10738 switch (N->getOpcode()) {
10740 assert(false && "Do not know how to custom type legalize this operation!");
10742 case ISD::SIGN_EXTEND_INREG:
10747 // We don't want to expand or promote these.
10749 case ISD::FP_TO_SINT: {
10750 std::pair<SDValue,SDValue> Vals =
10751 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10752 SDValue FIST = Vals.first, StackSlot = Vals.second;
10753 if (FIST.getNode() != 0) {
10754 EVT VT = N->getValueType(0);
10755 // Return a load from the stack slot.
10756 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10757 MachinePointerInfo(),
10758 false, false, false, 0));
10762 case ISD::READCYCLECOUNTER: {
10763 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10764 SDValue TheChain = N->getOperand(0);
10765 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10766 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10768 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10770 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10771 SDValue Ops[] = { eax, edx };
10772 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10773 Results.push_back(edx.getValue(1));
10776 case ISD::ATOMIC_CMP_SWAP: {
10777 EVT T = N->getValueType(0);
10778 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10779 bool Regs64bit = T == MVT::i128;
10780 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10781 SDValue cpInL, cpInH;
10782 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10783 DAG.getConstant(0, HalfT));
10784 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10785 DAG.getConstant(1, HalfT));
10786 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10787 Regs64bit ? X86::RAX : X86::EAX,
10789 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10790 Regs64bit ? X86::RDX : X86::EDX,
10791 cpInH, cpInL.getValue(1));
10792 SDValue swapInL, swapInH;
10793 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10794 DAG.getConstant(0, HalfT));
10795 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10796 DAG.getConstant(1, HalfT));
10797 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10798 Regs64bit ? X86::RBX : X86::EBX,
10799 swapInL, cpInH.getValue(1));
10800 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10801 Regs64bit ? X86::RCX : X86::ECX,
10802 swapInH, swapInL.getValue(1));
10803 SDValue Ops[] = { swapInH.getValue(0),
10805 swapInH.getValue(1) };
10806 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10807 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10808 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10809 X86ISD::LCMPXCHG8_DAG;
10810 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10812 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10813 Regs64bit ? X86::RAX : X86::EAX,
10814 HalfT, Result.getValue(1));
10815 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10816 Regs64bit ? X86::RDX : X86::EDX,
10817 HalfT, cpOutL.getValue(2));
10818 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10819 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10820 Results.push_back(cpOutH.getValue(1));
10823 case ISD::ATOMIC_LOAD_ADD:
10824 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10826 case ISD::ATOMIC_LOAD_AND:
10827 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10829 case ISD::ATOMIC_LOAD_NAND:
10830 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10832 case ISD::ATOMIC_LOAD_OR:
10833 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10835 case ISD::ATOMIC_LOAD_SUB:
10836 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10838 case ISD::ATOMIC_LOAD_XOR:
10839 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10841 case ISD::ATOMIC_SWAP:
10842 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10844 case ISD::ATOMIC_LOAD:
10845 ReplaceATOMIC_LOAD(N, Results, DAG);
10849 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10851 default: return NULL;
10852 case X86ISD::BSF: return "X86ISD::BSF";
10853 case X86ISD::BSR: return "X86ISD::BSR";
10854 case X86ISD::SHLD: return "X86ISD::SHLD";
10855 case X86ISD::SHRD: return "X86ISD::SHRD";
10856 case X86ISD::FAND: return "X86ISD::FAND";
10857 case X86ISD::FOR: return "X86ISD::FOR";
10858 case X86ISD::FXOR: return "X86ISD::FXOR";
10859 case X86ISD::FSRL: return "X86ISD::FSRL";
10860 case X86ISD::FILD: return "X86ISD::FILD";
10861 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10862 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10863 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10864 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10865 case X86ISD::FLD: return "X86ISD::FLD";
10866 case X86ISD::FST: return "X86ISD::FST";
10867 case X86ISD::CALL: return "X86ISD::CALL";
10868 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10869 case X86ISD::BT: return "X86ISD::BT";
10870 case X86ISD::CMP: return "X86ISD::CMP";
10871 case X86ISD::COMI: return "X86ISD::COMI";
10872 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10873 case X86ISD::SETCC: return "X86ISD::SETCC";
10874 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10875 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10876 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10877 case X86ISD::CMOV: return "X86ISD::CMOV";
10878 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10879 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10880 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10881 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10882 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10883 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10884 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10885 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10886 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10887 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10888 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10889 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10890 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10891 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10892 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10893 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10894 case X86ISD::HADD: return "X86ISD::HADD";
10895 case X86ISD::HSUB: return "X86ISD::HSUB";
10896 case X86ISD::FHADD: return "X86ISD::FHADD";
10897 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10898 case X86ISD::FMAX: return "X86ISD::FMAX";
10899 case X86ISD::FMIN: return "X86ISD::FMIN";
10900 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10901 case X86ISD::FRCP: return "X86ISD::FRCP";
10902 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10903 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10904 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10905 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10906 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10907 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10908 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10909 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10910 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10911 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10912 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10913 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10914 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10915 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10916 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10917 case X86ISD::VSHL: return "X86ISD::VSHL";
10918 case X86ISD::VSRL: return "X86ISD::VSRL";
10919 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10920 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10921 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10922 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10923 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10924 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10925 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10926 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10927 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10928 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10929 case X86ISD::ADD: return "X86ISD::ADD";
10930 case X86ISD::SUB: return "X86ISD::SUB";
10931 case X86ISD::ADC: return "X86ISD::ADC";
10932 case X86ISD::SBB: return "X86ISD::SBB";
10933 case X86ISD::SMUL: return "X86ISD::SMUL";
10934 case X86ISD::UMUL: return "X86ISD::UMUL";
10935 case X86ISD::INC: return "X86ISD::INC";
10936 case X86ISD::DEC: return "X86ISD::DEC";
10937 case X86ISD::OR: return "X86ISD::OR";
10938 case X86ISD::XOR: return "X86ISD::XOR";
10939 case X86ISD::AND: return "X86ISD::AND";
10940 case X86ISD::ANDN: return "X86ISD::ANDN";
10941 case X86ISD::BLSI: return "X86ISD::BLSI";
10942 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
10943 case X86ISD::BLSR: return "X86ISD::BLSR";
10944 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10945 case X86ISD::PTEST: return "X86ISD::PTEST";
10946 case X86ISD::TESTP: return "X86ISD::TESTP";
10947 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10948 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10949 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10950 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10951 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10952 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10953 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10954 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10955 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10956 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10957 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10958 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10959 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10960 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10961 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10962 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10963 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10964 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10965 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10966 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10967 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10968 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
10969 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
10970 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10971 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
10972 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
10973 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10974 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10975 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10976 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10977 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
10981 // isLegalAddressingMode - Return true if the addressing mode represented
10982 // by AM is legal for this target, for a load/store of the specified type.
10983 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10985 // X86 supports extremely general addressing modes.
10986 CodeModel::Model M = getTargetMachine().getCodeModel();
10987 Reloc::Model R = getTargetMachine().getRelocationModel();
10989 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10990 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10995 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10997 // If a reference to this global requires an extra load, we can't fold it.
10998 if (isGlobalStubReference(GVFlags))
11001 // If BaseGV requires a register for the PIC base, we cannot also have a
11002 // BaseReg specified.
11003 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11006 // If lower 4G is not available, then we must use rip-relative addressing.
11007 if ((M != CodeModel::Small || R != Reloc::Static) &&
11008 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11012 switch (AM.Scale) {
11018 // These scales always work.
11023 // These scales are formed with basereg+scalereg. Only accept if there is
11028 default: // Other stuff never works.
11036 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11037 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11039 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11040 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11041 if (NumBits1 <= NumBits2)
11046 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11047 if (!VT1.isInteger() || !VT2.isInteger())
11049 unsigned NumBits1 = VT1.getSizeInBits();
11050 unsigned NumBits2 = VT2.getSizeInBits();
11051 if (NumBits1 <= NumBits2)
11056 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11057 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11058 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11061 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11062 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11063 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11066 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11067 // i16 instructions are longer (0x66 prefix) and potentially slower.
11068 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11071 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11072 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11073 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11074 /// are assumed to be legal.
11076 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11078 // Very little shuffling can be done for 64-bit vectors right now.
11079 if (VT.getSizeInBits() == 64)
11082 // FIXME: pshufb, blends, shifts.
11083 return (VT.getVectorNumElements() == 2 ||
11084 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11085 isMOVLMask(M, VT) ||
11086 isSHUFPMask(M, VT) ||
11087 isPSHUFDMask(M, VT) ||
11088 isPSHUFHWMask(M, VT) ||
11089 isPSHUFLWMask(M, VT) ||
11090 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11091 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11092 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11093 isUNPCKL_v_undef_Mask(M, VT) ||
11094 isUNPCKH_v_undef_Mask(M, VT));
11098 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11100 unsigned NumElts = VT.getVectorNumElements();
11101 // FIXME: This collection of masks seems suspect.
11104 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11105 return (isMOVLMask(Mask, VT) ||
11106 isCommutedMOVLMask(Mask, VT, true) ||
11107 isSHUFPMask(Mask, VT) ||
11108 isSHUFPMask(Mask, VT, /* Commuted */ true));
11113 //===----------------------------------------------------------------------===//
11114 // X86 Scheduler Hooks
11115 //===----------------------------------------------------------------------===//
11117 // private utility function
11118 MachineBasicBlock *
11119 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11120 MachineBasicBlock *MBB,
11127 TargetRegisterClass *RC,
11128 bool invSrc) const {
11129 // For the atomic bitwise operator, we generate
11132 // ld t1 = [bitinstr.addr]
11133 // op t2 = t1, [bitinstr.val]
11135 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11137 // fallthrough -->nextMBB
11138 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11139 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11140 MachineFunction::iterator MBBIter = MBB;
11143 /// First build the CFG
11144 MachineFunction *F = MBB->getParent();
11145 MachineBasicBlock *thisMBB = MBB;
11146 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11147 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11148 F->insert(MBBIter, newMBB);
11149 F->insert(MBBIter, nextMBB);
11151 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11152 nextMBB->splice(nextMBB->begin(), thisMBB,
11153 llvm::next(MachineBasicBlock::iterator(bInstr)),
11155 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11157 // Update thisMBB to fall through to newMBB
11158 thisMBB->addSuccessor(newMBB);
11160 // newMBB jumps to itself and fall through to nextMBB
11161 newMBB->addSuccessor(nextMBB);
11162 newMBB->addSuccessor(newMBB);
11164 // Insert instructions into newMBB based on incoming instruction
11165 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11166 "unexpected number of operands");
11167 DebugLoc dl = bInstr->getDebugLoc();
11168 MachineOperand& destOper = bInstr->getOperand(0);
11169 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11170 int numArgs = bInstr->getNumOperands() - 1;
11171 for (int i=0; i < numArgs; ++i)
11172 argOpers[i] = &bInstr->getOperand(i+1);
11174 // x86 address has 4 operands: base, index, scale, and displacement
11175 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11176 int valArgIndx = lastAddrIndx + 1;
11178 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11179 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11180 for (int i=0; i <= lastAddrIndx; ++i)
11181 (*MIB).addOperand(*argOpers[i]);
11183 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11185 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11190 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11191 assert((argOpers[valArgIndx]->isReg() ||
11192 argOpers[valArgIndx]->isImm()) &&
11193 "invalid operand");
11194 if (argOpers[valArgIndx]->isReg())
11195 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11197 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11199 (*MIB).addOperand(*argOpers[valArgIndx]);
11201 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11204 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11205 for (int i=0; i <= lastAddrIndx; ++i)
11206 (*MIB).addOperand(*argOpers[i]);
11208 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11209 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11210 bInstr->memoperands_end());
11212 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11213 MIB.addReg(EAXreg);
11216 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11218 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11222 // private utility function: 64 bit atomics on 32 bit host.
11223 MachineBasicBlock *
11224 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11225 MachineBasicBlock *MBB,
11230 bool invSrc) const {
11231 // For the atomic bitwise operator, we generate
11232 // thisMBB (instructions are in pairs, except cmpxchg8b)
11233 // ld t1,t2 = [bitinstr.addr]
11235 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11236 // op t5, t6 <- out1, out2, [bitinstr.val]
11237 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11238 // mov ECX, EBX <- t5, t6
11239 // mov EAX, EDX <- t1, t2
11240 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11241 // mov t3, t4 <- EAX, EDX
11243 // result in out1, out2
11244 // fallthrough -->nextMBB
11246 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11247 const unsigned LoadOpc = X86::MOV32rm;
11248 const unsigned NotOpc = X86::NOT32r;
11249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11250 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11251 MachineFunction::iterator MBBIter = MBB;
11254 /// First build the CFG
11255 MachineFunction *F = MBB->getParent();
11256 MachineBasicBlock *thisMBB = MBB;
11257 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11258 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11259 F->insert(MBBIter, newMBB);
11260 F->insert(MBBIter, nextMBB);
11262 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11263 nextMBB->splice(nextMBB->begin(), thisMBB,
11264 llvm::next(MachineBasicBlock::iterator(bInstr)),
11266 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11268 // Update thisMBB to fall through to newMBB
11269 thisMBB->addSuccessor(newMBB);
11271 // newMBB jumps to itself and fall through to nextMBB
11272 newMBB->addSuccessor(nextMBB);
11273 newMBB->addSuccessor(newMBB);
11275 DebugLoc dl = bInstr->getDebugLoc();
11276 // Insert instructions into newMBB based on incoming instruction
11277 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11278 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11279 "unexpected number of operands");
11280 MachineOperand& dest1Oper = bInstr->getOperand(0);
11281 MachineOperand& dest2Oper = bInstr->getOperand(1);
11282 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11283 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11284 argOpers[i] = &bInstr->getOperand(i+2);
11286 // We use some of the operands multiple times, so conservatively just
11287 // clear any kill flags that might be present.
11288 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11289 argOpers[i]->setIsKill(false);
11292 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11293 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11295 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11296 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11297 for (int i=0; i <= lastAddrIndx; ++i)
11298 (*MIB).addOperand(*argOpers[i]);
11299 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11300 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11301 // add 4 to displacement.
11302 for (int i=0; i <= lastAddrIndx-2; ++i)
11303 (*MIB).addOperand(*argOpers[i]);
11304 MachineOperand newOp3 = *(argOpers[3]);
11305 if (newOp3.isImm())
11306 newOp3.setImm(newOp3.getImm()+4);
11308 newOp3.setOffset(newOp3.getOffset()+4);
11309 (*MIB).addOperand(newOp3);
11310 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11312 // t3/4 are defined later, at the bottom of the loop
11313 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11314 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11315 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11316 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11317 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11318 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11320 // The subsequent operations should be using the destination registers of
11321 //the PHI instructions.
11323 t1 = F->getRegInfo().createVirtualRegister(RC);
11324 t2 = F->getRegInfo().createVirtualRegister(RC);
11325 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11326 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11328 t1 = dest1Oper.getReg();
11329 t2 = dest2Oper.getReg();
11332 int valArgIndx = lastAddrIndx + 1;
11333 assert((argOpers[valArgIndx]->isReg() ||
11334 argOpers[valArgIndx]->isImm()) &&
11335 "invalid operand");
11336 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11337 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11338 if (argOpers[valArgIndx]->isReg())
11339 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11341 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11342 if (regOpcL != X86::MOV32rr)
11344 (*MIB).addOperand(*argOpers[valArgIndx]);
11345 assert(argOpers[valArgIndx + 1]->isReg() ==
11346 argOpers[valArgIndx]->isReg());
11347 assert(argOpers[valArgIndx + 1]->isImm() ==
11348 argOpers[valArgIndx]->isImm());
11349 if (argOpers[valArgIndx + 1]->isReg())
11350 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11352 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11353 if (regOpcH != X86::MOV32rr)
11355 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11357 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11359 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11362 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11364 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11367 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11368 for (int i=0; i <= lastAddrIndx; ++i)
11369 (*MIB).addOperand(*argOpers[i]);
11371 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11372 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11373 bInstr->memoperands_end());
11375 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11376 MIB.addReg(X86::EAX);
11377 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11378 MIB.addReg(X86::EDX);
11381 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11383 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11387 // private utility function
11388 MachineBasicBlock *
11389 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11390 MachineBasicBlock *MBB,
11391 unsigned cmovOpc) const {
11392 // For the atomic min/max operator, we generate
11395 // ld t1 = [min/max.addr]
11396 // mov t2 = [min/max.val]
11398 // cmov[cond] t2 = t1
11400 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11402 // fallthrough -->nextMBB
11404 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11405 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11406 MachineFunction::iterator MBBIter = MBB;
11409 /// First build the CFG
11410 MachineFunction *F = MBB->getParent();
11411 MachineBasicBlock *thisMBB = MBB;
11412 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11413 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11414 F->insert(MBBIter, newMBB);
11415 F->insert(MBBIter, nextMBB);
11417 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11418 nextMBB->splice(nextMBB->begin(), thisMBB,
11419 llvm::next(MachineBasicBlock::iterator(mInstr)),
11421 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11423 // Update thisMBB to fall through to newMBB
11424 thisMBB->addSuccessor(newMBB);
11426 // newMBB jumps to newMBB and fall through to nextMBB
11427 newMBB->addSuccessor(nextMBB);
11428 newMBB->addSuccessor(newMBB);
11430 DebugLoc dl = mInstr->getDebugLoc();
11431 // Insert instructions into newMBB based on incoming instruction
11432 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11433 "unexpected number of operands");
11434 MachineOperand& destOper = mInstr->getOperand(0);
11435 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11436 int numArgs = mInstr->getNumOperands() - 1;
11437 for (int i=0; i < numArgs; ++i)
11438 argOpers[i] = &mInstr->getOperand(i+1);
11440 // x86 address has 4 operands: base, index, scale, and displacement
11441 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11442 int valArgIndx = lastAddrIndx + 1;
11444 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11445 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11446 for (int i=0; i <= lastAddrIndx; ++i)
11447 (*MIB).addOperand(*argOpers[i]);
11449 // We only support register and immediate values
11450 assert((argOpers[valArgIndx]->isReg() ||
11451 argOpers[valArgIndx]->isImm()) &&
11452 "invalid operand");
11454 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11455 if (argOpers[valArgIndx]->isReg())
11456 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11458 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11459 (*MIB).addOperand(*argOpers[valArgIndx]);
11461 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11464 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11469 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11470 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11474 // Cmp and exchange if none has modified the memory location
11475 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11476 for (int i=0; i <= lastAddrIndx; ++i)
11477 (*MIB).addOperand(*argOpers[i]);
11479 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11480 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11481 mInstr->memoperands_end());
11483 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11484 MIB.addReg(X86::EAX);
11487 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11489 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11493 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11494 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11495 // in the .td file.
11496 MachineBasicBlock *
11497 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11498 unsigned numArgs, bool memArg) const {
11499 assert(Subtarget->hasSSE42orAVX() &&
11500 "Target must have SSE4.2 or AVX features enabled");
11502 DebugLoc dl = MI->getDebugLoc();
11503 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11505 if (!Subtarget->hasAVX()) {
11507 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11509 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11512 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11514 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11517 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11518 for (unsigned i = 0; i < numArgs; ++i) {
11519 MachineOperand &Op = MI->getOperand(i+1);
11520 if (!(Op.isReg() && Op.isImplicit()))
11521 MIB.addOperand(Op);
11523 BuildMI(*BB, MI, dl,
11524 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11525 MI->getOperand(0).getReg())
11526 .addReg(X86::XMM0);
11528 MI->eraseFromParent();
11532 MachineBasicBlock *
11533 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11534 DebugLoc dl = MI->getDebugLoc();
11535 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11537 // Address into RAX/EAX, other two args into ECX, EDX.
11538 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11539 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11540 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11541 for (int i = 0; i < X86::AddrNumOperands; ++i)
11542 MIB.addOperand(MI->getOperand(i));
11544 unsigned ValOps = X86::AddrNumOperands;
11545 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11546 .addReg(MI->getOperand(ValOps).getReg());
11547 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11548 .addReg(MI->getOperand(ValOps+1).getReg());
11550 // The instruction doesn't actually take any operands though.
11551 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11553 MI->eraseFromParent(); // The pseudo is gone now.
11557 MachineBasicBlock *
11558 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11559 DebugLoc dl = MI->getDebugLoc();
11560 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11562 // First arg in ECX, the second in EAX.
11563 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11564 .addReg(MI->getOperand(0).getReg());
11565 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11566 .addReg(MI->getOperand(1).getReg());
11568 // The instruction doesn't actually take any operands though.
11569 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11571 MI->eraseFromParent(); // The pseudo is gone now.
11575 MachineBasicBlock *
11576 X86TargetLowering::EmitVAARG64WithCustomInserter(
11578 MachineBasicBlock *MBB) const {
11579 // Emit va_arg instruction on X86-64.
11581 // Operands to this pseudo-instruction:
11582 // 0 ) Output : destination address (reg)
11583 // 1-5) Input : va_list address (addr, i64mem)
11584 // 6 ) ArgSize : Size (in bytes) of vararg type
11585 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11586 // 8 ) Align : Alignment of type
11587 // 9 ) EFLAGS (implicit-def)
11589 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11590 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11592 unsigned DestReg = MI->getOperand(0).getReg();
11593 MachineOperand &Base = MI->getOperand(1);
11594 MachineOperand &Scale = MI->getOperand(2);
11595 MachineOperand &Index = MI->getOperand(3);
11596 MachineOperand &Disp = MI->getOperand(4);
11597 MachineOperand &Segment = MI->getOperand(5);
11598 unsigned ArgSize = MI->getOperand(6).getImm();
11599 unsigned ArgMode = MI->getOperand(7).getImm();
11600 unsigned Align = MI->getOperand(8).getImm();
11602 // Memory Reference
11603 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11604 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11605 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11607 // Machine Information
11608 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11609 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11610 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11611 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11612 DebugLoc DL = MI->getDebugLoc();
11614 // struct va_list {
11617 // i64 overflow_area (address)
11618 // i64 reg_save_area (address)
11620 // sizeof(va_list) = 24
11621 // alignment(va_list) = 8
11623 unsigned TotalNumIntRegs = 6;
11624 unsigned TotalNumXMMRegs = 8;
11625 bool UseGPOffset = (ArgMode == 1);
11626 bool UseFPOffset = (ArgMode == 2);
11627 unsigned MaxOffset = TotalNumIntRegs * 8 +
11628 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11630 /* Align ArgSize to a multiple of 8 */
11631 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11632 bool NeedsAlign = (Align > 8);
11634 MachineBasicBlock *thisMBB = MBB;
11635 MachineBasicBlock *overflowMBB;
11636 MachineBasicBlock *offsetMBB;
11637 MachineBasicBlock *endMBB;
11639 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11640 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11641 unsigned OffsetReg = 0;
11643 if (!UseGPOffset && !UseFPOffset) {
11644 // If we only pull from the overflow region, we don't create a branch.
11645 // We don't need to alter control flow.
11646 OffsetDestReg = 0; // unused
11647 OverflowDestReg = DestReg;
11650 overflowMBB = thisMBB;
11653 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11654 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11655 // If not, pull from overflow_area. (branch to overflowMBB)
11660 // offsetMBB overflowMBB
11665 // Registers for the PHI in endMBB
11666 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11667 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11669 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11670 MachineFunction *MF = MBB->getParent();
11671 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11672 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11673 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11675 MachineFunction::iterator MBBIter = MBB;
11678 // Insert the new basic blocks
11679 MF->insert(MBBIter, offsetMBB);
11680 MF->insert(MBBIter, overflowMBB);
11681 MF->insert(MBBIter, endMBB);
11683 // Transfer the remainder of MBB and its successor edges to endMBB.
11684 endMBB->splice(endMBB->begin(), thisMBB,
11685 llvm::next(MachineBasicBlock::iterator(MI)),
11687 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11689 // Make offsetMBB and overflowMBB successors of thisMBB
11690 thisMBB->addSuccessor(offsetMBB);
11691 thisMBB->addSuccessor(overflowMBB);
11693 // endMBB is a successor of both offsetMBB and overflowMBB
11694 offsetMBB->addSuccessor(endMBB);
11695 overflowMBB->addSuccessor(endMBB);
11697 // Load the offset value into a register
11698 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11699 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11703 .addDisp(Disp, UseFPOffset ? 4 : 0)
11704 .addOperand(Segment)
11705 .setMemRefs(MMOBegin, MMOEnd);
11707 // Check if there is enough room left to pull this argument.
11708 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11710 .addImm(MaxOffset + 8 - ArgSizeA8);
11712 // Branch to "overflowMBB" if offset >= max
11713 // Fall through to "offsetMBB" otherwise
11714 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11715 .addMBB(overflowMBB);
11718 // In offsetMBB, emit code to use the reg_save_area.
11720 assert(OffsetReg != 0);
11722 // Read the reg_save_area address.
11723 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11724 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11729 .addOperand(Segment)
11730 .setMemRefs(MMOBegin, MMOEnd);
11732 // Zero-extend the offset
11733 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11734 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11737 .addImm(X86::sub_32bit);
11739 // Add the offset to the reg_save_area to get the final address.
11740 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11741 .addReg(OffsetReg64)
11742 .addReg(RegSaveReg);
11744 // Compute the offset for the next argument
11745 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11746 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11748 .addImm(UseFPOffset ? 16 : 8);
11750 // Store it back into the va_list.
11751 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11755 .addDisp(Disp, UseFPOffset ? 4 : 0)
11756 .addOperand(Segment)
11757 .addReg(NextOffsetReg)
11758 .setMemRefs(MMOBegin, MMOEnd);
11761 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11766 // Emit code to use overflow area
11769 // Load the overflow_area address into a register.
11770 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11771 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11776 .addOperand(Segment)
11777 .setMemRefs(MMOBegin, MMOEnd);
11779 // If we need to align it, do so. Otherwise, just copy the address
11780 // to OverflowDestReg.
11782 // Align the overflow address
11783 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11784 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11786 // aligned_addr = (addr + (align-1)) & ~(align-1)
11787 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11788 .addReg(OverflowAddrReg)
11791 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11793 .addImm(~(uint64_t)(Align-1));
11795 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11796 .addReg(OverflowAddrReg);
11799 // Compute the next overflow address after this argument.
11800 // (the overflow address should be kept 8-byte aligned)
11801 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11802 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11803 .addReg(OverflowDestReg)
11804 .addImm(ArgSizeA8);
11806 // Store the new overflow address.
11807 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11812 .addOperand(Segment)
11813 .addReg(NextAddrReg)
11814 .setMemRefs(MMOBegin, MMOEnd);
11816 // If we branched, emit the PHI to the front of endMBB.
11818 BuildMI(*endMBB, endMBB->begin(), DL,
11819 TII->get(X86::PHI), DestReg)
11820 .addReg(OffsetDestReg).addMBB(offsetMBB)
11821 .addReg(OverflowDestReg).addMBB(overflowMBB);
11824 // Erase the pseudo instruction
11825 MI->eraseFromParent();
11830 MachineBasicBlock *
11831 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11833 MachineBasicBlock *MBB) const {
11834 // Emit code to save XMM registers to the stack. The ABI says that the
11835 // number of registers to save is given in %al, so it's theoretically
11836 // possible to do an indirect jump trick to avoid saving all of them,
11837 // however this code takes a simpler approach and just executes all
11838 // of the stores if %al is non-zero. It's less code, and it's probably
11839 // easier on the hardware branch predictor, and stores aren't all that
11840 // expensive anyway.
11842 // Create the new basic blocks. One block contains all the XMM stores,
11843 // and one block is the final destination regardless of whether any
11844 // stores were performed.
11845 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11846 MachineFunction *F = MBB->getParent();
11847 MachineFunction::iterator MBBIter = MBB;
11849 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11850 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11851 F->insert(MBBIter, XMMSaveMBB);
11852 F->insert(MBBIter, EndMBB);
11854 // Transfer the remainder of MBB and its successor edges to EndMBB.
11855 EndMBB->splice(EndMBB->begin(), MBB,
11856 llvm::next(MachineBasicBlock::iterator(MI)),
11858 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11860 // The original block will now fall through to the XMM save block.
11861 MBB->addSuccessor(XMMSaveMBB);
11862 // The XMMSaveMBB will fall through to the end block.
11863 XMMSaveMBB->addSuccessor(EndMBB);
11865 // Now add the instructions.
11866 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11867 DebugLoc DL = MI->getDebugLoc();
11869 unsigned CountReg = MI->getOperand(0).getReg();
11870 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11871 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11873 if (!Subtarget->isTargetWin64()) {
11874 // If %al is 0, branch around the XMM save block.
11875 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11876 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11877 MBB->addSuccessor(EndMBB);
11880 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11881 // In the XMM save block, save all the XMM argument registers.
11882 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11883 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11884 MachineMemOperand *MMO =
11885 F->getMachineMemOperand(
11886 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11887 MachineMemOperand::MOStore,
11888 /*Size=*/16, /*Align=*/16);
11889 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11890 .addFrameIndex(RegSaveFrameIndex)
11891 .addImm(/*Scale=*/1)
11892 .addReg(/*IndexReg=*/0)
11893 .addImm(/*Disp=*/Offset)
11894 .addReg(/*Segment=*/0)
11895 .addReg(MI->getOperand(i).getReg())
11896 .addMemOperand(MMO);
11899 MI->eraseFromParent(); // The pseudo instruction is gone now.
11904 MachineBasicBlock *
11905 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11906 MachineBasicBlock *BB) const {
11907 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11908 DebugLoc DL = MI->getDebugLoc();
11910 // To "insert" a SELECT_CC instruction, we actually have to insert the
11911 // diamond control-flow pattern. The incoming instruction knows the
11912 // destination vreg to set, the condition code register to branch on, the
11913 // true/false values to select between, and a branch opcode to use.
11914 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11915 MachineFunction::iterator It = BB;
11921 // cmpTY ccX, r1, r2
11923 // fallthrough --> copy0MBB
11924 MachineBasicBlock *thisMBB = BB;
11925 MachineFunction *F = BB->getParent();
11926 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11927 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11928 F->insert(It, copy0MBB);
11929 F->insert(It, sinkMBB);
11931 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11932 // live into the sink and copy blocks.
11933 if (!MI->killsRegister(X86::EFLAGS)) {
11934 copy0MBB->addLiveIn(X86::EFLAGS);
11935 sinkMBB->addLiveIn(X86::EFLAGS);
11938 // Transfer the remainder of BB and its successor edges to sinkMBB.
11939 sinkMBB->splice(sinkMBB->begin(), BB,
11940 llvm::next(MachineBasicBlock::iterator(MI)),
11942 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11944 // Add the true and fallthrough blocks as its successors.
11945 BB->addSuccessor(copy0MBB);
11946 BB->addSuccessor(sinkMBB);
11948 // Create the conditional branch instruction.
11950 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11951 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11954 // %FalseValue = ...
11955 // # fallthrough to sinkMBB
11956 copy0MBB->addSuccessor(sinkMBB);
11959 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11961 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11962 TII->get(X86::PHI), MI->getOperand(0).getReg())
11963 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11964 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11966 MI->eraseFromParent(); // The pseudo instruction is gone now.
11970 MachineBasicBlock *
11971 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11972 bool Is64Bit) const {
11973 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11974 DebugLoc DL = MI->getDebugLoc();
11975 MachineFunction *MF = BB->getParent();
11976 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11978 assert(getTargetMachine().Options.EnableSegmentedStacks);
11980 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11981 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11984 // ... [Till the alloca]
11985 // If stacklet is not large enough, jump to mallocMBB
11988 // Allocate by subtracting from RSP
11989 // Jump to continueMBB
11992 // Allocate by call to runtime
11996 // [rest of original BB]
11999 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12000 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12001 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12003 MachineRegisterInfo &MRI = MF->getRegInfo();
12004 const TargetRegisterClass *AddrRegClass =
12005 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12007 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12008 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12009 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12010 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12011 sizeVReg = MI->getOperand(1).getReg(),
12012 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12014 MachineFunction::iterator MBBIter = BB;
12017 MF->insert(MBBIter, bumpMBB);
12018 MF->insert(MBBIter, mallocMBB);
12019 MF->insert(MBBIter, continueMBB);
12021 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12022 (MachineBasicBlock::iterator(MI)), BB->end());
12023 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12025 // Add code to the main basic block to check if the stack limit has been hit,
12026 // and if so, jump to mallocMBB otherwise to bumpMBB.
12027 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12028 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12029 .addReg(tmpSPVReg).addReg(sizeVReg);
12030 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12031 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12032 .addReg(SPLimitVReg);
12033 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12035 // bumpMBB simply decreases the stack pointer, since we know the current
12036 // stacklet has enough space.
12037 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12038 .addReg(SPLimitVReg);
12039 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12040 .addReg(SPLimitVReg);
12041 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12043 // Calls into a routine in libgcc to allocate more space from the heap.
12045 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12047 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12048 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12050 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12052 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12053 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12054 .addExternalSymbol("__morestack_allocate_stack_space");
12058 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12061 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12062 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12063 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12065 // Set up the CFG correctly.
12066 BB->addSuccessor(bumpMBB);
12067 BB->addSuccessor(mallocMBB);
12068 mallocMBB->addSuccessor(continueMBB);
12069 bumpMBB->addSuccessor(continueMBB);
12071 // Take care of the PHI nodes.
12072 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12073 MI->getOperand(0).getReg())
12074 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12075 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12077 // Delete the original pseudo instruction.
12078 MI->eraseFromParent();
12081 return continueMBB;
12084 MachineBasicBlock *
12085 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12086 MachineBasicBlock *BB) const {
12087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12088 DebugLoc DL = MI->getDebugLoc();
12090 assert(!Subtarget->isTargetEnvMacho());
12092 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12093 // non-trivial part is impdef of ESP.
12095 if (Subtarget->isTargetWin64()) {
12096 if (Subtarget->isTargetCygMing()) {
12097 // ___chkstk(Mingw64):
12098 // Clobbers R10, R11, RAX and EFLAGS.
12100 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12101 .addExternalSymbol("___chkstk")
12102 .addReg(X86::RAX, RegState::Implicit)
12103 .addReg(X86::RSP, RegState::Implicit)
12104 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12105 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12106 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12108 // __chkstk(MSVCRT): does not update stack pointer.
12109 // Clobbers R10, R11 and EFLAGS.
12110 // FIXME: RAX(allocated size) might be reused and not killed.
12111 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12112 .addExternalSymbol("__chkstk")
12113 .addReg(X86::RAX, RegState::Implicit)
12114 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12115 // RAX has the offset to subtracted from RSP.
12116 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12121 const char *StackProbeSymbol =
12122 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12124 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12125 .addExternalSymbol(StackProbeSymbol)
12126 .addReg(X86::EAX, RegState::Implicit)
12127 .addReg(X86::ESP, RegState::Implicit)
12128 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12129 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12130 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12133 MI->eraseFromParent(); // The pseudo instruction is gone now.
12137 MachineBasicBlock *
12138 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12139 MachineBasicBlock *BB) const {
12140 // This is pretty easy. We're taking the value that we received from
12141 // our load from the relocation, sticking it in either RDI (x86-64)
12142 // or EAX and doing an indirect call. The return value will then
12143 // be in the normal return register.
12144 const X86InstrInfo *TII
12145 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12146 DebugLoc DL = MI->getDebugLoc();
12147 MachineFunction *F = BB->getParent();
12149 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12150 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12152 if (Subtarget->is64Bit()) {
12153 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12154 TII->get(X86::MOV64rm), X86::RDI)
12156 .addImm(0).addReg(0)
12157 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12158 MI->getOperand(3).getTargetFlags())
12160 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12161 addDirectMem(MIB, X86::RDI);
12162 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12163 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12164 TII->get(X86::MOV32rm), X86::EAX)
12166 .addImm(0).addReg(0)
12167 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12168 MI->getOperand(3).getTargetFlags())
12170 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12171 addDirectMem(MIB, X86::EAX);
12173 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12174 TII->get(X86::MOV32rm), X86::EAX)
12175 .addReg(TII->getGlobalBaseReg(F))
12176 .addImm(0).addReg(0)
12177 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12178 MI->getOperand(3).getTargetFlags())
12180 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12181 addDirectMem(MIB, X86::EAX);
12184 MI->eraseFromParent(); // The pseudo instruction is gone now.
12188 MachineBasicBlock *
12189 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12190 MachineBasicBlock *BB) const {
12191 switch (MI->getOpcode()) {
12192 default: assert(0 && "Unexpected instr type to insert");
12193 case X86::TAILJMPd64:
12194 case X86::TAILJMPr64:
12195 case X86::TAILJMPm64:
12196 assert(0 && "TAILJMP64 would not be touched here.");
12197 case X86::TCRETURNdi64:
12198 case X86::TCRETURNri64:
12199 case X86::TCRETURNmi64:
12200 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12201 // On AMD64, additional defs should be added before register allocation.
12202 if (!Subtarget->isTargetWin64()) {
12203 MI->addRegisterDefined(X86::RSI);
12204 MI->addRegisterDefined(X86::RDI);
12205 MI->addRegisterDefined(X86::XMM6);
12206 MI->addRegisterDefined(X86::XMM7);
12207 MI->addRegisterDefined(X86::XMM8);
12208 MI->addRegisterDefined(X86::XMM9);
12209 MI->addRegisterDefined(X86::XMM10);
12210 MI->addRegisterDefined(X86::XMM11);
12211 MI->addRegisterDefined(X86::XMM12);
12212 MI->addRegisterDefined(X86::XMM13);
12213 MI->addRegisterDefined(X86::XMM14);
12214 MI->addRegisterDefined(X86::XMM15);
12217 case X86::WIN_ALLOCA:
12218 return EmitLoweredWinAlloca(MI, BB);
12219 case X86::SEG_ALLOCA_32:
12220 return EmitLoweredSegAlloca(MI, BB, false);
12221 case X86::SEG_ALLOCA_64:
12222 return EmitLoweredSegAlloca(MI, BB, true);
12223 case X86::TLSCall_32:
12224 case X86::TLSCall_64:
12225 return EmitLoweredTLSCall(MI, BB);
12226 case X86::CMOV_GR8:
12227 case X86::CMOV_FR32:
12228 case X86::CMOV_FR64:
12229 case X86::CMOV_V4F32:
12230 case X86::CMOV_V2F64:
12231 case X86::CMOV_V2I64:
12232 case X86::CMOV_V8F32:
12233 case X86::CMOV_V4F64:
12234 case X86::CMOV_V4I64:
12235 case X86::CMOV_GR16:
12236 case X86::CMOV_GR32:
12237 case X86::CMOV_RFP32:
12238 case X86::CMOV_RFP64:
12239 case X86::CMOV_RFP80:
12240 return EmitLoweredSelect(MI, BB);
12242 case X86::FP32_TO_INT16_IN_MEM:
12243 case X86::FP32_TO_INT32_IN_MEM:
12244 case X86::FP32_TO_INT64_IN_MEM:
12245 case X86::FP64_TO_INT16_IN_MEM:
12246 case X86::FP64_TO_INT32_IN_MEM:
12247 case X86::FP64_TO_INT64_IN_MEM:
12248 case X86::FP80_TO_INT16_IN_MEM:
12249 case X86::FP80_TO_INT32_IN_MEM:
12250 case X86::FP80_TO_INT64_IN_MEM: {
12251 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12252 DebugLoc DL = MI->getDebugLoc();
12254 // Change the floating point control register to use "round towards zero"
12255 // mode when truncating to an integer value.
12256 MachineFunction *F = BB->getParent();
12257 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12258 addFrameReference(BuildMI(*BB, MI, DL,
12259 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12261 // Load the old value of the high byte of the control word...
12263 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12264 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12267 // Set the high part to be round to zero...
12268 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12271 // Reload the modified control word now...
12272 addFrameReference(BuildMI(*BB, MI, DL,
12273 TII->get(X86::FLDCW16m)), CWFrameIdx);
12275 // Restore the memory image of control word to original value
12276 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12279 // Get the X86 opcode to use.
12281 switch (MI->getOpcode()) {
12282 default: llvm_unreachable("illegal opcode!");
12283 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12284 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12285 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12286 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12287 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12288 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12289 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12290 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12291 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12295 MachineOperand &Op = MI->getOperand(0);
12297 AM.BaseType = X86AddressMode::RegBase;
12298 AM.Base.Reg = Op.getReg();
12300 AM.BaseType = X86AddressMode::FrameIndexBase;
12301 AM.Base.FrameIndex = Op.getIndex();
12303 Op = MI->getOperand(1);
12305 AM.Scale = Op.getImm();
12306 Op = MI->getOperand(2);
12308 AM.IndexReg = Op.getImm();
12309 Op = MI->getOperand(3);
12310 if (Op.isGlobal()) {
12311 AM.GV = Op.getGlobal();
12313 AM.Disp = Op.getImm();
12315 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12316 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12318 // Reload the original control word now.
12319 addFrameReference(BuildMI(*BB, MI, DL,
12320 TII->get(X86::FLDCW16m)), CWFrameIdx);
12322 MI->eraseFromParent(); // The pseudo instruction is gone now.
12325 // String/text processing lowering.
12326 case X86::PCMPISTRM128REG:
12327 case X86::VPCMPISTRM128REG:
12328 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12329 case X86::PCMPISTRM128MEM:
12330 case X86::VPCMPISTRM128MEM:
12331 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12332 case X86::PCMPESTRM128REG:
12333 case X86::VPCMPESTRM128REG:
12334 return EmitPCMP(MI, BB, 5, false /* in mem */);
12335 case X86::PCMPESTRM128MEM:
12336 case X86::VPCMPESTRM128MEM:
12337 return EmitPCMP(MI, BB, 5, true /* in mem */);
12339 // Thread synchronization.
12341 return EmitMonitor(MI, BB);
12343 return EmitMwait(MI, BB);
12345 // Atomic Lowering.
12346 case X86::ATOMAND32:
12347 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12348 X86::AND32ri, X86::MOV32rm,
12350 X86::NOT32r, X86::EAX,
12351 X86::GR32RegisterClass);
12352 case X86::ATOMOR32:
12353 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12354 X86::OR32ri, X86::MOV32rm,
12356 X86::NOT32r, X86::EAX,
12357 X86::GR32RegisterClass);
12358 case X86::ATOMXOR32:
12359 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12360 X86::XOR32ri, X86::MOV32rm,
12362 X86::NOT32r, X86::EAX,
12363 X86::GR32RegisterClass);
12364 case X86::ATOMNAND32:
12365 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12366 X86::AND32ri, X86::MOV32rm,
12368 X86::NOT32r, X86::EAX,
12369 X86::GR32RegisterClass, true);
12370 case X86::ATOMMIN32:
12371 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12372 case X86::ATOMMAX32:
12373 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12374 case X86::ATOMUMIN32:
12375 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12376 case X86::ATOMUMAX32:
12377 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12379 case X86::ATOMAND16:
12380 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12381 X86::AND16ri, X86::MOV16rm,
12383 X86::NOT16r, X86::AX,
12384 X86::GR16RegisterClass);
12385 case X86::ATOMOR16:
12386 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12387 X86::OR16ri, X86::MOV16rm,
12389 X86::NOT16r, X86::AX,
12390 X86::GR16RegisterClass);
12391 case X86::ATOMXOR16:
12392 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12393 X86::XOR16ri, X86::MOV16rm,
12395 X86::NOT16r, X86::AX,
12396 X86::GR16RegisterClass);
12397 case X86::ATOMNAND16:
12398 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12399 X86::AND16ri, X86::MOV16rm,
12401 X86::NOT16r, X86::AX,
12402 X86::GR16RegisterClass, true);
12403 case X86::ATOMMIN16:
12404 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12405 case X86::ATOMMAX16:
12406 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12407 case X86::ATOMUMIN16:
12408 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12409 case X86::ATOMUMAX16:
12410 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12412 case X86::ATOMAND8:
12413 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12414 X86::AND8ri, X86::MOV8rm,
12416 X86::NOT8r, X86::AL,
12417 X86::GR8RegisterClass);
12419 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12420 X86::OR8ri, X86::MOV8rm,
12422 X86::NOT8r, X86::AL,
12423 X86::GR8RegisterClass);
12424 case X86::ATOMXOR8:
12425 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12426 X86::XOR8ri, X86::MOV8rm,
12428 X86::NOT8r, X86::AL,
12429 X86::GR8RegisterClass);
12430 case X86::ATOMNAND8:
12431 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12432 X86::AND8ri, X86::MOV8rm,
12434 X86::NOT8r, X86::AL,
12435 X86::GR8RegisterClass, true);
12436 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12437 // This group is for 64-bit host.
12438 case X86::ATOMAND64:
12439 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12440 X86::AND64ri32, X86::MOV64rm,
12442 X86::NOT64r, X86::RAX,
12443 X86::GR64RegisterClass);
12444 case X86::ATOMOR64:
12445 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12446 X86::OR64ri32, X86::MOV64rm,
12448 X86::NOT64r, X86::RAX,
12449 X86::GR64RegisterClass);
12450 case X86::ATOMXOR64:
12451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12452 X86::XOR64ri32, X86::MOV64rm,
12454 X86::NOT64r, X86::RAX,
12455 X86::GR64RegisterClass);
12456 case X86::ATOMNAND64:
12457 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12458 X86::AND64ri32, X86::MOV64rm,
12460 X86::NOT64r, X86::RAX,
12461 X86::GR64RegisterClass, true);
12462 case X86::ATOMMIN64:
12463 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12464 case X86::ATOMMAX64:
12465 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12466 case X86::ATOMUMIN64:
12467 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12468 case X86::ATOMUMAX64:
12469 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12471 // This group does 64-bit operations on a 32-bit host.
12472 case X86::ATOMAND6432:
12473 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12474 X86::AND32rr, X86::AND32rr,
12475 X86::AND32ri, X86::AND32ri,
12477 case X86::ATOMOR6432:
12478 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12479 X86::OR32rr, X86::OR32rr,
12480 X86::OR32ri, X86::OR32ri,
12482 case X86::ATOMXOR6432:
12483 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12484 X86::XOR32rr, X86::XOR32rr,
12485 X86::XOR32ri, X86::XOR32ri,
12487 case X86::ATOMNAND6432:
12488 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12489 X86::AND32rr, X86::AND32rr,
12490 X86::AND32ri, X86::AND32ri,
12492 case X86::ATOMADD6432:
12493 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12494 X86::ADD32rr, X86::ADC32rr,
12495 X86::ADD32ri, X86::ADC32ri,
12497 case X86::ATOMSUB6432:
12498 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12499 X86::SUB32rr, X86::SBB32rr,
12500 X86::SUB32ri, X86::SBB32ri,
12502 case X86::ATOMSWAP6432:
12503 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12504 X86::MOV32rr, X86::MOV32rr,
12505 X86::MOV32ri, X86::MOV32ri,
12507 case X86::VASTART_SAVE_XMM_REGS:
12508 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12510 case X86::VAARG_64:
12511 return EmitVAARG64WithCustomInserter(MI, BB);
12515 //===----------------------------------------------------------------------===//
12516 // X86 Optimization Hooks
12517 //===----------------------------------------------------------------------===//
12519 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12523 const SelectionDAG &DAG,
12524 unsigned Depth) const {
12525 unsigned Opc = Op.getOpcode();
12526 assert((Opc >= ISD::BUILTIN_OP_END ||
12527 Opc == ISD::INTRINSIC_WO_CHAIN ||
12528 Opc == ISD::INTRINSIC_W_CHAIN ||
12529 Opc == ISD::INTRINSIC_VOID) &&
12530 "Should use MaskedValueIsZero if you don't know whether Op"
12531 " is a target node!");
12533 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12547 // These nodes' second result is a boolean.
12548 if (Op.getResNo() == 0)
12551 case X86ISD::SETCC:
12552 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12553 Mask.getBitWidth() - 1);
12555 case ISD::INTRINSIC_WO_CHAIN: {
12556 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12557 unsigned NumLoBits = 0;
12560 case Intrinsic::x86_sse_movmsk_ps:
12561 case Intrinsic::x86_avx_movmsk_ps_256:
12562 case Intrinsic::x86_sse2_movmsk_pd:
12563 case Intrinsic::x86_avx_movmsk_pd_256:
12564 case Intrinsic::x86_mmx_pmovmskb:
12565 case Intrinsic::x86_sse2_pmovmskb_128: {
12566 // High bits of movmskp{s|d}, pmovmskb are known zero.
12568 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12569 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12570 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12571 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12572 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12573 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12575 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12576 Mask.getBitWidth() - NumLoBits);
12585 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12586 unsigned Depth) const {
12587 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12588 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12589 return Op.getValueType().getScalarType().getSizeInBits();
12595 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12596 /// node is a GlobalAddress + offset.
12597 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12598 const GlobalValue* &GA,
12599 int64_t &Offset) const {
12600 if (N->getOpcode() == X86ISD::Wrapper) {
12601 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12602 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12603 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12607 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12610 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12611 /// same as extracting the high 128-bit part of 256-bit vector and then
12612 /// inserting the result into the low part of a new 256-bit vector
12613 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12614 EVT VT = SVOp->getValueType(0);
12615 int NumElems = VT.getVectorNumElements();
12617 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12618 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12619 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12620 SVOp->getMaskElt(j) >= 0)
12626 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12627 /// same as extracting the low 128-bit part of 256-bit vector and then
12628 /// inserting the result into the high part of a new 256-bit vector
12629 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12630 EVT VT = SVOp->getValueType(0);
12631 int NumElems = VT.getVectorNumElements();
12633 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12634 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12635 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12636 SVOp->getMaskElt(j) >= 0)
12642 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12643 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12644 TargetLowering::DAGCombinerInfo &DCI) {
12645 DebugLoc dl = N->getDebugLoc();
12646 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12647 SDValue V1 = SVOp->getOperand(0);
12648 SDValue V2 = SVOp->getOperand(1);
12649 EVT VT = SVOp->getValueType(0);
12650 int NumElems = VT.getVectorNumElements();
12652 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12653 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12657 // V UNDEF BUILD_VECTOR UNDEF
12659 // CONCAT_VECTOR CONCAT_VECTOR
12662 // RESULT: V + zero extended
12664 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12665 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12666 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12669 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12672 // To match the shuffle mask, the first half of the mask should
12673 // be exactly the first vector, and all the rest a splat with the
12674 // first element of the second one.
12675 for (int i = 0; i < NumElems/2; ++i)
12676 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12677 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12680 // Emit a zeroed vector and insert the desired subvector on its
12682 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12683 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12684 DAG.getConstant(0, MVT::i32), DAG, dl);
12685 return DCI.CombineTo(N, InsV);
12688 //===--------------------------------------------------------------------===//
12689 // Combine some shuffles into subvector extracts and inserts:
12692 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12693 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12694 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12696 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12697 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12698 return DCI.CombineTo(N, InsV);
12701 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12702 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12703 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12704 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12705 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12706 return DCI.CombineTo(N, InsV);
12712 /// PerformShuffleCombine - Performs several different shuffle combines.
12713 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12714 TargetLowering::DAGCombinerInfo &DCI,
12715 const X86Subtarget *Subtarget) {
12716 DebugLoc dl = N->getDebugLoc();
12717 EVT VT = N->getValueType(0);
12719 // Don't create instructions with illegal types after legalize types has run.
12720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12721 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12724 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12725 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12726 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12727 return PerformShuffleCombine256(N, DAG, DCI);
12729 // Only handle 128 wide vector from here on.
12730 if (VT.getSizeInBits() != 128)
12733 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12734 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12735 // consecutive, non-overlapping, and in the right order.
12736 SmallVector<SDValue, 16> Elts;
12737 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12738 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12740 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12743 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12744 /// generation and convert it from being a bunch of shuffles and extracts
12745 /// to a simple store and scalar loads to extract the elements.
12746 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12747 const TargetLowering &TLI) {
12748 SDValue InputVector = N->getOperand(0);
12750 // Only operate on vectors of 4 elements, where the alternative shuffling
12751 // gets to be more expensive.
12752 if (InputVector.getValueType() != MVT::v4i32)
12755 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12756 // single use which is a sign-extend or zero-extend, and all elements are
12758 SmallVector<SDNode *, 4> Uses;
12759 unsigned ExtractedElements = 0;
12760 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12761 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12762 if (UI.getUse().getResNo() != InputVector.getResNo())
12765 SDNode *Extract = *UI;
12766 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12769 if (Extract->getValueType(0) != MVT::i32)
12771 if (!Extract->hasOneUse())
12773 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12774 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12776 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12779 // Record which element was extracted.
12780 ExtractedElements |=
12781 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12783 Uses.push_back(Extract);
12786 // If not all the elements were used, this may not be worthwhile.
12787 if (ExtractedElements != 15)
12790 // Ok, we've now decided to do the transformation.
12791 DebugLoc dl = InputVector.getDebugLoc();
12793 // Store the value to a temporary stack slot.
12794 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12795 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12796 MachinePointerInfo(), false, false, 0);
12798 // Replace each use (extract) with a load of the appropriate element.
12799 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12800 UE = Uses.end(); UI != UE; ++UI) {
12801 SDNode *Extract = *UI;
12803 // cOMpute the element's address.
12804 SDValue Idx = Extract->getOperand(1);
12806 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12807 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12808 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12810 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12811 StackPtr, OffsetVal);
12813 // Load the scalar.
12814 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12815 ScalarAddr, MachinePointerInfo(),
12816 false, false, false, 0);
12818 // Replace the exact with the load.
12819 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12822 // The replacement was made in place; don't return anything.
12826 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12828 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12829 const X86Subtarget *Subtarget) {
12830 DebugLoc DL = N->getDebugLoc();
12831 SDValue Cond = N->getOperand(0);
12832 // Get the LHS/RHS of the select.
12833 SDValue LHS = N->getOperand(1);
12834 SDValue RHS = N->getOperand(2);
12835 EVT VT = LHS.getValueType();
12837 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12838 // instructions match the semantics of the common C idiom x<y?x:y but not
12839 // x<=y?x:y, because of how they handle negative zero (which can be
12840 // ignored in unsafe-math mode).
12841 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12842 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12843 (Subtarget->hasXMMInt() ||
12844 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12845 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12847 unsigned Opcode = 0;
12848 // Check for x CC y ? x : y.
12849 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12850 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12854 // Converting this to a min would handle NaNs incorrectly, and swapping
12855 // the operands would cause it to handle comparisons between positive
12856 // and negative zero incorrectly.
12857 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12858 if (!DAG.getTarget().Options.UnsafeFPMath &&
12859 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12861 std::swap(LHS, RHS);
12863 Opcode = X86ISD::FMIN;
12866 // Converting this to a min would handle comparisons between positive
12867 // and negative zero incorrectly.
12868 if (!DAG.getTarget().Options.UnsafeFPMath &&
12869 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12871 Opcode = X86ISD::FMIN;
12874 // Converting this to a min would handle both negative zeros and NaNs
12875 // incorrectly, but we can swap the operands to fix both.
12876 std::swap(LHS, RHS);
12880 Opcode = X86ISD::FMIN;
12884 // Converting this to a max would handle comparisons between positive
12885 // and negative zero incorrectly.
12886 if (!DAG.getTarget().Options.UnsafeFPMath &&
12887 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12889 Opcode = X86ISD::FMAX;
12892 // Converting this to a max would handle NaNs incorrectly, and swapping
12893 // the operands would cause it to handle comparisons between positive
12894 // and negative zero incorrectly.
12895 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12896 if (!DAG.getTarget().Options.UnsafeFPMath &&
12897 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12899 std::swap(LHS, RHS);
12901 Opcode = X86ISD::FMAX;
12904 // Converting this to a max would handle both negative zeros and NaNs
12905 // incorrectly, but we can swap the operands to fix both.
12906 std::swap(LHS, RHS);
12910 Opcode = X86ISD::FMAX;
12913 // Check for x CC y ? y : x -- a min/max with reversed arms.
12914 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12915 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12919 // Converting this to a min would handle comparisons between positive
12920 // and negative zero incorrectly, and swapping the operands would
12921 // cause it to handle NaNs incorrectly.
12922 if (!DAG.getTarget().Options.UnsafeFPMath &&
12923 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12924 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12926 std::swap(LHS, RHS);
12928 Opcode = X86ISD::FMIN;
12931 // Converting this to a min would handle NaNs incorrectly.
12932 if (!DAG.getTarget().Options.UnsafeFPMath &&
12933 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12935 Opcode = X86ISD::FMIN;
12938 // Converting this to a min would handle both negative zeros and NaNs
12939 // incorrectly, but we can swap the operands to fix both.
12940 std::swap(LHS, RHS);
12944 Opcode = X86ISD::FMIN;
12948 // Converting this to a max would handle NaNs incorrectly.
12949 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12951 Opcode = X86ISD::FMAX;
12954 // Converting this to a max would handle comparisons between positive
12955 // and negative zero incorrectly, and swapping the operands would
12956 // cause it to handle NaNs incorrectly.
12957 if (!DAG.getTarget().Options.UnsafeFPMath &&
12958 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12959 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12961 std::swap(LHS, RHS);
12963 Opcode = X86ISD::FMAX;
12966 // Converting this to a max would handle both negative zeros and NaNs
12967 // incorrectly, but we can swap the operands to fix both.
12968 std::swap(LHS, RHS);
12972 Opcode = X86ISD::FMAX;
12978 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12981 // If this is a select between two integer constants, try to do some
12983 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12984 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12985 // Don't do this for crazy integer types.
12986 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12987 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12988 // so that TrueC (the true value) is larger than FalseC.
12989 bool NeedsCondInvert = false;
12991 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12992 // Efficiently invertible.
12993 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12994 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12995 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12996 NeedsCondInvert = true;
12997 std::swap(TrueC, FalseC);
13000 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13001 if (FalseC->getAPIntValue() == 0 &&
13002 TrueC->getAPIntValue().isPowerOf2()) {
13003 if (NeedsCondInvert) // Invert the condition if needed.
13004 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13005 DAG.getConstant(1, Cond.getValueType()));
13007 // Zero extend the condition if needed.
13008 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13010 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13011 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13012 DAG.getConstant(ShAmt, MVT::i8));
13015 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13016 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13017 if (NeedsCondInvert) // Invert the condition if needed.
13018 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13019 DAG.getConstant(1, Cond.getValueType()));
13021 // Zero extend the condition if needed.
13022 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13023 FalseC->getValueType(0), Cond);
13024 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13025 SDValue(FalseC, 0));
13028 // Optimize cases that will turn into an LEA instruction. This requires
13029 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13030 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13031 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13032 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13034 bool isFastMultiplier = false;
13036 switch ((unsigned char)Diff) {
13038 case 1: // result = add base, cond
13039 case 2: // result = lea base( , cond*2)
13040 case 3: // result = lea base(cond, cond*2)
13041 case 4: // result = lea base( , cond*4)
13042 case 5: // result = lea base(cond, cond*4)
13043 case 8: // result = lea base( , cond*8)
13044 case 9: // result = lea base(cond, cond*8)
13045 isFastMultiplier = true;
13050 if (isFastMultiplier) {
13051 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13052 if (NeedsCondInvert) // Invert the condition if needed.
13053 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13054 DAG.getConstant(1, Cond.getValueType()));
13056 // Zero extend the condition if needed.
13057 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13059 // Scale the condition by the difference.
13061 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13062 DAG.getConstant(Diff, Cond.getValueType()));
13064 // Add the base if non-zero.
13065 if (FalseC->getAPIntValue() != 0)
13066 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13067 SDValue(FalseC, 0));
13077 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13078 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13079 TargetLowering::DAGCombinerInfo &DCI) {
13080 DebugLoc DL = N->getDebugLoc();
13082 // If the flag operand isn't dead, don't touch this CMOV.
13083 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13086 SDValue FalseOp = N->getOperand(0);
13087 SDValue TrueOp = N->getOperand(1);
13088 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13089 SDValue Cond = N->getOperand(3);
13090 if (CC == X86::COND_E || CC == X86::COND_NE) {
13091 switch (Cond.getOpcode()) {
13095 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13096 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13097 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13101 // If this is a select between two integer constants, try to do some
13102 // optimizations. Note that the operands are ordered the opposite of SELECT
13104 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13105 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13106 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13107 // larger than FalseC (the false value).
13108 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13109 CC = X86::GetOppositeBranchCondition(CC);
13110 std::swap(TrueC, FalseC);
13113 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13114 // This is efficient for any integer data type (including i8/i16) and
13116 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13117 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13118 DAG.getConstant(CC, MVT::i8), Cond);
13120 // Zero extend the condition if needed.
13121 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13123 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13124 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13125 DAG.getConstant(ShAmt, MVT::i8));
13126 if (N->getNumValues() == 2) // Dead flag value?
13127 return DCI.CombineTo(N, Cond, SDValue());
13131 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13132 // for any integer data type, including i8/i16.
13133 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13134 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13135 DAG.getConstant(CC, MVT::i8), Cond);
13137 // Zero extend the condition if needed.
13138 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13139 FalseC->getValueType(0), Cond);
13140 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13141 SDValue(FalseC, 0));
13143 if (N->getNumValues() == 2) // Dead flag value?
13144 return DCI.CombineTo(N, Cond, SDValue());
13148 // Optimize cases that will turn into an LEA instruction. This requires
13149 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13150 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13151 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13152 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13154 bool isFastMultiplier = false;
13156 switch ((unsigned char)Diff) {
13158 case 1: // result = add base, cond
13159 case 2: // result = lea base( , cond*2)
13160 case 3: // result = lea base(cond, cond*2)
13161 case 4: // result = lea base( , cond*4)
13162 case 5: // result = lea base(cond, cond*4)
13163 case 8: // result = lea base( , cond*8)
13164 case 9: // result = lea base(cond, cond*8)
13165 isFastMultiplier = true;
13170 if (isFastMultiplier) {
13171 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13172 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13173 DAG.getConstant(CC, MVT::i8), Cond);
13174 // Zero extend the condition if needed.
13175 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13177 // Scale the condition by the difference.
13179 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13180 DAG.getConstant(Diff, Cond.getValueType()));
13182 // Add the base if non-zero.
13183 if (FalseC->getAPIntValue() != 0)
13184 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13185 SDValue(FalseC, 0));
13186 if (N->getNumValues() == 2) // Dead flag value?
13187 return DCI.CombineTo(N, Cond, SDValue());
13197 /// PerformMulCombine - Optimize a single multiply with constant into two
13198 /// in order to implement it with two cheaper instructions, e.g.
13199 /// LEA + SHL, LEA + LEA.
13200 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13201 TargetLowering::DAGCombinerInfo &DCI) {
13202 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13205 EVT VT = N->getValueType(0);
13206 if (VT != MVT::i64)
13209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13212 uint64_t MulAmt = C->getZExtValue();
13213 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13216 uint64_t MulAmt1 = 0;
13217 uint64_t MulAmt2 = 0;
13218 if ((MulAmt % 9) == 0) {
13220 MulAmt2 = MulAmt / 9;
13221 } else if ((MulAmt % 5) == 0) {
13223 MulAmt2 = MulAmt / 5;
13224 } else if ((MulAmt % 3) == 0) {
13226 MulAmt2 = MulAmt / 3;
13229 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13230 DebugLoc DL = N->getDebugLoc();
13232 if (isPowerOf2_64(MulAmt2) &&
13233 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13234 // If second multiplifer is pow2, issue it first. We want the multiply by
13235 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13237 std::swap(MulAmt1, MulAmt2);
13240 if (isPowerOf2_64(MulAmt1))
13241 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13242 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13244 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13245 DAG.getConstant(MulAmt1, VT));
13247 if (isPowerOf2_64(MulAmt2))
13248 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13249 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13251 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13252 DAG.getConstant(MulAmt2, VT));
13254 // Do not add new nodes to DAG combiner worklist.
13255 DCI.CombineTo(N, NewMul, false);
13260 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13261 SDValue N0 = N->getOperand(0);
13262 SDValue N1 = N->getOperand(1);
13263 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13264 EVT VT = N0.getValueType();
13266 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13267 // since the result of setcc_c is all zero's or all ones.
13268 if (VT.isInteger() && !VT.isVector() &&
13269 N1C && N0.getOpcode() == ISD::AND &&
13270 N0.getOperand(1).getOpcode() == ISD::Constant) {
13271 SDValue N00 = N0.getOperand(0);
13272 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13273 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13274 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13275 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13276 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13277 APInt ShAmt = N1C->getAPIntValue();
13278 Mask = Mask.shl(ShAmt);
13280 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13281 N00, DAG.getConstant(Mask, VT));
13286 // Hardware support for vector shifts is sparse which makes us scalarize the
13287 // vector operations in many cases. Also, on sandybridge ADD is faster than
13289 // (shl V, 1) -> add V,V
13290 if (isSplatVector(N1.getNode())) {
13291 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13293 // We shift all of the values by one. In many cases we do not have
13294 // hardware support for this operation. This is better expressed as an ADD
13296 if (N1C && (1 == N1C->getZExtValue())) {
13297 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13304 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13306 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13307 const X86Subtarget *Subtarget) {
13308 EVT VT = N->getValueType(0);
13309 if (N->getOpcode() == ISD::SHL) {
13310 SDValue V = PerformSHLCombine(N, DAG);
13311 if (V.getNode()) return V;
13314 // On X86 with SSE2 support, we can transform this to a vector shift if
13315 // all elements are shifted by the same amount. We can't do this in legalize
13316 // because the a constant vector is typically transformed to a constant pool
13317 // so we have no knowledge of the shift amount.
13318 if (!Subtarget->hasXMMInt())
13321 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13322 (!Subtarget->hasAVX2() ||
13323 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13326 SDValue ShAmtOp = N->getOperand(1);
13327 EVT EltVT = VT.getVectorElementType();
13328 DebugLoc DL = N->getDebugLoc();
13329 SDValue BaseShAmt = SDValue();
13330 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13331 unsigned NumElts = VT.getVectorNumElements();
13333 for (; i != NumElts; ++i) {
13334 SDValue Arg = ShAmtOp.getOperand(i);
13335 if (Arg.getOpcode() == ISD::UNDEF) continue;
13339 for (; i != NumElts; ++i) {
13340 SDValue Arg = ShAmtOp.getOperand(i);
13341 if (Arg.getOpcode() == ISD::UNDEF) continue;
13342 if (Arg != BaseShAmt) {
13346 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13347 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13348 SDValue InVec = ShAmtOp.getOperand(0);
13349 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13350 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13352 for (; i != NumElts; ++i) {
13353 SDValue Arg = InVec.getOperand(i);
13354 if (Arg.getOpcode() == ISD::UNDEF) continue;
13358 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13360 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13361 if (C->getZExtValue() == SplatIdx)
13362 BaseShAmt = InVec.getOperand(1);
13365 if (BaseShAmt.getNode() == 0)
13366 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13367 DAG.getIntPtrConstant(0));
13371 // The shift amount is an i32.
13372 if (EltVT.bitsGT(MVT::i32))
13373 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13374 else if (EltVT.bitsLT(MVT::i32))
13375 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13377 // The shift amount is identical so we can do a vector shift.
13378 SDValue ValOp = N->getOperand(0);
13379 switch (N->getOpcode()) {
13381 llvm_unreachable("Unknown shift opcode!");
13384 if (VT == MVT::v2i64)
13385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13386 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13388 if (VT == MVT::v4i32)
13389 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13390 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13392 if (VT == MVT::v8i16)
13393 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13394 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13396 if (VT == MVT::v4i64)
13397 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13398 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13400 if (VT == MVT::v8i32)
13401 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13402 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13404 if (VT == MVT::v16i16)
13405 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13406 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13410 if (VT == MVT::v4i32)
13411 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13412 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13414 if (VT == MVT::v8i16)
13415 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13416 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13418 if (VT == MVT::v8i32)
13419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13420 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13422 if (VT == MVT::v16i16)
13423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13424 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13428 if (VT == MVT::v2i64)
13429 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13430 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13432 if (VT == MVT::v4i32)
13433 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13434 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13436 if (VT == MVT::v8i16)
13437 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13438 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13440 if (VT == MVT::v4i64)
13441 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13442 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13444 if (VT == MVT::v8i32)
13445 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13446 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13448 if (VT == MVT::v16i16)
13449 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13450 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13458 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13459 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13460 // and friends. Likewise for OR -> CMPNEQSS.
13461 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13462 TargetLowering::DAGCombinerInfo &DCI,
13463 const X86Subtarget *Subtarget) {
13466 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13467 // we're requiring SSE2 for both.
13468 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13469 SDValue N0 = N->getOperand(0);
13470 SDValue N1 = N->getOperand(1);
13471 SDValue CMP0 = N0->getOperand(1);
13472 SDValue CMP1 = N1->getOperand(1);
13473 DebugLoc DL = N->getDebugLoc();
13475 // The SETCCs should both refer to the same CMP.
13476 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13479 SDValue CMP00 = CMP0->getOperand(0);
13480 SDValue CMP01 = CMP0->getOperand(1);
13481 EVT VT = CMP00.getValueType();
13483 if (VT == MVT::f32 || VT == MVT::f64) {
13484 bool ExpectingFlags = false;
13485 // Check for any users that want flags:
13486 for (SDNode::use_iterator UI = N->use_begin(),
13488 !ExpectingFlags && UI != UE; ++UI)
13489 switch (UI->getOpcode()) {
13494 ExpectingFlags = true;
13496 case ISD::CopyToReg:
13497 case ISD::SIGN_EXTEND:
13498 case ISD::ZERO_EXTEND:
13499 case ISD::ANY_EXTEND:
13503 if (!ExpectingFlags) {
13504 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13505 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13507 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13508 X86::CondCode tmp = cc0;
13513 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13514 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13515 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13516 X86ISD::NodeType NTOperator = is64BitFP ?
13517 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13518 // FIXME: need symbolic constants for these magic numbers.
13519 // See X86ATTInstPrinter.cpp:printSSECC().
13520 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13521 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13522 DAG.getConstant(x86cc, MVT::i8));
13523 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13525 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13526 DAG.getConstant(1, MVT::i32));
13527 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13528 return OneBitOfTruth;
13536 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13537 /// so it can be folded inside ANDNP.
13538 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13539 EVT VT = N->getValueType(0);
13541 // Match direct AllOnes for 128 and 256-bit vectors
13542 if (ISD::isBuildVectorAllOnes(N))
13545 // Look through a bit convert.
13546 if (N->getOpcode() == ISD::BITCAST)
13547 N = N->getOperand(0).getNode();
13549 // Sometimes the operand may come from a insert_subvector building a 256-bit
13551 if (VT.getSizeInBits() == 256 &&
13552 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13553 SDValue V1 = N->getOperand(0);
13554 SDValue V2 = N->getOperand(1);
13556 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13557 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13558 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13559 ISD::isBuildVectorAllOnes(V2.getNode()))
13566 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13567 TargetLowering::DAGCombinerInfo &DCI,
13568 const X86Subtarget *Subtarget) {
13569 if (DCI.isBeforeLegalizeOps())
13572 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13576 EVT VT = N->getValueType(0);
13578 // Create ANDN, BLSI, and BLSR instructions
13579 // BLSI is X & (-X)
13580 // BLSR is X & (X-1)
13581 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13582 SDValue N0 = N->getOperand(0);
13583 SDValue N1 = N->getOperand(1);
13584 DebugLoc DL = N->getDebugLoc();
13586 // Check LHS for not
13587 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13588 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13589 // Check RHS for not
13590 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13591 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13593 // Check LHS for neg
13594 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13595 isZero(N0.getOperand(0)))
13596 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13598 // Check RHS for neg
13599 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13600 isZero(N1.getOperand(0)))
13601 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13603 // Check LHS for X-1
13604 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13605 isAllOnes(N0.getOperand(1)))
13606 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13608 // Check RHS for X-1
13609 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13610 isAllOnes(N1.getOperand(1)))
13611 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13616 // Want to form ANDNP nodes:
13617 // 1) In the hopes of then easily combining them with OR and AND nodes
13618 // to form PBLEND/PSIGN.
13619 // 2) To match ANDN packed intrinsics
13620 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13623 SDValue N0 = N->getOperand(0);
13624 SDValue N1 = N->getOperand(1);
13625 DebugLoc DL = N->getDebugLoc();
13627 // Check LHS for vnot
13628 if (N0.getOpcode() == ISD::XOR &&
13629 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13630 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13631 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13633 // Check RHS for vnot
13634 if (N1.getOpcode() == ISD::XOR &&
13635 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13636 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13637 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13642 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13643 TargetLowering::DAGCombinerInfo &DCI,
13644 const X86Subtarget *Subtarget) {
13645 if (DCI.isBeforeLegalizeOps())
13648 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13652 EVT VT = N->getValueType(0);
13654 SDValue N0 = N->getOperand(0);
13655 SDValue N1 = N->getOperand(1);
13657 // look for psign/blend
13658 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13659 if (!Subtarget->hasSSSE3orAVX() ||
13660 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13663 // Canonicalize pandn to RHS
13664 if (N0.getOpcode() == X86ISD::ANDNP)
13666 // or (and (m, x), (pandn m, y))
13667 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13668 SDValue Mask = N1.getOperand(0);
13669 SDValue X = N1.getOperand(1);
13671 if (N0.getOperand(0) == Mask)
13672 Y = N0.getOperand(1);
13673 if (N0.getOperand(1) == Mask)
13674 Y = N0.getOperand(0);
13676 // Check to see if the mask appeared in both the AND and ANDNP and
13680 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13681 if (Mask.getOpcode() != ISD::BITCAST ||
13682 X.getOpcode() != ISD::BITCAST ||
13683 Y.getOpcode() != ISD::BITCAST)
13686 // Look through mask bitcast.
13687 Mask = Mask.getOperand(0);
13688 EVT MaskVT = Mask.getValueType();
13690 // Validate that the Mask operand is a vector sra node. The sra node
13691 // will be an intrinsic.
13692 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13695 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13696 // there is no psrai.b
13697 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13698 case Intrinsic::x86_sse2_psrai_w:
13699 case Intrinsic::x86_sse2_psrai_d:
13700 case Intrinsic::x86_avx2_psrai_w:
13701 case Intrinsic::x86_avx2_psrai_d:
13703 default: return SDValue();
13706 // Check that the SRA is all signbits.
13707 SDValue SraC = Mask.getOperand(2);
13708 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13709 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13710 if ((SraAmt + 1) != EltBits)
13713 DebugLoc DL = N->getDebugLoc();
13715 // Now we know we at least have a plendvb with the mask val. See if
13716 // we can form a psignb/w/d.
13717 // psign = x.type == y.type == mask.type && y = sub(0, x);
13718 X = X.getOperand(0);
13719 Y = Y.getOperand(0);
13720 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13721 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13722 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13723 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13724 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13725 Mask.getOperand(1));
13726 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13728 // PBLENDVB only available on SSE 4.1
13729 if (!Subtarget->hasSSE41orAVX())
13732 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13734 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13735 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13736 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13737 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13738 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13742 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13745 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13746 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13748 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13750 if (!N0.hasOneUse() || !N1.hasOneUse())
13753 SDValue ShAmt0 = N0.getOperand(1);
13754 if (ShAmt0.getValueType() != MVT::i8)
13756 SDValue ShAmt1 = N1.getOperand(1);
13757 if (ShAmt1.getValueType() != MVT::i8)
13759 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13760 ShAmt0 = ShAmt0.getOperand(0);
13761 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13762 ShAmt1 = ShAmt1.getOperand(0);
13764 DebugLoc DL = N->getDebugLoc();
13765 unsigned Opc = X86ISD::SHLD;
13766 SDValue Op0 = N0.getOperand(0);
13767 SDValue Op1 = N1.getOperand(0);
13768 if (ShAmt0.getOpcode() == ISD::SUB) {
13769 Opc = X86ISD::SHRD;
13770 std::swap(Op0, Op1);
13771 std::swap(ShAmt0, ShAmt1);
13774 unsigned Bits = VT.getSizeInBits();
13775 if (ShAmt1.getOpcode() == ISD::SUB) {
13776 SDValue Sum = ShAmt1.getOperand(0);
13777 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13778 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13779 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13780 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13781 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13782 return DAG.getNode(Opc, DL, VT,
13784 DAG.getNode(ISD::TRUNCATE, DL,
13787 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13788 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13790 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13791 return DAG.getNode(Opc, DL, VT,
13792 N0.getOperand(0), N1.getOperand(0),
13793 DAG.getNode(ISD::TRUNCATE, DL,
13800 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13801 TargetLowering::DAGCombinerInfo &DCI,
13802 const X86Subtarget *Subtarget) {
13803 if (DCI.isBeforeLegalizeOps())
13806 EVT VT = N->getValueType(0);
13808 if (VT != MVT::i32 && VT != MVT::i64)
13811 // Create BLSMSK instructions by finding X ^ (X-1)
13812 SDValue N0 = N->getOperand(0);
13813 SDValue N1 = N->getOperand(1);
13814 DebugLoc DL = N->getDebugLoc();
13816 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13817 isAllOnes(N0.getOperand(1)))
13818 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13820 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13821 isAllOnes(N1.getOperand(1)))
13822 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13827 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13828 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13829 const X86Subtarget *Subtarget) {
13830 LoadSDNode *Ld = cast<LoadSDNode>(N);
13831 EVT RegVT = Ld->getValueType(0);
13832 EVT MemVT = Ld->getMemoryVT();
13833 DebugLoc dl = Ld->getDebugLoc();
13834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13836 ISD::LoadExtType Ext = Ld->getExtensionType();
13838 // If this is a vector EXT Load then attempt to optimize it using a
13839 // shuffle. We need SSE4 for the shuffles.
13840 // TODO: It is possible to support ZExt by zeroing the undef values
13841 // during the shuffle phase or after the shuffle.
13842 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13843 assert(MemVT != RegVT && "Cannot extend to the same type");
13844 assert(MemVT.isVector() && "Must load a vector from memory");
13846 unsigned NumElems = RegVT.getVectorNumElements();
13847 unsigned RegSz = RegVT.getSizeInBits();
13848 unsigned MemSz = MemVT.getSizeInBits();
13849 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13850 // All sizes must be a power of two
13851 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13853 // Attempt to load the original value using a single load op.
13854 // Find a scalar type which is equal to the loaded word size.
13855 MVT SclrLoadTy = MVT::i8;
13856 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13857 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13858 MVT Tp = (MVT::SimpleValueType)tp;
13859 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13865 // Proceed if a load word is found.
13866 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13868 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13869 RegSz/SclrLoadTy.getSizeInBits());
13871 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13872 RegSz/MemVT.getScalarType().getSizeInBits());
13873 // Can't shuffle using an illegal type.
13874 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13876 // Perform a single load.
13877 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13879 Ld->getPointerInfo(), Ld->isVolatile(),
13880 Ld->isNonTemporal(), Ld->isInvariant(),
13881 Ld->getAlignment());
13883 // Insert the word loaded into a vector.
13884 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13885 LoadUnitVecVT, ScalarLoad);
13887 // Bitcast the loaded value to a vector of the original element type, in
13888 // the size of the target vector type.
13889 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13890 unsigned SizeRatio = RegSz/MemSz;
13892 // Redistribute the loaded elements into the different locations.
13893 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13894 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13896 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13897 DAG.getUNDEF(SlicedVec.getValueType()),
13898 ShuffleVec.data());
13900 // Bitcast to the requested type.
13901 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13902 // Replace the original load with the new sequence
13903 // and return the new chain.
13904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13905 return SDValue(ScalarLoad.getNode(), 1);
13911 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13912 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13913 const X86Subtarget *Subtarget) {
13914 StoreSDNode *St = cast<StoreSDNode>(N);
13915 EVT VT = St->getValue().getValueType();
13916 EVT StVT = St->getMemoryVT();
13917 DebugLoc dl = St->getDebugLoc();
13918 SDValue StoredVal = St->getOperand(1);
13919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13921 // If we are saving a concatenation of two XMM registers, perform two stores.
13922 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13923 // 128-bit ones. If in the future the cost becomes only one memory access the
13924 // first version would be better.
13925 if (VT.getSizeInBits() == 256 &&
13926 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13927 StoredVal.getNumOperands() == 2) {
13929 SDValue Value0 = StoredVal.getOperand(0);
13930 SDValue Value1 = StoredVal.getOperand(1);
13932 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13933 SDValue Ptr0 = St->getBasePtr();
13934 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13936 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13937 St->getPointerInfo(), St->isVolatile(),
13938 St->isNonTemporal(), St->getAlignment());
13939 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13940 St->getPointerInfo(), St->isVolatile(),
13941 St->isNonTemporal(), St->getAlignment());
13942 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13945 // Optimize trunc store (of multiple scalars) to shuffle and store.
13946 // First, pack all of the elements in one place. Next, store to memory
13947 // in fewer chunks.
13948 if (St->isTruncatingStore() && VT.isVector()) {
13949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13950 unsigned NumElems = VT.getVectorNumElements();
13951 assert(StVT != VT && "Cannot truncate to the same type");
13952 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13953 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13955 // From, To sizes and ElemCount must be pow of two
13956 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13957 // We are going to use the original vector elt for storing.
13958 // Accumulated smaller vector elements must be a multiple of the store size.
13959 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13961 unsigned SizeRatio = FromSz / ToSz;
13963 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13965 // Create a type on which we perform the shuffle
13966 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13967 StVT.getScalarType(), NumElems*SizeRatio);
13969 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13971 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13972 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13973 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13975 // Can't shuffle using an illegal type
13976 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13978 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13979 DAG.getUNDEF(WideVec.getValueType()),
13980 ShuffleVec.data());
13981 // At this point all of the data is stored at the bottom of the
13982 // register. We now need to save it to mem.
13984 // Find the largest store unit
13985 MVT StoreType = MVT::i8;
13986 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13987 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13988 MVT Tp = (MVT::SimpleValueType)tp;
13989 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13993 // Bitcast the original vector into a vector of store-size units
13994 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13995 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13996 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13997 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13998 SmallVector<SDValue, 8> Chains;
13999 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14000 TLI.getPointerTy());
14001 SDValue Ptr = St->getBasePtr();
14003 // Perform one or more big stores into memory.
14004 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14005 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14006 StoreType, ShuffWide,
14007 DAG.getIntPtrConstant(i));
14008 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14009 St->getPointerInfo(), St->isVolatile(),
14010 St->isNonTemporal(), St->getAlignment());
14011 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14012 Chains.push_back(Ch);
14015 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14020 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14021 // the FP state in cases where an emms may be missing.
14022 // A preferable solution to the general problem is to figure out the right
14023 // places to insert EMMS. This qualifies as a quick hack.
14025 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14026 if (VT.getSizeInBits() != 64)
14029 const Function *F = DAG.getMachineFunction().getFunction();
14030 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14031 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14032 && Subtarget->hasXMMInt();
14033 if ((VT.isVector() ||
14034 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14035 isa<LoadSDNode>(St->getValue()) &&
14036 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14037 St->getChain().hasOneUse() && !St->isVolatile()) {
14038 SDNode* LdVal = St->getValue().getNode();
14039 LoadSDNode *Ld = 0;
14040 int TokenFactorIndex = -1;
14041 SmallVector<SDValue, 8> Ops;
14042 SDNode* ChainVal = St->getChain().getNode();
14043 // Must be a store of a load. We currently handle two cases: the load
14044 // is a direct child, and it's under an intervening TokenFactor. It is
14045 // possible to dig deeper under nested TokenFactors.
14046 if (ChainVal == LdVal)
14047 Ld = cast<LoadSDNode>(St->getChain());
14048 else if (St->getValue().hasOneUse() &&
14049 ChainVal->getOpcode() == ISD::TokenFactor) {
14050 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14051 if (ChainVal->getOperand(i).getNode() == LdVal) {
14052 TokenFactorIndex = i;
14053 Ld = cast<LoadSDNode>(St->getValue());
14055 Ops.push_back(ChainVal->getOperand(i));
14059 if (!Ld || !ISD::isNormalLoad(Ld))
14062 // If this is not the MMX case, i.e. we are just turning i64 load/store
14063 // into f64 load/store, avoid the transformation if there are multiple
14064 // uses of the loaded value.
14065 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14068 DebugLoc LdDL = Ld->getDebugLoc();
14069 DebugLoc StDL = N->getDebugLoc();
14070 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14071 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14073 if (Subtarget->is64Bit() || F64IsLegal) {
14074 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14075 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14076 Ld->getPointerInfo(), Ld->isVolatile(),
14077 Ld->isNonTemporal(), Ld->isInvariant(),
14078 Ld->getAlignment());
14079 SDValue NewChain = NewLd.getValue(1);
14080 if (TokenFactorIndex != -1) {
14081 Ops.push_back(NewChain);
14082 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14085 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14086 St->getPointerInfo(),
14087 St->isVolatile(), St->isNonTemporal(),
14088 St->getAlignment());
14091 // Otherwise, lower to two pairs of 32-bit loads / stores.
14092 SDValue LoAddr = Ld->getBasePtr();
14093 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14094 DAG.getConstant(4, MVT::i32));
14096 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14097 Ld->getPointerInfo(),
14098 Ld->isVolatile(), Ld->isNonTemporal(),
14099 Ld->isInvariant(), Ld->getAlignment());
14100 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14101 Ld->getPointerInfo().getWithOffset(4),
14102 Ld->isVolatile(), Ld->isNonTemporal(),
14104 MinAlign(Ld->getAlignment(), 4));
14106 SDValue NewChain = LoLd.getValue(1);
14107 if (TokenFactorIndex != -1) {
14108 Ops.push_back(LoLd);
14109 Ops.push_back(HiLd);
14110 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14114 LoAddr = St->getBasePtr();
14115 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14116 DAG.getConstant(4, MVT::i32));
14118 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14119 St->getPointerInfo(),
14120 St->isVolatile(), St->isNonTemporal(),
14121 St->getAlignment());
14122 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14123 St->getPointerInfo().getWithOffset(4),
14125 St->isNonTemporal(),
14126 MinAlign(St->getAlignment(), 4));
14127 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14132 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14133 /// and return the operands for the horizontal operation in LHS and RHS. A
14134 /// horizontal operation performs the binary operation on successive elements
14135 /// of its first operand, then on successive elements of its second operand,
14136 /// returning the resulting values in a vector. For example, if
14137 /// A = < float a0, float a1, float a2, float a3 >
14139 /// B = < float b0, float b1, float b2, float b3 >
14140 /// then the result of doing a horizontal operation on A and B is
14141 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14142 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14143 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14144 /// set to A, RHS to B, and the routine returns 'true'.
14145 /// Note that the binary operation should have the property that if one of the
14146 /// operands is UNDEF then the result is UNDEF.
14147 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14148 // Look for the following pattern: if
14149 // A = < float a0, float a1, float a2, float a3 >
14150 // B = < float b0, float b1, float b2, float b3 >
14152 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14153 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14154 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14155 // which is A horizontal-op B.
14157 // At least one of the operands should be a vector shuffle.
14158 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14159 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14162 EVT VT = LHS.getValueType();
14164 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14165 "Unsupported vector type for horizontal add/sub");
14167 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14168 // operate independently on 128-bit lanes.
14169 unsigned NumElts = VT.getVectorNumElements();
14170 unsigned NumLanes = VT.getSizeInBits()/128;
14171 unsigned NumLaneElts = NumElts / NumLanes;
14172 assert((NumLaneElts % 2 == 0) &&
14173 "Vector type should have an even number of elements in each lane");
14174 unsigned HalfLaneElts = NumLaneElts/2;
14176 // View LHS in the form
14177 // LHS = VECTOR_SHUFFLE A, B, LMask
14178 // If LHS is not a shuffle then pretend it is the shuffle
14179 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14180 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14183 SmallVector<int, 16> LMask(NumElts);
14184 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14185 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14186 A = LHS.getOperand(0);
14187 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14188 B = LHS.getOperand(1);
14189 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14191 if (LHS.getOpcode() != ISD::UNDEF)
14193 for (unsigned i = 0; i != NumElts; ++i)
14197 // Likewise, view RHS in the form
14198 // RHS = VECTOR_SHUFFLE C, D, RMask
14200 SmallVector<int, 16> RMask(NumElts);
14201 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14202 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14203 C = RHS.getOperand(0);
14204 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14205 D = RHS.getOperand(1);
14206 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14208 if (RHS.getOpcode() != ISD::UNDEF)
14210 for (unsigned i = 0; i != NumElts; ++i)
14214 // Check that the shuffles are both shuffling the same vectors.
14215 if (!(A == C && B == D) && !(A == D && B == C))
14218 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14219 if (!A.getNode() && !B.getNode())
14222 // If A and B occur in reverse order in RHS, then "swap" them (which means
14223 // rewriting the mask).
14225 CommuteVectorShuffleMask(RMask, NumElts);
14227 // At this point LHS and RHS are equivalent to
14228 // LHS = VECTOR_SHUFFLE A, B, LMask
14229 // RHS = VECTOR_SHUFFLE A, B, RMask
14230 // Check that the masks correspond to performing a horizontal operation.
14231 for (unsigned i = 0; i != NumElts; ++i) {
14232 int LIdx = LMask[i], RIdx = RMask[i];
14234 // Ignore any UNDEF components.
14235 if (LIdx < 0 || RIdx < 0 ||
14236 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14237 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14240 // Check that successive elements are being operated on. If not, this is
14241 // not a horizontal operation.
14242 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14243 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14244 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14245 if (!(LIdx == Index && RIdx == Index + 1) &&
14246 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14250 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14251 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14255 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14256 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14257 const X86Subtarget *Subtarget) {
14258 EVT VT = N->getValueType(0);
14259 SDValue LHS = N->getOperand(0);
14260 SDValue RHS = N->getOperand(1);
14262 // Try to synthesize horizontal adds from adds of shuffles.
14263 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14264 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14265 isHorizontalBinOp(LHS, RHS, true))
14266 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14270 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14271 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14272 const X86Subtarget *Subtarget) {
14273 EVT VT = N->getValueType(0);
14274 SDValue LHS = N->getOperand(0);
14275 SDValue RHS = N->getOperand(1);
14277 // Try to synthesize horizontal subs from subs of shuffles.
14278 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14279 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14280 isHorizontalBinOp(LHS, RHS, false))
14281 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14285 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14286 /// X86ISD::FXOR nodes.
14287 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14288 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14289 // F[X]OR(0.0, x) -> x
14290 // F[X]OR(x, 0.0) -> x
14291 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14292 if (C->getValueAPF().isPosZero())
14293 return N->getOperand(1);
14294 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14295 if (C->getValueAPF().isPosZero())
14296 return N->getOperand(0);
14300 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14301 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14302 // FAND(0.0, x) -> 0.0
14303 // FAND(x, 0.0) -> 0.0
14304 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14305 if (C->getValueAPF().isPosZero())
14306 return N->getOperand(0);
14307 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14308 if (C->getValueAPF().isPosZero())
14309 return N->getOperand(1);
14313 static SDValue PerformBTCombine(SDNode *N,
14315 TargetLowering::DAGCombinerInfo &DCI) {
14316 // BT ignores high bits in the bit index operand.
14317 SDValue Op1 = N->getOperand(1);
14318 if (Op1.hasOneUse()) {
14319 unsigned BitWidth = Op1.getValueSizeInBits();
14320 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14321 APInt KnownZero, KnownOne;
14322 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14323 !DCI.isBeforeLegalizeOps());
14324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14325 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14326 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14327 DCI.CommitTargetLoweringOpt(TLO);
14332 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14333 SDValue Op = N->getOperand(0);
14334 if (Op.getOpcode() == ISD::BITCAST)
14335 Op = Op.getOperand(0);
14336 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14337 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14338 VT.getVectorElementType().getSizeInBits() ==
14339 OpVT.getVectorElementType().getSizeInBits()) {
14340 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14345 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14346 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14347 // (and (i32 x86isd::setcc_carry), 1)
14348 // This eliminates the zext. This transformation is necessary because
14349 // ISD::SETCC is always legalized to i8.
14350 DebugLoc dl = N->getDebugLoc();
14351 SDValue N0 = N->getOperand(0);
14352 EVT VT = N->getValueType(0);
14353 if (N0.getOpcode() == ISD::AND &&
14355 N0.getOperand(0).hasOneUse()) {
14356 SDValue N00 = N0.getOperand(0);
14357 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14359 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14360 if (!C || C->getZExtValue() != 1)
14362 return DAG.getNode(ISD::AND, dl, VT,
14363 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14364 N00.getOperand(0), N00.getOperand(1)),
14365 DAG.getConstant(1, VT));
14371 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14372 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14373 unsigned X86CC = N->getConstantOperandVal(0);
14374 SDValue EFLAG = N->getOperand(1);
14375 DebugLoc DL = N->getDebugLoc();
14377 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14378 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14380 if (X86CC == X86::COND_B)
14381 return DAG.getNode(ISD::AND, DL, MVT::i8,
14382 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14383 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14384 DAG.getConstant(1, MVT::i8));
14389 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14390 const X86TargetLowering *XTLI) {
14391 SDValue Op0 = N->getOperand(0);
14392 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14393 // a 32-bit target where SSE doesn't support i64->FP operations.
14394 if (Op0.getOpcode() == ISD::LOAD) {
14395 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14396 EVT VT = Ld->getValueType(0);
14397 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14398 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14399 !XTLI->getSubtarget()->is64Bit() &&
14400 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14401 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14402 Ld->getChain(), Op0, DAG);
14403 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14410 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14411 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14412 X86TargetLowering::DAGCombinerInfo &DCI) {
14413 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14414 // the result is either zero or one (depending on the input carry bit).
14415 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14416 if (X86::isZeroNode(N->getOperand(0)) &&
14417 X86::isZeroNode(N->getOperand(1)) &&
14418 // We don't have a good way to replace an EFLAGS use, so only do this when
14420 SDValue(N, 1).use_empty()) {
14421 DebugLoc DL = N->getDebugLoc();
14422 EVT VT = N->getValueType(0);
14423 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14424 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14425 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14426 DAG.getConstant(X86::COND_B,MVT::i8),
14428 DAG.getConstant(1, VT));
14429 return DCI.CombineTo(N, Res1, CarryOut);
14435 // fold (add Y, (sete X, 0)) -> adc 0, Y
14436 // (add Y, (setne X, 0)) -> sbb -1, Y
14437 // (sub (sete X, 0), Y) -> sbb 0, Y
14438 // (sub (setne X, 0), Y) -> adc -1, Y
14439 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14440 DebugLoc DL = N->getDebugLoc();
14442 // Look through ZExts.
14443 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14444 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14447 SDValue SetCC = Ext.getOperand(0);
14448 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14451 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14452 if (CC != X86::COND_E && CC != X86::COND_NE)
14455 SDValue Cmp = SetCC.getOperand(1);
14456 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14457 !X86::isZeroNode(Cmp.getOperand(1)) ||
14458 !Cmp.getOperand(0).getValueType().isInteger())
14461 SDValue CmpOp0 = Cmp.getOperand(0);
14462 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14463 DAG.getConstant(1, CmpOp0.getValueType()));
14465 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14466 if (CC == X86::COND_NE)
14467 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14468 DL, OtherVal.getValueType(), OtherVal,
14469 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14470 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14471 DL, OtherVal.getValueType(), OtherVal,
14472 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14475 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14476 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14477 const X86Subtarget *Subtarget) {
14478 EVT VT = N->getValueType(0);
14479 SDValue Op0 = N->getOperand(0);
14480 SDValue Op1 = N->getOperand(1);
14482 // Try to synthesize horizontal adds from adds of shuffles.
14483 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14484 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14485 isHorizontalBinOp(Op0, Op1, true))
14486 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14488 return OptimizeConditionalInDecrement(N, DAG);
14491 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14492 const X86Subtarget *Subtarget) {
14493 SDValue Op0 = N->getOperand(0);
14494 SDValue Op1 = N->getOperand(1);
14496 // X86 can't encode an immediate LHS of a sub. See if we can push the
14497 // negation into a preceding instruction.
14498 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14499 // If the RHS of the sub is a XOR with one use and a constant, invert the
14500 // immediate. Then add one to the LHS of the sub so we can turn
14501 // X-Y -> X+~Y+1, saving one register.
14502 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14503 isa<ConstantSDNode>(Op1.getOperand(1))) {
14504 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14505 EVT VT = Op0.getValueType();
14506 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14508 DAG.getConstant(~XorC, VT));
14509 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14510 DAG.getConstant(C->getAPIntValue()+1, VT));
14514 // Try to synthesize horizontal adds from adds of shuffles.
14515 EVT VT = N->getValueType(0);
14516 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14517 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14518 isHorizontalBinOp(Op0, Op1, true))
14519 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14521 return OptimizeConditionalInDecrement(N, DAG);
14524 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14525 DAGCombinerInfo &DCI) const {
14526 SelectionDAG &DAG = DCI.DAG;
14527 switch (N->getOpcode()) {
14529 case ISD::EXTRACT_VECTOR_ELT:
14530 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14532 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14533 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14534 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14535 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14536 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14537 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14540 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14541 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14542 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14543 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14544 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14545 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14546 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14547 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14548 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14550 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14551 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14552 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14553 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14554 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14555 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14556 case X86ISD::SHUFPS: // Handle all target specific shuffles
14557 case X86ISD::SHUFPD:
14558 case X86ISD::PALIGN:
14559 case X86ISD::UNPCKH:
14560 case X86ISD::UNPCKL:
14561 case X86ISD::MOVHLPS:
14562 case X86ISD::MOVLHPS:
14563 case X86ISD::PSHUFD:
14564 case X86ISD::PSHUFHW:
14565 case X86ISD::PSHUFLW:
14566 case X86ISD::MOVSS:
14567 case X86ISD::MOVSD:
14568 case X86ISD::VPERMILP:
14569 case X86ISD::VPERM2X128:
14570 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14576 /// isTypeDesirableForOp - Return true if the target has native support for
14577 /// the specified value type and it is 'desirable' to use the type for the
14578 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14579 /// instruction encodings are longer and some i16 instructions are slow.
14580 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14581 if (!isTypeLegal(VT))
14583 if (VT != MVT::i16)
14590 case ISD::SIGN_EXTEND:
14591 case ISD::ZERO_EXTEND:
14592 case ISD::ANY_EXTEND:
14605 /// IsDesirableToPromoteOp - This method query the target whether it is
14606 /// beneficial for dag combiner to promote the specified node. If true, it
14607 /// should return the desired promotion type by reference.
14608 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14609 EVT VT = Op.getValueType();
14610 if (VT != MVT::i16)
14613 bool Promote = false;
14614 bool Commute = false;
14615 switch (Op.getOpcode()) {
14618 LoadSDNode *LD = cast<LoadSDNode>(Op);
14619 // If the non-extending load has a single use and it's not live out, then it
14620 // might be folded.
14621 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14622 Op.hasOneUse()*/) {
14623 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14624 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14625 // The only case where we'd want to promote LOAD (rather then it being
14626 // promoted as an operand is when it's only use is liveout.
14627 if (UI->getOpcode() != ISD::CopyToReg)
14634 case ISD::SIGN_EXTEND:
14635 case ISD::ZERO_EXTEND:
14636 case ISD::ANY_EXTEND:
14641 SDValue N0 = Op.getOperand(0);
14642 // Look out for (store (shl (load), x)).
14643 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14656 SDValue N0 = Op.getOperand(0);
14657 SDValue N1 = Op.getOperand(1);
14658 if (!Commute && MayFoldLoad(N1))
14660 // Avoid disabling potential load folding opportunities.
14661 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14663 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14673 //===----------------------------------------------------------------------===//
14674 // X86 Inline Assembly Support
14675 //===----------------------------------------------------------------------===//
14677 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14678 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14680 std::string AsmStr = IA->getAsmString();
14682 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14683 SmallVector<StringRef, 4> AsmPieces;
14684 SplitString(AsmStr, AsmPieces, ";\n");
14686 switch (AsmPieces.size()) {
14687 default: return false;
14689 AsmStr = AsmPieces[0];
14691 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14693 // FIXME: this should verify that we are targeting a 486 or better. If not,
14694 // we will turn this bswap into something that will be lowered to logical ops
14695 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14696 // so don't worry about this.
14698 if (AsmPieces.size() == 2 &&
14699 (AsmPieces[0] == "bswap" ||
14700 AsmPieces[0] == "bswapq" ||
14701 AsmPieces[0] == "bswapl") &&
14702 (AsmPieces[1] == "$0" ||
14703 AsmPieces[1] == "${0:q}")) {
14704 // No need to check constraints, nothing other than the equivalent of
14705 // "=r,0" would be valid here.
14706 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14707 if (!Ty || Ty->getBitWidth() % 16 != 0)
14709 return IntrinsicLowering::LowerToByteSwap(CI);
14711 // rorw $$8, ${0:w} --> llvm.bswap.i16
14712 if (CI->getType()->isIntegerTy(16) &&
14713 AsmPieces.size() == 3 &&
14714 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14715 AsmPieces[1] == "$$8," &&
14716 AsmPieces[2] == "${0:w}" &&
14717 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14719 const std::string &ConstraintsStr = IA->getConstraintString();
14720 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14721 std::sort(AsmPieces.begin(), AsmPieces.end());
14722 if (AsmPieces.size() == 4 &&
14723 AsmPieces[0] == "~{cc}" &&
14724 AsmPieces[1] == "~{dirflag}" &&
14725 AsmPieces[2] == "~{flags}" &&
14726 AsmPieces[3] == "~{fpsr}") {
14727 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14728 if (!Ty || Ty->getBitWidth() % 16 != 0)
14730 return IntrinsicLowering::LowerToByteSwap(CI);
14735 if (CI->getType()->isIntegerTy(32) &&
14736 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14737 SmallVector<StringRef, 4> Words;
14738 SplitString(AsmPieces[0], Words, " \t,");
14739 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14740 Words[2] == "${0:w}") {
14742 SplitString(AsmPieces[1], Words, " \t,");
14743 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14744 Words[2] == "$0") {
14746 SplitString(AsmPieces[2], Words, " \t,");
14747 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14748 Words[2] == "${0:w}") {
14750 const std::string &ConstraintsStr = IA->getConstraintString();
14751 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14752 std::sort(AsmPieces.begin(), AsmPieces.end());
14753 if (AsmPieces.size() == 4 &&
14754 AsmPieces[0] == "~{cc}" &&
14755 AsmPieces[1] == "~{dirflag}" &&
14756 AsmPieces[2] == "~{flags}" &&
14757 AsmPieces[3] == "~{fpsr}") {
14758 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14759 if (!Ty || Ty->getBitWidth() % 16 != 0)
14761 return IntrinsicLowering::LowerToByteSwap(CI);
14768 if (CI->getType()->isIntegerTy(64)) {
14769 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14770 if (Constraints.size() >= 2 &&
14771 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14772 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14773 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14774 SmallVector<StringRef, 4> Words;
14775 SplitString(AsmPieces[0], Words, " \t");
14776 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14778 SplitString(AsmPieces[1], Words, " \t");
14779 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14781 SplitString(AsmPieces[2], Words, " \t,");
14782 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14783 Words[2] == "%edx") {
14784 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14785 if (!Ty || Ty->getBitWidth() % 16 != 0)
14787 return IntrinsicLowering::LowerToByteSwap(CI);
14800 /// getConstraintType - Given a constraint letter, return the type of
14801 /// constraint it is for this target.
14802 X86TargetLowering::ConstraintType
14803 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14804 if (Constraint.size() == 1) {
14805 switch (Constraint[0]) {
14816 return C_RegisterClass;
14840 return TargetLowering::getConstraintType(Constraint);
14843 /// Examine constraint type and operand type and determine a weight value.
14844 /// This object must already have been set up with the operand type
14845 /// and the current alternative constraint selected.
14846 TargetLowering::ConstraintWeight
14847 X86TargetLowering::getSingleConstraintMatchWeight(
14848 AsmOperandInfo &info, const char *constraint) const {
14849 ConstraintWeight weight = CW_Invalid;
14850 Value *CallOperandVal = info.CallOperandVal;
14851 // If we don't have a value, we can't do a match,
14852 // but allow it at the lowest weight.
14853 if (CallOperandVal == NULL)
14855 Type *type = CallOperandVal->getType();
14856 // Look at the constraint type.
14857 switch (*constraint) {
14859 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14870 if (CallOperandVal->getType()->isIntegerTy())
14871 weight = CW_SpecificReg;
14876 if (type->isFloatingPointTy())
14877 weight = CW_SpecificReg;
14880 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14881 weight = CW_SpecificReg;
14885 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14886 weight = CW_Register;
14889 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14890 if (C->getZExtValue() <= 31)
14891 weight = CW_Constant;
14895 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14896 if (C->getZExtValue() <= 63)
14897 weight = CW_Constant;
14901 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14902 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14903 weight = CW_Constant;
14907 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14908 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14909 weight = CW_Constant;
14913 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14914 if (C->getZExtValue() <= 3)
14915 weight = CW_Constant;
14919 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14920 if (C->getZExtValue() <= 0xff)
14921 weight = CW_Constant;
14926 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14927 weight = CW_Constant;
14931 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14932 if ((C->getSExtValue() >= -0x80000000LL) &&
14933 (C->getSExtValue() <= 0x7fffffffLL))
14934 weight = CW_Constant;
14938 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14939 if (C->getZExtValue() <= 0xffffffff)
14940 weight = CW_Constant;
14947 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14948 /// with another that has more specific requirements based on the type of the
14949 /// corresponding operand.
14950 const char *X86TargetLowering::
14951 LowerXConstraint(EVT ConstraintVT) const {
14952 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14953 // 'f' like normal targets.
14954 if (ConstraintVT.isFloatingPoint()) {
14955 if (Subtarget->hasXMMInt())
14957 if (Subtarget->hasXMM())
14961 return TargetLowering::LowerXConstraint(ConstraintVT);
14964 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14965 /// vector. If it is invalid, don't add anything to Ops.
14966 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14967 std::string &Constraint,
14968 std::vector<SDValue>&Ops,
14969 SelectionDAG &DAG) const {
14970 SDValue Result(0, 0);
14972 // Only support length 1 constraints for now.
14973 if (Constraint.length() > 1) return;
14975 char ConstraintLetter = Constraint[0];
14976 switch (ConstraintLetter) {
14979 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14980 if (C->getZExtValue() <= 31) {
14981 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14987 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14988 if (C->getZExtValue() <= 63) {
14989 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14996 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14997 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15003 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15004 if (C->getZExtValue() <= 255) {
15005 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15011 // 32-bit signed value
15012 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15013 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15014 C->getSExtValue())) {
15015 // Widen to 64 bits here to get it sign extended.
15016 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15019 // FIXME gcc accepts some relocatable values here too, but only in certain
15020 // memory models; it's complicated.
15025 // 32-bit unsigned value
15026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15027 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15028 C->getZExtValue())) {
15029 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15033 // FIXME gcc accepts some relocatable values here too, but only in certain
15034 // memory models; it's complicated.
15038 // Literal immediates are always ok.
15039 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15040 // Widen to 64 bits here to get it sign extended.
15041 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15045 // In any sort of PIC mode addresses need to be computed at runtime by
15046 // adding in a register or some sort of table lookup. These can't
15047 // be used as immediates.
15048 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15051 // If we are in non-pic codegen mode, we allow the address of a global (with
15052 // an optional displacement) to be used with 'i'.
15053 GlobalAddressSDNode *GA = 0;
15054 int64_t Offset = 0;
15056 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15058 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15059 Offset += GA->getOffset();
15061 } else if (Op.getOpcode() == ISD::ADD) {
15062 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15063 Offset += C->getZExtValue();
15064 Op = Op.getOperand(0);
15067 } else if (Op.getOpcode() == ISD::SUB) {
15068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15069 Offset += -C->getZExtValue();
15070 Op = Op.getOperand(0);
15075 // Otherwise, this isn't something we can handle, reject it.
15079 const GlobalValue *GV = GA->getGlobal();
15080 // If we require an extra load to get this address, as in PIC mode, we
15081 // can't accept it.
15082 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15083 getTargetMachine())))
15086 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15087 GA->getValueType(0), Offset);
15092 if (Result.getNode()) {
15093 Ops.push_back(Result);
15096 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15099 std::pair<unsigned, const TargetRegisterClass*>
15100 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15102 // First, see if this is a constraint that directly corresponds to an LLVM
15104 if (Constraint.size() == 1) {
15105 // GCC Constraint Letters
15106 switch (Constraint[0]) {
15108 // TODO: Slight differences here in allocation order and leaving
15109 // RIP in the class. Do they matter any more here than they do
15110 // in the normal allocation?
15111 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15112 if (Subtarget->is64Bit()) {
15113 if (VT == MVT::i32 || VT == MVT::f32)
15114 return std::make_pair(0U, X86::GR32RegisterClass);
15115 else if (VT == MVT::i16)
15116 return std::make_pair(0U, X86::GR16RegisterClass);
15117 else if (VT == MVT::i8 || VT == MVT::i1)
15118 return std::make_pair(0U, X86::GR8RegisterClass);
15119 else if (VT == MVT::i64 || VT == MVT::f64)
15120 return std::make_pair(0U, X86::GR64RegisterClass);
15123 // 32-bit fallthrough
15124 case 'Q': // Q_REGS
15125 if (VT == MVT::i32 || VT == MVT::f32)
15126 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15127 else if (VT == MVT::i16)
15128 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15129 else if (VT == MVT::i8 || VT == MVT::i1)
15130 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15131 else if (VT == MVT::i64)
15132 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15134 case 'r': // GENERAL_REGS
15135 case 'l': // INDEX_REGS
15136 if (VT == MVT::i8 || VT == MVT::i1)
15137 return std::make_pair(0U, X86::GR8RegisterClass);
15138 if (VT == MVT::i16)
15139 return std::make_pair(0U, X86::GR16RegisterClass);
15140 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15141 return std::make_pair(0U, X86::GR32RegisterClass);
15142 return std::make_pair(0U, X86::GR64RegisterClass);
15143 case 'R': // LEGACY_REGS
15144 if (VT == MVT::i8 || VT == MVT::i1)
15145 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15146 if (VT == MVT::i16)
15147 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15148 if (VT == MVT::i32 || !Subtarget->is64Bit())
15149 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15150 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15151 case 'f': // FP Stack registers.
15152 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15153 // value to the correct fpstack register class.
15154 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15155 return std::make_pair(0U, X86::RFP32RegisterClass);
15156 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15157 return std::make_pair(0U, X86::RFP64RegisterClass);
15158 return std::make_pair(0U, X86::RFP80RegisterClass);
15159 case 'y': // MMX_REGS if MMX allowed.
15160 if (!Subtarget->hasMMX()) break;
15161 return std::make_pair(0U, X86::VR64RegisterClass);
15162 case 'Y': // SSE_REGS if SSE2 allowed
15163 if (!Subtarget->hasXMMInt()) break;
15165 case 'x': // SSE_REGS if SSE1 allowed
15166 if (!Subtarget->hasXMM()) break;
15168 switch (VT.getSimpleVT().SimpleTy) {
15170 // Scalar SSE types.
15173 return std::make_pair(0U, X86::FR32RegisterClass);
15176 return std::make_pair(0U, X86::FR64RegisterClass);
15184 return std::make_pair(0U, X86::VR128RegisterClass);
15190 // Use the default implementation in TargetLowering to convert the register
15191 // constraint into a member of a register class.
15192 std::pair<unsigned, const TargetRegisterClass*> Res;
15193 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15195 // Not found as a standard register?
15196 if (Res.second == 0) {
15197 // Map st(0) -> st(7) -> ST0
15198 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15199 tolower(Constraint[1]) == 's' &&
15200 tolower(Constraint[2]) == 't' &&
15201 Constraint[3] == '(' &&
15202 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15203 Constraint[5] == ')' &&
15204 Constraint[6] == '}') {
15206 Res.first = X86::ST0+Constraint[4]-'0';
15207 Res.second = X86::RFP80RegisterClass;
15211 // GCC allows "st(0)" to be called just plain "st".
15212 if (StringRef("{st}").equals_lower(Constraint)) {
15213 Res.first = X86::ST0;
15214 Res.second = X86::RFP80RegisterClass;
15219 if (StringRef("{flags}").equals_lower(Constraint)) {
15220 Res.first = X86::EFLAGS;
15221 Res.second = X86::CCRRegisterClass;
15225 // 'A' means EAX + EDX.
15226 if (Constraint == "A") {
15227 Res.first = X86::EAX;
15228 Res.second = X86::GR32_ADRegisterClass;
15234 // Otherwise, check to see if this is a register class of the wrong value
15235 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15236 // turn into {ax},{dx}.
15237 if (Res.second->hasType(VT))
15238 return Res; // Correct type already, nothing to do.
15240 // All of the single-register GCC register classes map their values onto
15241 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15242 // really want an 8-bit or 32-bit register, map to the appropriate register
15243 // class and return the appropriate register.
15244 if (Res.second == X86::GR16RegisterClass) {
15245 if (VT == MVT::i8) {
15246 unsigned DestReg = 0;
15247 switch (Res.first) {
15249 case X86::AX: DestReg = X86::AL; break;
15250 case X86::DX: DestReg = X86::DL; break;
15251 case X86::CX: DestReg = X86::CL; break;
15252 case X86::BX: DestReg = X86::BL; break;
15255 Res.first = DestReg;
15256 Res.second = X86::GR8RegisterClass;
15258 } else if (VT == MVT::i32) {
15259 unsigned DestReg = 0;
15260 switch (Res.first) {
15262 case X86::AX: DestReg = X86::EAX; break;
15263 case X86::DX: DestReg = X86::EDX; break;
15264 case X86::CX: DestReg = X86::ECX; break;
15265 case X86::BX: DestReg = X86::EBX; break;
15266 case X86::SI: DestReg = X86::ESI; break;
15267 case X86::DI: DestReg = X86::EDI; break;
15268 case X86::BP: DestReg = X86::EBP; break;
15269 case X86::SP: DestReg = X86::ESP; break;
15272 Res.first = DestReg;
15273 Res.second = X86::GR32RegisterClass;
15275 } else if (VT == MVT::i64) {
15276 unsigned DestReg = 0;
15277 switch (Res.first) {
15279 case X86::AX: DestReg = X86::RAX; break;
15280 case X86::DX: DestReg = X86::RDX; break;
15281 case X86::CX: DestReg = X86::RCX; break;
15282 case X86::BX: DestReg = X86::RBX; break;
15283 case X86::SI: DestReg = X86::RSI; break;
15284 case X86::DI: DestReg = X86::RDI; break;
15285 case X86::BP: DestReg = X86::RBP; break;
15286 case X86::SP: DestReg = X86::RSP; break;
15289 Res.first = DestReg;
15290 Res.second = X86::GR64RegisterClass;
15293 } else if (Res.second == X86::FR32RegisterClass ||
15294 Res.second == X86::FR64RegisterClass ||
15295 Res.second == X86::VR128RegisterClass) {
15296 // Handle references to XMM physical registers that got mapped into the
15297 // wrong class. This can happen with constraints like {xmm0} where the
15298 // target independent register mapper will just pick the first match it can
15299 // find, ignoring the required type.
15300 if (VT == MVT::f32)
15301 Res.second = X86::FR32RegisterClass;
15302 else if (VT == MVT::f64)
15303 Res.second = X86::FR64RegisterClass;
15304 else if (X86::VR128RegisterClass->hasType(VT))
15305 Res.second = X86::VR128RegisterClass;