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/VariadicFunction.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
56 using namespace dwarf;
58 STATISTIC(NumTailCalls, "Number of tail calls");
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static SDValue Insert128BitVector(SDValue Result,
70 static SDValue Extract128BitVector(SDValue Vec,
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference. Idx is an index in the 128 bits we
78 /// want. It need not be aligned to a 128-bit bounday. That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
84 EVT VT = Vec.getValueType();
85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86 EVT ElVT = VT.getVectorElementType();
87 int Factor = VT.getSizeInBits()/128;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
95 if (isa<ConstantSDNode>(Idx)) {
96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
99 // we can match to VEXTRACTF128.
100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
102 // This is the index of the first element of the 128-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
117 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference. Idx is an index in the 128 bits
120 /// we want. It need not be aligned to a 128-bit bounday. That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
127 if (isa<ConstantSDNode>(Idx)) {
128 EVT VT = Vec.getValueType();
129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131 EVT ElVT = VT.getVectorElementType();
132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133 EVT ResultVT = Result.getValueType();
135 // Insert the relevant 128 bits.
136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
138 // This is the index of the first element of the 128-bit chunk
140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154 bool is64Bit = Subtarget->is64Bit();
156 if (Subtarget->isTargetEnvMacho()) {
158 return new X8664_MachoTargetObjectFile();
159 return new TargetLoweringObjectFileMachO();
162 if (Subtarget->isTargetELF())
163 return new TargetLoweringObjectFileELF();
164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165 return new TargetLoweringObjectFileCOFF();
166 llvm_unreachable("unknown subtarget type");
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<X86Subtarget>();
172 X86ScalarSSEf64 = Subtarget->hasXMMInt();
173 X86ScalarSSEf32 = Subtarget->hasXMM();
174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
176 RegInfo = TM.getRegisterInfo();
177 TD = getTargetData();
179 // Set up the TargetLowering object.
180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
182 // X86 is weird, it always uses i8 for shift amounts and setcc results.
183 setBooleanContents(ZeroOrOneBooleanContent);
184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
187 // For 64-bit since we have so many registers use the ILP scheduler, for
188 // 32-bit code use the register pressure specific scheduling.
189 if (Subtarget->is64Bit())
190 setSchedulingPreference(Sched::ILP);
192 setSchedulingPreference(Sched::RegPressure);
193 setStackPointerRegisterToSaveRestore(X86StackPtr);
195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196 // Setup Windows compiler runtime calls.
197 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199 setLibcallName(RTLIB::SREM_I64, "_allrem");
200 setLibcallName(RTLIB::UREM_I64, "_aullrem");
201 setLibcallName(RTLIB::MUL_I64, "_allmul");
202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
213 if (Subtarget->isTargetDarwin()) {
214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215 setUseUnderscoreSetJmp(false);
216 setUseUnderscoreLongJmp(false);
217 } else if (Subtarget->isTargetMingw()) {
218 // MS runtime is weird: it exports _setjmp, but longjmp!
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(false);
222 setUseUnderscoreSetJmp(true);
223 setUseUnderscoreLongJmp(true);
226 // Set up the register classes.
227 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230 if (Subtarget->is64Bit())
231 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
235 // We don't accept any truncstore of integer registers.
236 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
243 // SETOEQ and SETUNE require checking two conditions.
244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
260 } else if (!TM.Options.UseSoftFloat) {
261 // We have an algorithm for SSE2->double, and we turn this into a
262 // 64-bit FILD followed by conditional FADD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
264 // We have an algorithm for SSE2, and we turn this into a 64-bit
265 // FILD for other targets.
266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 if (!TM.Options.UseSoftFloat) {
275 // SSE has no i16 to fp conversion, only i32
276 if (X86ScalarSSEf32) {
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 // f32 and f64 cases are Legal, f80 case is not
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
290 // are Legal, f80 is custom lowered.
291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
308 // Handle FP_TO_UINT by promoting the destination to a larger signed
310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
317 } else if (!TM.Options.UseSoftFloat) {
318 // Since AVX is a superset of SSE3, only check for SSE here.
319 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320 // Expand FP_TO_UINT into a select.
321 // FIXME: We would like to use a Custom expander here eventually to do
322 // the optimal thing for SSE vs. the default expansion in the legalizer.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
325 // With SSE3 we can use fisttpll to convert to a signed i64; without
326 // SSE, we're stuck with a fistpll.
327 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
330 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331 if (!X86ScalarSSEf64) {
332 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
333 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
336 // Without SSE, i64->f64 goes through memory.
337 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
341 // Scalar integer divide and remainder are lowered to use operations that
342 // produce two results, to match the available instructions. This exposes
343 // the two-result form to trivial CSE, which is able to combine x/y and x%y
344 // into a single instruction.
346 // Scalar integer multiply-high is also lowered to use two-result
347 // operations, to match the available instructions. However, plain multiply
348 // (low) operations are left as Legal, as there are single-result
349 // instructions for this in x86. Using the two-result multiply instructions
350 // when both high and low results are needed must be arranged by dagcombine.
351 for (unsigned i = 0, e = 4; i != e; ++i) {
353 setOperationAction(ISD::MULHS, VT, Expand);
354 setOperationAction(ISD::MULHU, VT, Expand);
355 setOperationAction(ISD::SDIV, VT, Expand);
356 setOperationAction(ISD::UDIV, VT, Expand);
357 setOperationAction(ISD::SREM, VT, Expand);
358 setOperationAction(ISD::UREM, VT, Expand);
360 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361 setOperationAction(ISD::ADDC, VT, Custom);
362 setOperationAction(ISD::ADDE, VT, Custom);
363 setOperationAction(ISD::SUBC, VT, Custom);
364 setOperationAction(ISD::SUBE, VT, Custom);
367 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
368 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
369 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
370 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
376 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f32 , Expand);
378 setOperationAction(ISD::FREM , MVT::f64 , Expand);
379 setOperationAction(ISD::FREM , MVT::f80 , Expand);
380 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
382 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Expand);
383 if (Subtarget->hasBMI()) {
384 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
386 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
387 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
388 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
393 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i8 , Expand);
394 if (Subtarget->hasLZCNT()) {
395 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
397 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
398 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
399 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
400 if (Subtarget->is64Bit())
401 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
404 if (Subtarget->hasPOPCNT()) {
405 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
407 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
408 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
409 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
410 if (Subtarget->is64Bit())
411 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
414 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
415 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
417 // These should be promoted to a larger select which is supported.
418 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
419 // X86 wants to expand cmov itself.
420 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
421 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
422 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
423 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
424 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
425 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
426 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
427 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
428 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
429 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
430 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
431 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
434 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
436 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
439 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
440 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
441 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
442 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
443 if (Subtarget->is64Bit())
444 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
445 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
446 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
447 if (Subtarget->is64Bit()) {
448 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
449 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
450 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
451 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
452 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
454 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
455 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
456 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
457 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
458 if (Subtarget->is64Bit()) {
459 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
460 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
461 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
464 if (Subtarget->hasXMM())
465 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
467 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
468 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
470 // On X86 and X86-64, atomic operations are lowered to locked instructions.
471 // Locked instructions, in turn, have implicit fence semantics (all memory
472 // operations are flushed before issuing the locked instruction, and they
473 // are not buffered), so we can fold away the common pattern of
474 // fence-atomic-fence.
475 setShouldFoldAtomicFences(true);
477 // Expand certain atomics
478 for (unsigned i = 0, e = 4; i != e; ++i) {
480 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
481 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
485 if (!Subtarget->is64Bit()) {
486 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
488 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
489 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
490 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
491 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
492 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
493 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
496 if (Subtarget->hasCmpxchg16b()) {
497 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
500 // FIXME - use subtarget debug flags
501 if (!Subtarget->isTargetDarwin() &&
502 !Subtarget->isTargetELF() &&
503 !Subtarget->isTargetCygMing()) {
504 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
507 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
508 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
509 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
510 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
511 if (Subtarget->is64Bit()) {
512 setExceptionPointerRegister(X86::RAX);
513 setExceptionSelectorRegister(X86::RDX);
515 setExceptionPointerRegister(X86::EAX);
516 setExceptionSelectorRegister(X86::EDX);
518 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
519 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
521 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
522 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
524 setOperationAction(ISD::TRAP, MVT::Other, Legal);
526 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
527 setOperationAction(ISD::VASTART , MVT::Other, Custom);
528 setOperationAction(ISD::VAEND , MVT::Other, Expand);
529 if (Subtarget->is64Bit()) {
530 setOperationAction(ISD::VAARG , MVT::Other, Custom);
531 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
533 setOperationAction(ISD::VAARG , MVT::Other, Expand);
534 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
537 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
538 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
540 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542 MVT::i64 : MVT::i32, Custom);
543 else if (TM.Options.EnableSegmentedStacks)
544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545 MVT::i64 : MVT::i32, Custom);
547 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
548 MVT::i64 : MVT::i32, Expand);
550 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
551 // f32 and f64 use SSE.
552 // Set up the FP register classes.
553 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
554 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
556 // Use ANDPD to simulate FABS.
557 setOperationAction(ISD::FABS , MVT::f64, Custom);
558 setOperationAction(ISD::FABS , MVT::f32, Custom);
560 // Use XORP to simulate FNEG.
561 setOperationAction(ISD::FNEG , MVT::f64, Custom);
562 setOperationAction(ISD::FNEG , MVT::f32, Custom);
564 // Use ANDPD and ORPD to simulate FCOPYSIGN.
565 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
566 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
568 // Lower this to FGETSIGNx86 plus an AND.
569 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
570 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
572 // We don't support sin/cos/fmod
573 setOperationAction(ISD::FSIN , MVT::f64, Expand);
574 setOperationAction(ISD::FCOS , MVT::f64, Expand);
575 setOperationAction(ISD::FSIN , MVT::f32, Expand);
576 setOperationAction(ISD::FCOS , MVT::f32, Expand);
578 // Expand FP immediates into loads from the stack, except for the special
580 addLegalFPImmediate(APFloat(+0.0)); // xorpd
581 addLegalFPImmediate(APFloat(+0.0f)); // xorps
582 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
583 // Use SSE for f32, x87 for f64.
584 // Set up the FP register classes.
585 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
586 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
588 // Use ANDPS to simulate FABS.
589 setOperationAction(ISD::FABS , MVT::f32, Custom);
591 // Use XORP to simulate FNEG.
592 setOperationAction(ISD::FNEG , MVT::f32, Custom);
594 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
596 // Use ANDPS and ORPS to simulate FCOPYSIGN.
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
600 // We don't support sin/cos/fmod
601 setOperationAction(ISD::FSIN , MVT::f32, Expand);
602 setOperationAction(ISD::FCOS , MVT::f32, Expand);
604 // Special cases we handle for FP constants.
605 addLegalFPImmediate(APFloat(+0.0f)); // xorps
606 addLegalFPImmediate(APFloat(+0.0)); // FLD0
607 addLegalFPImmediate(APFloat(+1.0)); // FLD1
608 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
609 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611 if (!TM.Options.UnsafeFPMath) {
612 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
613 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
615 } else if (!TM.Options.UseSoftFloat) {
616 // f32 and f64 in x87.
617 // Set up the FP register classes.
618 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
619 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
621 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
622 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
623 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
626 if (!TM.Options.UnsafeFPMath) {
627 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
628 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
630 addLegalFPImmediate(APFloat(+0.0)); // FLD0
631 addLegalFPImmediate(APFloat(+1.0)); // FLD1
632 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
633 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
634 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
635 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
636 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
637 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
640 // We don't support FMA.
641 setOperationAction(ISD::FMA, MVT::f64, Expand);
642 setOperationAction(ISD::FMA, MVT::f32, Expand);
644 // Long double always uses X87.
645 if (!TM.Options.UseSoftFloat) {
646 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
647 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
648 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
651 addLegalFPImmediate(TmpFlt); // FLD0
653 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
656 APFloat TmpFlt2(+1.0);
657 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659 addLegalFPImmediate(TmpFlt2); // FLD1
660 TmpFlt2.changeSign();
661 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
664 if (!TM.Options.UnsafeFPMath) {
665 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
666 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
669 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
670 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
671 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
672 setOperationAction(ISD::FRINT, MVT::f80, Expand);
673 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
674 setOperationAction(ISD::FMA, MVT::f80, Expand);
677 // Always use a library call for pow.
678 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
679 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
680 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
682 setOperationAction(ISD::FLOG, MVT::f80, Expand);
683 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
684 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
685 setOperationAction(ISD::FEXP, MVT::f80, Expand);
686 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
688 // First set operation action for all vector types to either promote
689 // (for widening) or expand (for scalarization). Then we will selectively
690 // turn on ones that can be effectively codegen'd.
691 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
692 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
693 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
708 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
711 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
745 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
750 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
751 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
752 setTruncStoreAction((MVT::SimpleValueType)VT,
753 (MVT::SimpleValueType)InnerVT, Expand);
754 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
755 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
756 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
759 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
760 // with -msoft-float, disable use of MMX as well.
761 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
762 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
763 // No operations on x86mmx supported, everything uses intrinsics.
766 // MMX-sized vectors (other than x86mmx) are expected to be expanded
767 // into smaller operations.
768 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
769 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
770 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
771 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
772 setOperationAction(ISD::AND, MVT::v8i8, Expand);
773 setOperationAction(ISD::AND, MVT::v4i16, Expand);
774 setOperationAction(ISD::AND, MVT::v2i32, Expand);
775 setOperationAction(ISD::AND, MVT::v1i64, Expand);
776 setOperationAction(ISD::OR, MVT::v8i8, Expand);
777 setOperationAction(ISD::OR, MVT::v4i16, Expand);
778 setOperationAction(ISD::OR, MVT::v2i32, Expand);
779 setOperationAction(ISD::OR, MVT::v1i64, Expand);
780 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
781 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
782 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
783 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
784 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
785 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
786 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
787 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
789 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
790 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
791 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
792 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
793 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
794 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
795 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
796 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
798 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
799 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
801 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
802 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
803 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
804 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
805 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
806 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
807 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
808 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
809 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
811 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
812 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
815 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
816 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
818 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
819 // registers cannot be used even for integer operations.
820 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
821 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
822 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
823 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
825 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
826 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
827 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
828 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
829 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
830 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
831 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
832 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
833 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
834 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
835 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
836 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
837 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
838 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
839 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
840 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
842 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
843 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
844 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
845 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
847 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
848 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
849 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
850 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
851 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
853 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
854 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
855 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
856 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
857 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
859 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
860 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
861 EVT VT = (MVT::SimpleValueType)i;
862 // Do not attempt to custom lower non-power-of-2 vectors
863 if (!isPowerOf2_32(VT.getVectorNumElements()))
865 // Do not attempt to custom lower non-128-bit vectors
866 if (!VT.is128BitVector())
868 setOperationAction(ISD::BUILD_VECTOR,
869 VT.getSimpleVT().SimpleTy, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE,
871 VT.getSimpleVT().SimpleTy, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
873 VT.getSimpleVT().SimpleTy, Custom);
876 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
877 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
878 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
880 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
881 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
883 if (Subtarget->is64Bit()) {
884 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
885 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
888 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
889 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
890 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
893 // Do not attempt to promote non-128-bit vectors
894 if (!VT.is128BitVector())
897 setOperationAction(ISD::AND, SVT, Promote);
898 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
899 setOperationAction(ISD::OR, SVT, Promote);
900 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
901 setOperationAction(ISD::XOR, SVT, Promote);
902 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
903 setOperationAction(ISD::LOAD, SVT, Promote);
904 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
905 setOperationAction(ISD::SELECT, SVT, Promote);
906 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
909 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
911 // Custom lower v2i64 and v2f64 selects.
912 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
913 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
914 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
915 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
917 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
918 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
921 if (Subtarget->hasSSE41orAVX()) {
922 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
923 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
924 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
925 setOperationAction(ISD::FRINT, MVT::f32, Legal);
926 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
927 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
928 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
929 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
930 setOperationAction(ISD::FRINT, MVT::f64, Legal);
931 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
933 // FIXME: Do we need to handle scalar-to-vector here?
934 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
936 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
937 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
938 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
939 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
940 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
942 // i8 and i16 vectors are custom , because the source register and source
943 // source memory operand types are not the same width. f32 vectors are
944 // custom since the immediate controlling the insert encodes additional
946 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
947 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
948 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
953 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
954 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
956 // FIXME: these should be Legal but thats only for the case where
957 // the index is constant. For now custom expand to deal with that
958 if (Subtarget->is64Bit()) {
959 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
964 if (Subtarget->hasXMMInt()) {
965 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
966 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
968 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
969 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
971 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
972 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
974 if (Subtarget->hasAVX2()) {
975 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
976 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
978 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
979 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
981 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
983 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
984 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
986 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
987 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
989 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
993 if (Subtarget->hasSSE42orAVX())
994 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
996 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
997 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
998 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
999 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
1000 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
1001 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
1002 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
1004 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1005 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1006 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1008 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1009 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1010 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1011 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1012 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1013 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1015 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1016 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1017 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1018 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1019 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1020 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1022 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1023 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1024 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1026 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1027 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1028 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1029 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1030 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1031 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1034 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1037 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1040 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1042 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1043 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1044 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1045 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1047 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1048 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1049 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1051 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1052 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1053 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1054 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1056 if (Subtarget->hasAVX2()) {
1057 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1058 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1059 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1060 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1062 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1063 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1064 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1065 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1067 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1068 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1069 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1070 // Don't lower v32i8 because there is no 128-bit byte mul
1072 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1074 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1075 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1077 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1078 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1080 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1082 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1083 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1084 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1085 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1087 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1089 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1092 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1093 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1094 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1095 // Don't lower v32i8 because there is no 128-bit byte mul
1097 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1098 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1100 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1101 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1103 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1106 // Custom lower several nodes for 256-bit types.
1107 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1108 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1109 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1112 // Extract subvector is special because the value type
1113 // (result) is 128-bit but the source is 256-bit wide.
1114 if (VT.is128BitVector())
1115 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1117 // Do not attempt to custom lower other non-256-bit vectors
1118 if (!VT.is256BitVector())
1121 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1122 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1123 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1124 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1125 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1126 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1129 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1130 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1131 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1134 // Do not attempt to promote non-256-bit vectors
1135 if (!VT.is256BitVector())
1138 setOperationAction(ISD::AND, SVT, Promote);
1139 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1140 setOperationAction(ISD::OR, SVT, Promote);
1141 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1142 setOperationAction(ISD::XOR, SVT, Promote);
1143 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1144 setOperationAction(ISD::LOAD, SVT, Promote);
1145 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1146 setOperationAction(ISD::SELECT, SVT, Promote);
1147 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1151 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1152 // of this type with custom code.
1153 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1154 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1155 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1158 // We want to custom lower some of our intrinsics.
1159 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1162 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1163 // handle type legalization for these operations here.
1165 // FIXME: We really should do custom legalization for addition and
1166 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1167 // than generic legalization for 64-bit multiplication-with-overflow, though.
1168 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1169 // Add/Sub/Mul with overflow operations are custom lowered.
1171 setOperationAction(ISD::SADDO, VT, Custom);
1172 setOperationAction(ISD::UADDO, VT, Custom);
1173 setOperationAction(ISD::SSUBO, VT, Custom);
1174 setOperationAction(ISD::USUBO, VT, Custom);
1175 setOperationAction(ISD::SMULO, VT, Custom);
1176 setOperationAction(ISD::UMULO, VT, Custom);
1179 // There are no 8-bit 3-address imul/mul instructions
1180 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1181 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1183 if (!Subtarget->is64Bit()) {
1184 // These libcalls are not available in 32-bit.
1185 setLibcallName(RTLIB::SHL_I128, 0);
1186 setLibcallName(RTLIB::SRL_I128, 0);
1187 setLibcallName(RTLIB::SRA_I128, 0);
1190 // We have target-specific dag combine patterns for the following nodes:
1191 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1192 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1193 setTargetDAGCombine(ISD::BUILD_VECTOR);
1194 setTargetDAGCombine(ISD::VSELECT);
1195 setTargetDAGCombine(ISD::SELECT);
1196 setTargetDAGCombine(ISD::SHL);
1197 setTargetDAGCombine(ISD::SRA);
1198 setTargetDAGCombine(ISD::SRL);
1199 setTargetDAGCombine(ISD::OR);
1200 setTargetDAGCombine(ISD::AND);
1201 setTargetDAGCombine(ISD::ADD);
1202 setTargetDAGCombine(ISD::FADD);
1203 setTargetDAGCombine(ISD::FSUB);
1204 setTargetDAGCombine(ISD::SUB);
1205 setTargetDAGCombine(ISD::LOAD);
1206 setTargetDAGCombine(ISD::STORE);
1207 setTargetDAGCombine(ISD::ZERO_EXTEND);
1208 setTargetDAGCombine(ISD::SINT_TO_FP);
1209 if (Subtarget->is64Bit())
1210 setTargetDAGCombine(ISD::MUL);
1211 if (Subtarget->hasBMI())
1212 setTargetDAGCombine(ISD::XOR);
1214 computeRegisterProperties();
1216 // On Darwin, -Os means optimize for size without hurting performance,
1217 // do not reduce the limit.
1218 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1219 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1220 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1221 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1222 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1223 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1224 setPrefLoopAlignment(4); // 2^4 bytes.
1225 benefitFromCodePlacementOpt = true;
1227 setPrefFunctionAlignment(4); // 2^4 bytes.
1231 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1232 if (!VT.isVector()) return MVT::i8;
1233 return VT.changeVectorElementTypeToInteger();
1237 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1238 /// the desired ByVal argument alignment.
1239 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1242 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1243 if (VTy->getBitWidth() == 128)
1245 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1246 unsigned EltAlign = 0;
1247 getMaxByValAlign(ATy->getElementType(), EltAlign);
1248 if (EltAlign > MaxAlign)
1249 MaxAlign = EltAlign;
1250 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1251 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1252 unsigned EltAlign = 0;
1253 getMaxByValAlign(STy->getElementType(i), EltAlign);
1254 if (EltAlign > MaxAlign)
1255 MaxAlign = EltAlign;
1263 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1264 /// function arguments in the caller parameter area. For X86, aggregates
1265 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1266 /// are at 4-byte boundaries.
1267 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1268 if (Subtarget->is64Bit()) {
1269 // Max of 8 and alignment of type.
1270 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1277 if (Subtarget->hasXMM())
1278 getMaxByValAlign(Ty, Align);
1282 /// getOptimalMemOpType - Returns the target specific optimal type for load
1283 /// and store operations as a result of memset, memcpy, and memmove
1284 /// lowering. If DstAlign is zero that means it's safe to destination
1285 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1286 /// means there isn't a need to check it against alignment requirement,
1287 /// probably because the source does not need to be loaded. If
1288 /// 'IsZeroVal' is true, that means it's safe to return a
1289 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1290 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1291 /// constant so it does not need to be loaded.
1292 /// It returns EVT::Other if the type should be determined using generic
1293 /// target-independent logic.
1295 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1296 unsigned DstAlign, unsigned SrcAlign,
1299 MachineFunction &MF) const {
1300 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1301 // linux. This is because the stack realignment code can't handle certain
1302 // cases like PR2962. This should be removed when PR2962 is fixed.
1303 const Function *F = MF.getFunction();
1305 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1307 (Subtarget->isUnalignedMemAccessFast() ||
1308 ((DstAlign == 0 || DstAlign >= 16) &&
1309 (SrcAlign == 0 || SrcAlign >= 16))) &&
1310 Subtarget->getStackAlignment() >= 16) {
1311 if (Subtarget->hasAVX() &&
1312 Subtarget->getStackAlignment() >= 32)
1314 if (Subtarget->hasXMMInt())
1316 if (Subtarget->hasXMM())
1318 } else if (!MemcpyStrSrc && Size >= 8 &&
1319 !Subtarget->is64Bit() &&
1320 Subtarget->getStackAlignment() >= 8 &&
1321 Subtarget->hasXMMInt()) {
1322 // Do not use f64 to lower memcpy if source is string constant. It's
1323 // better to use i32 to avoid the loads.
1327 if (Subtarget->is64Bit() && Size >= 8)
1332 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1333 /// current function. The returned value is a member of the
1334 /// MachineJumpTableInfo::JTEntryKind enum.
1335 unsigned X86TargetLowering::getJumpTableEncoding() const {
1336 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1338 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1339 Subtarget->isPICStyleGOT())
1340 return MachineJumpTableInfo::EK_Custom32;
1342 // Otherwise, use the normal jump table encoding heuristics.
1343 return TargetLowering::getJumpTableEncoding();
1347 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1348 const MachineBasicBlock *MBB,
1349 unsigned uid,MCContext &Ctx) const{
1350 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1351 Subtarget->isPICStyleGOT());
1352 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1354 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1355 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1358 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1360 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1361 SelectionDAG &DAG) const {
1362 if (!Subtarget->is64Bit())
1363 // This doesn't have DebugLoc associated with it, but is not really the
1364 // same as a Register.
1365 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1369 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1370 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1372 const MCExpr *X86TargetLowering::
1373 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1374 MCContext &Ctx) const {
1375 // X86-64 uses RIP relative addressing based on the jump table label.
1376 if (Subtarget->isPICStyleRIPRel())
1377 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1379 // Otherwise, the reference is relative to the PIC base.
1380 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1383 // FIXME: Why this routine is here? Move to RegInfo!
1384 std::pair<const TargetRegisterClass*, uint8_t>
1385 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1386 const TargetRegisterClass *RRC = 0;
1388 switch (VT.getSimpleVT().SimpleTy) {
1390 return TargetLowering::findRepresentativeClass(VT);
1391 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1392 RRC = (Subtarget->is64Bit()
1393 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1396 RRC = X86::VR64RegisterClass;
1398 case MVT::f32: case MVT::f64:
1399 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1400 case MVT::v4f32: case MVT::v2f64:
1401 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1403 RRC = X86::VR128RegisterClass;
1406 return std::make_pair(RRC, Cost);
1409 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1410 unsigned &Offset) const {
1411 if (!Subtarget->isTargetLinux())
1414 if (Subtarget->is64Bit()) {
1415 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1417 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1430 //===----------------------------------------------------------------------===//
1431 // Return Value Calling Convention Implementation
1432 //===----------------------------------------------------------------------===//
1434 #include "X86GenCallingConv.inc"
1437 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1438 MachineFunction &MF, bool isVarArg,
1439 const SmallVectorImpl<ISD::OutputArg> &Outs,
1440 LLVMContext &Context) const {
1441 SmallVector<CCValAssign, 16> RVLocs;
1442 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1444 return CCInfo.CheckReturn(Outs, RetCC_X86);
1448 X86TargetLowering::LowerReturn(SDValue Chain,
1449 CallingConv::ID CallConv, bool isVarArg,
1450 const SmallVectorImpl<ISD::OutputArg> &Outs,
1451 const SmallVectorImpl<SDValue> &OutVals,
1452 DebugLoc dl, SelectionDAG &DAG) const {
1453 MachineFunction &MF = DAG.getMachineFunction();
1454 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1456 SmallVector<CCValAssign, 16> RVLocs;
1457 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1458 RVLocs, *DAG.getContext());
1459 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1461 // Add the regs to the liveout set for the function.
1462 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1463 for (unsigned i = 0; i != RVLocs.size(); ++i)
1464 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1465 MRI.addLiveOut(RVLocs[i].getLocReg());
1469 SmallVector<SDValue, 6> RetOps;
1470 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1471 // Operand #1 = Bytes To Pop
1472 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1475 // Copy the result values into the output registers.
1476 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1477 CCValAssign &VA = RVLocs[i];
1478 assert(VA.isRegLoc() && "Can only return in registers!");
1479 SDValue ValToCopy = OutVals[i];
1480 EVT ValVT = ValToCopy.getValueType();
1482 // If this is x86-64, and we disabled SSE, we can't return FP values,
1483 // or SSE or MMX vectors.
1484 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1485 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1486 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1487 report_fatal_error("SSE register return with SSE disabled");
1489 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1490 // llvm-gcc has never done it right and no one has noticed, so this
1491 // should be OK for now.
1492 if (ValVT == MVT::f64 &&
1493 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1494 report_fatal_error("SSE2 register return with SSE2 disabled");
1496 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1497 // the RET instruction and handled by the FP Stackifier.
1498 if (VA.getLocReg() == X86::ST0 ||
1499 VA.getLocReg() == X86::ST1) {
1500 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1501 // change the value to the FP stack register class.
1502 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1503 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1504 RetOps.push_back(ValToCopy);
1505 // Don't emit a copytoreg.
1509 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1510 // which is returned in RAX / RDX.
1511 if (Subtarget->is64Bit()) {
1512 if (ValVT == MVT::x86mmx) {
1513 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1514 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1515 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1517 // If we don't have SSE2 available, convert to v4f32 so the generated
1518 // register is legal.
1519 if (!Subtarget->hasXMMInt())
1520 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1525 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1526 Flag = Chain.getValue(1);
1529 // The x86-64 ABI for returning structs by value requires that we copy
1530 // the sret argument into %rax for the return. We saved the argument into
1531 // a virtual register in the entry block, so now we copy the value out
1533 if (Subtarget->is64Bit() &&
1534 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1535 MachineFunction &MF = DAG.getMachineFunction();
1536 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1537 unsigned Reg = FuncInfo->getSRetReturnReg();
1539 "SRetReturnReg should have been set in LowerFormalArguments().");
1540 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1542 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1543 Flag = Chain.getValue(1);
1545 // RAX now acts like a return value.
1546 MRI.addLiveOut(X86::RAX);
1549 RetOps[0] = Chain; // Update chain.
1551 // Add the flag if we have it.
1553 RetOps.push_back(Flag);
1555 return DAG.getNode(X86ISD::RET_FLAG, dl,
1556 MVT::Other, &RetOps[0], RetOps.size());
1559 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1560 if (N->getNumValues() != 1)
1562 if (!N->hasNUsesOfValue(1, 0))
1565 SDNode *Copy = *N->use_begin();
1566 if (Copy->getOpcode() != ISD::CopyToReg &&
1567 Copy->getOpcode() != ISD::FP_EXTEND)
1570 bool HasRet = false;
1571 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1573 if (UI->getOpcode() != X86ISD::RET_FLAG)
1582 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1583 ISD::NodeType ExtendKind) const {
1585 // TODO: Is this also valid on 32-bit?
1586 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1587 ReturnMVT = MVT::i8;
1589 ReturnMVT = MVT::i32;
1591 EVT MinVT = getRegisterType(Context, ReturnMVT);
1592 return VT.bitsLT(MinVT) ? MinVT : VT;
1595 /// LowerCallResult - Lower the result values of a call into the
1596 /// appropriate copies out of appropriate physical registers.
1599 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1600 CallingConv::ID CallConv, bool isVarArg,
1601 const SmallVectorImpl<ISD::InputArg> &Ins,
1602 DebugLoc dl, SelectionDAG &DAG,
1603 SmallVectorImpl<SDValue> &InVals) const {
1605 // Assign locations to each value returned by this call.
1606 SmallVector<CCValAssign, 16> RVLocs;
1607 bool Is64Bit = Subtarget->is64Bit();
1608 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1609 getTargetMachine(), RVLocs, *DAG.getContext());
1610 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1612 // Copy all of the result registers out of their specified physreg.
1613 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614 CCValAssign &VA = RVLocs[i];
1615 EVT CopyVT = VA.getValVT();
1617 // If this is x86-64, and we disabled SSE, we can't return FP values
1618 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1619 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1620 report_fatal_error("SSE register return with SSE disabled");
1625 // If this is a call to a function that returns an fp value on the floating
1626 // point stack, we must guarantee the the value is popped from the stack, so
1627 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1628 // if the return value is not used. We use the FpPOP_RETVAL instruction
1630 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1631 // If we prefer to use the value in xmm registers, copy it out as f80 and
1632 // use a truncate to move it from fp stack reg to xmm reg.
1633 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1634 SDValue Ops[] = { Chain, InFlag };
1635 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1636 MVT::Other, MVT::Glue, Ops, 2), 1);
1637 Val = Chain.getValue(0);
1639 // Round the f80 to the right size, which also moves it to the appropriate
1641 if (CopyVT != VA.getValVT())
1642 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1643 // This truncation won't change the value.
1644 DAG.getIntPtrConstant(1));
1646 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1647 CopyVT, InFlag).getValue(1);
1648 Val = Chain.getValue(0);
1650 InFlag = Chain.getValue(2);
1651 InVals.push_back(Val);
1658 //===----------------------------------------------------------------------===//
1659 // C & StdCall & Fast Calling Convention implementation
1660 //===----------------------------------------------------------------------===//
1661 // StdCall calling convention seems to be standard for many Windows' API
1662 // routines and around. It differs from C calling convention just a little:
1663 // callee should clean up the stack, not caller. Symbols should be also
1664 // decorated in some fancy way :) It doesn't support any vector arguments.
1665 // For info on fast calling convention see Fast Calling Convention (tail call)
1666 // implementation LowerX86_32FastCCCallTo.
1668 /// CallIsStructReturn - Determines whether a call uses struct return
1670 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1674 return Outs[0].Flags.isSRet();
1677 /// ArgsAreStructReturn - Determines whether a function uses struct
1678 /// return semantics.
1680 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1684 return Ins[0].Flags.isSRet();
1687 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1688 /// by "Src" to address "Dst" with size and alignment information specified by
1689 /// the specific parameter attribute. The copy will be passed as a byval
1690 /// function parameter.
1692 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1693 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1695 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1697 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1698 /*isVolatile*/false, /*AlwaysInline=*/true,
1699 MachinePointerInfo(), MachinePointerInfo());
1702 /// IsTailCallConvention - Return true if the calling convention is one that
1703 /// supports tail call optimization.
1704 static bool IsTailCallConvention(CallingConv::ID CC) {
1705 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1708 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1709 if (!CI->isTailCall())
1713 CallingConv::ID CalleeCC = CS.getCallingConv();
1714 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1720 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1721 /// a tailcall target by changing its ABI.
1722 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1723 bool GuaranteedTailCallOpt) {
1724 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1728 X86TargetLowering::LowerMemArgument(SDValue Chain,
1729 CallingConv::ID CallConv,
1730 const SmallVectorImpl<ISD::InputArg> &Ins,
1731 DebugLoc dl, SelectionDAG &DAG,
1732 const CCValAssign &VA,
1733 MachineFrameInfo *MFI,
1735 // Create the nodes corresponding to a load from this parameter slot.
1736 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1737 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1738 getTargetMachine().Options.GuaranteedTailCallOpt);
1739 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1742 // If value is passed by pointer we have address passed instead of the value
1744 if (VA.getLocInfo() == CCValAssign::Indirect)
1745 ValVT = VA.getLocVT();
1747 ValVT = VA.getValVT();
1749 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1750 // changed with more analysis.
1751 // In case of tail call optimization mark all arguments mutable. Since they
1752 // could be overwritten by lowering of arguments in case of a tail call.
1753 if (Flags.isByVal()) {
1754 unsigned Bytes = Flags.getByValSize();
1755 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1756 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1757 return DAG.getFrameIndex(FI, getPointerTy());
1759 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1760 VA.getLocMemOffset(), isImmutable);
1761 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1762 return DAG.getLoad(ValVT, dl, Chain, FIN,
1763 MachinePointerInfo::getFixedStack(FI),
1764 false, false, false, 0);
1769 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1770 CallingConv::ID CallConv,
1772 const SmallVectorImpl<ISD::InputArg> &Ins,
1775 SmallVectorImpl<SDValue> &InVals)
1777 MachineFunction &MF = DAG.getMachineFunction();
1778 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1780 const Function* Fn = MF.getFunction();
1781 if (Fn->hasExternalLinkage() &&
1782 Subtarget->isTargetCygMing() &&
1783 Fn->getName() == "main")
1784 FuncInfo->setForceFramePointer(true);
1786 MachineFrameInfo *MFI = MF.getFrameInfo();
1787 bool Is64Bit = Subtarget->is64Bit();
1788 bool IsWin64 = Subtarget->isTargetWin64();
1790 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1791 "Var args not supported with calling convention fastcc or ghc");
1793 // Assign locations to all of the incoming arguments.
1794 SmallVector<CCValAssign, 16> ArgLocs;
1795 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1796 ArgLocs, *DAG.getContext());
1798 // Allocate shadow area for Win64
1800 CCInfo.AllocateStack(32, 8);
1803 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1805 unsigned LastVal = ~0U;
1807 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1808 CCValAssign &VA = ArgLocs[i];
1809 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1811 assert(VA.getValNo() != LastVal &&
1812 "Don't support value assigned to multiple locs yet");
1814 LastVal = VA.getValNo();
1816 if (VA.isRegLoc()) {
1817 EVT RegVT = VA.getLocVT();
1818 TargetRegisterClass *RC = NULL;
1819 if (RegVT == MVT::i32)
1820 RC = X86::GR32RegisterClass;
1821 else if (Is64Bit && RegVT == MVT::i64)
1822 RC = X86::GR64RegisterClass;
1823 else if (RegVT == MVT::f32)
1824 RC = X86::FR32RegisterClass;
1825 else if (RegVT == MVT::f64)
1826 RC = X86::FR64RegisterClass;
1827 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1828 RC = X86::VR256RegisterClass;
1829 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1830 RC = X86::VR128RegisterClass;
1831 else if (RegVT == MVT::x86mmx)
1832 RC = X86::VR64RegisterClass;
1834 llvm_unreachable("Unknown argument type!");
1836 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1837 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1839 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1840 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1842 if (VA.getLocInfo() == CCValAssign::SExt)
1843 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1844 DAG.getValueType(VA.getValVT()));
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1847 DAG.getValueType(VA.getValVT()));
1848 else if (VA.getLocInfo() == CCValAssign::BCvt)
1849 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1851 if (VA.isExtInLoc()) {
1852 // Handle MMX values passed in XMM regs.
1853 if (RegVT.isVector()) {
1854 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1857 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1860 assert(VA.isMemLoc());
1861 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1864 // If value is passed via pointer - do a load.
1865 if (VA.getLocInfo() == CCValAssign::Indirect)
1866 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1867 MachinePointerInfo(), false, false, false, 0);
1869 InVals.push_back(ArgValue);
1872 // The x86-64 ABI for returning structs by value requires that we copy
1873 // the sret argument into %rax for the return. Save the argument into
1874 // a virtual register so that we can access it from the return points.
1875 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1876 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1877 unsigned Reg = FuncInfo->getSRetReturnReg();
1879 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1880 FuncInfo->setSRetReturnReg(Reg);
1882 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1883 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1886 unsigned StackSize = CCInfo.getNextStackOffset();
1887 // Align stack specially for tail calls.
1888 if (FuncIsMadeTailCallSafe(CallConv,
1889 MF.getTarget().Options.GuaranteedTailCallOpt))
1890 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1892 // If the function takes variable number of arguments, make a frame index for
1893 // the start of the first vararg value... for expansion of llvm.va_start.
1895 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1896 CallConv != CallingConv::X86_ThisCall)) {
1897 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1900 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1902 // FIXME: We should really autogenerate these arrays
1903 static const unsigned GPR64ArgRegsWin64[] = {
1904 X86::RCX, X86::RDX, X86::R8, X86::R9
1906 static const unsigned GPR64ArgRegs64Bit[] = {
1907 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1909 static const unsigned XMMArgRegs64Bit[] = {
1910 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1911 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1913 const unsigned *GPR64ArgRegs;
1914 unsigned NumXMMRegs = 0;
1917 // The XMM registers which might contain var arg parameters are shadowed
1918 // in their paired GPR. So we only need to save the GPR to their home
1920 TotalNumIntRegs = 4;
1921 GPR64ArgRegs = GPR64ArgRegsWin64;
1923 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1924 GPR64ArgRegs = GPR64ArgRegs64Bit;
1926 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1928 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1931 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1932 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1933 "SSE register cannot be used when SSE is disabled!");
1934 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1935 NoImplicitFloatOps) &&
1936 "SSE register cannot be used when SSE is disabled!");
1937 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1938 !Subtarget->hasXMM())
1939 // Kernel mode asks for SSE to be disabled, so don't push them
1941 TotalNumXMMRegs = 0;
1944 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1945 // Get to the caller-allocated home save location. Add 8 to account
1946 // for the return address.
1947 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1948 FuncInfo->setRegSaveFrameIndex(
1949 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1950 // Fixup to set vararg frame on shadow area (4 x i64).
1952 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1954 // For X86-64, if there are vararg parameters that are passed via
1955 // registers, then we must store them to their spots on the stack so they
1956 // may be loaded by deferencing the result of va_next.
1957 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1958 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1959 FuncInfo->setRegSaveFrameIndex(
1960 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1964 // Store the integer parameter registers.
1965 SmallVector<SDValue, 8> MemOps;
1966 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1968 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1969 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1970 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1971 DAG.getIntPtrConstant(Offset));
1972 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1973 X86::GR64RegisterClass);
1974 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1976 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1977 MachinePointerInfo::getFixedStack(
1978 FuncInfo->getRegSaveFrameIndex(), Offset),
1980 MemOps.push_back(Store);
1984 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1985 // Now store the XMM (fp + vector) parameter registers.
1986 SmallVector<SDValue, 11> SaveXMMOps;
1987 SaveXMMOps.push_back(Chain);
1989 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1990 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1991 SaveXMMOps.push_back(ALVal);
1993 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1994 FuncInfo->getRegSaveFrameIndex()));
1995 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1996 FuncInfo->getVarArgsFPOffset()));
1998 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1999 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2000 X86::VR128RegisterClass);
2001 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2002 SaveXMMOps.push_back(Val);
2004 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2006 &SaveXMMOps[0], SaveXMMOps.size()));
2009 if (!MemOps.empty())
2010 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2011 &MemOps[0], MemOps.size());
2015 // Some CCs need callee pop.
2016 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2017 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2018 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2020 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2021 // If this is an sret function, the return should pop the hidden pointer.
2022 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2023 FuncInfo->setBytesToPopOnReturn(4);
2027 // RegSaveFrameIndex is X86-64 only.
2028 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2029 if (CallConv == CallingConv::X86_FastCall ||
2030 CallConv == CallingConv::X86_ThisCall)
2031 // fastcc functions can't have varargs.
2032 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2035 FuncInfo->setArgumentStackSize(StackSize);
2041 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2042 SDValue StackPtr, SDValue Arg,
2043 DebugLoc dl, SelectionDAG &DAG,
2044 const CCValAssign &VA,
2045 ISD::ArgFlagsTy Flags) const {
2046 unsigned LocMemOffset = VA.getLocMemOffset();
2047 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2048 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2049 if (Flags.isByVal())
2050 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2052 return DAG.getStore(Chain, dl, Arg, PtrOff,
2053 MachinePointerInfo::getStack(LocMemOffset),
2057 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2058 /// optimization is performed and it is required.
2060 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2061 SDValue &OutRetAddr, SDValue Chain,
2062 bool IsTailCall, bool Is64Bit,
2063 int FPDiff, DebugLoc dl) const {
2064 // Adjust the Return address stack slot.
2065 EVT VT = getPointerTy();
2066 OutRetAddr = getReturnAddressFrameIndex(DAG);
2068 // Load the "old" Return address.
2069 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2070 false, false, false, 0);
2071 return SDValue(OutRetAddr.getNode(), 1);
2074 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2075 /// optimization is performed and it is required (FPDiff!=0).
2077 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2078 SDValue Chain, SDValue RetAddrFrIdx,
2079 bool Is64Bit, int FPDiff, DebugLoc dl) {
2080 // Store the return address to the appropriate stack slot.
2081 if (!FPDiff) return Chain;
2082 // Calculate the new stack slot for the return address.
2083 int SlotSize = Is64Bit ? 8 : 4;
2084 int NewReturnAddrFI =
2085 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2086 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2087 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2088 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2089 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2095 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2096 CallingConv::ID CallConv, bool isVarArg,
2098 const SmallVectorImpl<ISD::OutputArg> &Outs,
2099 const SmallVectorImpl<SDValue> &OutVals,
2100 const SmallVectorImpl<ISD::InputArg> &Ins,
2101 DebugLoc dl, SelectionDAG &DAG,
2102 SmallVectorImpl<SDValue> &InVals) const {
2103 MachineFunction &MF = DAG.getMachineFunction();
2104 bool Is64Bit = Subtarget->is64Bit();
2105 bool IsWin64 = Subtarget->isTargetWin64();
2106 bool IsStructRet = CallIsStructReturn(Outs);
2107 bool IsSibcall = false;
2110 // Check if it's really possible to do a tail call.
2111 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2112 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2113 Outs, OutVals, Ins, DAG);
2115 // Sibcalls are automatically detected tailcalls which do not require
2117 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2124 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2125 "Var args not supported with calling convention fastcc or ghc");
2127 // Analyze operands of the call, assigning locations to each operand.
2128 SmallVector<CCValAssign, 16> ArgLocs;
2129 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2130 ArgLocs, *DAG.getContext());
2132 // Allocate shadow area for Win64
2134 CCInfo.AllocateStack(32, 8);
2137 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2139 // Get a count of how many bytes are to be pushed on the stack.
2140 unsigned NumBytes = CCInfo.getNextStackOffset();
2142 // This is a sibcall. The memory operands are available in caller's
2143 // own caller's stack.
2145 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2146 IsTailCallConvention(CallConv))
2147 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2150 if (isTailCall && !IsSibcall) {
2151 // Lower arguments at fp - stackoffset + fpdiff.
2152 unsigned NumBytesCallerPushed =
2153 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2154 FPDiff = NumBytesCallerPushed - NumBytes;
2156 // Set the delta of movement of the returnaddr stackslot.
2157 // But only set if delta is greater than previous delta.
2158 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2159 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2163 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2165 SDValue RetAddrFrIdx;
2166 // Load return address for tail calls.
2167 if (isTailCall && FPDiff)
2168 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2169 Is64Bit, FPDiff, dl);
2171 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2172 SmallVector<SDValue, 8> MemOpChains;
2175 // Walk the register/memloc assignments, inserting copies/loads. In the case
2176 // of tail call optimization arguments are handle later.
2177 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2178 CCValAssign &VA = ArgLocs[i];
2179 EVT RegVT = VA.getLocVT();
2180 SDValue Arg = OutVals[i];
2181 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2182 bool isByVal = Flags.isByVal();
2184 // Promote the value if needed.
2185 switch (VA.getLocInfo()) {
2186 default: llvm_unreachable("Unknown loc info!");
2187 case CCValAssign::Full: break;
2188 case CCValAssign::SExt:
2189 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2191 case CCValAssign::ZExt:
2192 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2194 case CCValAssign::AExt:
2195 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2196 // Special case: passing MMX values in XMM registers.
2197 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2198 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2199 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2201 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2203 case CCValAssign::BCvt:
2204 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2206 case CCValAssign::Indirect: {
2207 // Store the argument.
2208 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2209 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2210 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2211 MachinePointerInfo::getFixedStack(FI),
2218 if (VA.isRegLoc()) {
2219 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2220 if (isVarArg && IsWin64) {
2221 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2222 // shadow reg if callee is a varargs function.
2223 unsigned ShadowReg = 0;
2224 switch (VA.getLocReg()) {
2225 case X86::XMM0: ShadowReg = X86::RCX; break;
2226 case X86::XMM1: ShadowReg = X86::RDX; break;
2227 case X86::XMM2: ShadowReg = X86::R8; break;
2228 case X86::XMM3: ShadowReg = X86::R9; break;
2231 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2233 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2234 assert(VA.isMemLoc());
2235 if (StackPtr.getNode() == 0)
2236 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2237 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2238 dl, DAG, VA, Flags));
2242 if (!MemOpChains.empty())
2243 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2244 &MemOpChains[0], MemOpChains.size());
2246 // Build a sequence of copy-to-reg nodes chained together with token chain
2247 // and flag operands which copy the outgoing args into registers.
2249 // Tail call byval lowering might overwrite argument registers so in case of
2250 // tail call optimization the copies to registers are lowered later.
2252 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2253 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2254 RegsToPass[i].second, InFlag);
2255 InFlag = Chain.getValue(1);
2258 if (Subtarget->isPICStyleGOT()) {
2259 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2262 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2263 DAG.getNode(X86ISD::GlobalBaseReg,
2264 DebugLoc(), getPointerTy()),
2266 InFlag = Chain.getValue(1);
2268 // If we are tail calling and generating PIC/GOT style code load the
2269 // address of the callee into ECX. The value in ecx is used as target of
2270 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2271 // for tail calls on PIC/GOT architectures. Normally we would just put the
2272 // address of GOT into ebx and then call target@PLT. But for tail calls
2273 // ebx would be restored (since ebx is callee saved) before jumping to the
2276 // Note: The actual moving to ECX is done further down.
2277 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2278 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2279 !G->getGlobal()->hasProtectedVisibility())
2280 Callee = LowerGlobalAddress(Callee, DAG);
2281 else if (isa<ExternalSymbolSDNode>(Callee))
2282 Callee = LowerExternalSymbol(Callee, DAG);
2286 if (Is64Bit && isVarArg && !IsWin64) {
2287 // From AMD64 ABI document:
2288 // For calls that may call functions that use varargs or stdargs
2289 // (prototype-less calls or calls to functions containing ellipsis (...) in
2290 // the declaration) %al is used as hidden argument to specify the number
2291 // of SSE registers used. The contents of %al do not need to match exactly
2292 // the number of registers, but must be an ubound on the number of SSE
2293 // registers used and is in the range 0 - 8 inclusive.
2295 // Count the number of XMM registers allocated.
2296 static const unsigned XMMArgRegs[] = {
2297 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2298 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2300 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2301 assert((Subtarget->hasXMM() || !NumXMMRegs)
2302 && "SSE registers cannot be used when SSE is disabled");
2304 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2305 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2306 InFlag = Chain.getValue(1);
2310 // For tail calls lower the arguments to the 'real' stack slot.
2312 // Force all the incoming stack arguments to be loaded from the stack
2313 // before any new outgoing arguments are stored to the stack, because the
2314 // outgoing stack slots may alias the incoming argument stack slots, and
2315 // the alias isn't otherwise explicit. This is slightly more conservative
2316 // than necessary, because it means that each store effectively depends
2317 // on every argument instead of just those arguments it would clobber.
2318 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2320 SmallVector<SDValue, 8> MemOpChains2;
2323 // Do not flag preceding copytoreg stuff together with the following stuff.
2325 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2326 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2327 CCValAssign &VA = ArgLocs[i];
2330 assert(VA.isMemLoc());
2331 SDValue Arg = OutVals[i];
2332 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2333 // Create frame index.
2334 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2335 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2336 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2337 FIN = DAG.getFrameIndex(FI, getPointerTy());
2339 if (Flags.isByVal()) {
2340 // Copy relative to framepointer.
2341 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2342 if (StackPtr.getNode() == 0)
2343 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2345 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2347 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2351 // Store relative to framepointer.
2352 MemOpChains2.push_back(
2353 DAG.getStore(ArgChain, dl, Arg, FIN,
2354 MachinePointerInfo::getFixedStack(FI),
2360 if (!MemOpChains2.empty())
2361 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2362 &MemOpChains2[0], MemOpChains2.size());
2364 // Copy arguments to their registers.
2365 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2366 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2367 RegsToPass[i].second, InFlag);
2368 InFlag = Chain.getValue(1);
2372 // Store the return address to the appropriate stack slot.
2373 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2377 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2378 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2379 // In the 64-bit large code model, we have to make all calls
2380 // through a register, since the call instruction's 32-bit
2381 // pc-relative offset may not be large enough to hold the whole
2383 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2384 // If the callee is a GlobalAddress node (quite common, every direct call
2385 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2388 // We should use extra load for direct calls to dllimported functions in
2390 const GlobalValue *GV = G->getGlobal();
2391 if (!GV->hasDLLImportLinkage()) {
2392 unsigned char OpFlags = 0;
2393 bool ExtraLoad = false;
2394 unsigned WrapperKind = ISD::DELETED_NODE;
2396 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2397 // external symbols most go through the PLT in PIC mode. If the symbol
2398 // has hidden or protected visibility, or if it is static or local, then
2399 // we don't need to use the PLT - we can directly call it.
2400 if (Subtarget->isTargetELF() &&
2401 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2402 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2403 OpFlags = X86II::MO_PLT;
2404 } else if (Subtarget->isPICStyleStubAny() &&
2405 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2406 (!Subtarget->getTargetTriple().isMacOSX() ||
2407 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2408 // PC-relative references to external symbols should go through $stub,
2409 // unless we're building with the leopard linker or later, which
2410 // automatically synthesizes these stubs.
2411 OpFlags = X86II::MO_DARWIN_STUB;
2412 } else if (Subtarget->isPICStyleRIPRel() &&
2413 isa<Function>(GV) &&
2414 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2415 // If the function is marked as non-lazy, generate an indirect call
2416 // which loads from the GOT directly. This avoids runtime overhead
2417 // at the cost of eager binding (and one extra byte of encoding).
2418 OpFlags = X86II::MO_GOTPCREL;
2419 WrapperKind = X86ISD::WrapperRIP;
2423 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2424 G->getOffset(), OpFlags);
2426 // Add a wrapper if needed.
2427 if (WrapperKind != ISD::DELETED_NODE)
2428 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2429 // Add extra indirection if needed.
2431 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2432 MachinePointerInfo::getGOT(),
2433 false, false, false, 0);
2435 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2436 unsigned char OpFlags = 0;
2438 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2439 // external symbols should go through the PLT.
2440 if (Subtarget->isTargetELF() &&
2441 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2442 OpFlags = X86II::MO_PLT;
2443 } else if (Subtarget->isPICStyleStubAny() &&
2444 (!Subtarget->getTargetTriple().isMacOSX() ||
2445 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2446 // PC-relative references to external symbols should go through $stub,
2447 // unless we're building with the leopard linker or later, which
2448 // automatically synthesizes these stubs.
2449 OpFlags = X86II::MO_DARWIN_STUB;
2452 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2456 // Returns a chain & a flag for retval copy to use.
2457 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2458 SmallVector<SDValue, 8> Ops;
2460 if (!IsSibcall && isTailCall) {
2461 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2462 DAG.getIntPtrConstant(0, true), InFlag);
2463 InFlag = Chain.getValue(1);
2466 Ops.push_back(Chain);
2467 Ops.push_back(Callee);
2470 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2472 // Add argument registers to the end of the list so that they are known live
2474 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2475 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2476 RegsToPass[i].second.getValueType()));
2478 // Add an implicit use GOT pointer in EBX.
2479 if (!isTailCall && Subtarget->isPICStyleGOT())
2480 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2482 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2483 if (Is64Bit && isVarArg && !IsWin64)
2484 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2486 if (InFlag.getNode())
2487 Ops.push_back(InFlag);
2491 //// If this is the first return lowered for this function, add the regs
2492 //// to the liveout set for the function.
2493 // This isn't right, although it's probably harmless on x86; liveouts
2494 // should be computed from returns not tail calls. Consider a void
2495 // function making a tail call to a function returning int.
2496 return DAG.getNode(X86ISD::TC_RETURN, dl,
2497 NodeTys, &Ops[0], Ops.size());
2500 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2501 InFlag = Chain.getValue(1);
2503 // Create the CALLSEQ_END node.
2504 unsigned NumBytesForCalleeToPush;
2505 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2506 getTargetMachine().Options.GuaranteedTailCallOpt))
2507 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2508 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2509 // If this is a call to a struct-return function, the callee
2510 // pops the hidden struct pointer, so we have to push it back.
2511 // This is common for Darwin/X86, Linux & Mingw32 targets.
2512 NumBytesForCalleeToPush = 4;
2514 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2516 // Returns a flag for retval copy to use.
2518 Chain = DAG.getCALLSEQ_END(Chain,
2519 DAG.getIntPtrConstant(NumBytes, true),
2520 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2523 InFlag = Chain.getValue(1);
2526 // Handle result values, copying them out of physregs into vregs that we
2528 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2529 Ins, dl, DAG, InVals);
2533 //===----------------------------------------------------------------------===//
2534 // Fast Calling Convention (tail call) implementation
2535 //===----------------------------------------------------------------------===//
2537 // Like std call, callee cleans arguments, convention except that ECX is
2538 // reserved for storing the tail called function address. Only 2 registers are
2539 // free for argument passing (inreg). Tail call optimization is performed
2541 // * tailcallopt is enabled
2542 // * caller/callee are fastcc
2543 // On X86_64 architecture with GOT-style position independent code only local
2544 // (within module) calls are supported at the moment.
2545 // To keep the stack aligned according to platform abi the function
2546 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2547 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2548 // If a tail called function callee has more arguments than the caller the
2549 // caller needs to make sure that there is room to move the RETADDR to. This is
2550 // achieved by reserving an area the size of the argument delta right after the
2551 // original REtADDR, but before the saved framepointer or the spilled registers
2552 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2564 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2565 /// for a 16 byte align requirement.
2567 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2568 SelectionDAG& DAG) const {
2569 MachineFunction &MF = DAG.getMachineFunction();
2570 const TargetMachine &TM = MF.getTarget();
2571 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2572 unsigned StackAlignment = TFI.getStackAlignment();
2573 uint64_t AlignMask = StackAlignment - 1;
2574 int64_t Offset = StackSize;
2575 uint64_t SlotSize = TD->getPointerSize();
2576 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2577 // Number smaller than 12 so just add the difference.
2578 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2580 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2581 Offset = ((~AlignMask) & Offset) + StackAlignment +
2582 (StackAlignment-SlotSize);
2587 /// MatchingStackOffset - Return true if the given stack call argument is
2588 /// already available in the same position (relatively) of the caller's
2589 /// incoming argument stack.
2591 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2592 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2593 const X86InstrInfo *TII) {
2594 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2596 if (Arg.getOpcode() == ISD::CopyFromReg) {
2597 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2598 if (!TargetRegisterInfo::isVirtualRegister(VR))
2600 MachineInstr *Def = MRI->getVRegDef(VR);
2603 if (!Flags.isByVal()) {
2604 if (!TII->isLoadFromStackSlot(Def, FI))
2607 unsigned Opcode = Def->getOpcode();
2608 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2609 Def->getOperand(1).isFI()) {
2610 FI = Def->getOperand(1).getIndex();
2611 Bytes = Flags.getByValSize();
2615 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2616 if (Flags.isByVal())
2617 // ByVal argument is passed in as a pointer but it's now being
2618 // dereferenced. e.g.
2619 // define @foo(%struct.X* %A) {
2620 // tail call @bar(%struct.X* byval %A)
2623 SDValue Ptr = Ld->getBasePtr();
2624 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2627 FI = FINode->getIndex();
2628 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2629 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2630 FI = FINode->getIndex();
2631 Bytes = Flags.getByValSize();
2635 assert(FI != INT_MAX);
2636 if (!MFI->isFixedObjectIndex(FI))
2638 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2641 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2642 /// for tail call optimization. Targets which want to do tail call
2643 /// optimization should implement this function.
2645 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2646 CallingConv::ID CalleeCC,
2648 bool isCalleeStructRet,
2649 bool isCallerStructRet,
2650 const SmallVectorImpl<ISD::OutputArg> &Outs,
2651 const SmallVectorImpl<SDValue> &OutVals,
2652 const SmallVectorImpl<ISD::InputArg> &Ins,
2653 SelectionDAG& DAG) const {
2654 if (!IsTailCallConvention(CalleeCC) &&
2655 CalleeCC != CallingConv::C)
2658 // If -tailcallopt is specified, make fastcc functions tail-callable.
2659 const MachineFunction &MF = DAG.getMachineFunction();
2660 const Function *CallerF = DAG.getMachineFunction().getFunction();
2661 CallingConv::ID CallerCC = CallerF->getCallingConv();
2662 bool CCMatch = CallerCC == CalleeCC;
2664 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2665 if (IsTailCallConvention(CalleeCC) && CCMatch)
2670 // Look for obvious safe cases to perform tail call optimization that do not
2671 // require ABI changes. This is what gcc calls sibcall.
2673 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2674 // emit a special epilogue.
2675 if (RegInfo->needsStackRealignment(MF))
2678 // Also avoid sibcall optimization if either caller or callee uses struct
2679 // return semantics.
2680 if (isCalleeStructRet || isCallerStructRet)
2683 // An stdcall caller is expected to clean up its arguments; the callee
2684 // isn't going to do that.
2685 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2688 // Do not sibcall optimize vararg calls unless all arguments are passed via
2690 if (isVarArg && !Outs.empty()) {
2692 // Optimizing for varargs on Win64 is unlikely to be safe without
2693 // additional testing.
2694 if (Subtarget->isTargetWin64())
2697 SmallVector<CCValAssign, 16> ArgLocs;
2698 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2699 getTargetMachine(), ArgLocs, *DAG.getContext());
2701 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2702 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2703 if (!ArgLocs[i].isRegLoc())
2707 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2708 // Therefore if it's not used by the call it is not safe to optimize this into
2710 bool Unused = false;
2711 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2718 SmallVector<CCValAssign, 16> RVLocs;
2719 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2720 getTargetMachine(), RVLocs, *DAG.getContext());
2721 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2722 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2723 CCValAssign &VA = RVLocs[i];
2724 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2729 // If the calling conventions do not match, then we'd better make sure the
2730 // results are returned in the same way as what the caller expects.
2732 SmallVector<CCValAssign, 16> RVLocs1;
2733 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2734 getTargetMachine(), RVLocs1, *DAG.getContext());
2735 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2737 SmallVector<CCValAssign, 16> RVLocs2;
2738 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2739 getTargetMachine(), RVLocs2, *DAG.getContext());
2740 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2742 if (RVLocs1.size() != RVLocs2.size())
2744 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2745 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2747 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2749 if (RVLocs1[i].isRegLoc()) {
2750 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2753 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2759 // If the callee takes no arguments then go on to check the results of the
2761 if (!Outs.empty()) {
2762 // Check if stack adjustment is needed. For now, do not do this if any
2763 // argument is passed on the stack.
2764 SmallVector<CCValAssign, 16> ArgLocs;
2765 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2766 getTargetMachine(), ArgLocs, *DAG.getContext());
2768 // Allocate shadow area for Win64
2769 if (Subtarget->isTargetWin64()) {
2770 CCInfo.AllocateStack(32, 8);
2773 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2774 if (CCInfo.getNextStackOffset()) {
2775 MachineFunction &MF = DAG.getMachineFunction();
2776 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2779 // Check if the arguments are already laid out in the right way as
2780 // the caller's fixed stack objects.
2781 MachineFrameInfo *MFI = MF.getFrameInfo();
2782 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2783 const X86InstrInfo *TII =
2784 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2785 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786 CCValAssign &VA = ArgLocs[i];
2787 SDValue Arg = OutVals[i];
2788 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2789 if (VA.getLocInfo() == CCValAssign::Indirect)
2791 if (!VA.isRegLoc()) {
2792 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2799 // If the tailcall address may be in a register, then make sure it's
2800 // possible to register allocate for it. In 32-bit, the call address can
2801 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2802 // callee-saved registers are restored. These happen to be the same
2803 // registers used to pass 'inreg' arguments so watch out for those.
2804 if (!Subtarget->is64Bit() &&
2805 !isa<GlobalAddressSDNode>(Callee) &&
2806 !isa<ExternalSymbolSDNode>(Callee)) {
2807 unsigned NumInRegs = 0;
2808 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2809 CCValAssign &VA = ArgLocs[i];
2812 unsigned Reg = VA.getLocReg();
2815 case X86::EAX: case X86::EDX: case X86::ECX:
2816 if (++NumInRegs == 3)
2828 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2829 return X86::createFastISel(funcInfo);
2833 //===----------------------------------------------------------------------===//
2834 // Other Lowering Hooks
2835 //===----------------------------------------------------------------------===//
2837 static bool MayFoldLoad(SDValue Op) {
2838 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2841 static bool MayFoldIntoStore(SDValue Op) {
2842 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2845 static bool isTargetShuffle(unsigned Opcode) {
2847 default: return false;
2848 case X86ISD::PSHUFD:
2849 case X86ISD::PSHUFHW:
2850 case X86ISD::PSHUFLW:
2851 case X86ISD::SHUFPD:
2852 case X86ISD::PALIGN:
2853 case X86ISD::SHUFPS:
2854 case X86ISD::MOVLHPS:
2855 case X86ISD::MOVLHPD:
2856 case X86ISD::MOVHLPS:
2857 case X86ISD::MOVLPS:
2858 case X86ISD::MOVLPD:
2859 case X86ISD::MOVSHDUP:
2860 case X86ISD::MOVSLDUP:
2861 case X86ISD::MOVDDUP:
2864 case X86ISD::UNPCKL:
2865 case X86ISD::UNPCKH:
2866 case X86ISD::VPERMILP:
2867 case X86ISD::VPERM2X128:
2873 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2874 SDValue V1, SelectionDAG &DAG) {
2876 default: llvm_unreachable("Unknown x86 shuffle node");
2877 case X86ISD::MOVSHDUP:
2878 case X86ISD::MOVSLDUP:
2879 case X86ISD::MOVDDUP:
2880 return DAG.getNode(Opc, dl, VT, V1);
2886 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2887 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2889 default: llvm_unreachable("Unknown x86 shuffle node");
2890 case X86ISD::PSHUFD:
2891 case X86ISD::PSHUFHW:
2892 case X86ISD::PSHUFLW:
2893 case X86ISD::VPERMILP:
2894 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2900 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2901 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2903 default: llvm_unreachable("Unknown x86 shuffle node");
2904 case X86ISD::PALIGN:
2905 case X86ISD::SHUFPD:
2906 case X86ISD::SHUFPS:
2907 case X86ISD::VPERM2X128:
2908 return DAG.getNode(Opc, dl, VT, V1, V2,
2909 DAG.getConstant(TargetMask, MVT::i8));
2914 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2915 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2917 default: llvm_unreachable("Unknown x86 shuffle node");
2918 case X86ISD::MOVLHPS:
2919 case X86ISD::MOVLHPD:
2920 case X86ISD::MOVHLPS:
2921 case X86ISD::MOVLPS:
2922 case X86ISD::MOVLPD:
2925 case X86ISD::UNPCKL:
2926 case X86ISD::UNPCKH:
2927 return DAG.getNode(Opc, dl, VT, V1, V2);
2932 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2933 MachineFunction &MF = DAG.getMachineFunction();
2934 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2935 int ReturnAddrIndex = FuncInfo->getRAIndex();
2937 if (ReturnAddrIndex == 0) {
2938 // Set up a frame object for the return address.
2939 uint64_t SlotSize = TD->getPointerSize();
2940 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2942 FuncInfo->setRAIndex(ReturnAddrIndex);
2945 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2949 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2950 bool hasSymbolicDisplacement) {
2951 // Offset should fit into 32 bit immediate field.
2952 if (!isInt<32>(Offset))
2955 // If we don't have a symbolic displacement - we don't have any extra
2957 if (!hasSymbolicDisplacement)
2960 // FIXME: Some tweaks might be needed for medium code model.
2961 if (M != CodeModel::Small && M != CodeModel::Kernel)
2964 // For small code model we assume that latest object is 16MB before end of 31
2965 // bits boundary. We may also accept pretty large negative constants knowing
2966 // that all objects are in the positive half of address space.
2967 if (M == CodeModel::Small && Offset < 16*1024*1024)
2970 // For kernel code model we know that all object resist in the negative half
2971 // of 32bits address space. We may not accept negative offsets, since they may
2972 // be just off and we may accept pretty large positive ones.
2973 if (M == CodeModel::Kernel && Offset > 0)
2979 /// isCalleePop - Determines whether the callee is required to pop its
2980 /// own arguments. Callee pop is necessary to support tail calls.
2981 bool X86::isCalleePop(CallingConv::ID CallingConv,
2982 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2986 switch (CallingConv) {
2989 case CallingConv::X86_StdCall:
2991 case CallingConv::X86_FastCall:
2993 case CallingConv::X86_ThisCall:
2995 case CallingConv::Fast:
2997 case CallingConv::GHC:
3002 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3003 /// specific condition code, returning the condition code and the LHS/RHS of the
3004 /// comparison to make.
3005 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3006 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3008 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3009 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3010 // X > -1 -> X == 0, jump !sign.
3011 RHS = DAG.getConstant(0, RHS.getValueType());
3012 return X86::COND_NS;
3013 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3014 // X < 0 -> X == 0, jump on sign.
3016 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3018 RHS = DAG.getConstant(0, RHS.getValueType());
3019 return X86::COND_LE;
3023 switch (SetCCOpcode) {
3024 default: llvm_unreachable("Invalid integer condition!");
3025 case ISD::SETEQ: return X86::COND_E;
3026 case ISD::SETGT: return X86::COND_G;
3027 case ISD::SETGE: return X86::COND_GE;
3028 case ISD::SETLT: return X86::COND_L;
3029 case ISD::SETLE: return X86::COND_LE;
3030 case ISD::SETNE: return X86::COND_NE;
3031 case ISD::SETULT: return X86::COND_B;
3032 case ISD::SETUGT: return X86::COND_A;
3033 case ISD::SETULE: return X86::COND_BE;
3034 case ISD::SETUGE: return X86::COND_AE;
3038 // First determine if it is required or is profitable to flip the operands.
3040 // If LHS is a foldable load, but RHS is not, flip the condition.
3041 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3042 !ISD::isNON_EXTLoad(RHS.getNode())) {
3043 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3044 std::swap(LHS, RHS);
3047 switch (SetCCOpcode) {
3053 std::swap(LHS, RHS);
3057 // On a floating point condition, the flags are set as follows:
3059 // 0 | 0 | 0 | X > Y
3060 // 0 | 0 | 1 | X < Y
3061 // 1 | 0 | 0 | X == Y
3062 // 1 | 1 | 1 | unordered
3063 switch (SetCCOpcode) {
3064 default: llvm_unreachable("Condcode should be pre-legalized away");
3066 case ISD::SETEQ: return X86::COND_E;
3067 case ISD::SETOLT: // flipped
3069 case ISD::SETGT: return X86::COND_A;
3070 case ISD::SETOLE: // flipped
3072 case ISD::SETGE: return X86::COND_AE;
3073 case ISD::SETUGT: // flipped
3075 case ISD::SETLT: return X86::COND_B;
3076 case ISD::SETUGE: // flipped
3078 case ISD::SETLE: return X86::COND_BE;
3080 case ISD::SETNE: return X86::COND_NE;
3081 case ISD::SETUO: return X86::COND_P;
3082 case ISD::SETO: return X86::COND_NP;
3084 case ISD::SETUNE: return X86::COND_INVALID;
3088 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3089 /// code. Current x86 isa includes the following FP cmov instructions:
3090 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3091 static bool hasFPCMov(unsigned X86CC) {
3107 /// isFPImmLegal - Returns true if the target can instruction select the
3108 /// specified FP immediate natively. If false, the legalizer will
3109 /// materialize the FP immediate as a load from a constant pool.
3110 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3111 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3112 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3118 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3119 /// the specified range (L, H].
3120 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3121 return (Val < 0) || (Val >= Low && Val < Hi);
3124 /// isUndefOrInRange - Return true if every element in Mask, begining
3125 /// from position Pos and ending in Pos+Size, falls within the specified
3126 /// range (L, L+Pos]. or is undef.
3127 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3128 int Pos, int Size, int Low, int Hi) {
3129 for (int i = Pos, e = Pos+Size; i != e; ++i)
3130 if (!isUndefOrInRange(Mask[i], Low, Hi))
3135 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3136 /// specified value.
3137 static bool isUndefOrEqual(int Val, int CmpVal) {
3138 if (Val < 0 || Val == CmpVal)
3143 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3144 /// from position Pos and ending in Pos+Size, falls within the specified
3145 /// sequential range (L, L+Pos]. or is undef.
3146 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3147 int Pos, int Size, int Low) {
3148 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3149 if (!isUndefOrEqual(Mask[i], Low))
3154 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3155 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3156 /// the second operand.
3157 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3158 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3159 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3160 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3161 return (Mask[0] < 2 && Mask[1] < 2);
3165 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3166 SmallVector<int, 8> M;
3168 return ::isPSHUFDMask(M, N->getValueType(0));
3171 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3172 /// is suitable for input to PSHUFHW.
3173 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174 if (VT != MVT::v8i16)
3177 // Lower quadword copied in order or undef.
3178 for (int i = 0; i != 4; ++i)
3179 if (Mask[i] >= 0 && Mask[i] != i)
3182 // Upper quadword shuffled.
3183 for (int i = 4; i != 8; ++i)
3184 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3190 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3191 SmallVector<int, 8> M;
3193 return ::isPSHUFHWMask(M, N->getValueType(0));
3196 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3197 /// is suitable for input to PSHUFLW.
3198 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3199 if (VT != MVT::v8i16)
3202 // Upper quadword copied in order.
3203 for (int i = 4; i != 8; ++i)
3204 if (Mask[i] >= 0 && Mask[i] != i)
3207 // Lower quadword shuffled.
3208 for (int i = 0; i != 4; ++i)
3215 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3216 SmallVector<int, 8> M;
3218 return ::isPSHUFLWMask(M, N->getValueType(0));
3221 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3222 /// is suitable for input to PALIGNR.
3223 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3224 bool hasSSSE3OrAVX) {
3225 int i, e = VT.getVectorNumElements();
3226 if (VT.getSizeInBits() != 128)
3229 // Do not handle v2i64 / v2f64 shuffles with palignr.
3230 if (e < 4 || !hasSSSE3OrAVX)
3233 for (i = 0; i != e; ++i)
3237 // All undef, not a palignr.
3241 // Make sure we're shifting in the right direction.
3245 int s = Mask[i] - i;
3247 // Check the rest of the elements to see if they are consecutive.
3248 for (++i; i != e; ++i) {
3250 if (m >= 0 && m != s+i)
3256 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3257 /// specifies a shuffle of elements that is suitable for input to 256-bit
3259 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3260 bool HasAVX, bool Commuted = false) {
3261 int NumElems = VT.getVectorNumElements();
3263 if (!HasAVX || VT.getSizeInBits() != 256)
3266 if (NumElems != 4 && NumElems != 8)
3269 // VSHUFPSY 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 => X7 X6 X5 X4 X3 X2 X1 X0
3274 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3276 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3277 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3279 // VSHUFPDY divides the resulting vector into 4 chunks.
3280 // The sources are also splitted into 4 chunks, and each destination
3281 // chunk must come from a different source chunk.
3283 // SRC1 => X3 X2 X1 X0
3284 // SRC2 => Y3 Y2 Y1 Y0
3286 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3288 unsigned QuarterSize = NumElems/4;
3289 unsigned HalfSize = QuarterSize*2;
3290 for (unsigned l = 0; l != 2; ++l) {
3291 unsigned LaneStart = l*HalfSize;
3292 for (unsigned s = 0; s != 2; ++s) {
3293 unsigned QuarterStart = s*QuarterSize;
3294 unsigned Src = (Commuted) ? (1-s) : s;
3295 unsigned SrcStart = Src*NumElems + LaneStart;
3296 for (unsigned i = 0; i != QuarterSize; ++i) {
3297 int Idx = Mask[i+QuarterStart+LaneStart];
3298 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3300 // For VSHUFPSY, the mask of the second half must be the same as the first
3301 // but with the appropriate offsets. This works in the same way as
3302 // VPERMILPS works with masks.
3303 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3305 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3314 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3315 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3316 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3318 EVT VT = SVOp->getValueType(0);
3319 int NumElems = VT.getVectorNumElements();
3321 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3322 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3324 int HalfSize = NumElems/2;
3325 unsigned Mul = (NumElems == 8) ? 2 : 1;
3327 for (int i = 0; i != NumElems; ++i) {
3328 int Elt = SVOp->getMaskElt(i);
3333 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3334 if (NumElems == 8) Shamt %= HalfSize;
3335 Mask |= Elt << (Shamt*Mul);
3341 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3342 /// the two vector operands have swapped position.
3343 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3344 unsigned NumElems) {
3345 for (unsigned i = 0; i != NumElems; ++i) {
3349 else if (idx < (int)NumElems)
3350 Mask[i] = idx + NumElems;
3352 Mask[i] = idx - NumElems;
3356 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3357 /// specifies a shuffle of elements that is suitable for input to 128-bit
3358 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3359 /// reverse of what x86 shuffles want.
3360 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3361 bool Commuted = false) {
3362 unsigned NumElems = VT.getVectorNumElements();
3364 if (VT.getSizeInBits() != 128)
3367 if (NumElems != 2 && NumElems != 4)
3370 unsigned Half = NumElems / 2;
3371 unsigned SrcStart = Commuted ? NumElems : 0;
3372 for (unsigned i = 0; i != Half; ++i)
3373 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3375 SrcStart = Commuted ? 0 : NumElems;
3376 for (unsigned i = Half; i != NumElems; ++i)
3377 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3383 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3384 SmallVector<int, 8> M;
3386 return ::isSHUFPMask(M, N->getValueType(0));
3389 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3390 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3391 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3392 EVT VT = N->getValueType(0);
3393 unsigned NumElems = VT.getVectorNumElements();
3395 if (VT.getSizeInBits() != 128)
3401 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3402 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3403 isUndefOrEqual(N->getMaskElt(1), 7) &&
3404 isUndefOrEqual(N->getMaskElt(2), 2) &&
3405 isUndefOrEqual(N->getMaskElt(3), 3);
3408 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3409 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3411 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3412 EVT VT = N->getValueType(0);
3413 unsigned NumElems = VT.getVectorNumElements();
3415 if (VT.getSizeInBits() != 128)
3421 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3422 isUndefOrEqual(N->getMaskElt(1), 3) &&
3423 isUndefOrEqual(N->getMaskElt(2), 2) &&
3424 isUndefOrEqual(N->getMaskElt(3), 3);
3427 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3428 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3429 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3430 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3432 if (NumElems != 2 && NumElems != 4)
3435 for (unsigned i = 0; i < NumElems/2; ++i)
3436 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3439 for (unsigned i = NumElems/2; i < NumElems; ++i)
3440 if (!isUndefOrEqual(N->getMaskElt(i), i))
3446 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3447 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3448 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3449 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3451 if ((NumElems != 2 && NumElems != 4)
3452 || N->getValueType(0).getSizeInBits() > 128)
3455 for (unsigned i = 0; i < NumElems/2; ++i)
3456 if (!isUndefOrEqual(N->getMaskElt(i), i))
3459 for (unsigned i = 0; i < NumElems/2; ++i)
3460 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3466 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3467 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3468 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3469 bool HasAVX2, bool V2IsSplat = false) {
3470 unsigned NumElts = VT.getVectorNumElements();
3472 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3473 "Unsupported vector type for unpckh");
3475 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3476 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3479 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3480 // independently on 128-bit lanes.
3481 unsigned NumLanes = VT.getSizeInBits()/128;
3482 unsigned NumLaneElts = NumElts/NumLanes;
3484 for (unsigned l = 0; l != NumLanes; ++l) {
3485 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3486 i != (l+1)*NumLaneElts;
3489 int BitI1 = Mask[i+1];
3490 if (!isUndefOrEqual(BitI, j))
3493 if (!isUndefOrEqual(BitI1, NumElts))
3496 if (!isUndefOrEqual(BitI1, j + NumElts))
3505 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3506 SmallVector<int, 8> M;
3508 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3511 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3513 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3514 bool HasAVX2, bool V2IsSplat = false) {
3515 unsigned NumElts = VT.getVectorNumElements();
3517 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3518 "Unsupported vector type for unpckh");
3520 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3521 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3524 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3525 // independently on 128-bit lanes.
3526 unsigned NumLanes = VT.getSizeInBits()/128;
3527 unsigned NumLaneElts = NumElts/NumLanes;
3529 for (unsigned l = 0; l != NumLanes; ++l) {
3530 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3531 i != (l+1)*NumLaneElts; i += 2, ++j) {
3533 int BitI1 = Mask[i+1];
3534 if (!isUndefOrEqual(BitI, j))
3537 if (isUndefOrEqual(BitI1, NumElts))
3540 if (!isUndefOrEqual(BitI1, j+NumElts))
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,
3559 unsigned NumElts = VT.getVectorNumElements();
3561 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3562 "Unsupported vector type for unpckh");
3564 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3565 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3568 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3569 // FIXME: Need a better way to get rid of this, there's no latency difference
3570 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3571 // the former later. We should also remove the "_undef" special mask.
3572 if (NumElts == 4 && VT.getSizeInBits() == 256)
3575 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3576 // independently on 128-bit lanes.
3577 unsigned NumLanes = VT.getSizeInBits()/128;
3578 unsigned NumLaneElts = NumElts/NumLanes;
3580 for (unsigned l = 0; l != NumLanes; ++l) {
3581 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3582 i != (l+1)*NumLaneElts;
3585 int BitI1 = Mask[i+1];
3587 if (!isUndefOrEqual(BitI, j))
3589 if (!isUndefOrEqual(BitI1, j))
3597 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3598 SmallVector<int, 8> M;
3600 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3603 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3604 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3606 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3608 unsigned NumElts = VT.getVectorNumElements();
3610 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3611 "Unsupported vector type for unpckh");
3613 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3614 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3617 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618 // independently on 128-bit lanes.
3619 unsigned NumLanes = VT.getSizeInBits()/128;
3620 unsigned NumLaneElts = NumElts/NumLanes;
3622 for (unsigned l = 0; l != NumLanes; ++l) {
3623 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3624 i != (l+1)*NumLaneElts; i += 2, ++j) {
3626 int BitI1 = Mask[i+1];
3627 if (!isUndefOrEqual(BitI, j))
3629 if (!isUndefOrEqual(BitI1, j))
3636 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3637 SmallVector<int, 8> M;
3639 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3642 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3643 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3644 /// MOVSD, and MOVD, i.e. setting the lowest element.
3645 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3646 if (VT.getVectorElementType().getSizeInBits() < 32)
3649 int NumElts = VT.getVectorNumElements();
3651 if (!isUndefOrEqual(Mask[0], NumElts))
3654 for (int i = 1; i < NumElts; ++i)
3655 if (!isUndefOrEqual(Mask[i], i))
3661 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3662 SmallVector<int, 8> M;
3664 return ::isMOVLMask(M, N->getValueType(0));
3667 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3668 /// as permutations between 128-bit chunks or halves. As an example: this
3670 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3671 /// The first half comes from the second half of V1 and the second half from the
3672 /// the second half of V2.
3673 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3675 if (!HasAVX || VT.getSizeInBits() != 256)
3678 // The shuffle result is divided into half A and half B. In total the two
3679 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3680 // B must come from C, D, E or F.
3681 int HalfSize = VT.getVectorNumElements()/2;
3682 bool MatchA = false, MatchB = false;
3684 // Check if A comes from one of C, D, E, F.
3685 for (int Half = 0; Half < 4; ++Half) {
3686 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3692 // Check if B comes from one of C, D, E, F.
3693 for (int Half = 0; Half < 4; ++Half) {
3694 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3700 return MatchA && MatchB;
3703 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3704 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3705 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3706 EVT VT = SVOp->getValueType(0);
3708 int HalfSize = VT.getVectorNumElements()/2;
3710 int FstHalf = 0, SndHalf = 0;
3711 for (int i = 0; i < HalfSize; ++i) {
3712 if (SVOp->getMaskElt(i) > 0) {
3713 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3717 for (int i = HalfSize; i < HalfSize*2; ++i) {
3718 if (SVOp->getMaskElt(i) > 0) {
3719 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3724 return (FstHalf | (SndHalf << 4));
3727 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3728 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3729 /// Note that VPERMIL mask matching is different depending whether theunderlying
3730 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3731 /// to the same elements of the low, but to the higher half of the source.
3732 /// In VPERMILPD the two lanes could be shuffled independently of each other
3733 /// with the same restriction that lanes can't be crossed.
3734 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3736 int NumElts = VT.getVectorNumElements();
3737 int NumLanes = VT.getSizeInBits()/128;
3742 // Only match 256-bit with 32/64-bit types
3743 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3746 int LaneSize = NumElts/NumLanes;
3747 for (int l = 0; l != NumLanes; ++l) {
3748 int LaneStart = l*LaneSize;
3749 for (int i = 0; i != LaneSize; ++i) {
3750 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3752 if (NumElts == 4 || l == 0)
3754 // VPERMILPS handling
3757 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3765 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3766 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3767 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3768 EVT VT = SVOp->getValueType(0);
3770 int NumElts = VT.getVectorNumElements();
3771 int NumLanes = VT.getSizeInBits()/128;
3772 int LaneSize = NumElts/NumLanes;
3774 // Although the mask is equal for both lanes do it twice to get the cases
3775 // where a mask will match because the same mask element is undef on the
3776 // first half but valid on the second. This would get pathological cases
3777 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3778 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3780 for (int i = 0; i != NumElts; ++i) {
3781 int MaskElt = SVOp->getMaskElt(i);
3784 MaskElt %= LaneSize;
3786 // VPERMILPSY, the mask of the first half must be equal to the second one
3787 if (NumElts == 8) Shamt %= LaneSize;
3788 Mask |= MaskElt << (Shamt*Shift);
3794 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3795 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3796 /// element of vector 2 and the other elements to come from vector 1 in order.
3797 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3798 bool V2IsSplat = false, bool V2IsUndef = false) {
3799 int NumOps = VT.getVectorNumElements();
3800 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3803 if (!isUndefOrEqual(Mask[0], 0))
3806 for (int i = 1; i < NumOps; ++i)
3807 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3808 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3809 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3815 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3816 bool V2IsUndef = false) {
3817 SmallVector<int, 8> M;
3819 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3822 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3824 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3825 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3826 const X86Subtarget *Subtarget) {
3827 if (!Subtarget->hasSSE3orAVX())
3830 // The second vector must be undef
3831 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3834 EVT VT = N->getValueType(0);
3835 unsigned NumElems = VT.getVectorNumElements();
3837 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3838 (VT.getSizeInBits() == 256 && NumElems != 8))
3841 // "i+1" is the value the indexed mask element must have
3842 for (unsigned i = 0; i < NumElems; i += 2)
3843 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3844 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3850 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3852 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3853 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3854 const X86Subtarget *Subtarget) {
3855 if (!Subtarget->hasSSE3orAVX())
3858 // The second vector must be undef
3859 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3862 EVT VT = N->getValueType(0);
3863 unsigned NumElems = VT.getVectorNumElements();
3865 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3866 (VT.getSizeInBits() == 256 && NumElems != 8))
3869 // "i" is the value the indexed mask element must have
3870 for (unsigned i = 0; i < NumElems; i += 2)
3871 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3872 !isUndefOrEqual(N->getMaskElt(i+1), i))
3878 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to 256-bit
3880 /// version of MOVDDUP.
3881 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3883 int NumElts = VT.getVectorNumElements();
3885 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3888 for (int i = 0; i != NumElts/2; ++i)
3889 if (!isUndefOrEqual(Mask[i], 0))
3891 for (int i = NumElts/2; i != NumElts; ++i)
3892 if (!isUndefOrEqual(Mask[i], NumElts/2))
3897 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3898 /// specifies a shuffle of elements that is suitable for input to 128-bit
3899 /// version of MOVDDUP.
3900 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3901 EVT VT = N->getValueType(0);
3903 if (VT.getSizeInBits() != 128)
3906 int e = VT.getVectorNumElements() / 2;
3907 for (int i = 0; i < e; ++i)
3908 if (!isUndefOrEqual(N->getMaskElt(i), i))
3910 for (int i = 0; i < e; ++i)
3911 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3916 /// isVEXTRACTF128Index - Return true if the specified
3917 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3918 /// suitable for input to VEXTRACTF128.
3919 bool X86::isVEXTRACTF128Index(SDNode *N) {
3920 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3923 // The index should be aligned on a 128-bit boundary.
3925 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3927 unsigned VL = N->getValueType(0).getVectorNumElements();
3928 unsigned VBits = N->getValueType(0).getSizeInBits();
3929 unsigned ElSize = VBits / VL;
3930 bool Result = (Index * ElSize) % 128 == 0;
3935 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3936 /// operand specifies a subvector insert that is suitable for input to
3938 bool X86::isVINSERTF128Index(SDNode *N) {
3939 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3942 // The index should be aligned on a 128-bit boundary.
3944 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3946 unsigned VL = N->getValueType(0).getVectorNumElements();
3947 unsigned VBits = N->getValueType(0).getSizeInBits();
3948 unsigned ElSize = VBits / VL;
3949 bool Result = (Index * ElSize) % 128 == 0;
3954 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3955 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3956 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3957 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3958 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3960 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3962 for (int i = 0; i < NumOperands; ++i) {
3963 int Val = SVOp->getMaskElt(NumOperands-i-1);
3964 if (Val < 0) Val = 0;
3965 if (Val >= NumOperands) Val -= NumOperands;
3967 if (i != NumOperands - 1)
3973 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3974 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3975 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3976 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3978 // 8 nodes, but we only care about the last 4.
3979 for (unsigned i = 7; i >= 4; --i) {
3980 int Val = SVOp->getMaskElt(i);
3989 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3990 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3991 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3992 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3994 // 8 nodes, but we only care about the first 4.
3995 for (int i = 3; i >= 0; --i) {
3996 int Val = SVOp->getMaskElt(i);
4005 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4006 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4007 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4008 EVT VT = SVOp->getValueType(0);
4009 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4013 for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4014 Val = SVOp->getMaskElt(i);
4018 assert(Val - i > 0 && "PALIGNR imm should be positive");
4019 return (Val - i) * EltSize;
4022 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4023 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4025 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4026 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4027 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4030 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4032 EVT VecVT = N->getOperand(0).getValueType();
4033 EVT ElVT = VecVT.getVectorElementType();
4035 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4036 return Index / NumElemsPerChunk;
4039 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4040 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4042 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4043 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4044 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4047 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4049 EVT VecVT = N->getValueType(0);
4050 EVT ElVT = VecVT.getVectorElementType();
4052 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4053 return Index / NumElemsPerChunk;
4056 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4058 bool X86::isZeroNode(SDValue Elt) {
4059 return ((isa<ConstantSDNode>(Elt) &&
4060 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4061 (isa<ConstantFPSDNode>(Elt) &&
4062 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4065 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4066 /// their permute mask.
4067 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4068 SelectionDAG &DAG) {
4069 EVT VT = SVOp->getValueType(0);
4070 unsigned NumElems = VT.getVectorNumElements();
4071 SmallVector<int, 8> MaskVec;
4073 for (unsigned i = 0; i != NumElems; ++i) {
4074 int idx = SVOp->getMaskElt(i);
4076 MaskVec.push_back(idx);
4077 else if (idx < (int)NumElems)
4078 MaskVec.push_back(idx + NumElems);
4080 MaskVec.push_back(idx - NumElems);
4082 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4083 SVOp->getOperand(0), &MaskVec[0]);
4086 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4087 /// match movhlps. The lower half elements should come from upper half of
4088 /// V1 (and in order), and the upper half elements should come from the upper
4089 /// half of V2 (and in order).
4090 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4091 EVT VT = Op->getValueType(0);
4092 if (VT.getSizeInBits() != 128)
4094 if (VT.getVectorNumElements() != 4)
4096 for (unsigned i = 0, e = 2; i != e; ++i)
4097 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4099 for (unsigned i = 2; i != 4; ++i)
4100 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4105 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4106 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4108 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4109 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4111 N = N->getOperand(0).getNode();
4112 if (!ISD::isNON_EXTLoad(N))
4115 *LD = cast<LoadSDNode>(N);
4119 // Test whether the given value is a vector value which will be legalized
4121 static bool WillBeConstantPoolLoad(SDNode *N) {
4122 if (N->getOpcode() != ISD::BUILD_VECTOR)
4125 // Check for any non-constant elements.
4126 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4127 switch (N->getOperand(i).getNode()->getOpcode()) {
4129 case ISD::ConstantFP:
4136 // Vectors of all-zeros and all-ones are materialized with special
4137 // instructions rather than being loaded.
4138 return !ISD::isBuildVectorAllZeros(N) &&
4139 !ISD::isBuildVectorAllOnes(N);
4142 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4143 /// match movlp{s|d}. The lower half elements should come from lower half of
4144 /// V1 (and in order), and the upper half elements should come from the upper
4145 /// half of V2 (and in order). And since V1 will become the source of the
4146 /// MOVLP, it must be either a vector load or a scalar load to vector.
4147 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4148 ShuffleVectorSDNode *Op) {
4149 EVT VT = Op->getValueType(0);
4150 if (VT.getSizeInBits() != 128)
4153 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4155 // Is V2 is a vector load, don't do this transformation. We will try to use
4156 // load folding shufps op.
4157 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4160 unsigned NumElems = VT.getVectorNumElements();
4162 if (NumElems != 2 && NumElems != 4)
4164 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4165 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4167 for (unsigned i = NumElems/2; i != NumElems; ++i)
4168 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4173 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4175 static bool isSplatVector(SDNode *N) {
4176 if (N->getOpcode() != ISD::BUILD_VECTOR)
4179 SDValue SplatValue = N->getOperand(0);
4180 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4181 if (N->getOperand(i) != SplatValue)
4186 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4187 /// to an zero vector.
4188 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4189 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4190 SDValue V1 = N->getOperand(0);
4191 SDValue V2 = N->getOperand(1);
4192 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4193 for (unsigned i = 0; i != NumElems; ++i) {
4194 int Idx = N->getMaskElt(i);
4195 if (Idx >= (int)NumElems) {
4196 unsigned Opc = V2.getOpcode();
4197 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4199 if (Opc != ISD::BUILD_VECTOR ||
4200 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4202 } else if (Idx >= 0) {
4203 unsigned Opc = V1.getOpcode();
4204 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4206 if (Opc != ISD::BUILD_VECTOR ||
4207 !X86::isZeroNode(V1.getOperand(Idx)))
4214 /// getZeroVector - Returns a vector of specified type with all zero elements.
4216 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4218 assert(VT.isVector() && "Expected a vector type");
4220 // Always build SSE zero vectors as <4 x i32> bitcasted
4221 // to their dest type. This ensures they get CSE'd.
4223 if (VT.getSizeInBits() == 128) { // SSE
4224 if (HasXMMInt) { // SSE2
4225 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4226 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4228 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4229 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4231 } else if (VT.getSizeInBits() == 256) { // AVX
4232 // 256-bit logic and arithmetic instructions in AVX are
4233 // all floating-point, no support for integer ops. Default
4234 // to emitting fp zeroed vectors then.
4235 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4236 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4237 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4239 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4242 /// getOnesVector - Returns a vector of specified type with all bits set.
4243 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4244 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4245 /// Then bitcast to their original type, ensuring they get CSE'd.
4246 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4248 assert(VT.isVector() && "Expected a vector type");
4249 assert((VT.is128BitVector() || VT.is256BitVector())
4250 && "Expected a 128-bit or 256-bit vector type");
4252 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4254 if (VT.getSizeInBits() == 256) {
4255 if (HasAVX2) { // AVX2
4256 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4257 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4259 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4260 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4261 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4262 Vec = Insert128BitVector(InsV, Vec,
4263 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4266 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4269 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4272 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4273 /// that point to V2 points to its first element.
4274 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4275 EVT VT = SVOp->getValueType(0);
4276 unsigned NumElems = VT.getVectorNumElements();
4278 bool Changed = false;
4279 SmallVector<int, 8> MaskVec;
4280 SVOp->getMask(MaskVec);
4282 for (unsigned i = 0; i != NumElems; ++i) {
4283 if (MaskVec[i] > (int)NumElems) {
4284 MaskVec[i] = NumElems;
4289 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4290 SVOp->getOperand(1), &MaskVec[0]);
4291 return SDValue(SVOp, 0);
4294 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4295 /// operation of specified width.
4296 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4298 unsigned NumElems = VT.getVectorNumElements();
4299 SmallVector<int, 8> Mask;
4300 Mask.push_back(NumElems);
4301 for (unsigned i = 1; i != NumElems; ++i)
4303 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4306 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4307 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4309 unsigned NumElems = VT.getVectorNumElements();
4310 SmallVector<int, 8> Mask;
4311 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4313 Mask.push_back(i + NumElems);
4315 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4318 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4319 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4321 unsigned NumElems = VT.getVectorNumElements();
4322 unsigned Half = NumElems/2;
4323 SmallVector<int, 8> Mask;
4324 for (unsigned i = 0; i != Half; ++i) {
4325 Mask.push_back(i + Half);
4326 Mask.push_back(i + NumElems + Half);
4328 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4331 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4332 // a generic shuffle instruction because the target has no such instructions.
4333 // Generate shuffles which repeat i16 and i8 several times until they can be
4334 // represented by v4f32 and then be manipulated by target suported shuffles.
4335 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4336 EVT VT = V.getValueType();
4337 int NumElems = VT.getVectorNumElements();
4338 DebugLoc dl = V.getDebugLoc();
4340 while (NumElems > 4) {
4341 if (EltNo < NumElems/2) {
4342 V = getUnpackl(DAG, dl, VT, V, V);
4344 V = getUnpackh(DAG, dl, VT, V, V);
4345 EltNo -= NumElems/2;
4352 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4353 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4354 EVT VT = V.getValueType();
4355 DebugLoc dl = V.getDebugLoc();
4356 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4357 && "Vector size not supported");
4359 if (VT.getSizeInBits() == 128) {
4360 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4361 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4362 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4365 // To use VPERMILPS to splat scalars, the second half of indicies must
4366 // refer to the higher part, which is a duplication of the lower one,
4367 // because VPERMILPS can only handle in-lane permutations.
4368 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4369 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4371 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4372 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4376 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4379 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4380 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4381 EVT SrcVT = SV->getValueType(0);
4382 SDValue V1 = SV->getOperand(0);
4383 DebugLoc dl = SV->getDebugLoc();
4385 int EltNo = SV->getSplatIndex();
4386 int NumElems = SrcVT.getVectorNumElements();
4387 unsigned Size = SrcVT.getSizeInBits();
4389 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4390 "Unknown how to promote splat for type");
4392 // Extract the 128-bit part containing the splat element and update
4393 // the splat element index when it refers to the higher register.
4395 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4396 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4398 EltNo -= NumElems/2;
4401 // All i16 and i8 vector types can't be used directly by a generic shuffle
4402 // instruction because the target has no such instruction. Generate shuffles
4403 // which repeat i16 and i8 several times until they fit in i32, and then can
4404 // be manipulated by target suported shuffles.
4405 EVT EltVT = SrcVT.getVectorElementType();
4406 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4407 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4409 // Recreate the 256-bit vector and place the same 128-bit vector
4410 // into the low and high part. This is necessary because we want
4411 // to use VPERM* to shuffle the vectors
4413 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4414 DAG.getConstant(0, MVT::i32), DAG, dl);
4415 V1 = Insert128BitVector(InsV, V1,
4416 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4419 return getLegalSplat(DAG, V1, EltNo);
4422 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4423 /// vector of zero or undef vector. This produces a shuffle where the low
4424 /// element of V2 is swizzled into the zero/undef vector, landing at element
4425 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4426 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4427 bool isZero, bool HasXMMInt,
4428 SelectionDAG &DAG) {
4429 EVT VT = V2.getValueType();
4431 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4432 unsigned NumElems = VT.getVectorNumElements();
4433 SmallVector<int, 16> MaskVec;
4434 for (unsigned i = 0; i != NumElems; ++i)
4435 // If this is the insertion idx, put the low elt of V2 here.
4436 MaskVec.push_back(i == Idx ? NumElems : i);
4437 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4440 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4441 /// element of the result of the vector shuffle.
4442 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4445 return SDValue(); // Limit search depth.
4447 SDValue V = SDValue(N, 0);
4448 EVT VT = V.getValueType();
4449 unsigned Opcode = V.getOpcode();
4451 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4452 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4453 Index = SV->getMaskElt(Index);
4456 return DAG.getUNDEF(VT.getVectorElementType());
4458 int NumElems = VT.getVectorNumElements();
4459 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4460 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4463 // Recurse into target specific vector shuffles to find scalars.
4464 if (isTargetShuffle(Opcode)) {
4465 int NumElems = VT.getVectorNumElements();
4466 SmallVector<unsigned, 16> ShuffleMask;
4470 case X86ISD::SHUFPS:
4471 case X86ISD::SHUFPD:
4472 ImmN = N->getOperand(N->getNumOperands()-1);
4473 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4476 case X86ISD::UNPCKH:
4477 DecodeUNPCKHMask(VT, ShuffleMask);
4479 case X86ISD::UNPCKL:
4480 DecodeUNPCKLMask(VT, ShuffleMask);
4482 case X86ISD::MOVHLPS:
4483 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4485 case X86ISD::MOVLHPS:
4486 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4488 case X86ISD::PSHUFD:
4489 ImmN = N->getOperand(N->getNumOperands()-1);
4490 DecodePSHUFMask(NumElems,
4491 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4494 case X86ISD::PSHUFHW:
4495 ImmN = N->getOperand(N->getNumOperands()-1);
4496 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4499 case X86ISD::PSHUFLW:
4500 ImmN = N->getOperand(N->getNumOperands()-1);
4501 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4505 case X86ISD::MOVSD: {
4506 // The index 0 always comes from the first element of the second source,
4507 // this is why MOVSS and MOVSD are used in the first place. The other
4508 // elements come from the other positions of the first source vector.
4509 unsigned OpNum = (Index == 0) ? 1 : 0;
4510 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4513 case X86ISD::VPERMILP:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4518 case X86ISD::VPERM2X128:
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4523 case X86ISD::MOVDDUP:
4524 case X86ISD::MOVLHPD:
4525 case X86ISD::MOVLPD:
4526 case X86ISD::MOVLPS:
4527 case X86ISD::MOVSHDUP:
4528 case X86ISD::MOVSLDUP:
4529 case X86ISD::PALIGN:
4530 return SDValue(); // Not yet implemented.
4532 assert(0 && "unknown target shuffle node");
4536 Index = ShuffleMask[Index];
4538 return DAG.getUNDEF(VT.getVectorElementType());
4540 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4541 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4545 // Actual nodes that may contain scalar elements
4546 if (Opcode == ISD::BITCAST) {
4547 V = V.getOperand(0);
4548 EVT SrcVT = V.getValueType();
4549 unsigned NumElems = VT.getVectorNumElements();
4551 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4555 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4556 return (Index == 0) ? V.getOperand(0)
4557 : DAG.getUNDEF(VT.getVectorElementType());
4559 if (V.getOpcode() == ISD::BUILD_VECTOR)
4560 return V.getOperand(Index);
4565 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4566 /// shuffle operation which come from a consecutively from a zero. The
4567 /// search can start in two different directions, from left or right.
4569 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4570 bool ZerosFromLeft, SelectionDAG &DAG) {
4573 while (i < NumElems) {
4574 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4575 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4576 if (!(Elt.getNode() &&
4577 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4585 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4586 /// MaskE correspond consecutively to elements from one of the vector operands,
4587 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4589 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4590 int OpIdx, int NumElems, unsigned &OpNum) {
4591 bool SeenV1 = false;
4592 bool SeenV2 = false;
4594 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4595 int Idx = SVOp->getMaskElt(i);
4596 // Ignore undef indicies
4605 // Only accept consecutive elements from the same vector
4606 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4610 OpNum = SeenV1 ? 0 : 1;
4614 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4615 /// logical left shift of a vector.
4616 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4617 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4618 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4619 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4620 false /* check zeros from right */, DAG);
4626 // Considering the elements in the mask that are not consecutive zeros,
4627 // check if they consecutively come from only one of the source vectors.
4629 // V1 = {X, A, B, C} 0
4631 // vector_shuffle V1, V2 <1, 2, 3, X>
4633 if (!isShuffleMaskConsecutive(SVOp,
4634 0, // Mask Start Index
4635 NumElems-NumZeros-1, // Mask End Index
4636 NumZeros, // Where to start looking in the src vector
4637 NumElems, // Number of elements in vector
4638 OpSrc)) // Which source operand ?
4643 ShVal = SVOp->getOperand(OpSrc);
4647 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4648 /// logical left shift of a vector.
4649 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4650 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4651 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4652 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4653 true /* check zeros from left */, DAG);
4659 // Considering the elements in the mask that are not consecutive zeros,
4660 // check if they consecutively come from only one of the source vectors.
4662 // 0 { A, B, X, X } = V2
4664 // vector_shuffle V1, V2 <X, X, 4, 5>
4666 if (!isShuffleMaskConsecutive(SVOp,
4667 NumZeros, // Mask Start Index
4668 NumElems-1, // Mask End Index
4669 0, // Where to start looking in the src vector
4670 NumElems, // Number of elements in vector
4671 OpSrc)) // Which source operand ?
4676 ShVal = SVOp->getOperand(OpSrc);
4680 /// isVectorShift - Returns true if the shuffle can be implemented as a
4681 /// logical left or right shift of a vector.
4682 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4683 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4684 // Although the logic below support any bitwidth size, there are no
4685 // shift instructions which handle more than 128-bit vectors.
4686 if (SVOp->getValueType(0).getSizeInBits() > 128)
4689 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4690 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4696 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4698 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4699 unsigned NumNonZero, unsigned NumZero,
4701 const TargetLowering &TLI) {
4705 DebugLoc dl = Op.getDebugLoc();
4708 for (unsigned i = 0; i < 16; ++i) {
4709 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4710 if (ThisIsNonZero && First) {
4712 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4714 V = DAG.getUNDEF(MVT::v8i16);
4719 SDValue ThisElt(0, 0), LastElt(0, 0);
4720 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4721 if (LastIsNonZero) {
4722 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4723 MVT::i16, Op.getOperand(i-1));
4725 if (ThisIsNonZero) {
4726 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4727 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4728 ThisElt, DAG.getConstant(8, MVT::i8));
4730 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4734 if (ThisElt.getNode())
4735 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4736 DAG.getIntPtrConstant(i/2));
4740 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4743 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4745 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4746 unsigned NumNonZero, unsigned NumZero,
4748 const TargetLowering &TLI) {
4752 DebugLoc dl = Op.getDebugLoc();
4755 for (unsigned i = 0; i < 8; ++i) {
4756 bool isNonZero = (NonZeros & (1 << i)) != 0;
4760 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4762 V = DAG.getUNDEF(MVT::v8i16);
4765 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4766 MVT::v8i16, V, Op.getOperand(i),
4767 DAG.getIntPtrConstant(i));
4774 /// getVShift - Return a vector logical shift node.
4776 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4777 unsigned NumBits, SelectionDAG &DAG,
4778 const TargetLowering &TLI, DebugLoc dl) {
4779 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4780 EVT ShVT = MVT::v2i64;
4781 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4782 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4783 return DAG.getNode(ISD::BITCAST, dl, VT,
4784 DAG.getNode(Opc, dl, ShVT, SrcOp,
4785 DAG.getConstant(NumBits,
4786 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4790 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4791 SelectionDAG &DAG) const {
4793 // Check if the scalar load can be widened into a vector load. And if
4794 // the address is "base + cst" see if the cst can be "absorbed" into
4795 // the shuffle mask.
4796 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4797 SDValue Ptr = LD->getBasePtr();
4798 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4800 EVT PVT = LD->getValueType(0);
4801 if (PVT != MVT::i32 && PVT != MVT::f32)
4806 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4807 FI = FINode->getIndex();
4809 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4810 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4811 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4812 Offset = Ptr.getConstantOperandVal(1);
4813 Ptr = Ptr.getOperand(0);
4818 // FIXME: 256-bit vector instructions don't require a strict alignment,
4819 // improve this code to support it better.
4820 unsigned RequiredAlign = VT.getSizeInBits()/8;
4821 SDValue Chain = LD->getChain();
4822 // Make sure the stack object alignment is at least 16 or 32.
4823 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4824 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4825 if (MFI->isFixedObjectIndex(FI)) {
4826 // Can't change the alignment. FIXME: It's possible to compute
4827 // the exact stack offset and reference FI + adjust offset instead.
4828 // If someone *really* cares about this. That's the way to implement it.
4831 MFI->setObjectAlignment(FI, RequiredAlign);
4835 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4836 // Ptr + (Offset & ~15).
4839 if ((Offset % RequiredAlign) & 3)
4841 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4843 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4844 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4846 int EltNo = (Offset - StartOffset) >> 2;
4847 int NumElems = VT.getVectorNumElements();
4849 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4850 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4851 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4852 LD->getPointerInfo().getWithOffset(StartOffset),
4853 false, false, false, 0);
4855 // Canonicalize it to a v4i32 or v8i32 shuffle.
4856 SmallVector<int, 8> Mask;
4857 for (int i = 0; i < NumElems; ++i)
4858 Mask.push_back(EltNo);
4860 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4861 return DAG.getNode(ISD::BITCAST, dl, NVT,
4862 DAG.getVectorShuffle(CanonVT, dl, V1,
4863 DAG.getUNDEF(CanonVT),&Mask[0]));
4869 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4870 /// vector of type 'VT', see if the elements can be replaced by a single large
4871 /// load which has the same value as a build_vector whose operands are 'elts'.
4873 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4875 /// FIXME: we'd also like to handle the case where the last elements are zero
4876 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4877 /// There's even a handy isZeroNode for that purpose.
4878 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4879 DebugLoc &DL, SelectionDAG &DAG) {
4880 EVT EltVT = VT.getVectorElementType();
4881 unsigned NumElems = Elts.size();
4883 LoadSDNode *LDBase = NULL;
4884 unsigned LastLoadedElt = -1U;
4886 // For each element in the initializer, see if we've found a load or an undef.
4887 // If we don't find an initial load element, or later load elements are
4888 // non-consecutive, bail out.
4889 for (unsigned i = 0; i < NumElems; ++i) {
4890 SDValue Elt = Elts[i];
4892 if (!Elt.getNode() ||
4893 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4896 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4898 LDBase = cast<LoadSDNode>(Elt.getNode());
4902 if (Elt.getOpcode() == ISD::UNDEF)
4905 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4906 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4911 // If we have found an entire vector of loads and undefs, then return a large
4912 // load of the entire vector width starting at the base pointer. If we found
4913 // consecutive loads for the low half, generate a vzext_load node.
4914 if (LastLoadedElt == NumElems - 1) {
4915 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4916 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4917 LDBase->getPointerInfo(),
4918 LDBase->isVolatile(), LDBase->isNonTemporal(),
4919 LDBase->isInvariant(), 0);
4920 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4921 LDBase->getPointerInfo(),
4922 LDBase->isVolatile(), LDBase->isNonTemporal(),
4923 LDBase->isInvariant(), LDBase->getAlignment());
4924 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4925 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4926 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4927 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4929 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4930 LDBase->getPointerInfo(),
4931 LDBase->getAlignment(),
4932 false/*isVolatile*/, true/*ReadMem*/,
4934 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4939 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4940 /// a vbroadcast node. We support two patterns:
4941 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4942 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4944 /// The scalar load node is returned when a pattern is found,
4945 /// or SDValue() otherwise.
4946 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4947 EVT VT = Op.getValueType();
4950 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4951 V = V.getOperand(0);
4953 //A suspected load to be broadcasted.
4956 switch (V.getOpcode()) {
4958 // Unknown pattern found.
4961 case ISD::BUILD_VECTOR: {
4962 // The BUILD_VECTOR node must be a splat.
4963 if (!isSplatVector(V.getNode()))
4966 Ld = V.getOperand(0);
4968 // The suspected load node has several users. Make sure that all
4969 // of its users are from the BUILD_VECTOR node.
4970 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4975 case ISD::VECTOR_SHUFFLE: {
4976 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4978 // Shuffles must have a splat mask where the first element is
4980 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4983 SDValue Sc = Op.getOperand(0);
4984 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4987 Ld = Sc.getOperand(0);
4989 // The scalar_to_vector node and the suspected
4990 // load node must have exactly one user.
4991 if (!Sc.hasOneUse() || !Ld.hasOneUse())
4997 // The scalar source must be a normal load.
4998 if (!ISD::isNormalLoad(Ld.getNode()))
5001 bool Is256 = VT.getSizeInBits() == 256;
5002 bool Is128 = VT.getSizeInBits() == 128;
5003 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5006 // VBroadcast to YMM
5007 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5008 ScalarSize == 32 || ScalarSize == 64 ))
5011 // VBroadcast to XMM
5012 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5013 ScalarSize == 16 || ScalarSize == 64 ))
5017 // VBroadcast to YMM
5018 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5021 // VBroadcast to XMM
5022 if (Is128 && (ScalarSize == 32))
5026 // Unsupported broadcast.
5031 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5032 DebugLoc dl = Op.getDebugLoc();
5034 EVT VT = Op.getValueType();
5035 EVT ExtVT = VT.getVectorElementType();
5036 unsigned NumElems = Op.getNumOperands();
5038 // Vectors containing all zeros can be matched by pxor and xorps later
5039 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5040 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5041 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5042 if (Op.getValueType() == MVT::v4i32 ||
5043 Op.getValueType() == MVT::v8i32)
5046 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5049 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5050 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5051 // vpcmpeqd on 256-bit vectors.
5052 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5053 if (Op.getValueType() == MVT::v4i32 ||
5054 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5057 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5060 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5061 if (Subtarget->hasAVX() && LD.getNode())
5062 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5064 unsigned EVTBits = ExtVT.getSizeInBits();
5066 unsigned NumZero = 0;
5067 unsigned NumNonZero = 0;
5068 unsigned NonZeros = 0;
5069 bool IsAllConstants = true;
5070 SmallSet<SDValue, 8> Values;
5071 for (unsigned i = 0; i < NumElems; ++i) {
5072 SDValue Elt = Op.getOperand(i);
5073 if (Elt.getOpcode() == ISD::UNDEF)
5076 if (Elt.getOpcode() != ISD::Constant &&
5077 Elt.getOpcode() != ISD::ConstantFP)
5078 IsAllConstants = false;
5079 if (X86::isZeroNode(Elt))
5082 NonZeros |= (1 << i);
5087 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5088 if (NumNonZero == 0)
5089 return DAG.getUNDEF(VT);
5091 // Special case for single non-zero, non-undef, element.
5092 if (NumNonZero == 1) {
5093 unsigned Idx = CountTrailingZeros_32(NonZeros);
5094 SDValue Item = Op.getOperand(Idx);
5096 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5097 // the value are obviously zero, truncate the value to i32 and do the
5098 // insertion that way. Only do this if the value is non-constant or if the
5099 // value is a constant being inserted into element 0. It is cheaper to do
5100 // a constant pool load than it is to do a movd + shuffle.
5101 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5102 (!IsAllConstants || Idx == 0)) {
5103 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5105 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5106 EVT VecVT = MVT::v4i32;
5107 unsigned VecElts = 4;
5109 // Truncate the value (which may itself be a constant) to i32, and
5110 // convert it to a vector with movd (S2V+shuffle to zero extend).
5111 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5112 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5113 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5114 Subtarget->hasXMMInt(), DAG);
5116 // Now we have our 32-bit value zero extended in the low element of
5117 // a vector. If Idx != 0, swizzle it into place.
5119 SmallVector<int, 4> Mask;
5120 Mask.push_back(Idx);
5121 for (unsigned i = 1; i != VecElts; ++i)
5123 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5124 DAG.getUNDEF(Item.getValueType()),
5127 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5131 // If we have a constant or non-constant insertion into the low element of
5132 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5133 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5134 // depending on what the source datatype is.
5137 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5138 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5139 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5140 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5141 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5142 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5144 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5145 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5146 unsigned NumBits = VT.getSizeInBits();
5147 assert((NumBits == 128 || NumBits == 256) &&
5148 "Expected an SSE or AVX value type!");
5149 EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5150 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5151 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5152 Subtarget->hasXMMInt(), DAG);
5153 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5157 // Is it a vector logical left shift?
5158 if (NumElems == 2 && Idx == 1 &&
5159 X86::isZeroNode(Op.getOperand(0)) &&
5160 !X86::isZeroNode(Op.getOperand(1))) {
5161 unsigned NumBits = VT.getSizeInBits();
5162 return getVShift(true, VT,
5163 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5164 VT, Op.getOperand(1)),
5165 NumBits/2, DAG, *this, dl);
5168 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5171 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5172 // is a non-constant being inserted into an element other than the low one,
5173 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5174 // movd/movss) to move this into the low element, then shuffle it into
5176 if (EVTBits == 32) {
5177 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5179 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5180 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5181 Subtarget->hasXMMInt(), DAG);
5182 SmallVector<int, 8> MaskVec;
5183 for (unsigned i = 0; i < NumElems; i++)
5184 MaskVec.push_back(i == Idx ? 0 : 1);
5185 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5189 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5190 if (Values.size() == 1) {
5191 if (EVTBits == 32) {
5192 // Instead of a shuffle like this:
5193 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5194 // Check if it's possible to issue this instead.
5195 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5196 unsigned Idx = CountTrailingZeros_32(NonZeros);
5197 SDValue Item = Op.getOperand(Idx);
5198 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5199 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5204 // A vector full of immediates; various special cases are already
5205 // handled, so this is best done with a single constant-pool load.
5209 // For AVX-length vectors, build the individual 128-bit pieces and use
5210 // shuffles to put them in place.
5211 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5212 SmallVector<SDValue, 32> V;
5213 for (unsigned i = 0; i < NumElems; ++i)
5214 V.push_back(Op.getOperand(i));
5216 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5218 // Build both the lower and upper subvector.
5219 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5220 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5223 // Recreate the wider vector with the lower and upper part.
5224 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5225 DAG.getConstant(0, MVT::i32), DAG, dl);
5226 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5230 // Let legalizer expand 2-wide build_vectors.
5231 if (EVTBits == 64) {
5232 if (NumNonZero == 1) {
5233 // One half is zero or undef.
5234 unsigned Idx = CountTrailingZeros_32(NonZeros);
5235 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5236 Op.getOperand(Idx));
5237 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5238 Subtarget->hasXMMInt(), DAG);
5243 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5244 if (EVTBits == 8 && NumElems == 16) {
5245 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5247 if (V.getNode()) return V;
5250 if (EVTBits == 16 && NumElems == 8) {
5251 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5253 if (V.getNode()) return V;
5256 // If element VT is == 32 bits, turn it into a number of shuffles.
5257 SmallVector<SDValue, 8> V;
5259 if (NumElems == 4 && NumZero > 0) {
5260 for (unsigned i = 0; i < 4; ++i) {
5261 bool isZero = !(NonZeros & (1 << i));
5263 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5265 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5268 for (unsigned i = 0; i < 2; ++i) {
5269 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5272 V[i] = V[i*2]; // Must be a zero vector.
5275 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5278 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5281 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5286 SmallVector<int, 8> MaskVec;
5287 bool Reverse = (NonZeros & 0x3) == 2;
5288 for (unsigned i = 0; i < 2; ++i)
5289 MaskVec.push_back(Reverse ? 1-i : i);
5290 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5291 for (unsigned i = 0; i < 2; ++i)
5292 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5293 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5296 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5297 // Check for a build vector of consecutive loads.
5298 for (unsigned i = 0; i < NumElems; ++i)
5299 V[i] = Op.getOperand(i);
5301 // Check for elements which are consecutive loads.
5302 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5306 // For SSE 4.1, use insertps to put the high elements into the low element.
5307 if (getSubtarget()->hasSSE41orAVX()) {
5309 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5310 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5312 Result = DAG.getUNDEF(VT);
5314 for (unsigned i = 1; i < NumElems; ++i) {
5315 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5316 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5317 Op.getOperand(i), DAG.getIntPtrConstant(i));
5322 // Otherwise, expand into a number of unpckl*, start by extending each of
5323 // our (non-undef) elements to the full vector width with the element in the
5324 // bottom slot of the vector (which generates no code for SSE).
5325 for (unsigned i = 0; i < NumElems; ++i) {
5326 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5327 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5329 V[i] = DAG.getUNDEF(VT);
5332 // Next, we iteratively mix elements, e.g. for v4f32:
5333 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5334 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5335 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5336 unsigned EltStride = NumElems >> 1;
5337 while (EltStride != 0) {
5338 for (unsigned i = 0; i < EltStride; ++i) {
5339 // If V[i+EltStride] is undef and this is the first round of mixing,
5340 // then it is safe to just drop this shuffle: V[i] is already in the
5341 // right place, the one element (since it's the first round) being
5342 // inserted as undef can be dropped. This isn't safe for successive
5343 // rounds because they will permute elements within both vectors.
5344 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5345 EltStride == NumElems/2)
5348 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5357 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5358 // them in a MMX register. This is better than doing a stack convert.
5359 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5360 DebugLoc dl = Op.getDebugLoc();
5361 EVT ResVT = Op.getValueType();
5363 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5364 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5366 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5367 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5368 InVec = Op.getOperand(1);
5369 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5370 unsigned NumElts = ResVT.getVectorNumElements();
5371 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5372 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5373 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5375 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5376 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5377 Mask[0] = 0; Mask[1] = 2;
5378 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5380 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5383 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5384 // to create 256-bit vectors from two other 128-bit ones.
5385 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5386 DebugLoc dl = Op.getDebugLoc();
5387 EVT ResVT = Op.getValueType();
5389 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5391 SDValue V1 = Op.getOperand(0);
5392 SDValue V2 = Op.getOperand(1);
5393 unsigned NumElems = ResVT.getVectorNumElements();
5395 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5396 DAG.getConstant(0, MVT::i32), DAG, dl);
5397 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5402 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5403 EVT ResVT = Op.getValueType();
5405 assert(Op.getNumOperands() == 2);
5406 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5407 "Unsupported CONCAT_VECTORS for value type");
5409 // We support concatenate two MMX registers and place them in a MMX register.
5410 // This is better than doing a stack convert.
5411 if (ResVT.is128BitVector())
5412 return LowerMMXCONCAT_VECTORS(Op, DAG);
5414 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5415 // from two other 128-bit ones.
5416 return LowerAVXCONCAT_VECTORS(Op, DAG);
5419 // v8i16 shuffles - Prefer shuffles in the following order:
5420 // 1. [all] pshuflw, pshufhw, optional move
5421 // 2. [ssse3] 1 x pshufb
5422 // 3. [ssse3] 2 x pshufb + 1 x por
5423 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5425 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5426 SelectionDAG &DAG) const {
5427 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5428 SDValue V1 = SVOp->getOperand(0);
5429 SDValue V2 = SVOp->getOperand(1);
5430 DebugLoc dl = SVOp->getDebugLoc();
5431 SmallVector<int, 8> MaskVals;
5433 // Determine if more than 1 of the words in each of the low and high quadwords
5434 // of the result come from the same quadword of one of the two inputs. Undef
5435 // mask values count as coming from any quadword, for better codegen.
5436 unsigned LoQuad[] = { 0, 0, 0, 0 };
5437 unsigned HiQuad[] = { 0, 0, 0, 0 };
5438 BitVector InputQuads(4);
5439 for (unsigned i = 0; i < 8; ++i) {
5440 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5441 int EltIdx = SVOp->getMaskElt(i);
5442 MaskVals.push_back(EltIdx);
5451 InputQuads.set(EltIdx / 4);
5454 int BestLoQuad = -1;
5455 unsigned MaxQuad = 1;
5456 for (unsigned i = 0; i < 4; ++i) {
5457 if (LoQuad[i] > MaxQuad) {
5459 MaxQuad = LoQuad[i];
5463 int BestHiQuad = -1;
5465 for (unsigned i = 0; i < 4; ++i) {
5466 if (HiQuad[i] > MaxQuad) {
5468 MaxQuad = HiQuad[i];
5472 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5473 // of the two input vectors, shuffle them into one input vector so only a
5474 // single pshufb instruction is necessary. If There are more than 2 input
5475 // quads, disable the next transformation since it does not help SSSE3.
5476 bool V1Used = InputQuads[0] || InputQuads[1];
5477 bool V2Used = InputQuads[2] || InputQuads[3];
5478 if (Subtarget->hasSSSE3orAVX()) {
5479 if (InputQuads.count() == 2 && V1Used && V2Used) {
5480 BestLoQuad = InputQuads.find_first();
5481 BestHiQuad = InputQuads.find_next(BestLoQuad);
5483 if (InputQuads.count() > 2) {
5489 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5490 // the shuffle mask. If a quad is scored as -1, that means that it contains
5491 // words from all 4 input quadwords.
5493 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5494 SmallVector<int, 8> MaskV;
5495 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5496 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5497 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5498 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5499 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5500 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5502 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5503 // source words for the shuffle, to aid later transformations.
5504 bool AllWordsInNewV = true;
5505 bool InOrder[2] = { true, true };
5506 for (unsigned i = 0; i != 8; ++i) {
5507 int idx = MaskVals[i];
5509 InOrder[i/4] = false;
5510 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5512 AllWordsInNewV = false;
5516 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5517 if (AllWordsInNewV) {
5518 for (int i = 0; i != 8; ++i) {
5519 int idx = MaskVals[i];
5522 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5523 if ((idx != i) && idx < 4)
5525 if ((idx != i) && idx > 3)
5534 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5535 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5536 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5537 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5538 unsigned TargetMask = 0;
5539 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5540 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5541 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5542 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5543 V1 = NewV.getOperand(0);
5544 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5548 // If we have SSSE3, and all words of the result are from 1 input vector,
5549 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5550 // is present, fall back to case 4.
5551 if (Subtarget->hasSSSE3orAVX()) {
5552 SmallVector<SDValue,16> pshufbMask;
5554 // If we have elements from both input vectors, set the high bit of the
5555 // shuffle mask element to zero out elements that come from V2 in the V1
5556 // mask, and elements that come from V1 in the V2 mask, so that the two
5557 // results can be OR'd together.
5558 bool TwoInputs = V1Used && V2Used;
5559 for (unsigned i = 0; i != 8; ++i) {
5560 int EltIdx = MaskVals[i] * 2;
5561 if (TwoInputs && (EltIdx >= 16)) {
5562 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5563 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5566 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5567 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5569 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5570 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5571 DAG.getNode(ISD::BUILD_VECTOR, dl,
5572 MVT::v16i8, &pshufbMask[0], 16));
5574 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5576 // Calculate the shuffle mask for the second input, shuffle it, and
5577 // OR it with the first shuffled input.
5579 for (unsigned i = 0; i != 8; ++i) {
5580 int EltIdx = MaskVals[i] * 2;
5582 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5583 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5586 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5587 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5589 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5590 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5591 DAG.getNode(ISD::BUILD_VECTOR, dl,
5592 MVT::v16i8, &pshufbMask[0], 16));
5593 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5594 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5597 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5598 // and update MaskVals with new element order.
5599 BitVector InOrder(8);
5600 if (BestLoQuad >= 0) {
5601 SmallVector<int, 8> MaskV;
5602 for (int i = 0; i != 4; ++i) {
5603 int idx = MaskVals[i];
5605 MaskV.push_back(-1);
5607 } else if ((idx / 4) == BestLoQuad) {
5608 MaskV.push_back(idx & 3);
5611 MaskV.push_back(-1);
5614 for (unsigned i = 4; i != 8; ++i)
5616 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5619 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5620 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5622 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5626 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5627 // and update MaskVals with the new element order.
5628 if (BestHiQuad >= 0) {
5629 SmallVector<int, 8> MaskV;
5630 for (unsigned i = 0; i != 4; ++i)
5632 for (unsigned i = 4; i != 8; ++i) {
5633 int idx = MaskVals[i];
5635 MaskV.push_back(-1);
5637 } else if ((idx / 4) == BestHiQuad) {
5638 MaskV.push_back((idx & 3) + 4);
5641 MaskV.push_back(-1);
5644 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5647 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5648 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5650 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5654 // In case BestHi & BestLo were both -1, which means each quadword has a word
5655 // from each of the four input quadwords, calculate the InOrder bitvector now
5656 // before falling through to the insert/extract cleanup.
5657 if (BestLoQuad == -1 && BestHiQuad == -1) {
5659 for (int i = 0; i != 8; ++i)
5660 if (MaskVals[i] < 0 || MaskVals[i] == i)
5664 // The other elements are put in the right place using pextrw and pinsrw.
5665 for (unsigned i = 0; i != 8; ++i) {
5668 int EltIdx = MaskVals[i];
5671 SDValue ExtOp = (EltIdx < 8)
5672 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5673 DAG.getIntPtrConstant(EltIdx))
5674 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5675 DAG.getIntPtrConstant(EltIdx - 8));
5676 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5677 DAG.getIntPtrConstant(i));
5682 // v16i8 shuffles - Prefer shuffles in the following order:
5683 // 1. [ssse3] 1 x pshufb
5684 // 2. [ssse3] 2 x pshufb + 1 x por
5685 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5687 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5689 const X86TargetLowering &TLI) {
5690 SDValue V1 = SVOp->getOperand(0);
5691 SDValue V2 = SVOp->getOperand(1);
5692 DebugLoc dl = SVOp->getDebugLoc();
5693 SmallVector<int, 16> MaskVals;
5694 SVOp->getMask(MaskVals);
5696 // If we have SSSE3, case 1 is generated when all result bytes come from
5697 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5698 // present, fall back to case 3.
5699 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5702 for (unsigned i = 0; i < 16; ++i) {
5703 int EltIdx = MaskVals[i];
5712 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5713 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5714 SmallVector<SDValue,16> pshufbMask;
5716 // If all result elements are from one input vector, then only translate
5717 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5719 // Otherwise, we have elements from both input vectors, and must zero out
5720 // elements that come from V2 in the first mask, and V1 in the second mask
5721 // so that we can OR them together.
5722 bool TwoInputs = !(V1Only || V2Only);
5723 for (unsigned i = 0; i != 16; ++i) {
5724 int EltIdx = MaskVals[i];
5725 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5726 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5729 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5731 // If all the elements are from V2, assign it to V1 and return after
5732 // building the first pshufb.
5735 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5736 DAG.getNode(ISD::BUILD_VECTOR, dl,
5737 MVT::v16i8, &pshufbMask[0], 16));
5741 // Calculate the shuffle mask for the second input, shuffle it, and
5742 // OR it with the first shuffled input.
5744 for (unsigned i = 0; i != 16; ++i) {
5745 int EltIdx = MaskVals[i];
5747 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5750 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5752 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5753 DAG.getNode(ISD::BUILD_VECTOR, dl,
5754 MVT::v16i8, &pshufbMask[0], 16));
5755 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5758 // No SSSE3 - Calculate in place words and then fix all out of place words
5759 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5760 // the 16 different words that comprise the two doublequadword input vectors.
5761 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5762 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5763 SDValue NewV = V2Only ? V2 : V1;
5764 for (int i = 0; i != 8; ++i) {
5765 int Elt0 = MaskVals[i*2];
5766 int Elt1 = MaskVals[i*2+1];
5768 // This word of the result is all undef, skip it.
5769 if (Elt0 < 0 && Elt1 < 0)
5772 // This word of the result is already in the correct place, skip it.
5773 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5775 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5778 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5779 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5782 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5783 // using a single extract together, load it and store it.
5784 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5785 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5786 DAG.getIntPtrConstant(Elt1 / 2));
5787 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5788 DAG.getIntPtrConstant(i));
5792 // If Elt1 is defined, extract it from the appropriate source. If the
5793 // source byte is not also odd, shift the extracted word left 8 bits
5794 // otherwise clear the bottom 8 bits if we need to do an or.
5796 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5797 DAG.getIntPtrConstant(Elt1 / 2));
5798 if ((Elt1 & 1) == 0)
5799 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5801 TLI.getShiftAmountTy(InsElt.getValueType())));
5803 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5804 DAG.getConstant(0xFF00, MVT::i16));
5806 // If Elt0 is defined, extract it from the appropriate source. If the
5807 // source byte is not also even, shift the extracted word right 8 bits. If
5808 // Elt1 was also defined, OR the extracted values together before
5809 // inserting them in the result.
5811 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5812 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5813 if ((Elt0 & 1) != 0)
5814 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5816 TLI.getShiftAmountTy(InsElt0.getValueType())));
5818 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5819 DAG.getConstant(0x00FF, MVT::i16));
5820 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5823 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5824 DAG.getIntPtrConstant(i));
5826 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5829 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5830 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5831 /// done when every pair / quad of shuffle mask elements point to elements in
5832 /// the right sequence. e.g.
5833 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5835 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5836 SelectionDAG &DAG, DebugLoc dl) {
5837 EVT VT = SVOp->getValueType(0);
5838 SDValue V1 = SVOp->getOperand(0);
5839 SDValue V2 = SVOp->getOperand(1);
5840 unsigned NumElems = VT.getVectorNumElements();
5841 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5843 switch (VT.getSimpleVT().SimpleTy) {
5844 default: assert(false && "Unexpected!");
5845 case MVT::v4f32: NewVT = MVT::v2f64; break;
5846 case MVT::v4i32: NewVT = MVT::v2i64; break;
5847 case MVT::v8i16: NewVT = MVT::v4i32; break;
5848 case MVT::v16i8: NewVT = MVT::v4i32; break;
5851 int Scale = NumElems / NewWidth;
5852 SmallVector<int, 8> MaskVec;
5853 for (unsigned i = 0; i < NumElems; i += Scale) {
5855 for (int j = 0; j < Scale; ++j) {
5856 int EltIdx = SVOp->getMaskElt(i+j);
5860 StartIdx = EltIdx - (EltIdx % Scale);
5861 if (EltIdx != StartIdx + j)
5865 MaskVec.push_back(-1);
5867 MaskVec.push_back(StartIdx / Scale);
5870 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5871 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5872 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5875 /// getVZextMovL - Return a zero-extending vector move low node.
5877 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5878 SDValue SrcOp, SelectionDAG &DAG,
5879 const X86Subtarget *Subtarget, DebugLoc dl) {
5880 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5881 LoadSDNode *LD = NULL;
5882 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5883 LD = dyn_cast<LoadSDNode>(SrcOp);
5885 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5887 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5888 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5889 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5890 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5891 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5893 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5894 return DAG.getNode(ISD::BITCAST, dl, VT,
5895 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5896 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5904 return DAG.getNode(ISD::BITCAST, dl, VT,
5905 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5906 DAG.getNode(ISD::BITCAST, dl,
5910 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5911 /// shuffle node referes to only one lane in the sources.
5912 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5913 EVT VT = SVOp->getValueType(0);
5914 int NumElems = VT.getVectorNumElements();
5915 int HalfSize = NumElems/2;
5916 SmallVector<int, 16> M;
5918 bool MatchA = false, MatchB = false;
5920 for (int l = 0; l < NumElems*2; l += HalfSize) {
5921 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5927 for (int l = 0; l < NumElems*2; l += HalfSize) {
5928 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5934 return MatchA && MatchB;
5937 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5938 /// which could not be matched by any known target speficic shuffle
5940 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5941 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5942 // If each half of a vector shuffle node referes to only one lane in the
5943 // source vectors, extract each used 128-bit lane and shuffle them using
5944 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5945 // the work to the legalizer.
5946 DebugLoc dl = SVOp->getDebugLoc();
5947 EVT VT = SVOp->getValueType(0);
5948 int NumElems = VT.getVectorNumElements();
5949 int HalfSize = NumElems/2;
5951 // Extract the reference for each half
5952 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5953 int FstVecOpNum = 0, SndVecOpNum = 0;
5954 for (int i = 0; i < HalfSize; ++i) {
5955 int Elt = SVOp->getMaskElt(i);
5956 if (SVOp->getMaskElt(i) < 0)
5958 FstVecOpNum = Elt/NumElems;
5959 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5962 for (int i = HalfSize; i < NumElems; ++i) {
5963 int Elt = SVOp->getMaskElt(i);
5964 if (SVOp->getMaskElt(i) < 0)
5966 SndVecOpNum = Elt/NumElems;
5967 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5971 // Extract the subvectors
5972 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5973 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5974 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5975 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5977 // Generate 128-bit shuffles
5978 SmallVector<int, 16> MaskV1, MaskV2;
5979 for (int i = 0; i < HalfSize; ++i) {
5980 int Elt = SVOp->getMaskElt(i);
5981 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5983 for (int i = HalfSize; i < NumElems; ++i) {
5984 int Elt = SVOp->getMaskElt(i);
5985 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5988 EVT NVT = V1.getValueType();
5989 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5990 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5992 // Concatenate the result back
5993 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5994 DAG.getConstant(0, MVT::i32), DAG, dl);
5995 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6002 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6003 /// 4 elements, and match them with several different shuffle types.
6005 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6006 SDValue V1 = SVOp->getOperand(0);
6007 SDValue V2 = SVOp->getOperand(1);
6008 DebugLoc dl = SVOp->getDebugLoc();
6009 EVT VT = SVOp->getValueType(0);
6011 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6013 SmallVector<std::pair<int, int>, 8> Locs;
6015 SmallVector<int, 8> Mask1(4U, -1);
6016 SmallVector<int, 8> PermMask;
6017 SVOp->getMask(PermMask);
6021 for (unsigned i = 0; i != 4; ++i) {
6022 int Idx = PermMask[i];
6024 Locs[i] = std::make_pair(-1, -1);
6026 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6028 Locs[i] = std::make_pair(0, NumLo);
6032 Locs[i] = std::make_pair(1, NumHi);
6034 Mask1[2+NumHi] = Idx;
6040 if (NumLo <= 2 && NumHi <= 2) {
6041 // If no more than two elements come from either vector. This can be
6042 // implemented with two shuffles. First shuffle gather the elements.
6043 // The second shuffle, which takes the first shuffle as both of its
6044 // vector operands, put the elements into the right order.
6045 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6047 SmallVector<int, 8> Mask2(4U, -1);
6049 for (unsigned i = 0; i != 4; ++i) {
6050 if (Locs[i].first == -1)
6053 unsigned Idx = (i < 2) ? 0 : 4;
6054 Idx += Locs[i].first * 2 + Locs[i].second;
6059 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6060 } else if (NumLo == 3 || NumHi == 3) {
6061 // Otherwise, we must have three elements from one vector, call it X, and
6062 // one element from the other, call it Y. First, use a shufps to build an
6063 // intermediate vector with the one element from Y and the element from X
6064 // that will be in the same half in the final destination (the indexes don't
6065 // matter). Then, use a shufps to build the final vector, taking the half
6066 // containing the element from Y from the intermediate, and the other half
6069 // Normalize it so the 3 elements come from V1.
6070 CommuteVectorShuffleMask(PermMask, 4);
6074 // Find the element from V2.
6076 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6077 int Val = PermMask[HiIndex];
6084 Mask1[0] = PermMask[HiIndex];
6086 Mask1[2] = PermMask[HiIndex^1];
6088 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6091 Mask1[0] = PermMask[0];
6092 Mask1[1] = PermMask[1];
6093 Mask1[2] = HiIndex & 1 ? 6 : 4;
6094 Mask1[3] = HiIndex & 1 ? 4 : 6;
6095 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6097 Mask1[0] = HiIndex & 1 ? 2 : 0;
6098 Mask1[1] = HiIndex & 1 ? 0 : 2;
6099 Mask1[2] = PermMask[2];
6100 Mask1[3] = PermMask[3];
6105 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6109 // Break it into (shuffle shuffle_hi, shuffle_lo).
6112 SmallVector<int,8> LoMask(4U, -1);
6113 SmallVector<int,8> HiMask(4U, -1);
6115 SmallVector<int,8> *MaskPtr = &LoMask;
6116 unsigned MaskIdx = 0;
6119 for (unsigned i = 0; i != 4; ++i) {
6126 int Idx = PermMask[i];
6128 Locs[i] = std::make_pair(-1, -1);
6129 } else if (Idx < 4) {
6130 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6131 (*MaskPtr)[LoIdx] = Idx;
6134 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6135 (*MaskPtr)[HiIdx] = Idx;
6140 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6141 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6142 SmallVector<int, 8> MaskOps;
6143 for (unsigned i = 0; i != 4; ++i) {
6144 if (Locs[i].first == -1) {
6145 MaskOps.push_back(-1);
6147 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6148 MaskOps.push_back(Idx);
6151 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6154 static bool MayFoldVectorLoad(SDValue V) {
6155 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6156 V = V.getOperand(0);
6157 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6158 V = V.getOperand(0);
6159 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6160 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6161 // BUILD_VECTOR (load), undef
6162 V = V.getOperand(0);
6168 // FIXME: the version above should always be used. Since there's
6169 // a bug where several vector shuffles can't be folded because the
6170 // DAG is not updated during lowering and a node claims to have two
6171 // uses while it only has one, use this version, and let isel match
6172 // another instruction if the load really happens to have more than
6173 // one use. Remove this version after this bug get fixed.
6174 // rdar://8434668, PR8156
6175 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6176 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6177 V = V.getOperand(0);
6178 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6179 V = V.getOperand(0);
6180 if (ISD::isNormalLoad(V.getNode()))
6185 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6186 /// a vector extract, and if both can be later optimized into a single load.
6187 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6188 /// here because otherwise a target specific shuffle node is going to be
6189 /// emitted for this shuffle, and the optimization not done.
6190 /// FIXME: This is probably not the best approach, but fix the problem
6191 /// until the right path is decided.
6193 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6194 const TargetLowering &TLI) {
6195 EVT VT = V.getValueType();
6196 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6198 // Be sure that the vector shuffle is present in a pattern like this:
6199 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6203 SDNode *N = *V.getNode()->use_begin();
6204 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6207 SDValue EltNo = N->getOperand(1);
6208 if (!isa<ConstantSDNode>(EltNo))
6211 // If the bit convert changed the number of elements, it is unsafe
6212 // to examine the mask.
6213 bool HasShuffleIntoBitcast = false;
6214 if (V.getOpcode() == ISD::BITCAST) {
6215 EVT SrcVT = V.getOperand(0).getValueType();
6216 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6218 V = V.getOperand(0);
6219 HasShuffleIntoBitcast = true;
6222 // Select the input vector, guarding against out of range extract vector.
6223 unsigned NumElems = VT.getVectorNumElements();
6224 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6225 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6226 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6228 // Skip one more bit_convert if necessary
6229 if (V.getOpcode() == ISD::BITCAST)
6230 V = V.getOperand(0);
6232 if (ISD::isNormalLoad(V.getNode())) {
6233 // Is the original load suitable?
6234 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6236 // FIXME: avoid the multi-use bug that is preventing lots of
6237 // of foldings to be detected, this is still wrong of course, but
6238 // give the temporary desired behavior, and if it happens that
6239 // the load has real more uses, during isel it will not fold, and
6240 // will generate poor code.
6241 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6244 if (!HasShuffleIntoBitcast)
6247 // If there's a bitcast before the shuffle, check if the load type and
6248 // alignment is valid.
6249 unsigned Align = LN0->getAlignment();
6251 TLI.getTargetData()->getABITypeAlignment(
6252 VT.getTypeForEVT(*DAG.getContext()));
6254 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6262 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6263 EVT VT = Op.getValueType();
6265 // Canonizalize to v2f64.
6266 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6267 return DAG.getNode(ISD::BITCAST, dl, VT,
6268 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6273 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6275 SDValue V1 = Op.getOperand(0);
6276 SDValue V2 = Op.getOperand(1);
6277 EVT VT = Op.getValueType();
6279 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6281 if (HasXMMInt && VT == MVT::v2f64)
6282 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6284 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6285 return DAG.getNode(ISD::BITCAST, dl, VT,
6286 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6287 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6288 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6292 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6293 SDValue V1 = Op.getOperand(0);
6294 SDValue V2 = Op.getOperand(1);
6295 EVT VT = Op.getValueType();
6297 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6298 "unsupported shuffle type");
6300 if (V2.getOpcode() == ISD::UNDEF)
6304 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6307 static inline unsigned getSHUFPOpcode(EVT VT) {
6308 switch(VT.getSimpleVT().SimpleTy) {
6309 case MVT::v8i32: // Use fp unit for int unpack.
6311 case MVT::v4i32: // Use fp unit for int unpack.
6312 case MVT::v4f32: return X86ISD::SHUFPS;
6313 case MVT::v4i64: // Use fp unit for int unpack.
6315 case MVT::v2i64: // Use fp unit for int unpack.
6316 case MVT::v2f64: return X86ISD::SHUFPD;
6318 llvm_unreachable("Unknown type for shufp*");
6324 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6325 SDValue V1 = Op.getOperand(0);
6326 SDValue V2 = Op.getOperand(1);
6327 EVT VT = Op.getValueType();
6328 unsigned NumElems = VT.getVectorNumElements();
6330 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6331 // operand of these instructions is only memory, so check if there's a
6332 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6334 bool CanFoldLoad = false;
6336 // Trivial case, when V2 comes from a load.
6337 if (MayFoldVectorLoad(V2))
6340 // When V1 is a load, it can be folded later into a store in isel, example:
6341 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6343 // (MOVLPSmr addr:$src1, VR128:$src2)
6344 // So, recognize this potential and also use MOVLPS or MOVLPD
6345 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6348 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6350 if (HasXMMInt && NumElems == 2)
6351 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6354 // If we don't care about the second element, procede to use movss.
6355 if (SVOp->getMaskElt(1) != -1)
6356 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6359 // movl and movlp will both match v2i64, but v2i64 is never matched by
6360 // movl earlier because we make it strict to avoid messing with the movlp load
6361 // folding logic (see the code above getMOVLP call). Match it here then,
6362 // this is horrible, but will stay like this until we move all shuffle
6363 // matching to x86 specific nodes. Note that for the 1st condition all
6364 // types are matched with movsd.
6366 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6367 // as to remove this logic from here, as much as possible
6368 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6369 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6370 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6373 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6375 // Invert the operand order and use SHUFPS to match it.
6376 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6377 X86::getShuffleSHUFImmediate(SVOp), DAG);
6381 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6382 const TargetLowering &TLI,
6383 const X86Subtarget *Subtarget) {
6384 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6385 EVT VT = Op.getValueType();
6386 DebugLoc dl = Op.getDebugLoc();
6387 SDValue V1 = Op.getOperand(0);
6388 SDValue V2 = Op.getOperand(1);
6390 if (isZeroShuffle(SVOp))
6391 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6393 // Handle splat operations
6394 if (SVOp->isSplat()) {
6395 unsigned NumElem = VT.getVectorNumElements();
6396 int Size = VT.getSizeInBits();
6397 // Special case, this is the only place now where it's allowed to return
6398 // a vector_shuffle operation without using a target specific node, because
6399 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6400 // this be moved to DAGCombine instead?
6401 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6404 // Use vbroadcast whenever the splat comes from a foldable load
6405 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6406 if (Subtarget->hasAVX() && LD.getNode())
6407 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6409 // Handle splats by matching through known shuffle masks
6410 if ((Size == 128 && NumElem <= 4) ||
6411 (Size == 256 && NumElem < 8))
6414 // All remaning splats are promoted to target supported vector shuffles.
6415 return PromoteSplat(SVOp, DAG);
6418 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6420 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6421 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6422 if (NewOp.getNode())
6423 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6424 } else if ((VT == MVT::v4i32 ||
6425 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6426 // FIXME: Figure out a cleaner way to do this.
6427 // Try to make use of movq to zero out the top part.
6428 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6429 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6430 if (NewOp.getNode()) {
6431 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6432 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6433 DAG, Subtarget, dl);
6435 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6436 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6437 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6438 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6439 DAG, Subtarget, dl);
6446 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6447 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6448 SDValue V1 = Op.getOperand(0);
6449 SDValue V2 = Op.getOperand(1);
6450 EVT VT = Op.getValueType();
6451 DebugLoc dl = Op.getDebugLoc();
6452 unsigned NumElems = VT.getVectorNumElements();
6453 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6454 bool V1IsSplat = false;
6455 bool V2IsSplat = false;
6456 bool HasXMMInt = Subtarget->hasXMMInt();
6457 bool HasAVX = Subtarget->hasAVX();
6458 bool HasAVX2 = Subtarget->hasAVX2();
6459 MachineFunction &MF = DAG.getMachineFunction();
6460 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6462 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6464 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6466 // Vector shuffle lowering takes 3 steps:
6468 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6469 // narrowing and commutation of operands should be handled.
6470 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6472 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6473 // so the shuffle can be broken into other shuffles and the legalizer can
6474 // try the lowering again.
6476 // The general idea is that no vector_shuffle operation should be left to
6477 // be matched during isel, all of them must be converted to a target specific
6480 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6481 // narrowing and commutation of operands should be handled. The actual code
6482 // doesn't include all of those, work in progress...
6483 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6484 if (NewOp.getNode())
6487 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6488 // unpckh_undef). Only use pshufd if speed is more important than size.
6489 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6490 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6491 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6492 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6494 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6495 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6496 return getMOVDDup(Op, dl, V1, DAG);
6498 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6499 return getMOVHighToLow(Op, dl, DAG);
6501 // Use to match splats
6502 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6503 (VT == MVT::v2f64 || VT == MVT::v2i64))
6504 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6506 if (X86::isPSHUFDMask(SVOp)) {
6507 // The actual implementation will match the mask in the if above and then
6508 // during isel it can match several different instructions, not only pshufd
6509 // as its name says, sad but true, emulate the behavior for now...
6510 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6511 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6513 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6515 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6516 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6518 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6522 // Check if this can be converted into a logical shift.
6523 bool isLeft = false;
6526 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6527 if (isShift && ShVal.hasOneUse()) {
6528 // If the shifted value has multiple uses, it may be cheaper to use
6529 // v_set0 + movlhps or movhlps, etc.
6530 EVT EltVT = VT.getVectorElementType();
6531 ShAmt *= EltVT.getSizeInBits();
6532 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6535 if (X86::isMOVLMask(SVOp)) {
6536 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6537 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6538 if (!X86::isMOVLPMask(SVOp)) {
6539 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6540 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6542 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6543 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6547 // FIXME: fold these into legal mask.
6548 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6549 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6551 if (X86::isMOVHLPSMask(SVOp))
6552 return getMOVHighToLow(Op, dl, DAG);
6554 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6555 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6557 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6558 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6560 if (X86::isMOVLPMask(SVOp))
6561 return getMOVLP(Op, dl, DAG, HasXMMInt);
6563 if (ShouldXformToMOVHLPS(SVOp) ||
6564 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6565 return CommuteVectorShuffle(SVOp, DAG);
6568 // No better options. Use a vshl / vsrl.
6569 EVT EltVT = VT.getVectorElementType();
6570 ShAmt *= EltVT.getSizeInBits();
6571 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6574 bool Commuted = false;
6575 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6576 // 1,1,1,1 -> v8i16 though.
6577 V1IsSplat = isSplatVector(V1.getNode());
6578 V2IsSplat = isSplatVector(V2.getNode());
6580 // Canonicalize the splat or undef, if present, to be on the RHS.
6581 if (V1IsSplat && !V2IsSplat) {
6582 Op = CommuteVectorShuffle(SVOp, DAG);
6583 SVOp = cast<ShuffleVectorSDNode>(Op);
6584 V1 = SVOp->getOperand(0);
6585 V2 = SVOp->getOperand(1);
6586 std::swap(V1IsSplat, V2IsSplat);
6590 SmallVector<int, 32> M;
6593 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6594 // Shuffling low element of v1 into undef, just return v1.
6597 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6598 // the instruction selector will not match, so get a canonical MOVL with
6599 // swapped operands to undo the commute.
6600 return getMOVL(DAG, dl, VT, V2, V1);
6603 if (isUNPCKLMask(M, VT, HasAVX2))
6604 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6606 if (isUNPCKHMask(M, VT, HasAVX2))
6607 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6610 // Normalize mask so all entries that point to V2 points to its first
6611 // element then try to match unpck{h|l} again. If match, return a
6612 // new vector_shuffle with the corrected mask.
6613 SDValue NewMask = NormalizeMask(SVOp, DAG);
6614 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6615 if (NSVOp != SVOp) {
6616 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6618 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6625 // Commute is back and try unpck* again.
6626 // FIXME: this seems wrong.
6627 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6628 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6630 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6631 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6633 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6634 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6637 // Normalize the node to match x86 shuffle ops if needed
6638 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6639 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6640 return CommuteVectorShuffle(SVOp, DAG);
6642 // The checks below are all present in isShuffleMaskLegal, but they are
6643 // inlined here right now to enable us to directly emit target specific
6644 // nodes, and remove one by one until they don't return Op anymore.
6646 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6647 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6648 getShufflePALIGNRImmediate(SVOp),
6651 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6652 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6653 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6654 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6657 if (isPSHUFHWMask(M, VT))
6658 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6659 X86::getShufflePSHUFHWImmediate(SVOp),
6662 if (isPSHUFLWMask(M, VT))
6663 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6664 X86::getShufflePSHUFLWImmediate(SVOp),
6667 if (isSHUFPMask(M, VT))
6668 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6669 X86::getShuffleSHUFImmediate(SVOp), DAG);
6671 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6672 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6673 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6674 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6676 //===--------------------------------------------------------------------===//
6677 // Generate target specific nodes for 128 or 256-bit shuffles only
6678 // supported in the AVX instruction set.
6681 // Handle VMOVDDUPY permutations
6682 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6683 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6685 // Handle VPERMILPS/D* permutations
6686 if (isVPERMILPMask(M, VT, HasAVX))
6687 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6688 getShuffleVPERMILPImmediate(SVOp), DAG);
6690 // Handle VPERM2F128/VPERM2I128 permutations
6691 if (isVPERM2X128Mask(M, VT, HasAVX))
6692 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6693 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6695 // Handle VSHUFPS/DY permutations
6696 if (isVSHUFPYMask(M, VT, HasAVX))
6697 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6698 getShuffleVSHUFPYImmediate(SVOp), DAG);
6700 //===--------------------------------------------------------------------===//
6701 // Since no target specific shuffle was selected for this generic one,
6702 // lower it into other known shuffles. FIXME: this isn't true yet, but
6703 // this is the plan.
6706 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6707 if (VT == MVT::v8i16) {
6708 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6709 if (NewOp.getNode())
6713 if (VT == MVT::v16i8) {
6714 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6715 if (NewOp.getNode())
6719 // Handle all 128-bit wide vectors with 4 elements, and match them with
6720 // several different shuffle types.
6721 if (NumElems == 4 && VT.getSizeInBits() == 128)
6722 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6724 // Handle general 256-bit shuffles
6725 if (VT.is256BitVector())
6726 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6732 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6733 SelectionDAG &DAG) const {
6734 EVT VT = Op.getValueType();
6735 DebugLoc dl = Op.getDebugLoc();
6737 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6740 if (VT.getSizeInBits() == 8) {
6741 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6742 Op.getOperand(0), Op.getOperand(1));
6743 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6744 DAG.getValueType(VT));
6745 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6746 } else if (VT.getSizeInBits() == 16) {
6747 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6748 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6750 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6751 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6752 DAG.getNode(ISD::BITCAST, dl,
6756 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6757 Op.getOperand(0), Op.getOperand(1));
6758 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6759 DAG.getValueType(VT));
6760 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6761 } else if (VT == MVT::f32) {
6762 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6763 // the result back to FR32 register. It's only worth matching if the
6764 // result has a single use which is a store or a bitcast to i32. And in
6765 // the case of a store, it's not worth it if the index is a constant 0,
6766 // because a MOVSSmr can be used instead, which is smaller and faster.
6767 if (!Op.hasOneUse())
6769 SDNode *User = *Op.getNode()->use_begin();
6770 if ((User->getOpcode() != ISD::STORE ||
6771 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6772 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6773 (User->getOpcode() != ISD::BITCAST ||
6774 User->getValueType(0) != MVT::i32))
6776 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6777 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6780 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6781 } else if (VT == MVT::i32 || VT == MVT::i64) {
6782 // ExtractPS/pextrq works with constant index.
6783 if (isa<ConstantSDNode>(Op.getOperand(1)))
6791 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6792 SelectionDAG &DAG) const {
6793 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6796 SDValue Vec = Op.getOperand(0);
6797 EVT VecVT = Vec.getValueType();
6799 // If this is a 256-bit vector result, first extract the 128-bit vector and
6800 // then extract the element from the 128-bit vector.
6801 if (VecVT.getSizeInBits() == 256) {
6802 DebugLoc dl = Op.getNode()->getDebugLoc();
6803 unsigned NumElems = VecVT.getVectorNumElements();
6804 SDValue Idx = Op.getOperand(1);
6805 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6807 // Get the 128-bit vector.
6808 bool Upper = IdxVal >= NumElems/2;
6809 Vec = Extract128BitVector(Vec,
6810 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6812 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6813 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6816 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6818 if (Subtarget->hasSSE41orAVX()) {
6819 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6824 EVT VT = Op.getValueType();
6825 DebugLoc dl = Op.getDebugLoc();
6826 // TODO: handle v16i8.
6827 if (VT.getSizeInBits() == 16) {
6828 SDValue Vec = Op.getOperand(0);
6829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6831 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6832 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6833 DAG.getNode(ISD::BITCAST, dl,
6836 // Transform it so it match pextrw which produces a 32-bit result.
6837 EVT EltVT = MVT::i32;
6838 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6839 Op.getOperand(0), Op.getOperand(1));
6840 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6841 DAG.getValueType(VT));
6842 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6843 } else if (VT.getSizeInBits() == 32) {
6844 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6848 // SHUFPS the element to the lowest double word, then movss.
6849 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6850 EVT VVT = Op.getOperand(0).getValueType();
6851 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6852 DAG.getUNDEF(VVT), Mask);
6853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6854 DAG.getIntPtrConstant(0));
6855 } else if (VT.getSizeInBits() == 64) {
6856 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6857 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6858 // to match extract_elt for f64.
6859 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6863 // UNPCKHPD the element to the lowest double word, then movsd.
6864 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6865 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6866 int Mask[2] = { 1, -1 };
6867 EVT VVT = Op.getOperand(0).getValueType();
6868 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6869 DAG.getUNDEF(VVT), Mask);
6870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6871 DAG.getIntPtrConstant(0));
6878 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6879 SelectionDAG &DAG) const {
6880 EVT VT = Op.getValueType();
6881 EVT EltVT = VT.getVectorElementType();
6882 DebugLoc dl = Op.getDebugLoc();
6884 SDValue N0 = Op.getOperand(0);
6885 SDValue N1 = Op.getOperand(1);
6886 SDValue N2 = Op.getOperand(2);
6888 if (VT.getSizeInBits() == 256)
6891 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6892 isa<ConstantSDNode>(N2)) {
6894 if (VT == MVT::v8i16)
6895 Opc = X86ISD::PINSRW;
6896 else if (VT == MVT::v16i8)
6897 Opc = X86ISD::PINSRB;
6899 Opc = X86ISD::PINSRB;
6901 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6903 if (N1.getValueType() != MVT::i32)
6904 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6905 if (N2.getValueType() != MVT::i32)
6906 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6907 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6908 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6909 // Bits [7:6] of the constant are the source select. This will always be
6910 // zero here. The DAG Combiner may combine an extract_elt index into these
6911 // bits. For example (insert (extract, 3), 2) could be matched by putting
6912 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6913 // Bits [5:4] of the constant are the destination select. This is the
6914 // value of the incoming immediate.
6915 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6916 // combine either bitwise AND or insert of float 0.0 to set these bits.
6917 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6918 // Create this as a scalar to vector..
6919 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6920 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6921 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6922 isa<ConstantSDNode>(N2)) {
6923 // PINSR* works with constant index.
6930 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6931 EVT VT = Op.getValueType();
6932 EVT EltVT = VT.getVectorElementType();
6934 DebugLoc dl = Op.getDebugLoc();
6935 SDValue N0 = Op.getOperand(0);
6936 SDValue N1 = Op.getOperand(1);
6937 SDValue N2 = Op.getOperand(2);
6939 // If this is a 256-bit vector result, first extract the 128-bit vector,
6940 // insert the element into the extracted half and then place it back.
6941 if (VT.getSizeInBits() == 256) {
6942 if (!isa<ConstantSDNode>(N2))
6945 // Get the desired 128-bit vector half.
6946 unsigned NumElems = VT.getVectorNumElements();
6947 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6948 bool Upper = IdxVal >= NumElems/2;
6949 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6950 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6952 // Insert the element into the desired half.
6953 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6954 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6956 // Insert the changed part back to the 256-bit vector
6957 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6960 if (Subtarget->hasSSE41orAVX())
6961 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6963 if (EltVT == MVT::i8)
6966 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6967 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6968 // as its second argument.
6969 if (N1.getValueType() != MVT::i32)
6970 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6971 if (N2.getValueType() != MVT::i32)
6972 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6973 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6979 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6980 LLVMContext *Context = DAG.getContext();
6981 DebugLoc dl = Op.getDebugLoc();
6982 EVT OpVT = Op.getValueType();
6984 // If this is a 256-bit vector result, first insert into a 128-bit
6985 // vector and then insert into the 256-bit vector.
6986 if (OpVT.getSizeInBits() > 128) {
6987 // Insert into a 128-bit vector.
6988 EVT VT128 = EVT::getVectorVT(*Context,
6989 OpVT.getVectorElementType(),
6990 OpVT.getVectorNumElements() / 2);
6992 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6994 // Insert the 128-bit vector.
6995 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6996 DAG.getConstant(0, MVT::i32),
7000 if (Op.getValueType() == MVT::v1i64 &&
7001 Op.getOperand(0).getValueType() == MVT::i64)
7002 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7004 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7005 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7006 "Expected an SSE type!");
7007 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7008 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7011 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7012 // a simple subregister reference or explicit instructions to grab
7013 // upper bits of a vector.
7015 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7016 if (Subtarget->hasAVX()) {
7017 DebugLoc dl = Op.getNode()->getDebugLoc();
7018 SDValue Vec = Op.getNode()->getOperand(0);
7019 SDValue Idx = Op.getNode()->getOperand(1);
7021 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7022 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7023 return Extract128BitVector(Vec, Idx, DAG, dl);
7029 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7030 // simple superregister reference or explicit instructions to insert
7031 // the upper bits of a vector.
7033 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7034 if (Subtarget->hasAVX()) {
7035 DebugLoc dl = Op.getNode()->getDebugLoc();
7036 SDValue Vec = Op.getNode()->getOperand(0);
7037 SDValue SubVec = Op.getNode()->getOperand(1);
7038 SDValue Idx = Op.getNode()->getOperand(2);
7040 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7041 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7042 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7048 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7049 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7050 // one of the above mentioned nodes. It has to be wrapped because otherwise
7051 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7052 // be used to form addressing mode. These wrapped nodes will be selected
7055 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7056 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7058 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7060 unsigned char OpFlag = 0;
7061 unsigned WrapperKind = X86ISD::Wrapper;
7062 CodeModel::Model M = getTargetMachine().getCodeModel();
7064 if (Subtarget->isPICStyleRIPRel() &&
7065 (M == CodeModel::Small || M == CodeModel::Kernel))
7066 WrapperKind = X86ISD::WrapperRIP;
7067 else if (Subtarget->isPICStyleGOT())
7068 OpFlag = X86II::MO_GOTOFF;
7069 else if (Subtarget->isPICStyleStubPIC())
7070 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7072 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7074 CP->getOffset(), OpFlag);
7075 DebugLoc DL = CP->getDebugLoc();
7076 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7077 // With PIC, the address is actually $g + Offset.
7079 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7080 DAG.getNode(X86ISD::GlobalBaseReg,
7081 DebugLoc(), getPointerTy()),
7088 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7089 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7091 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7093 unsigned char OpFlag = 0;
7094 unsigned WrapperKind = X86ISD::Wrapper;
7095 CodeModel::Model M = getTargetMachine().getCodeModel();
7097 if (Subtarget->isPICStyleRIPRel() &&
7098 (M == CodeModel::Small || M == CodeModel::Kernel))
7099 WrapperKind = X86ISD::WrapperRIP;
7100 else if (Subtarget->isPICStyleGOT())
7101 OpFlag = X86II::MO_GOTOFF;
7102 else if (Subtarget->isPICStyleStubPIC())
7103 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7105 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7107 DebugLoc DL = JT->getDebugLoc();
7108 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7110 // With PIC, the address is actually $g + Offset.
7112 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7113 DAG.getNode(X86ISD::GlobalBaseReg,
7114 DebugLoc(), getPointerTy()),
7121 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7122 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7124 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7126 unsigned char OpFlag = 0;
7127 unsigned WrapperKind = X86ISD::Wrapper;
7128 CodeModel::Model M = getTargetMachine().getCodeModel();
7130 if (Subtarget->isPICStyleRIPRel() &&
7131 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7132 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7133 OpFlag = X86II::MO_GOTPCREL;
7134 WrapperKind = X86ISD::WrapperRIP;
7135 } else if (Subtarget->isPICStyleGOT()) {
7136 OpFlag = X86II::MO_GOT;
7137 } else if (Subtarget->isPICStyleStubPIC()) {
7138 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7139 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7140 OpFlag = X86II::MO_DARWIN_NONLAZY;
7143 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7145 DebugLoc DL = Op.getDebugLoc();
7146 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7149 // With PIC, the address is actually $g + Offset.
7150 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7151 !Subtarget->is64Bit()) {
7152 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7153 DAG.getNode(X86ISD::GlobalBaseReg,
7154 DebugLoc(), getPointerTy()),
7158 // For symbols that require a load from a stub to get the address, emit the
7160 if (isGlobalStubReference(OpFlag))
7161 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7162 MachinePointerInfo::getGOT(), false, false, false, 0);
7168 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7169 // Create the TargetBlockAddressAddress node.
7170 unsigned char OpFlags =
7171 Subtarget->ClassifyBlockAddressReference();
7172 CodeModel::Model M = getTargetMachine().getCodeModel();
7173 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7174 DebugLoc dl = Op.getDebugLoc();
7175 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7176 /*isTarget=*/true, OpFlags);
7178 if (Subtarget->isPICStyleRIPRel() &&
7179 (M == CodeModel::Small || M == CodeModel::Kernel))
7180 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7182 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7184 // With PIC, the address is actually $g + Offset.
7185 if (isGlobalRelativeToPICBase(OpFlags)) {
7186 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7187 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7195 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7197 SelectionDAG &DAG) const {
7198 // Create the TargetGlobalAddress node, folding in the constant
7199 // offset if it is legal.
7200 unsigned char OpFlags =
7201 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7202 CodeModel::Model M = getTargetMachine().getCodeModel();
7204 if (OpFlags == X86II::MO_NO_FLAG &&
7205 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7206 // A direct static reference to a global.
7207 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7210 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7213 if (Subtarget->isPICStyleRIPRel() &&
7214 (M == CodeModel::Small || M == CodeModel::Kernel))
7215 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7217 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7219 // With PIC, the address is actually $g + Offset.
7220 if (isGlobalRelativeToPICBase(OpFlags)) {
7221 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7222 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7226 // For globals that require a load from a stub to get the address, emit the
7228 if (isGlobalStubReference(OpFlags))
7229 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7230 MachinePointerInfo::getGOT(), false, false, false, 0);
7232 // If there was a non-zero offset that we didn't fold, create an explicit
7235 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7236 DAG.getConstant(Offset, getPointerTy()));
7242 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7243 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7244 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7245 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7249 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7250 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7251 unsigned char OperandFlags) {
7252 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7253 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7254 DebugLoc dl = GA->getDebugLoc();
7255 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7256 GA->getValueType(0),
7260 SDValue Ops[] = { Chain, TGA, *InFlag };
7261 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7263 SDValue Ops[] = { Chain, TGA };
7264 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7267 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7268 MFI->setAdjustsStack(true);
7270 SDValue Flag = Chain.getValue(1);
7271 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7274 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7276 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7279 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7280 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7281 DAG.getNode(X86ISD::GlobalBaseReg,
7282 DebugLoc(), PtrVT), InFlag);
7283 InFlag = Chain.getValue(1);
7285 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7288 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7290 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7292 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7293 X86::RAX, X86II::MO_TLSGD);
7296 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7297 // "local exec" model.
7298 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7299 const EVT PtrVT, TLSModel::Model model,
7301 DebugLoc dl = GA->getDebugLoc();
7303 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7304 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7305 is64Bit ? 257 : 256));
7307 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7308 DAG.getIntPtrConstant(0),
7309 MachinePointerInfo(Ptr),
7310 false, false, false, 0);
7312 unsigned char OperandFlags = 0;
7313 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7315 unsigned WrapperKind = X86ISD::Wrapper;
7316 if (model == TLSModel::LocalExec) {
7317 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7318 } else if (is64Bit) {
7319 assert(model == TLSModel::InitialExec);
7320 OperandFlags = X86II::MO_GOTTPOFF;
7321 WrapperKind = X86ISD::WrapperRIP;
7323 assert(model == TLSModel::InitialExec);
7324 OperandFlags = X86II::MO_INDNTPOFF;
7327 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7329 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7330 GA->getValueType(0),
7331 GA->getOffset(), OperandFlags);
7332 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7334 if (model == TLSModel::InitialExec)
7335 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7336 MachinePointerInfo::getGOT(), false, false, false, 0);
7338 // The address of the thread local variable is the add of the thread
7339 // pointer with the offset of the variable.
7340 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7344 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7346 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7347 const GlobalValue *GV = GA->getGlobal();
7349 if (Subtarget->isTargetELF()) {
7350 // TODO: implement the "local dynamic" model
7351 // TODO: implement the "initial exec"model for pic executables
7353 // If GV is an alias then use the aliasee for determining
7354 // thread-localness.
7355 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7356 GV = GA->resolveAliasedGlobal(false);
7358 TLSModel::Model model
7359 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7362 case TLSModel::GeneralDynamic:
7363 case TLSModel::LocalDynamic: // not implemented
7364 if (Subtarget->is64Bit())
7365 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7366 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7368 case TLSModel::InitialExec:
7369 case TLSModel::LocalExec:
7370 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7371 Subtarget->is64Bit());
7373 } else if (Subtarget->isTargetDarwin()) {
7374 // Darwin only has one model of TLS. Lower to that.
7375 unsigned char OpFlag = 0;
7376 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7377 X86ISD::WrapperRIP : X86ISD::Wrapper;
7379 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7381 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7382 !Subtarget->is64Bit();
7384 OpFlag = X86II::MO_TLVP_PIC_BASE;
7386 OpFlag = X86II::MO_TLVP;
7387 DebugLoc DL = Op.getDebugLoc();
7388 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7389 GA->getValueType(0),
7390 GA->getOffset(), OpFlag);
7391 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7393 // With PIC32, the address is actually $g + Offset.
7395 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7396 DAG.getNode(X86ISD::GlobalBaseReg,
7397 DebugLoc(), getPointerTy()),
7400 // Lowering the machine isd will make sure everything is in the right
7402 SDValue Chain = DAG.getEntryNode();
7403 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7404 SDValue Args[] = { Chain, Offset };
7405 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7407 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7408 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7409 MFI->setAdjustsStack(true);
7411 // And our return value (tls address) is in the standard call return value
7413 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7414 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7419 "TLS not implemented for this target.");
7421 llvm_unreachable("Unreachable");
7426 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7427 /// take a 2 x i32 value to shift plus a shift amount.
7428 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7429 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7430 EVT VT = Op.getValueType();
7431 unsigned VTBits = VT.getSizeInBits();
7432 DebugLoc dl = Op.getDebugLoc();
7433 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7434 SDValue ShOpLo = Op.getOperand(0);
7435 SDValue ShOpHi = Op.getOperand(1);
7436 SDValue ShAmt = Op.getOperand(2);
7437 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7438 DAG.getConstant(VTBits - 1, MVT::i8))
7439 : DAG.getConstant(0, VT);
7442 if (Op.getOpcode() == ISD::SHL_PARTS) {
7443 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7444 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7446 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7447 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7450 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7451 DAG.getConstant(VTBits, MVT::i8));
7452 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7453 AndNode, DAG.getConstant(0, MVT::i8));
7456 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7457 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7458 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7460 if (Op.getOpcode() == ISD::SHL_PARTS) {
7461 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7462 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7464 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7465 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7468 SDValue Ops[2] = { Lo, Hi };
7469 return DAG.getMergeValues(Ops, 2, dl);
7472 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7473 SelectionDAG &DAG) const {
7474 EVT SrcVT = Op.getOperand(0).getValueType();
7476 if (SrcVT.isVector())
7479 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7480 "Unknown SINT_TO_FP to lower!");
7482 // These are really Legal; return the operand so the caller accepts it as
7484 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7486 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7487 Subtarget->is64Bit()) {
7491 DebugLoc dl = Op.getDebugLoc();
7492 unsigned Size = SrcVT.getSizeInBits()/8;
7493 MachineFunction &MF = DAG.getMachineFunction();
7494 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7495 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7496 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7498 MachinePointerInfo::getFixedStack(SSFI),
7500 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7503 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7505 SelectionDAG &DAG) const {
7507 DebugLoc DL = Op.getDebugLoc();
7509 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7511 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7513 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7515 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7517 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7518 MachineMemOperand *MMO;
7520 int SSFI = FI->getIndex();
7522 DAG.getMachineFunction()
7523 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7524 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7526 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7527 StackSlot = StackSlot.getOperand(1);
7529 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7530 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7532 Tys, Ops, array_lengthof(Ops),
7536 Chain = Result.getValue(1);
7537 SDValue InFlag = Result.getValue(2);
7539 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7540 // shouldn't be necessary except that RFP cannot be live across
7541 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7542 MachineFunction &MF = DAG.getMachineFunction();
7543 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7544 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7545 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7546 Tys = DAG.getVTList(MVT::Other);
7548 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7550 MachineMemOperand *MMO =
7551 DAG.getMachineFunction()
7552 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7553 MachineMemOperand::MOStore, SSFISize, SSFISize);
7555 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7556 Ops, array_lengthof(Ops),
7557 Op.getValueType(), MMO);
7558 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7559 MachinePointerInfo::getFixedStack(SSFI),
7560 false, false, false, 0);
7566 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7567 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7568 SelectionDAG &DAG) const {
7569 // This algorithm is not obvious. Here it is in C code, more or less:
7571 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7572 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7573 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7575 // Copy ints to xmm registers.
7576 __m128i xh = _mm_cvtsi32_si128( hi );
7577 __m128i xl = _mm_cvtsi32_si128( lo );
7579 // Combine into low half of a single xmm register.
7580 __m128i x = _mm_unpacklo_epi32( xh, xl );
7584 // Merge in appropriate exponents to give the integer bits the right
7586 x = _mm_unpacklo_epi32( x, exp );
7588 // Subtract away the biases to deal with the IEEE-754 double precision
7590 d = _mm_sub_pd( (__m128d) x, bias );
7592 // All conversions up to here are exact. The correctly rounded result is
7593 // calculated using the current rounding mode using the following
7595 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7596 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7597 // store doesn't really need to be here (except
7598 // maybe to zero the other double)
7603 DebugLoc dl = Op.getDebugLoc();
7604 LLVMContext *Context = DAG.getContext();
7606 // Build some magic constants.
7607 SmallVector<Constant*,4> CV0;
7608 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7609 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7610 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7611 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7612 Constant *C0 = ConstantVector::get(CV0);
7613 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7615 SmallVector<Constant*,2> CV1;
7617 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7619 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7620 Constant *C1 = ConstantVector::get(CV1);
7621 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7623 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7624 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7626 DAG.getIntPtrConstant(1)));
7627 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7628 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7630 DAG.getIntPtrConstant(0)));
7631 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7632 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7633 MachinePointerInfo::getConstantPool(),
7634 false, false, false, 16);
7635 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7636 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7637 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7638 MachinePointerInfo::getConstantPool(),
7639 false, false, false, 16);
7640 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7642 // Add the halves; easiest way is to swap them into another reg first.
7643 int ShufMask[2] = { 1, -1 };
7644 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7645 DAG.getUNDEF(MVT::v2f64), ShufMask);
7646 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7647 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7648 DAG.getIntPtrConstant(0));
7651 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7652 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7653 SelectionDAG &DAG) const {
7654 DebugLoc dl = Op.getDebugLoc();
7655 // FP constant to bias correct the final result.
7656 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7659 // Load the 32-bit value into an XMM register.
7660 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7663 // Zero out the upper parts of the register.
7664 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7667 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7668 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7669 DAG.getIntPtrConstant(0));
7671 // Or the load with the bias.
7672 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7673 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7674 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7676 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7677 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7678 MVT::v2f64, Bias)));
7679 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7680 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7681 DAG.getIntPtrConstant(0));
7683 // Subtract the bias.
7684 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7686 // Handle final rounding.
7687 EVT DestVT = Op.getValueType();
7689 if (DestVT.bitsLT(MVT::f64)) {
7690 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7691 DAG.getIntPtrConstant(0));
7692 } else if (DestVT.bitsGT(MVT::f64)) {
7693 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7696 // Handle final rounding.
7700 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7701 SelectionDAG &DAG) const {
7702 SDValue N0 = Op.getOperand(0);
7703 DebugLoc dl = Op.getDebugLoc();
7705 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7706 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7707 // the optimization here.
7708 if (DAG.SignBitIsZero(N0))
7709 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7711 EVT SrcVT = N0.getValueType();
7712 EVT DstVT = Op.getValueType();
7713 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7714 return LowerUINT_TO_FP_i64(Op, DAG);
7715 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7716 return LowerUINT_TO_FP_i32(Op, DAG);
7718 // Make a 64-bit buffer, and use it to build an FILD.
7719 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7720 if (SrcVT == MVT::i32) {
7721 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7722 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7723 getPointerTy(), StackSlot, WordOff);
7724 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7725 StackSlot, MachinePointerInfo(),
7727 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7728 OffsetSlot, MachinePointerInfo(),
7730 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7734 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7735 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7736 StackSlot, MachinePointerInfo(),
7738 // For i64 source, we need to add the appropriate power of 2 if the input
7739 // was negative. This is the same as the optimization in
7740 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7741 // we must be careful to do the computation in x87 extended precision, not
7742 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7743 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7744 MachineMemOperand *MMO =
7745 DAG.getMachineFunction()
7746 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7747 MachineMemOperand::MOLoad, 8, 8);
7749 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7750 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7751 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7754 APInt FF(32, 0x5F800000ULL);
7756 // Check whether the sign bit is set.
7757 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7758 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7761 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7762 SDValue FudgePtr = DAG.getConstantPool(
7763 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7766 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7767 SDValue Zero = DAG.getIntPtrConstant(0);
7768 SDValue Four = DAG.getIntPtrConstant(4);
7769 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7771 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7773 // Load the value out, extending it from f32 to f80.
7774 // FIXME: Avoid the extend by constructing the right constant pool?
7775 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7776 FudgePtr, MachinePointerInfo::getConstantPool(),
7777 MVT::f32, false, false, 4);
7778 // Extend everything to 80 bits to force it to be done on x87.
7779 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7780 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7783 std::pair<SDValue,SDValue> X86TargetLowering::
7784 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7785 DebugLoc DL = Op.getDebugLoc();
7787 EVT DstTy = Op.getValueType();
7790 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7794 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7795 DstTy.getSimpleVT() >= MVT::i16 &&
7796 "Unknown FP_TO_SINT to lower!");
7798 // These are really Legal.
7799 if (DstTy == MVT::i32 &&
7800 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7801 return std::make_pair(SDValue(), SDValue());
7802 if (Subtarget->is64Bit() &&
7803 DstTy == MVT::i64 &&
7804 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7805 return std::make_pair(SDValue(), SDValue());
7807 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7809 MachineFunction &MF = DAG.getMachineFunction();
7810 unsigned MemSize = DstTy.getSizeInBits()/8;
7811 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7812 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7817 switch (DstTy.getSimpleVT().SimpleTy) {
7818 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7819 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7820 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7821 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7824 SDValue Chain = DAG.getEntryNode();
7825 SDValue Value = Op.getOperand(0);
7826 EVT TheVT = Op.getOperand(0).getValueType();
7827 if (isScalarFPTypeInSSEReg(TheVT)) {
7828 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7829 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7830 MachinePointerInfo::getFixedStack(SSFI),
7832 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7834 Chain, StackSlot, DAG.getValueType(TheVT)
7837 MachineMemOperand *MMO =
7838 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7839 MachineMemOperand::MOLoad, MemSize, MemSize);
7840 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7842 Chain = Value.getValue(1);
7843 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7844 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7847 MachineMemOperand *MMO =
7848 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7849 MachineMemOperand::MOStore, MemSize, MemSize);
7851 // Build the FP_TO_INT*_IN_MEM
7852 SDValue Ops[] = { Chain, Value, StackSlot };
7853 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7854 Ops, 3, DstTy, MMO);
7856 return std::make_pair(FIST, StackSlot);
7859 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7860 SelectionDAG &DAG) const {
7861 if (Op.getValueType().isVector())
7864 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7865 SDValue FIST = Vals.first, StackSlot = Vals.second;
7866 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7867 if (FIST.getNode() == 0) return Op;
7870 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7871 FIST, StackSlot, MachinePointerInfo(),
7872 false, false, false, 0);
7875 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7876 SelectionDAG &DAG) const {
7877 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7878 SDValue FIST = Vals.first, StackSlot = Vals.second;
7879 assert(FIST.getNode() && "Unexpected failure");
7882 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7883 FIST, StackSlot, MachinePointerInfo(),
7884 false, false, false, 0);
7887 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7888 SelectionDAG &DAG) const {
7889 LLVMContext *Context = DAG.getContext();
7890 DebugLoc dl = Op.getDebugLoc();
7891 EVT VT = Op.getValueType();
7894 EltVT = VT.getVectorElementType();
7895 SmallVector<Constant*,4> CV;
7896 if (EltVT == MVT::f64) {
7897 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7900 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7903 Constant *C = ConstantVector::get(CV);
7904 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7905 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7906 MachinePointerInfo::getConstantPool(),
7907 false, false, false, 16);
7908 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7911 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7912 LLVMContext *Context = DAG.getContext();
7913 DebugLoc dl = Op.getDebugLoc();
7914 EVT VT = Op.getValueType();
7916 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7917 if (VT.isVector()) {
7918 EltVT = VT.getVectorElementType();
7919 NumElts = VT.getVectorNumElements();
7921 SmallVector<Constant*,8> CV;
7922 if (EltVT == MVT::f64) {
7923 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7924 CV.assign(NumElts, C);
7926 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7927 CV.assign(NumElts, C);
7929 Constant *C = ConstantVector::get(CV);
7930 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7931 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7932 MachinePointerInfo::getConstantPool(),
7933 false, false, false, 16);
7934 if (VT.isVector()) {
7935 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7936 return DAG.getNode(ISD::BITCAST, dl, VT,
7937 DAG.getNode(ISD::XOR, dl, XORVT,
7938 DAG.getNode(ISD::BITCAST, dl, XORVT,
7940 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7942 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7946 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7947 LLVMContext *Context = DAG.getContext();
7948 SDValue Op0 = Op.getOperand(0);
7949 SDValue Op1 = Op.getOperand(1);
7950 DebugLoc dl = Op.getDebugLoc();
7951 EVT VT = Op.getValueType();
7952 EVT SrcVT = Op1.getValueType();
7954 // If second operand is smaller, extend it first.
7955 if (SrcVT.bitsLT(VT)) {
7956 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7959 // And if it is bigger, shrink it first.
7960 if (SrcVT.bitsGT(VT)) {
7961 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7965 // At this point the operands and the result should have the same
7966 // type, and that won't be f80 since that is not custom lowered.
7968 // First get the sign bit of second operand.
7969 SmallVector<Constant*,4> CV;
7970 if (SrcVT == MVT::f64) {
7971 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7972 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7974 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7975 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7976 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7977 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7979 Constant *C = ConstantVector::get(CV);
7980 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7981 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7982 MachinePointerInfo::getConstantPool(),
7983 false, false, false, 16);
7984 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7986 // Shift sign bit right or left if the two operands have different types.
7987 if (SrcVT.bitsGT(VT)) {
7988 // Op0 is MVT::f32, Op1 is MVT::f64.
7989 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7990 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7991 DAG.getConstant(32, MVT::i32));
7992 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7993 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7994 DAG.getIntPtrConstant(0));
7997 // Clear first operand sign bit.
7999 if (VT == MVT::f64) {
8000 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8001 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8003 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8004 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8005 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8006 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8008 C = ConstantVector::get(CV);
8009 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8010 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8011 MachinePointerInfo::getConstantPool(),
8012 false, false, false, 16);
8013 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8015 // Or the value with the sign bit.
8016 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8019 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8020 SDValue N0 = Op.getOperand(0);
8021 DebugLoc dl = Op.getDebugLoc();
8022 EVT VT = Op.getValueType();
8024 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8025 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8026 DAG.getConstant(1, VT));
8027 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8030 /// Emit nodes that will be selected as "test Op0,Op0", or something
8032 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8033 SelectionDAG &DAG) const {
8034 DebugLoc dl = Op.getDebugLoc();
8036 // CF and OF aren't always set the way we want. Determine which
8037 // of these we need.
8038 bool NeedCF = false;
8039 bool NeedOF = false;
8042 case X86::COND_A: case X86::COND_AE:
8043 case X86::COND_B: case X86::COND_BE:
8046 case X86::COND_G: case X86::COND_GE:
8047 case X86::COND_L: case X86::COND_LE:
8048 case X86::COND_O: case X86::COND_NO:
8053 // See if we can use the EFLAGS value from the operand instead of
8054 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8055 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8056 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8057 // Emit a CMP with 0, which is the TEST pattern.
8058 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8059 DAG.getConstant(0, Op.getValueType()));
8061 unsigned Opcode = 0;
8062 unsigned NumOperands = 0;
8063 switch (Op.getNode()->getOpcode()) {
8065 // Due to an isel shortcoming, be conservative if this add is likely to be
8066 // selected as part of a load-modify-store instruction. When the root node
8067 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8068 // uses of other nodes in the match, such as the ADD in this case. This
8069 // leads to the ADD being left around and reselected, with the result being
8070 // two adds in the output. Alas, even if none our users are stores, that
8071 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8072 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8073 // climbing the DAG back to the root, and it doesn't seem to be worth the
8075 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8076 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8077 if (UI->getOpcode() != ISD::CopyToReg &&
8078 UI->getOpcode() != ISD::SETCC &&
8079 UI->getOpcode() != ISD::STORE)
8082 if (ConstantSDNode *C =
8083 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8084 // An add of one will be selected as an INC.
8085 if (C->getAPIntValue() == 1) {
8086 Opcode = X86ISD::INC;
8091 // An add of negative one (subtract of one) will be selected as a DEC.
8092 if (C->getAPIntValue().isAllOnesValue()) {
8093 Opcode = X86ISD::DEC;
8099 // Otherwise use a regular EFLAGS-setting add.
8100 Opcode = X86ISD::ADD;
8104 // If the primary and result isn't used, don't bother using X86ISD::AND,
8105 // because a TEST instruction will be better.
8106 bool NonFlagUse = false;
8107 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8108 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8110 unsigned UOpNo = UI.getOperandNo();
8111 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8112 // Look pass truncate.
8113 UOpNo = User->use_begin().getOperandNo();
8114 User = *User->use_begin();
8117 if (User->getOpcode() != ISD::BRCOND &&
8118 User->getOpcode() != ISD::SETCC &&
8119 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8132 // Due to the ISEL shortcoming noted above, be conservative if this op is
8133 // likely to be selected as part of a load-modify-store instruction.
8134 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8135 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8136 if (UI->getOpcode() == ISD::STORE)
8139 // Otherwise use a regular EFLAGS-setting instruction.
8140 switch (Op.getNode()->getOpcode()) {
8141 default: llvm_unreachable("unexpected operator!");
8142 case ISD::SUB: Opcode = X86ISD::SUB; break;
8143 case ISD::OR: Opcode = X86ISD::OR; break;
8144 case ISD::XOR: Opcode = X86ISD::XOR; break;
8145 case ISD::AND: Opcode = X86ISD::AND; break;
8157 return SDValue(Op.getNode(), 1);
8164 // Emit a CMP with 0, which is the TEST pattern.
8165 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8166 DAG.getConstant(0, Op.getValueType()));
8168 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8169 SmallVector<SDValue, 4> Ops;
8170 for (unsigned i = 0; i != NumOperands; ++i)
8171 Ops.push_back(Op.getOperand(i));
8173 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8174 DAG.ReplaceAllUsesWith(Op, New);
8175 return SDValue(New.getNode(), 1);
8178 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8180 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8181 SelectionDAG &DAG) const {
8182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8183 if (C->getAPIntValue() == 0)
8184 return EmitTest(Op0, X86CC, DAG);
8186 DebugLoc dl = Op0.getDebugLoc();
8187 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8190 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8191 /// if it's possible.
8192 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8193 DebugLoc dl, SelectionDAG &DAG) const {
8194 SDValue Op0 = And.getOperand(0);
8195 SDValue Op1 = And.getOperand(1);
8196 if (Op0.getOpcode() == ISD::TRUNCATE)
8197 Op0 = Op0.getOperand(0);
8198 if (Op1.getOpcode() == ISD::TRUNCATE)
8199 Op1 = Op1.getOperand(0);
8202 if (Op1.getOpcode() == ISD::SHL)
8203 std::swap(Op0, Op1);
8204 if (Op0.getOpcode() == ISD::SHL) {
8205 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8206 if (And00C->getZExtValue() == 1) {
8207 // If we looked past a truncate, check that it's only truncating away
8209 unsigned BitWidth = Op0.getValueSizeInBits();
8210 unsigned AndBitWidth = And.getValueSizeInBits();
8211 if (BitWidth > AndBitWidth) {
8212 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8213 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8214 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8218 RHS = Op0.getOperand(1);
8220 } else if (Op1.getOpcode() == ISD::Constant) {
8221 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8222 uint64_t AndRHSVal = AndRHS->getZExtValue();
8223 SDValue AndLHS = Op0;
8225 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8226 LHS = AndLHS.getOperand(0);
8227 RHS = AndLHS.getOperand(1);
8230 // Use BT if the immediate can't be encoded in a TEST instruction.
8231 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8233 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8237 if (LHS.getNode()) {
8238 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8239 // instruction. Since the shift amount is in-range-or-undefined, we know
8240 // that doing a bittest on the i32 value is ok. We extend to i32 because
8241 // the encoding for the i16 version is larger than the i32 version.
8242 // Also promote i16 to i32 for performance / code size reason.
8243 if (LHS.getValueType() == MVT::i8 ||
8244 LHS.getValueType() == MVT::i16)
8245 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8247 // If the operand types disagree, extend the shift amount to match. Since
8248 // BT ignores high bits (like shifts) we can use anyextend.
8249 if (LHS.getValueType() != RHS.getValueType())
8250 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8252 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8253 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8254 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8255 DAG.getConstant(Cond, MVT::i8), BT);
8261 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8263 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8265 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8266 SDValue Op0 = Op.getOperand(0);
8267 SDValue Op1 = Op.getOperand(1);
8268 DebugLoc dl = Op.getDebugLoc();
8269 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8271 // Optimize to BT if possible.
8272 // Lower (X & (1 << N)) == 0 to BT(X, N).
8273 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8274 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8275 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8276 Op1.getOpcode() == ISD::Constant &&
8277 cast<ConstantSDNode>(Op1)->isNullValue() &&
8278 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8279 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8280 if (NewSetCC.getNode())
8284 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8286 if (Op1.getOpcode() == ISD::Constant &&
8287 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8288 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8289 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8291 // If the input is a setcc, then reuse the input setcc or use a new one with
8292 // the inverted condition.
8293 if (Op0.getOpcode() == X86ISD::SETCC) {
8294 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8295 bool Invert = (CC == ISD::SETNE) ^
8296 cast<ConstantSDNode>(Op1)->isNullValue();
8297 if (!Invert) return Op0;
8299 CCode = X86::GetOppositeBranchCondition(CCode);
8300 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8301 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8305 bool isFP = Op1.getValueType().isFloatingPoint();
8306 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8307 if (X86CC == X86::COND_INVALID)
8310 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8311 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8312 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8315 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8316 // ones, and then concatenate the result back.
8317 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8318 EVT VT = Op.getValueType();
8320 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8321 "Unsupported value type for operation");
8323 int NumElems = VT.getVectorNumElements();
8324 DebugLoc dl = Op.getDebugLoc();
8325 SDValue CC = Op.getOperand(2);
8326 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8327 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8329 // Extract the LHS vectors
8330 SDValue LHS = Op.getOperand(0);
8331 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8332 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8334 // Extract the RHS vectors
8335 SDValue RHS = Op.getOperand(1);
8336 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8337 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8339 // Issue the operation on the smaller types and concatenate the result back
8340 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8341 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8342 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8343 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8344 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8348 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8350 SDValue Op0 = Op.getOperand(0);
8351 SDValue Op1 = Op.getOperand(1);
8352 SDValue CC = Op.getOperand(2);
8353 EVT VT = Op.getValueType();
8354 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8355 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8356 DebugLoc dl = Op.getDebugLoc();
8360 EVT EltVT = Op0.getValueType().getVectorElementType();
8361 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8363 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8366 // SSE Condition code mapping:
8375 switch (SetCCOpcode) {
8378 case ISD::SETEQ: SSECC = 0; break;
8380 case ISD::SETGT: Swap = true; // Fallthrough
8382 case ISD::SETOLT: SSECC = 1; break;
8384 case ISD::SETGE: Swap = true; // Fallthrough
8386 case ISD::SETOLE: SSECC = 2; break;
8387 case ISD::SETUO: SSECC = 3; break;
8389 case ISD::SETNE: SSECC = 4; break;
8390 case ISD::SETULE: Swap = true;
8391 case ISD::SETUGE: SSECC = 5; break;
8392 case ISD::SETULT: Swap = true;
8393 case ISD::SETUGT: SSECC = 6; break;
8394 case ISD::SETO: SSECC = 7; break;
8397 std::swap(Op0, Op1);
8399 // In the two special cases we can't handle, emit two comparisons.
8401 if (SetCCOpcode == ISD::SETUEQ) {
8403 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8404 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8405 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8406 } else if (SetCCOpcode == ISD::SETONE) {
8408 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8409 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8410 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8412 llvm_unreachable("Illegal FP comparison");
8414 // Handle all other FP comparisons here.
8415 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8418 // Break 256-bit integer vector compare into smaller ones.
8419 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8420 return Lower256IntVSETCC(Op, DAG);
8422 // We are handling one of the integer comparisons here. Since SSE only has
8423 // GT and EQ comparisons for integer, swapping operands and multiple
8424 // operations may be required for some comparisons.
8425 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8426 bool Swap = false, Invert = false, FlipSigns = false;
8428 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8430 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8431 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8432 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8433 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8436 switch (SetCCOpcode) {
8438 case ISD::SETNE: Invert = true;
8439 case ISD::SETEQ: Opc = EQOpc; break;
8440 case ISD::SETLT: Swap = true;
8441 case ISD::SETGT: Opc = GTOpc; break;
8442 case ISD::SETGE: Swap = true;
8443 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8444 case ISD::SETULT: Swap = true;
8445 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8446 case ISD::SETUGE: Swap = true;
8447 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8450 std::swap(Op0, Op1);
8452 // Check that the operation in question is available (most are plain SSE2,
8453 // but PCMPGTQ and PCMPEQQ have different requirements).
8454 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8456 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8459 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8460 // bits of the inputs before performing those operations.
8462 EVT EltVT = VT.getVectorElementType();
8463 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8465 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8466 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8468 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8469 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8472 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8474 // If the logical-not of the result is required, perform that now.
8476 Result = DAG.getNOT(dl, Result, VT);
8481 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8482 static bool isX86LogicalCmp(SDValue Op) {
8483 unsigned Opc = Op.getNode()->getOpcode();
8484 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8486 if (Op.getResNo() == 1 &&
8487 (Opc == X86ISD::ADD ||
8488 Opc == X86ISD::SUB ||
8489 Opc == X86ISD::ADC ||
8490 Opc == X86ISD::SBB ||
8491 Opc == X86ISD::SMUL ||
8492 Opc == X86ISD::UMUL ||
8493 Opc == X86ISD::INC ||
8494 Opc == X86ISD::DEC ||
8495 Opc == X86ISD::OR ||
8496 Opc == X86ISD::XOR ||
8497 Opc == X86ISD::AND))
8500 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8506 static bool isZero(SDValue V) {
8507 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8508 return C && C->isNullValue();
8511 static bool isAllOnes(SDValue V) {
8512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8513 return C && C->isAllOnesValue();
8516 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8517 bool addTest = true;
8518 SDValue Cond = Op.getOperand(0);
8519 SDValue Op1 = Op.getOperand(1);
8520 SDValue Op2 = Op.getOperand(2);
8521 DebugLoc DL = Op.getDebugLoc();
8524 if (Cond.getOpcode() == ISD::SETCC) {
8525 SDValue NewCond = LowerSETCC(Cond, DAG);
8526 if (NewCond.getNode())
8530 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8531 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8532 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8533 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8534 if (Cond.getOpcode() == X86ISD::SETCC &&
8535 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8536 isZero(Cond.getOperand(1).getOperand(1))) {
8537 SDValue Cmp = Cond.getOperand(1);
8539 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8541 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8542 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8543 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8545 SDValue CmpOp0 = Cmp.getOperand(0);
8546 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8547 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8549 SDValue Res = // Res = 0 or -1.
8550 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8551 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8553 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8554 Res = DAG.getNOT(DL, Res, Res.getValueType());
8556 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8557 if (N2C == 0 || !N2C->isNullValue())
8558 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8563 // Look past (and (setcc_carry (cmp ...)), 1).
8564 if (Cond.getOpcode() == ISD::AND &&
8565 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8566 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8567 if (C && C->getAPIntValue() == 1)
8568 Cond = Cond.getOperand(0);
8571 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8572 // setting operand in place of the X86ISD::SETCC.
8573 unsigned CondOpcode = Cond.getOpcode();
8574 if (CondOpcode == X86ISD::SETCC ||
8575 CondOpcode == X86ISD::SETCC_CARRY) {
8576 CC = Cond.getOperand(0);
8578 SDValue Cmp = Cond.getOperand(1);
8579 unsigned Opc = Cmp.getOpcode();
8580 EVT VT = Op.getValueType();
8582 bool IllegalFPCMov = false;
8583 if (VT.isFloatingPoint() && !VT.isVector() &&
8584 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8585 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8587 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8588 Opc == X86ISD::BT) { // FIXME
8592 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8593 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8594 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8595 Cond.getOperand(0).getValueType() != MVT::i8)) {
8596 SDValue LHS = Cond.getOperand(0);
8597 SDValue RHS = Cond.getOperand(1);
8601 switch (CondOpcode) {
8602 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8603 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8604 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8605 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8606 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8607 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8608 default: llvm_unreachable("unexpected overflowing operator");
8610 if (CondOpcode == ISD::UMULO)
8611 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8614 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8616 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8618 if (CondOpcode == ISD::UMULO)
8619 Cond = X86Op.getValue(2);
8621 Cond = X86Op.getValue(1);
8623 CC = DAG.getConstant(X86Cond, MVT::i8);
8628 // Look pass the truncate.
8629 if (Cond.getOpcode() == ISD::TRUNCATE)
8630 Cond = Cond.getOperand(0);
8632 // We know the result of AND is compared against zero. Try to match
8634 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8635 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8636 if (NewSetCC.getNode()) {
8637 CC = NewSetCC.getOperand(0);
8638 Cond = NewSetCC.getOperand(1);
8645 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8646 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8649 // a < b ? -1 : 0 -> RES = ~setcc_carry
8650 // a < b ? 0 : -1 -> RES = setcc_carry
8651 // a >= b ? -1 : 0 -> RES = setcc_carry
8652 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8653 if (Cond.getOpcode() == X86ISD::CMP) {
8654 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8656 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8657 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8658 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8659 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8660 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8661 return DAG.getNOT(DL, Res, Res.getValueType());
8666 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8667 // condition is true.
8668 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8669 SDValue Ops[] = { Op2, Op1, CC, Cond };
8670 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8673 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8674 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8675 // from the AND / OR.
8676 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8677 Opc = Op.getOpcode();
8678 if (Opc != ISD::OR && Opc != ISD::AND)
8680 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8681 Op.getOperand(0).hasOneUse() &&
8682 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8683 Op.getOperand(1).hasOneUse());
8686 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8687 // 1 and that the SETCC node has a single use.
8688 static bool isXor1OfSetCC(SDValue Op) {
8689 if (Op.getOpcode() != ISD::XOR)
8691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8692 if (N1C && N1C->getAPIntValue() == 1) {
8693 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8694 Op.getOperand(0).hasOneUse();
8699 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8700 bool addTest = true;
8701 SDValue Chain = Op.getOperand(0);
8702 SDValue Cond = Op.getOperand(1);
8703 SDValue Dest = Op.getOperand(2);
8704 DebugLoc dl = Op.getDebugLoc();
8706 bool Inverted = false;
8708 if (Cond.getOpcode() == ISD::SETCC) {
8709 // Check for setcc([su]{add,sub,mul}o == 0).
8710 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8711 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8712 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8713 Cond.getOperand(0).getResNo() == 1 &&
8714 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8715 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8716 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8717 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8718 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8719 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8721 Cond = Cond.getOperand(0);
8723 SDValue NewCond = LowerSETCC(Cond, DAG);
8724 if (NewCond.getNode())
8729 // FIXME: LowerXALUO doesn't handle these!!
8730 else if (Cond.getOpcode() == X86ISD::ADD ||
8731 Cond.getOpcode() == X86ISD::SUB ||
8732 Cond.getOpcode() == X86ISD::SMUL ||
8733 Cond.getOpcode() == X86ISD::UMUL)
8734 Cond = LowerXALUO(Cond, DAG);
8737 // Look pass (and (setcc_carry (cmp ...)), 1).
8738 if (Cond.getOpcode() == ISD::AND &&
8739 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8741 if (C && C->getAPIntValue() == 1)
8742 Cond = Cond.getOperand(0);
8745 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8746 // setting operand in place of the X86ISD::SETCC.
8747 unsigned CondOpcode = Cond.getOpcode();
8748 if (CondOpcode == X86ISD::SETCC ||
8749 CondOpcode == X86ISD::SETCC_CARRY) {
8750 CC = Cond.getOperand(0);
8752 SDValue Cmp = Cond.getOperand(1);
8753 unsigned Opc = Cmp.getOpcode();
8754 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8755 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8759 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8763 // These can only come from an arithmetic instruction with overflow,
8764 // e.g. SADDO, UADDO.
8765 Cond = Cond.getNode()->getOperand(1);
8771 CondOpcode = Cond.getOpcode();
8772 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8773 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8774 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8775 Cond.getOperand(0).getValueType() != MVT::i8)) {
8776 SDValue LHS = Cond.getOperand(0);
8777 SDValue RHS = Cond.getOperand(1);
8781 switch (CondOpcode) {
8782 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8783 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8784 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8785 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8786 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8787 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8788 default: llvm_unreachable("unexpected overflowing operator");
8791 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8792 if (CondOpcode == ISD::UMULO)
8793 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8796 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8798 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8800 if (CondOpcode == ISD::UMULO)
8801 Cond = X86Op.getValue(2);
8803 Cond = X86Op.getValue(1);
8805 CC = DAG.getConstant(X86Cond, MVT::i8);
8809 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8810 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8811 if (CondOpc == ISD::OR) {
8812 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8813 // two branches instead of an explicit OR instruction with a
8815 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8816 isX86LogicalCmp(Cmp)) {
8817 CC = Cond.getOperand(0).getOperand(0);
8818 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8819 Chain, Dest, CC, Cmp);
8820 CC = Cond.getOperand(1).getOperand(0);
8824 } else { // ISD::AND
8825 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8826 // two branches instead of an explicit AND instruction with a
8827 // separate test. However, we only do this if this block doesn't
8828 // have a fall-through edge, because this requires an explicit
8829 // jmp when the condition is false.
8830 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8831 isX86LogicalCmp(Cmp) &&
8832 Op.getNode()->hasOneUse()) {
8833 X86::CondCode CCode =
8834 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8835 CCode = X86::GetOppositeBranchCondition(CCode);
8836 CC = DAG.getConstant(CCode, MVT::i8);
8837 SDNode *User = *Op.getNode()->use_begin();
8838 // Look for an unconditional branch following this conditional branch.
8839 // We need this because we need to reverse the successors in order
8840 // to implement FCMP_OEQ.
8841 if (User->getOpcode() == ISD::BR) {
8842 SDValue FalseBB = User->getOperand(1);
8844 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8845 assert(NewBR == User);
8849 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8850 Chain, Dest, CC, Cmp);
8851 X86::CondCode CCode =
8852 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8853 CCode = X86::GetOppositeBranchCondition(CCode);
8854 CC = DAG.getConstant(CCode, MVT::i8);
8860 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8861 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8862 // It should be transformed during dag combiner except when the condition
8863 // is set by a arithmetics with overflow node.
8864 X86::CondCode CCode =
8865 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8866 CCode = X86::GetOppositeBranchCondition(CCode);
8867 CC = DAG.getConstant(CCode, MVT::i8);
8868 Cond = Cond.getOperand(0).getOperand(1);
8870 } else if (Cond.getOpcode() == ISD::SETCC &&
8871 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8872 // For FCMP_OEQ, we can emit
8873 // two branches instead of an explicit AND instruction with a
8874 // separate test. However, we only do this if this block doesn't
8875 // have a fall-through edge, because this requires an explicit
8876 // jmp when the condition is false.
8877 if (Op.getNode()->hasOneUse()) {
8878 SDNode *User = *Op.getNode()->use_begin();
8879 // Look for an unconditional branch following this conditional branch.
8880 // We need this because we need to reverse the successors in order
8881 // to implement FCMP_OEQ.
8882 if (User->getOpcode() == ISD::BR) {
8883 SDValue FalseBB = User->getOperand(1);
8885 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8886 assert(NewBR == User);
8890 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8891 Cond.getOperand(0), Cond.getOperand(1));
8892 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8893 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8894 Chain, Dest, CC, Cmp);
8895 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8900 } else if (Cond.getOpcode() == ISD::SETCC &&
8901 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8902 // For FCMP_UNE, we can emit
8903 // two branches instead of an explicit AND instruction with a
8904 // separate test. However, we only do this if this block doesn't
8905 // have a fall-through edge, because this requires an explicit
8906 // jmp when the condition is false.
8907 if (Op.getNode()->hasOneUse()) {
8908 SDNode *User = *Op.getNode()->use_begin();
8909 // Look for an unconditional branch following this conditional branch.
8910 // We need this because we need to reverse the successors in order
8911 // to implement FCMP_UNE.
8912 if (User->getOpcode() == ISD::BR) {
8913 SDValue FalseBB = User->getOperand(1);
8915 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8916 assert(NewBR == User);
8919 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8920 Cond.getOperand(0), Cond.getOperand(1));
8921 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8922 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8923 Chain, Dest, CC, Cmp);
8924 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8934 // Look pass the truncate.
8935 if (Cond.getOpcode() == ISD::TRUNCATE)
8936 Cond = Cond.getOperand(0);
8938 // We know the result of AND is compared against zero. Try to match
8940 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8941 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8942 if (NewSetCC.getNode()) {
8943 CC = NewSetCC.getOperand(0);
8944 Cond = NewSetCC.getOperand(1);
8951 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8952 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8954 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8955 Chain, Dest, CC, Cond);
8959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8960 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8962 // that the guard pages used by the OS virtual memory manager are allocated in
8963 // correct sequence.
8965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8966 SelectionDAG &DAG) const {
8967 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8968 getTargetMachine().Options.EnableSegmentedStacks) &&
8969 "This should be used only on Windows targets or when segmented stacks "
8971 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8972 DebugLoc dl = Op.getDebugLoc();
8975 SDValue Chain = Op.getOperand(0);
8976 SDValue Size = Op.getOperand(1);
8977 // FIXME: Ensure alignment here
8979 bool Is64Bit = Subtarget->is64Bit();
8980 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8982 if (getTargetMachine().Options.EnableSegmentedStacks) {
8983 MachineFunction &MF = DAG.getMachineFunction();
8984 MachineRegisterInfo &MRI = MF.getRegInfo();
8987 // The 64 bit implementation of segmented stacks needs to clobber both r10
8988 // r11. This makes it impossible to use it along with nested parameters.
8989 const Function *F = MF.getFunction();
8991 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8993 if (I->hasNestAttr())
8994 report_fatal_error("Cannot use segmented stacks with functions that "
8995 "have nested arguments.");
8998 const TargetRegisterClass *AddrRegClass =
8999 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9000 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9001 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9002 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9003 DAG.getRegister(Vreg, SPTy));
9004 SDValue Ops1[2] = { Value, Chain };
9005 return DAG.getMergeValues(Ops1, 2, dl);
9008 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9010 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9011 Flag = Chain.getValue(1);
9012 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9014 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9015 Flag = Chain.getValue(1);
9017 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9019 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9020 return DAG.getMergeValues(Ops1, 2, dl);
9024 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9025 MachineFunction &MF = DAG.getMachineFunction();
9026 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9028 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9029 DebugLoc DL = Op.getDebugLoc();
9031 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9032 // vastart just stores the address of the VarArgsFrameIndex slot into the
9033 // memory location argument.
9034 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9036 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9037 MachinePointerInfo(SV), false, false, 0);
9041 // gp_offset (0 - 6 * 8)
9042 // fp_offset (48 - 48 + 8 * 16)
9043 // overflow_arg_area (point to parameters coming in memory).
9045 SmallVector<SDValue, 8> MemOps;
9046 SDValue FIN = Op.getOperand(1);
9048 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9049 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9051 FIN, MachinePointerInfo(SV), false, false, 0);
9052 MemOps.push_back(Store);
9055 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9056 FIN, DAG.getIntPtrConstant(4));
9057 Store = DAG.getStore(Op.getOperand(0), DL,
9058 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9060 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9061 MemOps.push_back(Store);
9063 // Store ptr to overflow_arg_area
9064 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9065 FIN, DAG.getIntPtrConstant(4));
9066 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9068 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9069 MachinePointerInfo(SV, 8),
9071 MemOps.push_back(Store);
9073 // Store ptr to reg_save_area.
9074 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9075 FIN, DAG.getIntPtrConstant(8));
9076 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9078 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9079 MachinePointerInfo(SV, 16), false, false, 0);
9080 MemOps.push_back(Store);
9081 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9082 &MemOps[0], MemOps.size());
9085 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9086 assert(Subtarget->is64Bit() &&
9087 "LowerVAARG only handles 64-bit va_arg!");
9088 assert((Subtarget->isTargetLinux() ||
9089 Subtarget->isTargetDarwin()) &&
9090 "Unhandled target in LowerVAARG");
9091 assert(Op.getNode()->getNumOperands() == 4);
9092 SDValue Chain = Op.getOperand(0);
9093 SDValue SrcPtr = Op.getOperand(1);
9094 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9095 unsigned Align = Op.getConstantOperandVal(3);
9096 DebugLoc dl = Op.getDebugLoc();
9098 EVT ArgVT = Op.getNode()->getValueType(0);
9099 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9100 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9103 // Decide which area this value should be read from.
9104 // TODO: Implement the AMD64 ABI in its entirety. This simple
9105 // selection mechanism works only for the basic types.
9106 if (ArgVT == MVT::f80) {
9107 llvm_unreachable("va_arg for f80 not yet implemented");
9108 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9109 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9110 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9111 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9113 llvm_unreachable("Unhandled argument type in LowerVAARG");
9117 // Sanity Check: Make sure using fp_offset makes sense.
9118 assert(!getTargetMachine().Options.UseSoftFloat &&
9119 !(DAG.getMachineFunction()
9120 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9121 Subtarget->hasXMM());
9124 // Insert VAARG_64 node into the DAG
9125 // VAARG_64 returns two values: Variable Argument Address, Chain
9126 SmallVector<SDValue, 11> InstOps;
9127 InstOps.push_back(Chain);
9128 InstOps.push_back(SrcPtr);
9129 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9130 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9131 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9132 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9133 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9134 VTs, &InstOps[0], InstOps.size(),
9136 MachinePointerInfo(SV),
9141 Chain = VAARG.getValue(1);
9143 // Load the next argument and return it
9144 return DAG.getLoad(ArgVT, dl,
9147 MachinePointerInfo(),
9148 false, false, false, 0);
9151 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9152 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9153 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9154 SDValue Chain = Op.getOperand(0);
9155 SDValue DstPtr = Op.getOperand(1);
9156 SDValue SrcPtr = Op.getOperand(2);
9157 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9158 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9159 DebugLoc DL = Op.getDebugLoc();
9161 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9162 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9164 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9168 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9169 DebugLoc dl = Op.getDebugLoc();
9170 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9172 default: return SDValue(); // Don't custom lower most intrinsics.
9173 // Comparison intrinsics.
9174 case Intrinsic::x86_sse_comieq_ss:
9175 case Intrinsic::x86_sse_comilt_ss:
9176 case Intrinsic::x86_sse_comile_ss:
9177 case Intrinsic::x86_sse_comigt_ss:
9178 case Intrinsic::x86_sse_comige_ss:
9179 case Intrinsic::x86_sse_comineq_ss:
9180 case Intrinsic::x86_sse_ucomieq_ss:
9181 case Intrinsic::x86_sse_ucomilt_ss:
9182 case Intrinsic::x86_sse_ucomile_ss:
9183 case Intrinsic::x86_sse_ucomigt_ss:
9184 case Intrinsic::x86_sse_ucomige_ss:
9185 case Intrinsic::x86_sse_ucomineq_ss:
9186 case Intrinsic::x86_sse2_comieq_sd:
9187 case Intrinsic::x86_sse2_comilt_sd:
9188 case Intrinsic::x86_sse2_comile_sd:
9189 case Intrinsic::x86_sse2_comigt_sd:
9190 case Intrinsic::x86_sse2_comige_sd:
9191 case Intrinsic::x86_sse2_comineq_sd:
9192 case Intrinsic::x86_sse2_ucomieq_sd:
9193 case Intrinsic::x86_sse2_ucomilt_sd:
9194 case Intrinsic::x86_sse2_ucomile_sd:
9195 case Intrinsic::x86_sse2_ucomigt_sd:
9196 case Intrinsic::x86_sse2_ucomige_sd:
9197 case Intrinsic::x86_sse2_ucomineq_sd: {
9199 ISD::CondCode CC = ISD::SETCC_INVALID;
9202 case Intrinsic::x86_sse_comieq_ss:
9203 case Intrinsic::x86_sse2_comieq_sd:
9207 case Intrinsic::x86_sse_comilt_ss:
9208 case Intrinsic::x86_sse2_comilt_sd:
9212 case Intrinsic::x86_sse_comile_ss:
9213 case Intrinsic::x86_sse2_comile_sd:
9217 case Intrinsic::x86_sse_comigt_ss:
9218 case Intrinsic::x86_sse2_comigt_sd:
9222 case Intrinsic::x86_sse_comige_ss:
9223 case Intrinsic::x86_sse2_comige_sd:
9227 case Intrinsic::x86_sse_comineq_ss:
9228 case Intrinsic::x86_sse2_comineq_sd:
9232 case Intrinsic::x86_sse_ucomieq_ss:
9233 case Intrinsic::x86_sse2_ucomieq_sd:
9234 Opc = X86ISD::UCOMI;
9237 case Intrinsic::x86_sse_ucomilt_ss:
9238 case Intrinsic::x86_sse2_ucomilt_sd:
9239 Opc = X86ISD::UCOMI;
9242 case Intrinsic::x86_sse_ucomile_ss:
9243 case Intrinsic::x86_sse2_ucomile_sd:
9244 Opc = X86ISD::UCOMI;
9247 case Intrinsic::x86_sse_ucomigt_ss:
9248 case Intrinsic::x86_sse2_ucomigt_sd:
9249 Opc = X86ISD::UCOMI;
9252 case Intrinsic::x86_sse_ucomige_ss:
9253 case Intrinsic::x86_sse2_ucomige_sd:
9254 Opc = X86ISD::UCOMI;
9257 case Intrinsic::x86_sse_ucomineq_ss:
9258 case Intrinsic::x86_sse2_ucomineq_sd:
9259 Opc = X86ISD::UCOMI;
9264 SDValue LHS = Op.getOperand(1);
9265 SDValue RHS = Op.getOperand(2);
9266 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9267 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9268 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9269 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9270 DAG.getConstant(X86CC, MVT::i8), Cond);
9271 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9273 // Arithmetic intrinsics.
9274 case Intrinsic::x86_sse3_hadd_ps:
9275 case Intrinsic::x86_sse3_hadd_pd:
9276 case Intrinsic::x86_avx_hadd_ps_256:
9277 case Intrinsic::x86_avx_hadd_pd_256:
9278 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9279 Op.getOperand(1), Op.getOperand(2));
9280 case Intrinsic::x86_sse3_hsub_ps:
9281 case Intrinsic::x86_sse3_hsub_pd:
9282 case Intrinsic::x86_avx_hsub_ps_256:
9283 case Intrinsic::x86_avx_hsub_pd_256:
9284 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9285 Op.getOperand(1), Op.getOperand(2));
9286 case Intrinsic::x86_avx2_psllv_d:
9287 case Intrinsic::x86_avx2_psllv_q:
9288 case Intrinsic::x86_avx2_psllv_d_256:
9289 case Intrinsic::x86_avx2_psllv_q_256:
9290 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9291 Op.getOperand(1), Op.getOperand(2));
9292 case Intrinsic::x86_avx2_psrlv_d:
9293 case Intrinsic::x86_avx2_psrlv_q:
9294 case Intrinsic::x86_avx2_psrlv_d_256:
9295 case Intrinsic::x86_avx2_psrlv_q_256:
9296 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9297 Op.getOperand(1), Op.getOperand(2));
9298 case Intrinsic::x86_avx2_psrav_d:
9299 case Intrinsic::x86_avx2_psrav_d_256:
9300 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9301 Op.getOperand(1), Op.getOperand(2));
9303 // ptest and testp intrinsics. The intrinsic these come from are designed to
9304 // return an integer value, not just an instruction so lower it to the ptest
9305 // or testp pattern and a setcc for the result.
9306 case Intrinsic::x86_sse41_ptestz:
9307 case Intrinsic::x86_sse41_ptestc:
9308 case Intrinsic::x86_sse41_ptestnzc:
9309 case Intrinsic::x86_avx_ptestz_256:
9310 case Intrinsic::x86_avx_ptestc_256:
9311 case Intrinsic::x86_avx_ptestnzc_256:
9312 case Intrinsic::x86_avx_vtestz_ps:
9313 case Intrinsic::x86_avx_vtestc_ps:
9314 case Intrinsic::x86_avx_vtestnzc_ps:
9315 case Intrinsic::x86_avx_vtestz_pd:
9316 case Intrinsic::x86_avx_vtestc_pd:
9317 case Intrinsic::x86_avx_vtestnzc_pd:
9318 case Intrinsic::x86_avx_vtestz_ps_256:
9319 case Intrinsic::x86_avx_vtestc_ps_256:
9320 case Intrinsic::x86_avx_vtestnzc_ps_256:
9321 case Intrinsic::x86_avx_vtestz_pd_256:
9322 case Intrinsic::x86_avx_vtestc_pd_256:
9323 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9324 bool IsTestPacked = false;
9327 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9328 case Intrinsic::x86_avx_vtestz_ps:
9329 case Intrinsic::x86_avx_vtestz_pd:
9330 case Intrinsic::x86_avx_vtestz_ps_256:
9331 case Intrinsic::x86_avx_vtestz_pd_256:
9332 IsTestPacked = true; // Fallthrough
9333 case Intrinsic::x86_sse41_ptestz:
9334 case Intrinsic::x86_avx_ptestz_256:
9336 X86CC = X86::COND_E;
9338 case Intrinsic::x86_avx_vtestc_ps:
9339 case Intrinsic::x86_avx_vtestc_pd:
9340 case Intrinsic::x86_avx_vtestc_ps_256:
9341 case Intrinsic::x86_avx_vtestc_pd_256:
9342 IsTestPacked = true; // Fallthrough
9343 case Intrinsic::x86_sse41_ptestc:
9344 case Intrinsic::x86_avx_ptestc_256:
9346 X86CC = X86::COND_B;
9348 case Intrinsic::x86_avx_vtestnzc_ps:
9349 case Intrinsic::x86_avx_vtestnzc_pd:
9350 case Intrinsic::x86_avx_vtestnzc_ps_256:
9351 case Intrinsic::x86_avx_vtestnzc_pd_256:
9352 IsTestPacked = true; // Fallthrough
9353 case Intrinsic::x86_sse41_ptestnzc:
9354 case Intrinsic::x86_avx_ptestnzc_256:
9356 X86CC = X86::COND_A;
9360 SDValue LHS = Op.getOperand(1);
9361 SDValue RHS = Op.getOperand(2);
9362 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9363 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9364 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9365 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9366 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9369 // Fix vector shift instructions where the last operand is a non-immediate
9371 case Intrinsic::x86_avx2_pslli_w:
9372 case Intrinsic::x86_avx2_pslli_d:
9373 case Intrinsic::x86_avx2_pslli_q:
9374 case Intrinsic::x86_avx2_psrli_w:
9375 case Intrinsic::x86_avx2_psrli_d:
9376 case Intrinsic::x86_avx2_psrli_q:
9377 case Intrinsic::x86_avx2_psrai_w:
9378 case Intrinsic::x86_avx2_psrai_d:
9379 case Intrinsic::x86_sse2_pslli_w:
9380 case Intrinsic::x86_sse2_pslli_d:
9381 case Intrinsic::x86_sse2_pslli_q:
9382 case Intrinsic::x86_sse2_psrli_w:
9383 case Intrinsic::x86_sse2_psrli_d:
9384 case Intrinsic::x86_sse2_psrli_q:
9385 case Intrinsic::x86_sse2_psrai_w:
9386 case Intrinsic::x86_sse2_psrai_d:
9387 case Intrinsic::x86_mmx_pslli_w:
9388 case Intrinsic::x86_mmx_pslli_d:
9389 case Intrinsic::x86_mmx_pslli_q:
9390 case Intrinsic::x86_mmx_psrli_w:
9391 case Intrinsic::x86_mmx_psrli_d:
9392 case Intrinsic::x86_mmx_psrli_q:
9393 case Intrinsic::x86_mmx_psrai_w:
9394 case Intrinsic::x86_mmx_psrai_d: {
9395 SDValue ShAmt = Op.getOperand(2);
9396 if (isa<ConstantSDNode>(ShAmt))
9399 unsigned NewIntNo = 0;
9400 EVT ShAmtVT = MVT::v4i32;
9402 case Intrinsic::x86_sse2_pslli_w:
9403 NewIntNo = Intrinsic::x86_sse2_psll_w;
9405 case Intrinsic::x86_sse2_pslli_d:
9406 NewIntNo = Intrinsic::x86_sse2_psll_d;
9408 case Intrinsic::x86_sse2_pslli_q:
9409 NewIntNo = Intrinsic::x86_sse2_psll_q;
9411 case Intrinsic::x86_sse2_psrli_w:
9412 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9414 case Intrinsic::x86_sse2_psrli_d:
9415 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9417 case Intrinsic::x86_sse2_psrli_q:
9418 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9420 case Intrinsic::x86_sse2_psrai_w:
9421 NewIntNo = Intrinsic::x86_sse2_psra_w;
9423 case Intrinsic::x86_sse2_psrai_d:
9424 NewIntNo = Intrinsic::x86_sse2_psra_d;
9426 case Intrinsic::x86_avx2_pslli_w:
9427 NewIntNo = Intrinsic::x86_avx2_psll_w;
9429 case Intrinsic::x86_avx2_pslli_d:
9430 NewIntNo = Intrinsic::x86_avx2_psll_d;
9432 case Intrinsic::x86_avx2_pslli_q:
9433 NewIntNo = Intrinsic::x86_avx2_psll_q;
9435 case Intrinsic::x86_avx2_psrli_w:
9436 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9438 case Intrinsic::x86_avx2_psrli_d:
9439 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9441 case Intrinsic::x86_avx2_psrli_q:
9442 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9444 case Intrinsic::x86_avx2_psrai_w:
9445 NewIntNo = Intrinsic::x86_avx2_psra_w;
9447 case Intrinsic::x86_avx2_psrai_d:
9448 NewIntNo = Intrinsic::x86_avx2_psra_d;
9451 ShAmtVT = MVT::v2i32;
9453 case Intrinsic::x86_mmx_pslli_w:
9454 NewIntNo = Intrinsic::x86_mmx_psll_w;
9456 case Intrinsic::x86_mmx_pslli_d:
9457 NewIntNo = Intrinsic::x86_mmx_psll_d;
9459 case Intrinsic::x86_mmx_pslli_q:
9460 NewIntNo = Intrinsic::x86_mmx_psll_q;
9462 case Intrinsic::x86_mmx_psrli_w:
9463 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9465 case Intrinsic::x86_mmx_psrli_d:
9466 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9468 case Intrinsic::x86_mmx_psrli_q:
9469 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9471 case Intrinsic::x86_mmx_psrai_w:
9472 NewIntNo = Intrinsic::x86_mmx_psra_w;
9474 case Intrinsic::x86_mmx_psrai_d:
9475 NewIntNo = Intrinsic::x86_mmx_psra_d;
9477 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9483 // The vector shift intrinsics with scalars uses 32b shift amounts but
9484 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9488 ShOps[1] = DAG.getConstant(0, MVT::i32);
9489 if (ShAmtVT == MVT::v4i32) {
9490 ShOps[2] = DAG.getUNDEF(MVT::i32);
9491 ShOps[3] = DAG.getUNDEF(MVT::i32);
9492 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9494 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9495 // FIXME this must be lowered to get rid of the invalid type.
9498 EVT VT = Op.getValueType();
9499 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9500 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9501 DAG.getConstant(NewIntNo, MVT::i32),
9502 Op.getOperand(1), ShAmt);
9507 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9508 SelectionDAG &DAG) const {
9509 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9510 MFI->setReturnAddressIsTaken(true);
9512 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9513 DebugLoc dl = Op.getDebugLoc();
9516 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9518 DAG.getConstant(TD->getPointerSize(),
9519 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9520 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9521 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9523 MachinePointerInfo(), false, false, false, 0);
9526 // Just load the return address.
9527 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9528 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9529 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9532 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9533 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9534 MFI->setFrameAddressIsTaken(true);
9536 EVT VT = Op.getValueType();
9537 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9538 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9539 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9540 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9542 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9543 MachinePointerInfo(),
9544 false, false, false, 0);
9548 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9549 SelectionDAG &DAG) const {
9550 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9553 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9554 MachineFunction &MF = DAG.getMachineFunction();
9555 SDValue Chain = Op.getOperand(0);
9556 SDValue Offset = Op.getOperand(1);
9557 SDValue Handler = Op.getOperand(2);
9558 DebugLoc dl = Op.getDebugLoc();
9560 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9561 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9563 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9565 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9566 DAG.getIntPtrConstant(TD->getPointerSize()));
9567 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9568 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9570 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9571 MF.getRegInfo().addLiveOut(StoreAddrReg);
9573 return DAG.getNode(X86ISD::EH_RETURN, dl,
9575 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9578 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9579 SelectionDAG &DAG) const {
9580 return Op.getOperand(0);
9583 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9584 SelectionDAG &DAG) const {
9585 SDValue Root = Op.getOperand(0);
9586 SDValue Trmp = Op.getOperand(1); // trampoline
9587 SDValue FPtr = Op.getOperand(2); // nested function
9588 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9589 DebugLoc dl = Op.getDebugLoc();
9591 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9593 if (Subtarget->is64Bit()) {
9594 SDValue OutChains[6];
9596 // Large code-model.
9597 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9598 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9600 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9601 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9603 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9605 // Load the pointer to the nested function into R11.
9606 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9607 SDValue Addr = Trmp;
9608 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9609 Addr, MachinePointerInfo(TrmpAddr),
9612 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9613 DAG.getConstant(2, MVT::i64));
9614 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9615 MachinePointerInfo(TrmpAddr, 2),
9618 // Load the 'nest' parameter value into R10.
9619 // R10 is specified in X86CallingConv.td
9620 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9621 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9622 DAG.getConstant(10, MVT::i64));
9623 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9624 Addr, MachinePointerInfo(TrmpAddr, 10),
9627 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9628 DAG.getConstant(12, MVT::i64));
9629 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9630 MachinePointerInfo(TrmpAddr, 12),
9633 // Jump to the nested function.
9634 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9635 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9636 DAG.getConstant(20, MVT::i64));
9637 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9638 Addr, MachinePointerInfo(TrmpAddr, 20),
9641 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9642 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9643 DAG.getConstant(22, MVT::i64));
9644 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9645 MachinePointerInfo(TrmpAddr, 22),
9648 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9650 const Function *Func =
9651 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9652 CallingConv::ID CC = Func->getCallingConv();
9657 llvm_unreachable("Unsupported calling convention");
9658 case CallingConv::C:
9659 case CallingConv::X86_StdCall: {
9660 // Pass 'nest' parameter in ECX.
9661 // Must be kept in sync with X86CallingConv.td
9664 // Check that ECX wasn't needed by an 'inreg' parameter.
9665 FunctionType *FTy = Func->getFunctionType();
9666 const AttrListPtr &Attrs = Func->getAttributes();
9668 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9669 unsigned InRegCount = 0;
9672 for (FunctionType::param_iterator I = FTy->param_begin(),
9673 E = FTy->param_end(); I != E; ++I, ++Idx)
9674 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9675 // FIXME: should only count parameters that are lowered to integers.
9676 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9678 if (InRegCount > 2) {
9679 report_fatal_error("Nest register in use - reduce number of inreg"
9685 case CallingConv::X86_FastCall:
9686 case CallingConv::X86_ThisCall:
9687 case CallingConv::Fast:
9688 // Pass 'nest' parameter in EAX.
9689 // Must be kept in sync with X86CallingConv.td
9694 SDValue OutChains[4];
9697 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9698 DAG.getConstant(10, MVT::i32));
9699 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9701 // This is storing the opcode for MOV32ri.
9702 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9703 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9704 OutChains[0] = DAG.getStore(Root, dl,
9705 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9706 Trmp, MachinePointerInfo(TrmpAddr),
9709 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9710 DAG.getConstant(1, MVT::i32));
9711 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9712 MachinePointerInfo(TrmpAddr, 1),
9715 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9716 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9717 DAG.getConstant(5, MVT::i32));
9718 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9719 MachinePointerInfo(TrmpAddr, 5),
9722 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9723 DAG.getConstant(6, MVT::i32));
9724 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9725 MachinePointerInfo(TrmpAddr, 6),
9728 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9732 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9733 SelectionDAG &DAG) const {
9735 The rounding mode is in bits 11:10 of FPSR, and has the following
9742 FLT_ROUNDS, on the other hand, expects the following:
9749 To perform the conversion, we do:
9750 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9753 MachineFunction &MF = DAG.getMachineFunction();
9754 const TargetMachine &TM = MF.getTarget();
9755 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9756 unsigned StackAlignment = TFI.getStackAlignment();
9757 EVT VT = Op.getValueType();
9758 DebugLoc DL = Op.getDebugLoc();
9760 // Save FP Control Word to stack slot
9761 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9762 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9765 MachineMemOperand *MMO =
9766 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9767 MachineMemOperand::MOStore, 2, 2);
9769 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9770 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9771 DAG.getVTList(MVT::Other),
9772 Ops, 2, MVT::i16, MMO);
9774 // Load FP Control Word from stack slot
9775 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9776 MachinePointerInfo(), false, false, false, 0);
9778 // Transform as necessary
9780 DAG.getNode(ISD::SRL, DL, MVT::i16,
9781 DAG.getNode(ISD::AND, DL, MVT::i16,
9782 CWD, DAG.getConstant(0x800, MVT::i16)),
9783 DAG.getConstant(11, MVT::i8));
9785 DAG.getNode(ISD::SRL, DL, MVT::i16,
9786 DAG.getNode(ISD::AND, DL, MVT::i16,
9787 CWD, DAG.getConstant(0x400, MVT::i16)),
9788 DAG.getConstant(9, MVT::i8));
9791 DAG.getNode(ISD::AND, DL, MVT::i16,
9792 DAG.getNode(ISD::ADD, DL, MVT::i16,
9793 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9794 DAG.getConstant(1, MVT::i16)),
9795 DAG.getConstant(3, MVT::i16));
9798 return DAG.getNode((VT.getSizeInBits() < 16 ?
9799 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9802 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9803 EVT VT = Op.getValueType();
9805 unsigned NumBits = VT.getSizeInBits();
9806 DebugLoc dl = Op.getDebugLoc();
9808 Op = Op.getOperand(0);
9809 if (VT == MVT::i8) {
9810 // Zero extend to i32 since there is not an i8 bsr.
9812 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9815 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9816 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9817 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9819 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9822 DAG.getConstant(NumBits+NumBits-1, OpVT),
9823 DAG.getConstant(X86::COND_E, MVT::i8),
9826 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9828 // Finally xor with NumBits-1.
9829 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9832 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9836 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9837 EVT VT = Op.getValueType();
9839 unsigned NumBits = VT.getSizeInBits();
9840 DebugLoc dl = Op.getDebugLoc();
9842 Op = Op.getOperand(0);
9843 if (VT == MVT::i8) {
9845 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9848 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9849 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9850 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9852 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9855 DAG.getConstant(NumBits, OpVT),
9856 DAG.getConstant(X86::COND_E, MVT::i8),
9859 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9862 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9866 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9867 // ones, and then concatenate the result back.
9868 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9869 EVT VT = Op.getValueType();
9871 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9872 "Unsupported value type for operation");
9874 int NumElems = VT.getVectorNumElements();
9875 DebugLoc dl = Op.getDebugLoc();
9876 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9877 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9879 // Extract the LHS vectors
9880 SDValue LHS = Op.getOperand(0);
9881 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9882 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9884 // Extract the RHS vectors
9885 SDValue RHS = Op.getOperand(1);
9886 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9887 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9889 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9890 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9892 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9893 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9894 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9897 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9898 assert(Op.getValueType().getSizeInBits() == 256 &&
9899 Op.getValueType().isInteger() &&
9900 "Only handle AVX 256-bit vector integer operation");
9901 return Lower256IntArith(Op, DAG);
9904 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9905 assert(Op.getValueType().getSizeInBits() == 256 &&
9906 Op.getValueType().isInteger() &&
9907 "Only handle AVX 256-bit vector integer operation");
9908 return Lower256IntArith(Op, DAG);
9911 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9912 EVT VT = Op.getValueType();
9914 // Decompose 256-bit ops into smaller 128-bit ops.
9915 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9916 return Lower256IntArith(Op, DAG);
9918 DebugLoc dl = Op.getDebugLoc();
9920 SDValue A = Op.getOperand(0);
9921 SDValue B = Op.getOperand(1);
9923 if (VT == MVT::v4i64) {
9924 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9926 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9927 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9928 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9929 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9930 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9932 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9933 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9934 // return AloBlo + AloBhi + AhiBlo;
9936 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9937 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9938 A, DAG.getConstant(32, MVT::i32));
9939 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9940 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9941 B, DAG.getConstant(32, MVT::i32));
9942 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9943 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9945 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9946 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9948 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9949 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9951 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9952 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9953 AloBhi, DAG.getConstant(32, MVT::i32));
9954 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9955 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9956 AhiBlo, DAG.getConstant(32, MVT::i32));
9957 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9958 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9962 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9964 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9965 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9966 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9967 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9968 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9970 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9971 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9972 // return AloBlo + AloBhi + AhiBlo;
9974 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9975 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9976 A, DAG.getConstant(32, MVT::i32));
9977 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9978 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9979 B, DAG.getConstant(32, MVT::i32));
9980 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9981 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9983 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9984 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9986 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9987 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9989 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9990 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9991 AloBhi, DAG.getConstant(32, MVT::i32));
9992 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9993 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9994 AhiBlo, DAG.getConstant(32, MVT::i32));
9995 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9996 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10000 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10002 EVT VT = Op.getValueType();
10003 DebugLoc dl = Op.getDebugLoc();
10004 SDValue R = Op.getOperand(0);
10005 SDValue Amt = Op.getOperand(1);
10006 LLVMContext *Context = DAG.getContext();
10008 if (!Subtarget->hasXMMInt())
10011 // Optimize shl/srl/sra with constant shift amount.
10012 if (isSplatVector(Amt.getNode())) {
10013 SDValue SclrAmt = Amt->getOperand(0);
10014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10015 uint64_t ShiftAmt = C->getZExtValue();
10017 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10018 // Make a large shift.
10020 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10021 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10022 R, DAG.getConstant(ShiftAmt, MVT::i32));
10023 // Zero out the rightmost bits.
10024 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10026 return DAG.getNode(ISD::AND, dl, VT, SHL,
10027 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10030 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10031 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10032 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10033 R, DAG.getConstant(ShiftAmt, MVT::i32));
10035 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10036 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10037 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10038 R, DAG.getConstant(ShiftAmt, MVT::i32));
10040 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10041 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10042 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10043 R, DAG.getConstant(ShiftAmt, MVT::i32));
10045 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10046 // Make a large shift.
10048 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10049 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10050 R, DAG.getConstant(ShiftAmt, MVT::i32));
10051 // Zero out the leftmost bits.
10052 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10054 return DAG.getNode(ISD::AND, dl, VT, SRL,
10055 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10058 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10059 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10060 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10061 R, DAG.getConstant(ShiftAmt, MVT::i32));
10063 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10064 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10066 R, DAG.getConstant(ShiftAmt, MVT::i32));
10068 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10069 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10070 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10071 R, DAG.getConstant(ShiftAmt, MVT::i32));
10073 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10074 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10075 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10076 R, DAG.getConstant(ShiftAmt, MVT::i32));
10078 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10079 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10080 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10081 R, DAG.getConstant(ShiftAmt, MVT::i32));
10083 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10084 if (ShiftAmt == 7) {
10085 // R s>> 7 === R s< 0
10086 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10087 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10090 // R s>> a === ((R u>> a) ^ m) - m
10091 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10092 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10094 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10095 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10096 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10100 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10101 if (Op.getOpcode() == ISD::SHL) {
10102 // Make a large shift.
10104 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10105 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10106 R, DAG.getConstant(ShiftAmt, MVT::i32));
10107 // Zero out the rightmost bits.
10108 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10110 return DAG.getNode(ISD::AND, dl, VT, SHL,
10111 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10113 if (Op.getOpcode() == ISD::SRL) {
10114 // Make a large shift.
10116 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10117 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10118 R, DAG.getConstant(ShiftAmt, MVT::i32));
10119 // Zero out the leftmost bits.
10120 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10122 return DAG.getNode(ISD::AND, dl, VT, SRL,
10123 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10125 if (Op.getOpcode() == ISD::SRA) {
10126 if (ShiftAmt == 7) {
10127 // R s>> 7 === R s< 0
10128 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10129 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10132 // R s>> a === ((R u>> a) ^ m) - m
10133 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10134 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10136 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10137 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10138 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10145 // Lower SHL with variable shift amount.
10146 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10147 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10148 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10149 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10151 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10153 std::vector<Constant*> CV(4, CI);
10154 Constant *C = ConstantVector::get(CV);
10155 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10156 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10157 MachinePointerInfo::getConstantPool(),
10158 false, false, false, 16);
10160 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10161 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10162 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10163 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10165 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10166 assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10167 "Need SSE2 for pslli/pcmpeq.");
10170 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10171 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10172 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10174 // Turn 'a' into a mask suitable for VSELECT
10175 SDValue VSelM = DAG.getConstant(0x80, VT);
10176 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10177 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10178 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10181 SDValue CM1 = DAG.getConstant(0x0f, VT);
10182 SDValue CM2 = DAG.getConstant(0x3f, VT);
10184 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10185 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10186 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10187 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10188 DAG.getConstant(4, MVT::i32));
10189 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10192 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10193 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10194 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10195 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10198 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10199 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10200 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10201 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10202 DAG.getConstant(2, MVT::i32));
10203 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10206 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10207 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10208 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10209 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10212 // return VSELECT(r, r+r, a);
10213 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10214 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10218 // Decompose 256-bit shifts into smaller 128-bit shifts.
10219 if (VT.getSizeInBits() == 256) {
10220 int NumElems = VT.getVectorNumElements();
10221 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10222 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10224 // Extract the two vectors
10225 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10226 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10229 // Recreate the shift amount vectors
10230 SDValue Amt1, Amt2;
10231 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10232 // Constant shift amount
10233 SmallVector<SDValue, 4> Amt1Csts;
10234 SmallVector<SDValue, 4> Amt2Csts;
10235 for (int i = 0; i < NumElems/2; ++i)
10236 Amt1Csts.push_back(Amt->getOperand(i));
10237 for (int i = NumElems/2; i < NumElems; ++i)
10238 Amt2Csts.push_back(Amt->getOperand(i));
10240 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10241 &Amt1Csts[0], NumElems/2);
10242 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10243 &Amt2Csts[0], NumElems/2);
10245 // Variable shift amount
10246 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10247 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10251 // Issue new vector shifts for the smaller types
10252 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10253 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10255 // Concatenate the result back
10256 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10262 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10263 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10264 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10265 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10266 // has only one use.
10267 SDNode *N = Op.getNode();
10268 SDValue LHS = N->getOperand(0);
10269 SDValue RHS = N->getOperand(1);
10270 unsigned BaseOp = 0;
10272 DebugLoc DL = Op.getDebugLoc();
10273 switch (Op.getOpcode()) {
10274 default: llvm_unreachable("Unknown ovf instruction!");
10276 // A subtract of one will be selected as a INC. Note that INC doesn't
10277 // set CF, so we can't do this for UADDO.
10278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10280 BaseOp = X86ISD::INC;
10281 Cond = X86::COND_O;
10284 BaseOp = X86ISD::ADD;
10285 Cond = X86::COND_O;
10288 BaseOp = X86ISD::ADD;
10289 Cond = X86::COND_B;
10292 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10293 // set CF, so we can't do this for USUBO.
10294 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10296 BaseOp = X86ISD::DEC;
10297 Cond = X86::COND_O;
10300 BaseOp = X86ISD::SUB;
10301 Cond = X86::COND_O;
10304 BaseOp = X86ISD::SUB;
10305 Cond = X86::COND_B;
10308 BaseOp = X86ISD::SMUL;
10309 Cond = X86::COND_O;
10311 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10312 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10314 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10317 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10318 DAG.getConstant(X86::COND_O, MVT::i32),
10319 SDValue(Sum.getNode(), 2));
10321 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10325 // Also sets EFLAGS.
10326 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10327 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10330 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10331 DAG.getConstant(Cond, MVT::i32),
10332 SDValue(Sum.getNode(), 1));
10334 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10337 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10338 DebugLoc dl = Op.getDebugLoc();
10339 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10340 EVT VT = Op.getValueType();
10342 if (Subtarget->hasXMMInt() && VT.isVector()) {
10343 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10344 ExtraVT.getScalarType().getSizeInBits();
10345 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10347 unsigned SHLIntrinsicsID = 0;
10348 unsigned SRAIntrinsicsID = 0;
10349 switch (VT.getSimpleVT().SimpleTy) {
10353 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10354 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10357 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10358 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10362 if (!Subtarget->hasAVX())
10364 if (!Subtarget->hasAVX2()) {
10365 // needs to be split
10366 int NumElems = VT.getVectorNumElements();
10367 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10368 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10370 // Extract the LHS vectors
10371 SDValue LHS = Op.getOperand(0);
10372 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10373 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10375 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10376 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10378 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10379 int ExtraNumElems = ExtraVT.getVectorNumElements();
10380 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10382 SDValue Extra = DAG.getValueType(ExtraVT);
10384 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10385 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10387 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10389 if (VT == MVT::v8i32) {
10390 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10391 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10393 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10394 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10398 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10399 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10400 Op.getOperand(0), ShAmt);
10402 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10403 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10411 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10412 DebugLoc dl = Op.getDebugLoc();
10414 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10415 // There isn't any reason to disable it if the target processor supports it.
10416 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10417 SDValue Chain = Op.getOperand(0);
10418 SDValue Zero = DAG.getConstant(0, MVT::i32);
10420 DAG.getRegister(X86::ESP, MVT::i32), // Base
10421 DAG.getTargetConstant(1, MVT::i8), // Scale
10422 DAG.getRegister(0, MVT::i32), // Index
10423 DAG.getTargetConstant(0, MVT::i32), // Disp
10424 DAG.getRegister(0, MVT::i32), // Segment.
10429 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10430 array_lengthof(Ops));
10431 return SDValue(Res, 0);
10434 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10436 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10438 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10439 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10440 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10441 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10443 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10444 if (!Op1 && !Op2 && !Op3 && Op4)
10445 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10447 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10448 if (Op1 && !Op2 && !Op3 && !Op4)
10449 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10451 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10453 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10456 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10457 SelectionDAG &DAG) const {
10458 DebugLoc dl = Op.getDebugLoc();
10459 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10460 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10461 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10462 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10464 // The only fence that needs an instruction is a sequentially-consistent
10465 // cross-thread fence.
10466 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10467 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10468 // no-sse2). There isn't any reason to disable it if the target processor
10470 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10471 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10473 SDValue Chain = Op.getOperand(0);
10474 SDValue Zero = DAG.getConstant(0, MVT::i32);
10476 DAG.getRegister(X86::ESP, MVT::i32), // Base
10477 DAG.getTargetConstant(1, MVT::i8), // Scale
10478 DAG.getRegister(0, MVT::i32), // Index
10479 DAG.getTargetConstant(0, MVT::i32), // Disp
10480 DAG.getRegister(0, MVT::i32), // Segment.
10485 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10486 array_lengthof(Ops));
10487 return SDValue(Res, 0);
10490 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10491 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10495 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10496 EVT T = Op.getValueType();
10497 DebugLoc DL = Op.getDebugLoc();
10500 switch(T.getSimpleVT().SimpleTy) {
10502 assert(false && "Invalid value type!");
10503 case MVT::i8: Reg = X86::AL; size = 1; break;
10504 case MVT::i16: Reg = X86::AX; size = 2; break;
10505 case MVT::i32: Reg = X86::EAX; size = 4; break;
10507 assert(Subtarget->is64Bit() && "Node not type legal!");
10508 Reg = X86::RAX; size = 8;
10511 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10512 Op.getOperand(2), SDValue());
10513 SDValue Ops[] = { cpIn.getValue(0),
10516 DAG.getTargetConstant(size, MVT::i8),
10517 cpIn.getValue(1) };
10518 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10519 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10520 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10523 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10527 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10528 SelectionDAG &DAG) const {
10529 assert(Subtarget->is64Bit() && "Result not type legalized?");
10530 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10531 SDValue TheChain = Op.getOperand(0);
10532 DebugLoc dl = Op.getDebugLoc();
10533 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10534 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10535 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10537 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10538 DAG.getConstant(32, MVT::i8));
10540 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10543 return DAG.getMergeValues(Ops, 2, dl);
10546 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10547 SelectionDAG &DAG) const {
10548 EVT SrcVT = Op.getOperand(0).getValueType();
10549 EVT DstVT = Op.getValueType();
10550 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10551 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10552 assert((DstVT == MVT::i64 ||
10553 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10554 "Unexpected custom BITCAST");
10555 // i64 <=> MMX conversions are Legal.
10556 if (SrcVT==MVT::i64 && DstVT.isVector())
10558 if (DstVT==MVT::i64 && SrcVT.isVector())
10560 // MMX <=> MMX conversions are Legal.
10561 if (SrcVT.isVector() && DstVT.isVector())
10563 // All other conversions need to be expanded.
10567 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10568 SDNode *Node = Op.getNode();
10569 DebugLoc dl = Node->getDebugLoc();
10570 EVT T = Node->getValueType(0);
10571 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10572 DAG.getConstant(0, T), Node->getOperand(2));
10573 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10574 cast<AtomicSDNode>(Node)->getMemoryVT(),
10575 Node->getOperand(0),
10576 Node->getOperand(1), negOp,
10577 cast<AtomicSDNode>(Node)->getSrcValue(),
10578 cast<AtomicSDNode>(Node)->getAlignment(),
10579 cast<AtomicSDNode>(Node)->getOrdering(),
10580 cast<AtomicSDNode>(Node)->getSynchScope());
10583 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10584 SDNode *Node = Op.getNode();
10585 DebugLoc dl = Node->getDebugLoc();
10586 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10588 // Convert seq_cst store -> xchg
10589 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10590 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10591 // (The only way to get a 16-byte store is cmpxchg16b)
10592 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10593 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10594 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10595 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10596 cast<AtomicSDNode>(Node)->getMemoryVT(),
10597 Node->getOperand(0),
10598 Node->getOperand(1), Node->getOperand(2),
10599 cast<AtomicSDNode>(Node)->getMemOperand(),
10600 cast<AtomicSDNode>(Node)->getOrdering(),
10601 cast<AtomicSDNode>(Node)->getSynchScope());
10602 return Swap.getValue(1);
10604 // Other atomic stores have a simple pattern.
10608 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10609 EVT VT = Op.getNode()->getValueType(0);
10611 // Let legalize expand this if it isn't a legal type yet.
10612 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10615 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10618 bool ExtraOp = false;
10619 switch (Op.getOpcode()) {
10620 default: assert(0 && "Invalid code");
10621 case ISD::ADDC: Opc = X86ISD::ADD; break;
10622 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10623 case ISD::SUBC: Opc = X86ISD::SUB; break;
10624 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10628 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10630 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10631 Op.getOperand(1), Op.getOperand(2));
10634 /// LowerOperation - Provide custom lowering hooks for some operations.
10636 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10637 switch (Op.getOpcode()) {
10638 default: llvm_unreachable("Should not custom lower this!");
10639 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10640 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10641 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10642 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10643 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10644 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10645 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10646 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10647 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10648 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10649 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10650 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10651 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10652 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10653 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10654 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10655 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10656 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10657 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10658 case ISD::SHL_PARTS:
10659 case ISD::SRA_PARTS:
10660 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10661 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10662 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10663 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10664 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10665 case ISD::FABS: return LowerFABS(Op, DAG);
10666 case ISD::FNEG: return LowerFNEG(Op, DAG);
10667 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10668 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10669 case ISD::SETCC: return LowerSETCC(Op, DAG);
10670 case ISD::SELECT: return LowerSELECT(Op, DAG);
10671 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10672 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10673 case ISD::VASTART: return LowerVASTART(Op, DAG);
10674 case ISD::VAARG: return LowerVAARG(Op, DAG);
10675 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10676 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10677 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10678 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10679 case ISD::FRAME_TO_ARGS_OFFSET:
10680 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10681 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10682 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10683 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10684 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10685 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10686 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10687 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10688 case ISD::MUL: return LowerMUL(Op, DAG);
10691 case ISD::SHL: return LowerShift(Op, DAG);
10697 case ISD::UMULO: return LowerXALUO(Op, DAG);
10698 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10699 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10703 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10704 case ISD::ADD: return LowerADD(Op, DAG);
10705 case ISD::SUB: return LowerSUB(Op, DAG);
10709 static void ReplaceATOMIC_LOAD(SDNode *Node,
10710 SmallVectorImpl<SDValue> &Results,
10711 SelectionDAG &DAG) {
10712 DebugLoc dl = Node->getDebugLoc();
10713 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10715 // Convert wide load -> cmpxchg8b/cmpxchg16b
10716 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10717 // (The only way to get a 16-byte load is cmpxchg16b)
10718 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10719 SDValue Zero = DAG.getConstant(0, VT);
10720 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10721 Node->getOperand(0),
10722 Node->getOperand(1), Zero, Zero,
10723 cast<AtomicSDNode>(Node)->getMemOperand(),
10724 cast<AtomicSDNode>(Node)->getOrdering(),
10725 cast<AtomicSDNode>(Node)->getSynchScope());
10726 Results.push_back(Swap.getValue(0));
10727 Results.push_back(Swap.getValue(1));
10730 void X86TargetLowering::
10731 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10732 SelectionDAG &DAG, unsigned NewOp) const {
10733 DebugLoc dl = Node->getDebugLoc();
10734 assert (Node->getValueType(0) == MVT::i64 &&
10735 "Only know how to expand i64 atomics");
10737 SDValue Chain = Node->getOperand(0);
10738 SDValue In1 = Node->getOperand(1);
10739 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10740 Node->getOperand(2), DAG.getIntPtrConstant(0));
10741 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10742 Node->getOperand(2), DAG.getIntPtrConstant(1));
10743 SDValue Ops[] = { Chain, In1, In2L, In2H };
10744 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10746 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10747 cast<MemSDNode>(Node)->getMemOperand());
10748 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10749 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10750 Results.push_back(Result.getValue(2));
10753 /// ReplaceNodeResults - Replace a node with an illegal result type
10754 /// with a new node built out of custom code.
10755 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10756 SmallVectorImpl<SDValue>&Results,
10757 SelectionDAG &DAG) const {
10758 DebugLoc dl = N->getDebugLoc();
10759 switch (N->getOpcode()) {
10761 assert(false && "Do not know how to custom type legalize this operation!");
10763 case ISD::SIGN_EXTEND_INREG:
10768 // We don't want to expand or promote these.
10770 case ISD::FP_TO_SINT: {
10771 std::pair<SDValue,SDValue> Vals =
10772 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10773 SDValue FIST = Vals.first, StackSlot = Vals.second;
10774 if (FIST.getNode() != 0) {
10775 EVT VT = N->getValueType(0);
10776 // Return a load from the stack slot.
10777 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10778 MachinePointerInfo(),
10779 false, false, false, 0));
10783 case ISD::READCYCLECOUNTER: {
10784 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10785 SDValue TheChain = N->getOperand(0);
10786 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10787 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10789 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10791 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10792 SDValue Ops[] = { eax, edx };
10793 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10794 Results.push_back(edx.getValue(1));
10797 case ISD::ATOMIC_CMP_SWAP: {
10798 EVT T = N->getValueType(0);
10799 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10800 bool Regs64bit = T == MVT::i128;
10801 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10802 SDValue cpInL, cpInH;
10803 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10804 DAG.getConstant(0, HalfT));
10805 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10806 DAG.getConstant(1, HalfT));
10807 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10808 Regs64bit ? X86::RAX : X86::EAX,
10810 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10811 Regs64bit ? X86::RDX : X86::EDX,
10812 cpInH, cpInL.getValue(1));
10813 SDValue swapInL, swapInH;
10814 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10815 DAG.getConstant(0, HalfT));
10816 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10817 DAG.getConstant(1, HalfT));
10818 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10819 Regs64bit ? X86::RBX : X86::EBX,
10820 swapInL, cpInH.getValue(1));
10821 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10822 Regs64bit ? X86::RCX : X86::ECX,
10823 swapInH, swapInL.getValue(1));
10824 SDValue Ops[] = { swapInH.getValue(0),
10826 swapInH.getValue(1) };
10827 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10828 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10829 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10830 X86ISD::LCMPXCHG8_DAG;
10831 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10833 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10834 Regs64bit ? X86::RAX : X86::EAX,
10835 HalfT, Result.getValue(1));
10836 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10837 Regs64bit ? X86::RDX : X86::EDX,
10838 HalfT, cpOutL.getValue(2));
10839 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10840 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10841 Results.push_back(cpOutH.getValue(1));
10844 case ISD::ATOMIC_LOAD_ADD:
10845 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10847 case ISD::ATOMIC_LOAD_AND:
10848 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10850 case ISD::ATOMIC_LOAD_NAND:
10851 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10853 case ISD::ATOMIC_LOAD_OR:
10854 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10856 case ISD::ATOMIC_LOAD_SUB:
10857 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10859 case ISD::ATOMIC_LOAD_XOR:
10860 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10862 case ISD::ATOMIC_SWAP:
10863 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10865 case ISD::ATOMIC_LOAD:
10866 ReplaceATOMIC_LOAD(N, Results, DAG);
10870 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10872 default: return NULL;
10873 case X86ISD::BSF: return "X86ISD::BSF";
10874 case X86ISD::BSR: return "X86ISD::BSR";
10875 case X86ISD::SHLD: return "X86ISD::SHLD";
10876 case X86ISD::SHRD: return "X86ISD::SHRD";
10877 case X86ISD::FAND: return "X86ISD::FAND";
10878 case X86ISD::FOR: return "X86ISD::FOR";
10879 case X86ISD::FXOR: return "X86ISD::FXOR";
10880 case X86ISD::FSRL: return "X86ISD::FSRL";
10881 case X86ISD::FILD: return "X86ISD::FILD";
10882 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10883 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10884 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10885 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10886 case X86ISD::FLD: return "X86ISD::FLD";
10887 case X86ISD::FST: return "X86ISD::FST";
10888 case X86ISD::CALL: return "X86ISD::CALL";
10889 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10890 case X86ISD::BT: return "X86ISD::BT";
10891 case X86ISD::CMP: return "X86ISD::CMP";
10892 case X86ISD::COMI: return "X86ISD::COMI";
10893 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10894 case X86ISD::SETCC: return "X86ISD::SETCC";
10895 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10896 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10897 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10898 case X86ISD::CMOV: return "X86ISD::CMOV";
10899 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10900 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10901 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10902 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10903 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10904 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10905 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10906 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10907 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10908 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10909 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10910 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10911 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10912 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10913 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10914 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10915 case X86ISD::HADD: return "X86ISD::HADD";
10916 case X86ISD::HSUB: return "X86ISD::HSUB";
10917 case X86ISD::FHADD: return "X86ISD::FHADD";
10918 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10919 case X86ISD::FMAX: return "X86ISD::FMAX";
10920 case X86ISD::FMIN: return "X86ISD::FMIN";
10921 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10922 case X86ISD::FRCP: return "X86ISD::FRCP";
10923 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10924 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10925 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10926 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10927 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10928 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10929 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10930 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10931 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10932 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10933 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10934 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10935 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10936 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10937 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10938 case X86ISD::VSHL: return "X86ISD::VSHL";
10939 case X86ISD::VSRL: return "X86ISD::VSRL";
10940 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10941 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10942 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10943 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10944 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10945 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10946 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10947 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10948 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10949 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10950 case X86ISD::ADD: return "X86ISD::ADD";
10951 case X86ISD::SUB: return "X86ISD::SUB";
10952 case X86ISD::ADC: return "X86ISD::ADC";
10953 case X86ISD::SBB: return "X86ISD::SBB";
10954 case X86ISD::SMUL: return "X86ISD::SMUL";
10955 case X86ISD::UMUL: return "X86ISD::UMUL";
10956 case X86ISD::INC: return "X86ISD::INC";
10957 case X86ISD::DEC: return "X86ISD::DEC";
10958 case X86ISD::OR: return "X86ISD::OR";
10959 case X86ISD::XOR: return "X86ISD::XOR";
10960 case X86ISD::AND: return "X86ISD::AND";
10961 case X86ISD::ANDN: return "X86ISD::ANDN";
10962 case X86ISD::BLSI: return "X86ISD::BLSI";
10963 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
10964 case X86ISD::BLSR: return "X86ISD::BLSR";
10965 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10966 case X86ISD::PTEST: return "X86ISD::PTEST";
10967 case X86ISD::TESTP: return "X86ISD::TESTP";
10968 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10969 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10970 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10971 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10972 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10973 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10974 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10975 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10976 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10977 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10978 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10979 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10980 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10981 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10982 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10983 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10984 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10985 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10986 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10987 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10988 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
10989 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
10990 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10991 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
10992 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
10993 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10994 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10995 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10996 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10997 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11001 // isLegalAddressingMode - Return true if the addressing mode represented
11002 // by AM is legal for this target, for a load/store of the specified type.
11003 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11005 // X86 supports extremely general addressing modes.
11006 CodeModel::Model M = getTargetMachine().getCodeModel();
11007 Reloc::Model R = getTargetMachine().getRelocationModel();
11009 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11010 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11015 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11017 // If a reference to this global requires an extra load, we can't fold it.
11018 if (isGlobalStubReference(GVFlags))
11021 // If BaseGV requires a register for the PIC base, we cannot also have a
11022 // BaseReg specified.
11023 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11026 // If lower 4G is not available, then we must use rip-relative addressing.
11027 if ((M != CodeModel::Small || R != Reloc::Static) &&
11028 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11032 switch (AM.Scale) {
11038 // These scales always work.
11043 // These scales are formed with basereg+scalereg. Only accept if there is
11048 default: // Other stuff never works.
11056 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11057 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11059 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11060 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11061 if (NumBits1 <= NumBits2)
11066 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11067 if (!VT1.isInteger() || !VT2.isInteger())
11069 unsigned NumBits1 = VT1.getSizeInBits();
11070 unsigned NumBits2 = VT2.getSizeInBits();
11071 if (NumBits1 <= NumBits2)
11076 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11077 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11078 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11081 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11082 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11083 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11086 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11087 // i16 instructions are longer (0x66 prefix) and potentially slower.
11088 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11091 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11092 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11093 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11094 /// are assumed to be legal.
11096 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11098 // Very little shuffling can be done for 64-bit vectors right now.
11099 if (VT.getSizeInBits() == 64)
11102 // FIXME: pshufb, blends, shifts.
11103 return (VT.getVectorNumElements() == 2 ||
11104 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11105 isMOVLMask(M, VT) ||
11106 isSHUFPMask(M, VT) ||
11107 isPSHUFDMask(M, VT) ||
11108 isPSHUFHWMask(M, VT) ||
11109 isPSHUFLWMask(M, VT) ||
11110 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11111 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11112 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11113 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11114 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11118 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11120 unsigned NumElts = VT.getVectorNumElements();
11121 // FIXME: This collection of masks seems suspect.
11124 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11125 return (isMOVLMask(Mask, VT) ||
11126 isCommutedMOVLMask(Mask, VT, true) ||
11127 isSHUFPMask(Mask, VT) ||
11128 isSHUFPMask(Mask, VT, /* Commuted */ true));
11133 //===----------------------------------------------------------------------===//
11134 // X86 Scheduler Hooks
11135 //===----------------------------------------------------------------------===//
11137 // private utility function
11138 MachineBasicBlock *
11139 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11140 MachineBasicBlock *MBB,
11147 TargetRegisterClass *RC,
11148 bool invSrc) const {
11149 // For the atomic bitwise operator, we generate
11152 // ld t1 = [bitinstr.addr]
11153 // op t2 = t1, [bitinstr.val]
11155 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11157 // fallthrough -->nextMBB
11158 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11159 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11160 MachineFunction::iterator MBBIter = MBB;
11163 /// First build the CFG
11164 MachineFunction *F = MBB->getParent();
11165 MachineBasicBlock *thisMBB = MBB;
11166 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11168 F->insert(MBBIter, newMBB);
11169 F->insert(MBBIter, nextMBB);
11171 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11172 nextMBB->splice(nextMBB->begin(), thisMBB,
11173 llvm::next(MachineBasicBlock::iterator(bInstr)),
11175 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11177 // Update thisMBB to fall through to newMBB
11178 thisMBB->addSuccessor(newMBB);
11180 // newMBB jumps to itself and fall through to nextMBB
11181 newMBB->addSuccessor(nextMBB);
11182 newMBB->addSuccessor(newMBB);
11184 // Insert instructions into newMBB based on incoming instruction
11185 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11186 "unexpected number of operands");
11187 DebugLoc dl = bInstr->getDebugLoc();
11188 MachineOperand& destOper = bInstr->getOperand(0);
11189 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11190 int numArgs = bInstr->getNumOperands() - 1;
11191 for (int i=0; i < numArgs; ++i)
11192 argOpers[i] = &bInstr->getOperand(i+1);
11194 // x86 address has 4 operands: base, index, scale, and displacement
11195 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11196 int valArgIndx = lastAddrIndx + 1;
11198 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11199 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11200 for (int i=0; i <= lastAddrIndx; ++i)
11201 (*MIB).addOperand(*argOpers[i]);
11203 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11205 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11210 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11211 assert((argOpers[valArgIndx]->isReg() ||
11212 argOpers[valArgIndx]->isImm()) &&
11213 "invalid operand");
11214 if (argOpers[valArgIndx]->isReg())
11215 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11217 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11219 (*MIB).addOperand(*argOpers[valArgIndx]);
11221 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11224 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11225 for (int i=0; i <= lastAddrIndx; ++i)
11226 (*MIB).addOperand(*argOpers[i]);
11228 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11229 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11230 bInstr->memoperands_end());
11232 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11233 MIB.addReg(EAXreg);
11236 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11238 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11242 // private utility function: 64 bit atomics on 32 bit host.
11243 MachineBasicBlock *
11244 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11245 MachineBasicBlock *MBB,
11250 bool invSrc) const {
11251 // For the atomic bitwise operator, we generate
11252 // thisMBB (instructions are in pairs, except cmpxchg8b)
11253 // ld t1,t2 = [bitinstr.addr]
11255 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11256 // op t5, t6 <- out1, out2, [bitinstr.val]
11257 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11258 // mov ECX, EBX <- t5, t6
11259 // mov EAX, EDX <- t1, t2
11260 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11261 // mov t3, t4 <- EAX, EDX
11263 // result in out1, out2
11264 // fallthrough -->nextMBB
11266 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11267 const unsigned LoadOpc = X86::MOV32rm;
11268 const unsigned NotOpc = X86::NOT32r;
11269 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11270 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11271 MachineFunction::iterator MBBIter = MBB;
11274 /// First build the CFG
11275 MachineFunction *F = MBB->getParent();
11276 MachineBasicBlock *thisMBB = MBB;
11277 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11278 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11279 F->insert(MBBIter, newMBB);
11280 F->insert(MBBIter, nextMBB);
11282 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11283 nextMBB->splice(nextMBB->begin(), thisMBB,
11284 llvm::next(MachineBasicBlock::iterator(bInstr)),
11286 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11288 // Update thisMBB to fall through to newMBB
11289 thisMBB->addSuccessor(newMBB);
11291 // newMBB jumps to itself and fall through to nextMBB
11292 newMBB->addSuccessor(nextMBB);
11293 newMBB->addSuccessor(newMBB);
11295 DebugLoc dl = bInstr->getDebugLoc();
11296 // Insert instructions into newMBB based on incoming instruction
11297 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11298 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11299 "unexpected number of operands");
11300 MachineOperand& dest1Oper = bInstr->getOperand(0);
11301 MachineOperand& dest2Oper = bInstr->getOperand(1);
11302 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11303 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11304 argOpers[i] = &bInstr->getOperand(i+2);
11306 // We use some of the operands multiple times, so conservatively just
11307 // clear any kill flags that might be present.
11308 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11309 argOpers[i]->setIsKill(false);
11312 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11313 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11315 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11316 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11317 for (int i=0; i <= lastAddrIndx; ++i)
11318 (*MIB).addOperand(*argOpers[i]);
11319 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11320 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11321 // add 4 to displacement.
11322 for (int i=0; i <= lastAddrIndx-2; ++i)
11323 (*MIB).addOperand(*argOpers[i]);
11324 MachineOperand newOp3 = *(argOpers[3]);
11325 if (newOp3.isImm())
11326 newOp3.setImm(newOp3.getImm()+4);
11328 newOp3.setOffset(newOp3.getOffset()+4);
11329 (*MIB).addOperand(newOp3);
11330 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11332 // t3/4 are defined later, at the bottom of the loop
11333 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11334 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11335 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11336 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11337 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11338 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11340 // The subsequent operations should be using the destination registers of
11341 //the PHI instructions.
11343 t1 = F->getRegInfo().createVirtualRegister(RC);
11344 t2 = F->getRegInfo().createVirtualRegister(RC);
11345 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11346 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11348 t1 = dest1Oper.getReg();
11349 t2 = dest2Oper.getReg();
11352 int valArgIndx = lastAddrIndx + 1;
11353 assert((argOpers[valArgIndx]->isReg() ||
11354 argOpers[valArgIndx]->isImm()) &&
11355 "invalid operand");
11356 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11357 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11358 if (argOpers[valArgIndx]->isReg())
11359 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11361 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11362 if (regOpcL != X86::MOV32rr)
11364 (*MIB).addOperand(*argOpers[valArgIndx]);
11365 assert(argOpers[valArgIndx + 1]->isReg() ==
11366 argOpers[valArgIndx]->isReg());
11367 assert(argOpers[valArgIndx + 1]->isImm() ==
11368 argOpers[valArgIndx]->isImm());
11369 if (argOpers[valArgIndx + 1]->isReg())
11370 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11372 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11373 if (regOpcH != X86::MOV32rr)
11375 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11377 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11379 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11382 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11384 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11387 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11388 for (int i=0; i <= lastAddrIndx; ++i)
11389 (*MIB).addOperand(*argOpers[i]);
11391 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11392 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11393 bInstr->memoperands_end());
11395 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11396 MIB.addReg(X86::EAX);
11397 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11398 MIB.addReg(X86::EDX);
11401 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11403 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11407 // private utility function
11408 MachineBasicBlock *
11409 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11410 MachineBasicBlock *MBB,
11411 unsigned cmovOpc) const {
11412 // For the atomic min/max operator, we generate
11415 // ld t1 = [min/max.addr]
11416 // mov t2 = [min/max.val]
11418 // cmov[cond] t2 = t1
11420 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11422 // fallthrough -->nextMBB
11424 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11425 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11426 MachineFunction::iterator MBBIter = MBB;
11429 /// First build the CFG
11430 MachineFunction *F = MBB->getParent();
11431 MachineBasicBlock *thisMBB = MBB;
11432 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11433 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11434 F->insert(MBBIter, newMBB);
11435 F->insert(MBBIter, nextMBB);
11437 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11438 nextMBB->splice(nextMBB->begin(), thisMBB,
11439 llvm::next(MachineBasicBlock::iterator(mInstr)),
11441 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11443 // Update thisMBB to fall through to newMBB
11444 thisMBB->addSuccessor(newMBB);
11446 // newMBB jumps to newMBB and fall through to nextMBB
11447 newMBB->addSuccessor(nextMBB);
11448 newMBB->addSuccessor(newMBB);
11450 DebugLoc dl = mInstr->getDebugLoc();
11451 // Insert instructions into newMBB based on incoming instruction
11452 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11453 "unexpected number of operands");
11454 MachineOperand& destOper = mInstr->getOperand(0);
11455 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11456 int numArgs = mInstr->getNumOperands() - 1;
11457 for (int i=0; i < numArgs; ++i)
11458 argOpers[i] = &mInstr->getOperand(i+1);
11460 // x86 address has 4 operands: base, index, scale, and displacement
11461 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11462 int valArgIndx = lastAddrIndx + 1;
11464 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11465 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11466 for (int i=0; i <= lastAddrIndx; ++i)
11467 (*MIB).addOperand(*argOpers[i]);
11469 // We only support register and immediate values
11470 assert((argOpers[valArgIndx]->isReg() ||
11471 argOpers[valArgIndx]->isImm()) &&
11472 "invalid operand");
11474 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11475 if (argOpers[valArgIndx]->isReg())
11476 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11478 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11479 (*MIB).addOperand(*argOpers[valArgIndx]);
11481 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11484 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11489 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11490 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11494 // Cmp and exchange if none has modified the memory location
11495 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11496 for (int i=0; i <= lastAddrIndx; ++i)
11497 (*MIB).addOperand(*argOpers[i]);
11499 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11500 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11501 mInstr->memoperands_end());
11503 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11504 MIB.addReg(X86::EAX);
11507 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11509 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11513 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11514 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11515 // in the .td file.
11516 MachineBasicBlock *
11517 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11518 unsigned numArgs, bool memArg) const {
11519 assert(Subtarget->hasSSE42orAVX() &&
11520 "Target must have SSE4.2 or AVX features enabled");
11522 DebugLoc dl = MI->getDebugLoc();
11523 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11525 if (!Subtarget->hasAVX()) {
11527 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11529 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11532 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11534 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11537 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11538 for (unsigned i = 0; i < numArgs; ++i) {
11539 MachineOperand &Op = MI->getOperand(i+1);
11540 if (!(Op.isReg() && Op.isImplicit()))
11541 MIB.addOperand(Op);
11543 BuildMI(*BB, MI, dl,
11544 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11545 MI->getOperand(0).getReg())
11546 .addReg(X86::XMM0);
11548 MI->eraseFromParent();
11552 MachineBasicBlock *
11553 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11554 DebugLoc dl = MI->getDebugLoc();
11555 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11557 // Address into RAX/EAX, other two args into ECX, EDX.
11558 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11559 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11560 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11561 for (int i = 0; i < X86::AddrNumOperands; ++i)
11562 MIB.addOperand(MI->getOperand(i));
11564 unsigned ValOps = X86::AddrNumOperands;
11565 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11566 .addReg(MI->getOperand(ValOps).getReg());
11567 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11568 .addReg(MI->getOperand(ValOps+1).getReg());
11570 // The instruction doesn't actually take any operands though.
11571 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11573 MI->eraseFromParent(); // The pseudo is gone now.
11577 MachineBasicBlock *
11578 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11579 DebugLoc dl = MI->getDebugLoc();
11580 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11582 // First arg in ECX, the second in EAX.
11583 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11584 .addReg(MI->getOperand(0).getReg());
11585 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11586 .addReg(MI->getOperand(1).getReg());
11588 // The instruction doesn't actually take any operands though.
11589 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11591 MI->eraseFromParent(); // The pseudo is gone now.
11595 MachineBasicBlock *
11596 X86TargetLowering::EmitVAARG64WithCustomInserter(
11598 MachineBasicBlock *MBB) const {
11599 // Emit va_arg instruction on X86-64.
11601 // Operands to this pseudo-instruction:
11602 // 0 ) Output : destination address (reg)
11603 // 1-5) Input : va_list address (addr, i64mem)
11604 // 6 ) ArgSize : Size (in bytes) of vararg type
11605 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11606 // 8 ) Align : Alignment of type
11607 // 9 ) EFLAGS (implicit-def)
11609 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11610 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11612 unsigned DestReg = MI->getOperand(0).getReg();
11613 MachineOperand &Base = MI->getOperand(1);
11614 MachineOperand &Scale = MI->getOperand(2);
11615 MachineOperand &Index = MI->getOperand(3);
11616 MachineOperand &Disp = MI->getOperand(4);
11617 MachineOperand &Segment = MI->getOperand(5);
11618 unsigned ArgSize = MI->getOperand(6).getImm();
11619 unsigned ArgMode = MI->getOperand(7).getImm();
11620 unsigned Align = MI->getOperand(8).getImm();
11622 // Memory Reference
11623 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11624 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11625 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11627 // Machine Information
11628 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11629 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11630 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11631 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11632 DebugLoc DL = MI->getDebugLoc();
11634 // struct va_list {
11637 // i64 overflow_area (address)
11638 // i64 reg_save_area (address)
11640 // sizeof(va_list) = 24
11641 // alignment(va_list) = 8
11643 unsigned TotalNumIntRegs = 6;
11644 unsigned TotalNumXMMRegs = 8;
11645 bool UseGPOffset = (ArgMode == 1);
11646 bool UseFPOffset = (ArgMode == 2);
11647 unsigned MaxOffset = TotalNumIntRegs * 8 +
11648 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11650 /* Align ArgSize to a multiple of 8 */
11651 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11652 bool NeedsAlign = (Align > 8);
11654 MachineBasicBlock *thisMBB = MBB;
11655 MachineBasicBlock *overflowMBB;
11656 MachineBasicBlock *offsetMBB;
11657 MachineBasicBlock *endMBB;
11659 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11660 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11661 unsigned OffsetReg = 0;
11663 if (!UseGPOffset && !UseFPOffset) {
11664 // If we only pull from the overflow region, we don't create a branch.
11665 // We don't need to alter control flow.
11666 OffsetDestReg = 0; // unused
11667 OverflowDestReg = DestReg;
11670 overflowMBB = thisMBB;
11673 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11674 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11675 // If not, pull from overflow_area. (branch to overflowMBB)
11680 // offsetMBB overflowMBB
11685 // Registers for the PHI in endMBB
11686 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11687 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11689 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11690 MachineFunction *MF = MBB->getParent();
11691 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11692 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11693 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11695 MachineFunction::iterator MBBIter = MBB;
11698 // Insert the new basic blocks
11699 MF->insert(MBBIter, offsetMBB);
11700 MF->insert(MBBIter, overflowMBB);
11701 MF->insert(MBBIter, endMBB);
11703 // Transfer the remainder of MBB and its successor edges to endMBB.
11704 endMBB->splice(endMBB->begin(), thisMBB,
11705 llvm::next(MachineBasicBlock::iterator(MI)),
11707 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11709 // Make offsetMBB and overflowMBB successors of thisMBB
11710 thisMBB->addSuccessor(offsetMBB);
11711 thisMBB->addSuccessor(overflowMBB);
11713 // endMBB is a successor of both offsetMBB and overflowMBB
11714 offsetMBB->addSuccessor(endMBB);
11715 overflowMBB->addSuccessor(endMBB);
11717 // Load the offset value into a register
11718 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11719 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11723 .addDisp(Disp, UseFPOffset ? 4 : 0)
11724 .addOperand(Segment)
11725 .setMemRefs(MMOBegin, MMOEnd);
11727 // Check if there is enough room left to pull this argument.
11728 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11730 .addImm(MaxOffset + 8 - ArgSizeA8);
11732 // Branch to "overflowMBB" if offset >= max
11733 // Fall through to "offsetMBB" otherwise
11734 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11735 .addMBB(overflowMBB);
11738 // In offsetMBB, emit code to use the reg_save_area.
11740 assert(OffsetReg != 0);
11742 // Read the reg_save_area address.
11743 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11744 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11749 .addOperand(Segment)
11750 .setMemRefs(MMOBegin, MMOEnd);
11752 // Zero-extend the offset
11753 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11754 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11757 .addImm(X86::sub_32bit);
11759 // Add the offset to the reg_save_area to get the final address.
11760 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11761 .addReg(OffsetReg64)
11762 .addReg(RegSaveReg);
11764 // Compute the offset for the next argument
11765 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11766 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11768 .addImm(UseFPOffset ? 16 : 8);
11770 // Store it back into the va_list.
11771 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11775 .addDisp(Disp, UseFPOffset ? 4 : 0)
11776 .addOperand(Segment)
11777 .addReg(NextOffsetReg)
11778 .setMemRefs(MMOBegin, MMOEnd);
11781 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11786 // Emit code to use overflow area
11789 // Load the overflow_area address into a register.
11790 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11791 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11796 .addOperand(Segment)
11797 .setMemRefs(MMOBegin, MMOEnd);
11799 // If we need to align it, do so. Otherwise, just copy the address
11800 // to OverflowDestReg.
11802 // Align the overflow address
11803 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11804 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11806 // aligned_addr = (addr + (align-1)) & ~(align-1)
11807 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11808 .addReg(OverflowAddrReg)
11811 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11813 .addImm(~(uint64_t)(Align-1));
11815 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11816 .addReg(OverflowAddrReg);
11819 // Compute the next overflow address after this argument.
11820 // (the overflow address should be kept 8-byte aligned)
11821 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11822 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11823 .addReg(OverflowDestReg)
11824 .addImm(ArgSizeA8);
11826 // Store the new overflow address.
11827 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11832 .addOperand(Segment)
11833 .addReg(NextAddrReg)
11834 .setMemRefs(MMOBegin, MMOEnd);
11836 // If we branched, emit the PHI to the front of endMBB.
11838 BuildMI(*endMBB, endMBB->begin(), DL,
11839 TII->get(X86::PHI), DestReg)
11840 .addReg(OffsetDestReg).addMBB(offsetMBB)
11841 .addReg(OverflowDestReg).addMBB(overflowMBB);
11844 // Erase the pseudo instruction
11845 MI->eraseFromParent();
11850 MachineBasicBlock *
11851 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11853 MachineBasicBlock *MBB) const {
11854 // Emit code to save XMM registers to the stack. The ABI says that the
11855 // number of registers to save is given in %al, so it's theoretically
11856 // possible to do an indirect jump trick to avoid saving all of them,
11857 // however this code takes a simpler approach and just executes all
11858 // of the stores if %al is non-zero. It's less code, and it's probably
11859 // easier on the hardware branch predictor, and stores aren't all that
11860 // expensive anyway.
11862 // Create the new basic blocks. One block contains all the XMM stores,
11863 // and one block is the final destination regardless of whether any
11864 // stores were performed.
11865 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11866 MachineFunction *F = MBB->getParent();
11867 MachineFunction::iterator MBBIter = MBB;
11869 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11870 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11871 F->insert(MBBIter, XMMSaveMBB);
11872 F->insert(MBBIter, EndMBB);
11874 // Transfer the remainder of MBB and its successor edges to EndMBB.
11875 EndMBB->splice(EndMBB->begin(), MBB,
11876 llvm::next(MachineBasicBlock::iterator(MI)),
11878 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11880 // The original block will now fall through to the XMM save block.
11881 MBB->addSuccessor(XMMSaveMBB);
11882 // The XMMSaveMBB will fall through to the end block.
11883 XMMSaveMBB->addSuccessor(EndMBB);
11885 // Now add the instructions.
11886 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887 DebugLoc DL = MI->getDebugLoc();
11889 unsigned CountReg = MI->getOperand(0).getReg();
11890 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11891 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11893 if (!Subtarget->isTargetWin64()) {
11894 // If %al is 0, branch around the XMM save block.
11895 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11896 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11897 MBB->addSuccessor(EndMBB);
11900 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11901 // In the XMM save block, save all the XMM argument registers.
11902 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11903 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11904 MachineMemOperand *MMO =
11905 F->getMachineMemOperand(
11906 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11907 MachineMemOperand::MOStore,
11908 /*Size=*/16, /*Align=*/16);
11909 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11910 .addFrameIndex(RegSaveFrameIndex)
11911 .addImm(/*Scale=*/1)
11912 .addReg(/*IndexReg=*/0)
11913 .addImm(/*Disp=*/Offset)
11914 .addReg(/*Segment=*/0)
11915 .addReg(MI->getOperand(i).getReg())
11916 .addMemOperand(MMO);
11919 MI->eraseFromParent(); // The pseudo instruction is gone now.
11924 MachineBasicBlock *
11925 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11926 MachineBasicBlock *BB) const {
11927 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11928 DebugLoc DL = MI->getDebugLoc();
11930 // To "insert" a SELECT_CC instruction, we actually have to insert the
11931 // diamond control-flow pattern. The incoming instruction knows the
11932 // destination vreg to set, the condition code register to branch on, the
11933 // true/false values to select between, and a branch opcode to use.
11934 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11935 MachineFunction::iterator It = BB;
11941 // cmpTY ccX, r1, r2
11943 // fallthrough --> copy0MBB
11944 MachineBasicBlock *thisMBB = BB;
11945 MachineFunction *F = BB->getParent();
11946 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11947 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11948 F->insert(It, copy0MBB);
11949 F->insert(It, sinkMBB);
11951 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11952 // live into the sink and copy blocks.
11953 if (!MI->killsRegister(X86::EFLAGS)) {
11954 copy0MBB->addLiveIn(X86::EFLAGS);
11955 sinkMBB->addLiveIn(X86::EFLAGS);
11958 // Transfer the remainder of BB and its successor edges to sinkMBB.
11959 sinkMBB->splice(sinkMBB->begin(), BB,
11960 llvm::next(MachineBasicBlock::iterator(MI)),
11962 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11964 // Add the true and fallthrough blocks as its successors.
11965 BB->addSuccessor(copy0MBB);
11966 BB->addSuccessor(sinkMBB);
11968 // Create the conditional branch instruction.
11970 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11971 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11974 // %FalseValue = ...
11975 // # fallthrough to sinkMBB
11976 copy0MBB->addSuccessor(sinkMBB);
11979 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11981 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11982 TII->get(X86::PHI), MI->getOperand(0).getReg())
11983 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11984 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11986 MI->eraseFromParent(); // The pseudo instruction is gone now.
11990 MachineBasicBlock *
11991 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11992 bool Is64Bit) const {
11993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11994 DebugLoc DL = MI->getDebugLoc();
11995 MachineFunction *MF = BB->getParent();
11996 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11998 assert(getTargetMachine().Options.EnableSegmentedStacks);
12000 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12001 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12004 // ... [Till the alloca]
12005 // If stacklet is not large enough, jump to mallocMBB
12008 // Allocate by subtracting from RSP
12009 // Jump to continueMBB
12012 // Allocate by call to runtime
12016 // [rest of original BB]
12019 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12020 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12021 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12023 MachineRegisterInfo &MRI = MF->getRegInfo();
12024 const TargetRegisterClass *AddrRegClass =
12025 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12027 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12028 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12029 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12030 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12031 sizeVReg = MI->getOperand(1).getReg(),
12032 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12034 MachineFunction::iterator MBBIter = BB;
12037 MF->insert(MBBIter, bumpMBB);
12038 MF->insert(MBBIter, mallocMBB);
12039 MF->insert(MBBIter, continueMBB);
12041 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12042 (MachineBasicBlock::iterator(MI)), BB->end());
12043 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12045 // Add code to the main basic block to check if the stack limit has been hit,
12046 // and if so, jump to mallocMBB otherwise to bumpMBB.
12047 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12048 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12049 .addReg(tmpSPVReg).addReg(sizeVReg);
12050 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12051 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12052 .addReg(SPLimitVReg);
12053 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12055 // bumpMBB simply decreases the stack pointer, since we know the current
12056 // stacklet has enough space.
12057 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12058 .addReg(SPLimitVReg);
12059 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12060 .addReg(SPLimitVReg);
12061 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12063 // Calls into a routine in libgcc to allocate more space from the heap.
12065 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12067 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12068 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12070 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12072 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12073 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12074 .addExternalSymbol("__morestack_allocate_stack_space");
12078 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12081 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12082 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12083 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12085 // Set up the CFG correctly.
12086 BB->addSuccessor(bumpMBB);
12087 BB->addSuccessor(mallocMBB);
12088 mallocMBB->addSuccessor(continueMBB);
12089 bumpMBB->addSuccessor(continueMBB);
12091 // Take care of the PHI nodes.
12092 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12093 MI->getOperand(0).getReg())
12094 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12095 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12097 // Delete the original pseudo instruction.
12098 MI->eraseFromParent();
12101 return continueMBB;
12104 MachineBasicBlock *
12105 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12106 MachineBasicBlock *BB) const {
12107 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12108 DebugLoc DL = MI->getDebugLoc();
12110 assert(!Subtarget->isTargetEnvMacho());
12112 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12113 // non-trivial part is impdef of ESP.
12115 if (Subtarget->isTargetWin64()) {
12116 if (Subtarget->isTargetCygMing()) {
12117 // ___chkstk(Mingw64):
12118 // Clobbers R10, R11, RAX and EFLAGS.
12120 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12121 .addExternalSymbol("___chkstk")
12122 .addReg(X86::RAX, RegState::Implicit)
12123 .addReg(X86::RSP, RegState::Implicit)
12124 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12125 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12126 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12128 // __chkstk(MSVCRT): does not update stack pointer.
12129 // Clobbers R10, R11 and EFLAGS.
12130 // FIXME: RAX(allocated size) might be reused and not killed.
12131 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12132 .addExternalSymbol("__chkstk")
12133 .addReg(X86::RAX, RegState::Implicit)
12134 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12135 // RAX has the offset to subtracted from RSP.
12136 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12141 const char *StackProbeSymbol =
12142 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12144 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12145 .addExternalSymbol(StackProbeSymbol)
12146 .addReg(X86::EAX, RegState::Implicit)
12147 .addReg(X86::ESP, RegState::Implicit)
12148 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12149 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12150 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12153 MI->eraseFromParent(); // The pseudo instruction is gone now.
12157 MachineBasicBlock *
12158 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12159 MachineBasicBlock *BB) const {
12160 // This is pretty easy. We're taking the value that we received from
12161 // our load from the relocation, sticking it in either RDI (x86-64)
12162 // or EAX and doing an indirect call. The return value will then
12163 // be in the normal return register.
12164 const X86InstrInfo *TII
12165 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12166 DebugLoc DL = MI->getDebugLoc();
12167 MachineFunction *F = BB->getParent();
12169 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12170 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12172 if (Subtarget->is64Bit()) {
12173 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12174 TII->get(X86::MOV64rm), X86::RDI)
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::CALL64m));
12181 addDirectMem(MIB, X86::RDI);
12182 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12183 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12184 TII->get(X86::MOV32rm), X86::EAX)
12186 .addImm(0).addReg(0)
12187 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12188 MI->getOperand(3).getTargetFlags())
12190 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12191 addDirectMem(MIB, X86::EAX);
12193 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12194 TII->get(X86::MOV32rm), X86::EAX)
12195 .addReg(TII->getGlobalBaseReg(F))
12196 .addImm(0).addReg(0)
12197 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12198 MI->getOperand(3).getTargetFlags())
12200 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12201 addDirectMem(MIB, X86::EAX);
12204 MI->eraseFromParent(); // The pseudo instruction is gone now.
12208 MachineBasicBlock *
12209 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12210 MachineBasicBlock *BB) const {
12211 switch (MI->getOpcode()) {
12212 default: assert(0 && "Unexpected instr type to insert");
12213 case X86::TAILJMPd64:
12214 case X86::TAILJMPr64:
12215 case X86::TAILJMPm64:
12216 assert(0 && "TAILJMP64 would not be touched here.");
12217 case X86::TCRETURNdi64:
12218 case X86::TCRETURNri64:
12219 case X86::TCRETURNmi64:
12220 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12221 // On AMD64, additional defs should be added before register allocation.
12222 if (!Subtarget->isTargetWin64()) {
12223 MI->addRegisterDefined(X86::RSI);
12224 MI->addRegisterDefined(X86::RDI);
12225 MI->addRegisterDefined(X86::XMM6);
12226 MI->addRegisterDefined(X86::XMM7);
12227 MI->addRegisterDefined(X86::XMM8);
12228 MI->addRegisterDefined(X86::XMM9);
12229 MI->addRegisterDefined(X86::XMM10);
12230 MI->addRegisterDefined(X86::XMM11);
12231 MI->addRegisterDefined(X86::XMM12);
12232 MI->addRegisterDefined(X86::XMM13);
12233 MI->addRegisterDefined(X86::XMM14);
12234 MI->addRegisterDefined(X86::XMM15);
12237 case X86::WIN_ALLOCA:
12238 return EmitLoweredWinAlloca(MI, BB);
12239 case X86::SEG_ALLOCA_32:
12240 return EmitLoweredSegAlloca(MI, BB, false);
12241 case X86::SEG_ALLOCA_64:
12242 return EmitLoweredSegAlloca(MI, BB, true);
12243 case X86::TLSCall_32:
12244 case X86::TLSCall_64:
12245 return EmitLoweredTLSCall(MI, BB);
12246 case X86::CMOV_GR8:
12247 case X86::CMOV_FR32:
12248 case X86::CMOV_FR64:
12249 case X86::CMOV_V4F32:
12250 case X86::CMOV_V2F64:
12251 case X86::CMOV_V2I64:
12252 case X86::CMOV_V8F32:
12253 case X86::CMOV_V4F64:
12254 case X86::CMOV_V4I64:
12255 case X86::CMOV_GR16:
12256 case X86::CMOV_GR32:
12257 case X86::CMOV_RFP32:
12258 case X86::CMOV_RFP64:
12259 case X86::CMOV_RFP80:
12260 return EmitLoweredSelect(MI, BB);
12262 case X86::FP32_TO_INT16_IN_MEM:
12263 case X86::FP32_TO_INT32_IN_MEM:
12264 case X86::FP32_TO_INT64_IN_MEM:
12265 case X86::FP64_TO_INT16_IN_MEM:
12266 case X86::FP64_TO_INT32_IN_MEM:
12267 case X86::FP64_TO_INT64_IN_MEM:
12268 case X86::FP80_TO_INT16_IN_MEM:
12269 case X86::FP80_TO_INT32_IN_MEM:
12270 case X86::FP80_TO_INT64_IN_MEM: {
12271 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272 DebugLoc DL = MI->getDebugLoc();
12274 // Change the floating point control register to use "round towards zero"
12275 // mode when truncating to an integer value.
12276 MachineFunction *F = BB->getParent();
12277 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12278 addFrameReference(BuildMI(*BB, MI, DL,
12279 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12281 // Load the old value of the high byte of the control word...
12283 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12284 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12287 // Set the high part to be round to zero...
12288 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12291 // Reload the modified control word now...
12292 addFrameReference(BuildMI(*BB, MI, DL,
12293 TII->get(X86::FLDCW16m)), CWFrameIdx);
12295 // Restore the memory image of control word to original value
12296 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12299 // Get the X86 opcode to use.
12301 switch (MI->getOpcode()) {
12302 default: llvm_unreachable("illegal opcode!");
12303 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12304 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12305 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12306 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12307 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12308 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12309 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12310 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12311 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12315 MachineOperand &Op = MI->getOperand(0);
12317 AM.BaseType = X86AddressMode::RegBase;
12318 AM.Base.Reg = Op.getReg();
12320 AM.BaseType = X86AddressMode::FrameIndexBase;
12321 AM.Base.FrameIndex = Op.getIndex();
12323 Op = MI->getOperand(1);
12325 AM.Scale = Op.getImm();
12326 Op = MI->getOperand(2);
12328 AM.IndexReg = Op.getImm();
12329 Op = MI->getOperand(3);
12330 if (Op.isGlobal()) {
12331 AM.GV = Op.getGlobal();
12333 AM.Disp = Op.getImm();
12335 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12336 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12338 // Reload the original control word now.
12339 addFrameReference(BuildMI(*BB, MI, DL,
12340 TII->get(X86::FLDCW16m)), CWFrameIdx);
12342 MI->eraseFromParent(); // The pseudo instruction is gone now.
12345 // String/text processing lowering.
12346 case X86::PCMPISTRM128REG:
12347 case X86::VPCMPISTRM128REG:
12348 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12349 case X86::PCMPISTRM128MEM:
12350 case X86::VPCMPISTRM128MEM:
12351 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12352 case X86::PCMPESTRM128REG:
12353 case X86::VPCMPESTRM128REG:
12354 return EmitPCMP(MI, BB, 5, false /* in mem */);
12355 case X86::PCMPESTRM128MEM:
12356 case X86::VPCMPESTRM128MEM:
12357 return EmitPCMP(MI, BB, 5, true /* in mem */);
12359 // Thread synchronization.
12361 return EmitMonitor(MI, BB);
12363 return EmitMwait(MI, BB);
12365 // Atomic Lowering.
12366 case X86::ATOMAND32:
12367 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12368 X86::AND32ri, X86::MOV32rm,
12370 X86::NOT32r, X86::EAX,
12371 X86::GR32RegisterClass);
12372 case X86::ATOMOR32:
12373 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12374 X86::OR32ri, X86::MOV32rm,
12376 X86::NOT32r, X86::EAX,
12377 X86::GR32RegisterClass);
12378 case X86::ATOMXOR32:
12379 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12380 X86::XOR32ri, X86::MOV32rm,
12382 X86::NOT32r, X86::EAX,
12383 X86::GR32RegisterClass);
12384 case X86::ATOMNAND32:
12385 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12386 X86::AND32ri, X86::MOV32rm,
12388 X86::NOT32r, X86::EAX,
12389 X86::GR32RegisterClass, true);
12390 case X86::ATOMMIN32:
12391 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12392 case X86::ATOMMAX32:
12393 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12394 case X86::ATOMUMIN32:
12395 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12396 case X86::ATOMUMAX32:
12397 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12399 case X86::ATOMAND16:
12400 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12401 X86::AND16ri, X86::MOV16rm,
12403 X86::NOT16r, X86::AX,
12404 X86::GR16RegisterClass);
12405 case X86::ATOMOR16:
12406 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12407 X86::OR16ri, X86::MOV16rm,
12409 X86::NOT16r, X86::AX,
12410 X86::GR16RegisterClass);
12411 case X86::ATOMXOR16:
12412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12413 X86::XOR16ri, X86::MOV16rm,
12415 X86::NOT16r, X86::AX,
12416 X86::GR16RegisterClass);
12417 case X86::ATOMNAND16:
12418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12419 X86::AND16ri, X86::MOV16rm,
12421 X86::NOT16r, X86::AX,
12422 X86::GR16RegisterClass, true);
12423 case X86::ATOMMIN16:
12424 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12425 case X86::ATOMMAX16:
12426 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12427 case X86::ATOMUMIN16:
12428 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12429 case X86::ATOMUMAX16:
12430 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12432 case X86::ATOMAND8:
12433 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12434 X86::AND8ri, X86::MOV8rm,
12436 X86::NOT8r, X86::AL,
12437 X86::GR8RegisterClass);
12439 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12440 X86::OR8ri, X86::MOV8rm,
12442 X86::NOT8r, X86::AL,
12443 X86::GR8RegisterClass);
12444 case X86::ATOMXOR8:
12445 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12446 X86::XOR8ri, X86::MOV8rm,
12448 X86::NOT8r, X86::AL,
12449 X86::GR8RegisterClass);
12450 case X86::ATOMNAND8:
12451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12452 X86::AND8ri, X86::MOV8rm,
12454 X86::NOT8r, X86::AL,
12455 X86::GR8RegisterClass, true);
12456 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12457 // This group is for 64-bit host.
12458 case X86::ATOMAND64:
12459 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12460 X86::AND64ri32, X86::MOV64rm,
12462 X86::NOT64r, X86::RAX,
12463 X86::GR64RegisterClass);
12464 case X86::ATOMOR64:
12465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12466 X86::OR64ri32, X86::MOV64rm,
12468 X86::NOT64r, X86::RAX,
12469 X86::GR64RegisterClass);
12470 case X86::ATOMXOR64:
12471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12472 X86::XOR64ri32, X86::MOV64rm,
12474 X86::NOT64r, X86::RAX,
12475 X86::GR64RegisterClass);
12476 case X86::ATOMNAND64:
12477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12478 X86::AND64ri32, X86::MOV64rm,
12480 X86::NOT64r, X86::RAX,
12481 X86::GR64RegisterClass, true);
12482 case X86::ATOMMIN64:
12483 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12484 case X86::ATOMMAX64:
12485 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12486 case X86::ATOMUMIN64:
12487 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12488 case X86::ATOMUMAX64:
12489 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12491 // This group does 64-bit operations on a 32-bit host.
12492 case X86::ATOMAND6432:
12493 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12494 X86::AND32rr, X86::AND32rr,
12495 X86::AND32ri, X86::AND32ri,
12497 case X86::ATOMOR6432:
12498 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12499 X86::OR32rr, X86::OR32rr,
12500 X86::OR32ri, X86::OR32ri,
12502 case X86::ATOMXOR6432:
12503 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12504 X86::XOR32rr, X86::XOR32rr,
12505 X86::XOR32ri, X86::XOR32ri,
12507 case X86::ATOMNAND6432:
12508 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12509 X86::AND32rr, X86::AND32rr,
12510 X86::AND32ri, X86::AND32ri,
12512 case X86::ATOMADD6432:
12513 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12514 X86::ADD32rr, X86::ADC32rr,
12515 X86::ADD32ri, X86::ADC32ri,
12517 case X86::ATOMSUB6432:
12518 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12519 X86::SUB32rr, X86::SBB32rr,
12520 X86::SUB32ri, X86::SBB32ri,
12522 case X86::ATOMSWAP6432:
12523 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12524 X86::MOV32rr, X86::MOV32rr,
12525 X86::MOV32ri, X86::MOV32ri,
12527 case X86::VASTART_SAVE_XMM_REGS:
12528 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12530 case X86::VAARG_64:
12531 return EmitVAARG64WithCustomInserter(MI, BB);
12535 //===----------------------------------------------------------------------===//
12536 // X86 Optimization Hooks
12537 //===----------------------------------------------------------------------===//
12539 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12543 const SelectionDAG &DAG,
12544 unsigned Depth) const {
12545 unsigned Opc = Op.getOpcode();
12546 assert((Opc >= ISD::BUILTIN_OP_END ||
12547 Opc == ISD::INTRINSIC_WO_CHAIN ||
12548 Opc == ISD::INTRINSIC_W_CHAIN ||
12549 Opc == ISD::INTRINSIC_VOID) &&
12550 "Should use MaskedValueIsZero if you don't know whether Op"
12551 " is a target node!");
12553 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12567 // These nodes' second result is a boolean.
12568 if (Op.getResNo() == 0)
12571 case X86ISD::SETCC:
12572 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12573 Mask.getBitWidth() - 1);
12575 case ISD::INTRINSIC_WO_CHAIN: {
12576 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12577 unsigned NumLoBits = 0;
12580 case Intrinsic::x86_sse_movmsk_ps:
12581 case Intrinsic::x86_avx_movmsk_ps_256:
12582 case Intrinsic::x86_sse2_movmsk_pd:
12583 case Intrinsic::x86_avx_movmsk_pd_256:
12584 case Intrinsic::x86_mmx_pmovmskb:
12585 case Intrinsic::x86_sse2_pmovmskb_128: {
12586 // High bits of movmskp{s|d}, pmovmskb are known zero.
12588 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12589 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12590 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12591 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12592 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12593 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12595 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12596 Mask.getBitWidth() - NumLoBits);
12605 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12606 unsigned Depth) const {
12607 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12608 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12609 return Op.getValueType().getScalarType().getSizeInBits();
12615 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12616 /// node is a GlobalAddress + offset.
12617 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12618 const GlobalValue* &GA,
12619 int64_t &Offset) const {
12620 if (N->getOpcode() == X86ISD::Wrapper) {
12621 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12622 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12623 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12627 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12630 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12631 /// same as extracting the high 128-bit part of 256-bit vector and then
12632 /// inserting the result into the low part of a new 256-bit vector
12633 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12634 EVT VT = SVOp->getValueType(0);
12635 int NumElems = VT.getVectorNumElements();
12637 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12638 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12639 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12640 SVOp->getMaskElt(j) >= 0)
12646 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12647 /// same as extracting the low 128-bit part of 256-bit vector and then
12648 /// inserting the result into the high part of a new 256-bit vector
12649 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12650 EVT VT = SVOp->getValueType(0);
12651 int NumElems = VT.getVectorNumElements();
12653 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12654 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12655 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12656 SVOp->getMaskElt(j) >= 0)
12662 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12663 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12664 TargetLowering::DAGCombinerInfo &DCI) {
12665 DebugLoc dl = N->getDebugLoc();
12666 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12667 SDValue V1 = SVOp->getOperand(0);
12668 SDValue V2 = SVOp->getOperand(1);
12669 EVT VT = SVOp->getValueType(0);
12670 int NumElems = VT.getVectorNumElements();
12672 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12673 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12677 // V UNDEF BUILD_VECTOR UNDEF
12679 // CONCAT_VECTOR CONCAT_VECTOR
12682 // RESULT: V + zero extended
12684 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12685 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12686 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12689 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12692 // To match the shuffle mask, the first half of the mask should
12693 // be exactly the first vector, and all the rest a splat with the
12694 // first element of the second one.
12695 for (int i = 0; i < NumElems/2; ++i)
12696 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12697 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12700 // Emit a zeroed vector and insert the desired subvector on its
12702 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12703 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12704 DAG.getConstant(0, MVT::i32), DAG, dl);
12705 return DCI.CombineTo(N, InsV);
12708 //===--------------------------------------------------------------------===//
12709 // Combine some shuffles into subvector extracts and inserts:
12712 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12713 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12714 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12716 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12717 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12718 return DCI.CombineTo(N, InsV);
12721 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12722 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12723 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12724 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12725 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12726 return DCI.CombineTo(N, InsV);
12732 /// PerformShuffleCombine - Performs several different shuffle combines.
12733 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12734 TargetLowering::DAGCombinerInfo &DCI,
12735 const X86Subtarget *Subtarget) {
12736 DebugLoc dl = N->getDebugLoc();
12737 EVT VT = N->getValueType(0);
12739 // Don't create instructions with illegal types after legalize types has run.
12740 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12741 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12744 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12745 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12746 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12747 return PerformShuffleCombine256(N, DAG, DCI);
12749 // Only handle 128 wide vector from here on.
12750 if (VT.getSizeInBits() != 128)
12753 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12754 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12755 // consecutive, non-overlapping, and in the right order.
12756 SmallVector<SDValue, 16> Elts;
12757 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12758 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12760 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12763 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12764 /// generation and convert it from being a bunch of shuffles and extracts
12765 /// to a simple store and scalar loads to extract the elements.
12766 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12767 const TargetLowering &TLI) {
12768 SDValue InputVector = N->getOperand(0);
12770 // Only operate on vectors of 4 elements, where the alternative shuffling
12771 // gets to be more expensive.
12772 if (InputVector.getValueType() != MVT::v4i32)
12775 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12776 // single use which is a sign-extend or zero-extend, and all elements are
12778 SmallVector<SDNode *, 4> Uses;
12779 unsigned ExtractedElements = 0;
12780 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12781 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12782 if (UI.getUse().getResNo() != InputVector.getResNo())
12785 SDNode *Extract = *UI;
12786 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12789 if (Extract->getValueType(0) != MVT::i32)
12791 if (!Extract->hasOneUse())
12793 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12794 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12796 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12799 // Record which element was extracted.
12800 ExtractedElements |=
12801 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12803 Uses.push_back(Extract);
12806 // If not all the elements were used, this may not be worthwhile.
12807 if (ExtractedElements != 15)
12810 // Ok, we've now decided to do the transformation.
12811 DebugLoc dl = InputVector.getDebugLoc();
12813 // Store the value to a temporary stack slot.
12814 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12815 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12816 MachinePointerInfo(), false, false, 0);
12818 // Replace each use (extract) with a load of the appropriate element.
12819 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12820 UE = Uses.end(); UI != UE; ++UI) {
12821 SDNode *Extract = *UI;
12823 // cOMpute the element's address.
12824 SDValue Idx = Extract->getOperand(1);
12826 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12827 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12828 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12830 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12831 StackPtr, OffsetVal);
12833 // Load the scalar.
12834 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12835 ScalarAddr, MachinePointerInfo(),
12836 false, false, false, 0);
12838 // Replace the exact with the load.
12839 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12842 // The replacement was made in place; don't return anything.
12846 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12848 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12849 const X86Subtarget *Subtarget) {
12850 DebugLoc DL = N->getDebugLoc();
12851 SDValue Cond = N->getOperand(0);
12852 // Get the LHS/RHS of the select.
12853 SDValue LHS = N->getOperand(1);
12854 SDValue RHS = N->getOperand(2);
12855 EVT VT = LHS.getValueType();
12857 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12858 // instructions match the semantics of the common C idiom x<y?x:y but not
12859 // x<=y?x:y, because of how they handle negative zero (which can be
12860 // ignored in unsafe-math mode).
12861 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12862 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12863 (Subtarget->hasXMMInt() ||
12864 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12865 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12867 unsigned Opcode = 0;
12868 // Check for x CC y ? x : y.
12869 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12870 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12874 // Converting this to a min would handle NaNs incorrectly, and swapping
12875 // the operands would cause it to handle comparisons between positive
12876 // and negative zero incorrectly.
12877 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12878 if (!DAG.getTarget().Options.UnsafeFPMath &&
12879 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12881 std::swap(LHS, RHS);
12883 Opcode = X86ISD::FMIN;
12886 // Converting this to a min would handle comparisons between positive
12887 // and negative zero incorrectly.
12888 if (!DAG.getTarget().Options.UnsafeFPMath &&
12889 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12891 Opcode = X86ISD::FMIN;
12894 // Converting this to a min would handle both negative zeros and NaNs
12895 // incorrectly, but we can swap the operands to fix both.
12896 std::swap(LHS, RHS);
12900 Opcode = X86ISD::FMIN;
12904 // Converting this to a max would handle comparisons between positive
12905 // and negative zero incorrectly.
12906 if (!DAG.getTarget().Options.UnsafeFPMath &&
12907 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12909 Opcode = X86ISD::FMAX;
12912 // Converting this to a max would handle NaNs incorrectly, and swapping
12913 // the operands would cause it to handle comparisons between positive
12914 // and negative zero incorrectly.
12915 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12916 if (!DAG.getTarget().Options.UnsafeFPMath &&
12917 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12919 std::swap(LHS, RHS);
12921 Opcode = X86ISD::FMAX;
12924 // Converting this to a max would handle both negative zeros and NaNs
12925 // incorrectly, but we can swap the operands to fix both.
12926 std::swap(LHS, RHS);
12930 Opcode = X86ISD::FMAX;
12933 // Check for x CC y ? y : x -- a min/max with reversed arms.
12934 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12935 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12939 // Converting this to a min would handle comparisons between positive
12940 // and negative zero incorrectly, and swapping the operands would
12941 // cause it to handle NaNs incorrectly.
12942 if (!DAG.getTarget().Options.UnsafeFPMath &&
12943 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12944 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12946 std::swap(LHS, RHS);
12948 Opcode = X86ISD::FMIN;
12951 // Converting this to a min would handle NaNs incorrectly.
12952 if (!DAG.getTarget().Options.UnsafeFPMath &&
12953 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12955 Opcode = X86ISD::FMIN;
12958 // Converting this to a min would handle both negative zeros and NaNs
12959 // incorrectly, but we can swap the operands to fix both.
12960 std::swap(LHS, RHS);
12964 Opcode = X86ISD::FMIN;
12968 // Converting this to a max would handle NaNs incorrectly.
12969 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12971 Opcode = X86ISD::FMAX;
12974 // Converting this to a max would handle comparisons between positive
12975 // and negative zero incorrectly, and swapping the operands would
12976 // cause it to handle NaNs incorrectly.
12977 if (!DAG.getTarget().Options.UnsafeFPMath &&
12978 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12979 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12981 std::swap(LHS, RHS);
12983 Opcode = X86ISD::FMAX;
12986 // Converting this to a max would handle both negative zeros and NaNs
12987 // incorrectly, but we can swap the operands to fix both.
12988 std::swap(LHS, RHS);
12992 Opcode = X86ISD::FMAX;
12998 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13001 // If this is a select between two integer constants, try to do some
13003 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13004 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13005 // Don't do this for crazy integer types.
13006 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13007 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13008 // so that TrueC (the true value) is larger than FalseC.
13009 bool NeedsCondInvert = false;
13011 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13012 // Efficiently invertible.
13013 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13014 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13015 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13016 NeedsCondInvert = true;
13017 std::swap(TrueC, FalseC);
13020 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13021 if (FalseC->getAPIntValue() == 0 &&
13022 TrueC->getAPIntValue().isPowerOf2()) {
13023 if (NeedsCondInvert) // Invert the condition if needed.
13024 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13025 DAG.getConstant(1, Cond.getValueType()));
13027 // Zero extend the condition if needed.
13028 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13030 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13031 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13032 DAG.getConstant(ShAmt, MVT::i8));
13035 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13036 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13037 if (NeedsCondInvert) // Invert the condition if needed.
13038 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13039 DAG.getConstant(1, Cond.getValueType()));
13041 // Zero extend the condition if needed.
13042 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13043 FalseC->getValueType(0), Cond);
13044 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13045 SDValue(FalseC, 0));
13048 // Optimize cases that will turn into an LEA instruction. This requires
13049 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13050 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13051 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13052 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13054 bool isFastMultiplier = false;
13056 switch ((unsigned char)Diff) {
13058 case 1: // result = add base, cond
13059 case 2: // result = lea base( , cond*2)
13060 case 3: // result = lea base(cond, cond*2)
13061 case 4: // result = lea base( , cond*4)
13062 case 5: // result = lea base(cond, cond*4)
13063 case 8: // result = lea base( , cond*8)
13064 case 9: // result = lea base(cond, cond*8)
13065 isFastMultiplier = true;
13070 if (isFastMultiplier) {
13071 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13072 if (NeedsCondInvert) // Invert the condition if needed.
13073 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13074 DAG.getConstant(1, Cond.getValueType()));
13076 // Zero extend the condition if needed.
13077 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13079 // Scale the condition by the difference.
13081 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13082 DAG.getConstant(Diff, Cond.getValueType()));
13084 // Add the base if non-zero.
13085 if (FalseC->getAPIntValue() != 0)
13086 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13087 SDValue(FalseC, 0));
13097 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13098 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13099 TargetLowering::DAGCombinerInfo &DCI) {
13100 DebugLoc DL = N->getDebugLoc();
13102 // If the flag operand isn't dead, don't touch this CMOV.
13103 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13106 SDValue FalseOp = N->getOperand(0);
13107 SDValue TrueOp = N->getOperand(1);
13108 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13109 SDValue Cond = N->getOperand(3);
13110 if (CC == X86::COND_E || CC == X86::COND_NE) {
13111 switch (Cond.getOpcode()) {
13115 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13116 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13117 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13121 // If this is a select between two integer constants, try to do some
13122 // optimizations. Note that the operands are ordered the opposite of SELECT
13124 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13125 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13126 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13127 // larger than FalseC (the false value).
13128 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13129 CC = X86::GetOppositeBranchCondition(CC);
13130 std::swap(TrueC, FalseC);
13133 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13134 // This is efficient for any integer data type (including i8/i16) and
13136 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13137 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13138 DAG.getConstant(CC, MVT::i8), Cond);
13140 // Zero extend the condition if needed.
13141 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13143 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13144 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13145 DAG.getConstant(ShAmt, MVT::i8));
13146 if (N->getNumValues() == 2) // Dead flag value?
13147 return DCI.CombineTo(N, Cond, SDValue());
13151 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13152 // for any integer data type, including i8/i16.
13153 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13154 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13155 DAG.getConstant(CC, MVT::i8), Cond);
13157 // Zero extend the condition if needed.
13158 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13159 FalseC->getValueType(0), Cond);
13160 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13161 SDValue(FalseC, 0));
13163 if (N->getNumValues() == 2) // Dead flag value?
13164 return DCI.CombineTo(N, Cond, SDValue());
13168 // Optimize cases that will turn into an LEA instruction. This requires
13169 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13170 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13171 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13172 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13174 bool isFastMultiplier = false;
13176 switch ((unsigned char)Diff) {
13178 case 1: // result = add base, cond
13179 case 2: // result = lea base( , cond*2)
13180 case 3: // result = lea base(cond, cond*2)
13181 case 4: // result = lea base( , cond*4)
13182 case 5: // result = lea base(cond, cond*4)
13183 case 8: // result = lea base( , cond*8)
13184 case 9: // result = lea base(cond, cond*8)
13185 isFastMultiplier = true;
13190 if (isFastMultiplier) {
13191 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13192 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13193 DAG.getConstant(CC, MVT::i8), Cond);
13194 // Zero extend the condition if needed.
13195 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13197 // Scale the condition by the difference.
13199 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13200 DAG.getConstant(Diff, Cond.getValueType()));
13202 // Add the base if non-zero.
13203 if (FalseC->getAPIntValue() != 0)
13204 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13205 SDValue(FalseC, 0));
13206 if (N->getNumValues() == 2) // Dead flag value?
13207 return DCI.CombineTo(N, Cond, SDValue());
13217 /// PerformMulCombine - Optimize a single multiply with constant into two
13218 /// in order to implement it with two cheaper instructions, e.g.
13219 /// LEA + SHL, LEA + LEA.
13220 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13221 TargetLowering::DAGCombinerInfo &DCI) {
13222 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13225 EVT VT = N->getValueType(0);
13226 if (VT != MVT::i64)
13229 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13232 uint64_t MulAmt = C->getZExtValue();
13233 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13236 uint64_t MulAmt1 = 0;
13237 uint64_t MulAmt2 = 0;
13238 if ((MulAmt % 9) == 0) {
13240 MulAmt2 = MulAmt / 9;
13241 } else if ((MulAmt % 5) == 0) {
13243 MulAmt2 = MulAmt / 5;
13244 } else if ((MulAmt % 3) == 0) {
13246 MulAmt2 = MulAmt / 3;
13249 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13250 DebugLoc DL = N->getDebugLoc();
13252 if (isPowerOf2_64(MulAmt2) &&
13253 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13254 // If second multiplifer is pow2, issue it first. We want the multiply by
13255 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13257 std::swap(MulAmt1, MulAmt2);
13260 if (isPowerOf2_64(MulAmt1))
13261 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13262 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13264 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13265 DAG.getConstant(MulAmt1, VT));
13267 if (isPowerOf2_64(MulAmt2))
13268 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13269 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13271 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13272 DAG.getConstant(MulAmt2, VT));
13274 // Do not add new nodes to DAG combiner worklist.
13275 DCI.CombineTo(N, NewMul, false);
13280 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13281 SDValue N0 = N->getOperand(0);
13282 SDValue N1 = N->getOperand(1);
13283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13284 EVT VT = N0.getValueType();
13286 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13287 // since the result of setcc_c is all zero's or all ones.
13288 if (VT.isInteger() && !VT.isVector() &&
13289 N1C && N0.getOpcode() == ISD::AND &&
13290 N0.getOperand(1).getOpcode() == ISD::Constant) {
13291 SDValue N00 = N0.getOperand(0);
13292 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13293 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13294 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13295 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13296 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13297 APInt ShAmt = N1C->getAPIntValue();
13298 Mask = Mask.shl(ShAmt);
13300 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13301 N00, DAG.getConstant(Mask, VT));
13306 // Hardware support for vector shifts is sparse which makes us scalarize the
13307 // vector operations in many cases. Also, on sandybridge ADD is faster than
13309 // (shl V, 1) -> add V,V
13310 if (isSplatVector(N1.getNode())) {
13311 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13312 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13313 // We shift all of the values by one. In many cases we do not have
13314 // hardware support for this operation. This is better expressed as an ADD
13316 if (N1C && (1 == N1C->getZExtValue())) {
13317 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13324 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13326 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13327 const X86Subtarget *Subtarget) {
13328 EVT VT = N->getValueType(0);
13329 if (N->getOpcode() == ISD::SHL) {
13330 SDValue V = PerformSHLCombine(N, DAG);
13331 if (V.getNode()) return V;
13334 // On X86 with SSE2 support, we can transform this to a vector shift if
13335 // all elements are shifted by the same amount. We can't do this in legalize
13336 // because the a constant vector is typically transformed to a constant pool
13337 // so we have no knowledge of the shift amount.
13338 if (!Subtarget->hasXMMInt())
13341 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13342 (!Subtarget->hasAVX2() ||
13343 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13346 SDValue ShAmtOp = N->getOperand(1);
13347 EVT EltVT = VT.getVectorElementType();
13348 DebugLoc DL = N->getDebugLoc();
13349 SDValue BaseShAmt = SDValue();
13350 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13351 unsigned NumElts = VT.getVectorNumElements();
13353 for (; i != NumElts; ++i) {
13354 SDValue Arg = ShAmtOp.getOperand(i);
13355 if (Arg.getOpcode() == ISD::UNDEF) continue;
13359 for (; i != NumElts; ++i) {
13360 SDValue Arg = ShAmtOp.getOperand(i);
13361 if (Arg.getOpcode() == ISD::UNDEF) continue;
13362 if (Arg != BaseShAmt) {
13366 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13367 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13368 SDValue InVec = ShAmtOp.getOperand(0);
13369 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13370 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13372 for (; i != NumElts; ++i) {
13373 SDValue Arg = InVec.getOperand(i);
13374 if (Arg.getOpcode() == ISD::UNDEF) continue;
13378 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13380 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13381 if (C->getZExtValue() == SplatIdx)
13382 BaseShAmt = InVec.getOperand(1);
13385 if (BaseShAmt.getNode() == 0)
13386 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13387 DAG.getIntPtrConstant(0));
13391 // The shift amount is an i32.
13392 if (EltVT.bitsGT(MVT::i32))
13393 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13394 else if (EltVT.bitsLT(MVT::i32))
13395 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13397 // The shift amount is identical so we can do a vector shift.
13398 SDValue ValOp = N->getOperand(0);
13399 switch (N->getOpcode()) {
13401 llvm_unreachable("Unknown shift opcode!");
13404 if (VT == MVT::v2i64)
13405 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13406 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13408 if (VT == MVT::v4i32)
13409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13410 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13412 if (VT == MVT::v8i16)
13413 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13414 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13416 if (VT == MVT::v4i64)
13417 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13418 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13420 if (VT == MVT::v8i32)
13421 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13422 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13424 if (VT == MVT::v16i16)
13425 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13426 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13430 if (VT == MVT::v4i32)
13431 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13432 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13434 if (VT == MVT::v8i16)
13435 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13436 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13438 if (VT == MVT::v8i32)
13439 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13440 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13442 if (VT == MVT::v16i16)
13443 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13444 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13448 if (VT == MVT::v2i64)
13449 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13450 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13452 if (VT == MVT::v4i32)
13453 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13454 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13456 if (VT == MVT::v8i16)
13457 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13458 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13460 if (VT == MVT::v4i64)
13461 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13462 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13464 if (VT == MVT::v8i32)
13465 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13466 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13468 if (VT == MVT::v16i16)
13469 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13470 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13478 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13479 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13480 // and friends. Likewise for OR -> CMPNEQSS.
13481 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13482 TargetLowering::DAGCombinerInfo &DCI,
13483 const X86Subtarget *Subtarget) {
13486 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13487 // we're requiring SSE2 for both.
13488 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13489 SDValue N0 = N->getOperand(0);
13490 SDValue N1 = N->getOperand(1);
13491 SDValue CMP0 = N0->getOperand(1);
13492 SDValue CMP1 = N1->getOperand(1);
13493 DebugLoc DL = N->getDebugLoc();
13495 // The SETCCs should both refer to the same CMP.
13496 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13499 SDValue CMP00 = CMP0->getOperand(0);
13500 SDValue CMP01 = CMP0->getOperand(1);
13501 EVT VT = CMP00.getValueType();
13503 if (VT == MVT::f32 || VT == MVT::f64) {
13504 bool ExpectingFlags = false;
13505 // Check for any users that want flags:
13506 for (SDNode::use_iterator UI = N->use_begin(),
13508 !ExpectingFlags && UI != UE; ++UI)
13509 switch (UI->getOpcode()) {
13514 ExpectingFlags = true;
13516 case ISD::CopyToReg:
13517 case ISD::SIGN_EXTEND:
13518 case ISD::ZERO_EXTEND:
13519 case ISD::ANY_EXTEND:
13523 if (!ExpectingFlags) {
13524 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13525 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13527 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13528 X86::CondCode tmp = cc0;
13533 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13534 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13535 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13536 X86ISD::NodeType NTOperator = is64BitFP ?
13537 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13538 // FIXME: need symbolic constants for these magic numbers.
13539 // See X86ATTInstPrinter.cpp:printSSECC().
13540 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13541 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13542 DAG.getConstant(x86cc, MVT::i8));
13543 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13545 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13546 DAG.getConstant(1, MVT::i32));
13547 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13548 return OneBitOfTruth;
13556 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13557 /// so it can be folded inside ANDNP.
13558 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13559 EVT VT = N->getValueType(0);
13561 // Match direct AllOnes for 128 and 256-bit vectors
13562 if (ISD::isBuildVectorAllOnes(N))
13565 // Look through a bit convert.
13566 if (N->getOpcode() == ISD::BITCAST)
13567 N = N->getOperand(0).getNode();
13569 // Sometimes the operand may come from a insert_subvector building a 256-bit
13571 if (VT.getSizeInBits() == 256 &&
13572 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13573 SDValue V1 = N->getOperand(0);
13574 SDValue V2 = N->getOperand(1);
13576 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13577 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13578 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13579 ISD::isBuildVectorAllOnes(V2.getNode()))
13586 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13587 TargetLowering::DAGCombinerInfo &DCI,
13588 const X86Subtarget *Subtarget) {
13589 if (DCI.isBeforeLegalizeOps())
13592 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13596 EVT VT = N->getValueType(0);
13598 // Create ANDN, BLSI, and BLSR instructions
13599 // BLSI is X & (-X)
13600 // BLSR is X & (X-1)
13601 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13602 SDValue N0 = N->getOperand(0);
13603 SDValue N1 = N->getOperand(1);
13604 DebugLoc DL = N->getDebugLoc();
13606 // Check LHS for not
13607 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13608 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13609 // Check RHS for not
13610 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13611 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13613 // Check LHS for neg
13614 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13615 isZero(N0.getOperand(0)))
13616 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13618 // Check RHS for neg
13619 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13620 isZero(N1.getOperand(0)))
13621 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13623 // Check LHS for X-1
13624 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13625 isAllOnes(N0.getOperand(1)))
13626 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13628 // Check RHS for X-1
13629 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13630 isAllOnes(N1.getOperand(1)))
13631 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13636 // Want to form ANDNP nodes:
13637 // 1) In the hopes of then easily combining them with OR and AND nodes
13638 // to form PBLEND/PSIGN.
13639 // 2) To match ANDN packed intrinsics
13640 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13643 SDValue N0 = N->getOperand(0);
13644 SDValue N1 = N->getOperand(1);
13645 DebugLoc DL = N->getDebugLoc();
13647 // Check LHS for vnot
13648 if (N0.getOpcode() == ISD::XOR &&
13649 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13650 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13651 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13653 // Check RHS for vnot
13654 if (N1.getOpcode() == ISD::XOR &&
13655 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13656 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13657 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13662 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13663 TargetLowering::DAGCombinerInfo &DCI,
13664 const X86Subtarget *Subtarget) {
13665 if (DCI.isBeforeLegalizeOps())
13668 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13672 EVT VT = N->getValueType(0);
13674 SDValue N0 = N->getOperand(0);
13675 SDValue N1 = N->getOperand(1);
13677 // look for psign/blend
13678 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13679 if (!Subtarget->hasSSSE3orAVX() ||
13680 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13683 // Canonicalize pandn to RHS
13684 if (N0.getOpcode() == X86ISD::ANDNP)
13686 // or (and (m, x), (pandn m, y))
13687 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13688 SDValue Mask = N1.getOperand(0);
13689 SDValue X = N1.getOperand(1);
13691 if (N0.getOperand(0) == Mask)
13692 Y = N0.getOperand(1);
13693 if (N0.getOperand(1) == Mask)
13694 Y = N0.getOperand(0);
13696 // Check to see if the mask appeared in both the AND and ANDNP and
13700 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13701 if (Mask.getOpcode() != ISD::BITCAST ||
13702 X.getOpcode() != ISD::BITCAST ||
13703 Y.getOpcode() != ISD::BITCAST)
13706 // Look through mask bitcast.
13707 Mask = Mask.getOperand(0);
13708 EVT MaskVT = Mask.getValueType();
13710 // Validate that the Mask operand is a vector sra node. The sra node
13711 // will be an intrinsic.
13712 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13715 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13716 // there is no psrai.b
13717 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13718 case Intrinsic::x86_sse2_psrai_w:
13719 case Intrinsic::x86_sse2_psrai_d:
13720 case Intrinsic::x86_avx2_psrai_w:
13721 case Intrinsic::x86_avx2_psrai_d:
13723 default: return SDValue();
13726 // Check that the SRA is all signbits.
13727 SDValue SraC = Mask.getOperand(2);
13728 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13729 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13730 if ((SraAmt + 1) != EltBits)
13733 DebugLoc DL = N->getDebugLoc();
13735 // Now we know we at least have a plendvb with the mask val. See if
13736 // we can form a psignb/w/d.
13737 // psign = x.type == y.type == mask.type && y = sub(0, x);
13738 X = X.getOperand(0);
13739 Y = Y.getOperand(0);
13740 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13741 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13742 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13743 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13744 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13745 Mask.getOperand(1));
13746 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13748 // PBLENDVB only available on SSE 4.1
13749 if (!Subtarget->hasSSE41orAVX())
13752 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13754 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13755 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13756 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13757 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13758 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13762 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13765 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13766 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13768 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13770 if (!N0.hasOneUse() || !N1.hasOneUse())
13773 SDValue ShAmt0 = N0.getOperand(1);
13774 if (ShAmt0.getValueType() != MVT::i8)
13776 SDValue ShAmt1 = N1.getOperand(1);
13777 if (ShAmt1.getValueType() != MVT::i8)
13779 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13780 ShAmt0 = ShAmt0.getOperand(0);
13781 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13782 ShAmt1 = ShAmt1.getOperand(0);
13784 DebugLoc DL = N->getDebugLoc();
13785 unsigned Opc = X86ISD::SHLD;
13786 SDValue Op0 = N0.getOperand(0);
13787 SDValue Op1 = N1.getOperand(0);
13788 if (ShAmt0.getOpcode() == ISD::SUB) {
13789 Opc = X86ISD::SHRD;
13790 std::swap(Op0, Op1);
13791 std::swap(ShAmt0, ShAmt1);
13794 unsigned Bits = VT.getSizeInBits();
13795 if (ShAmt1.getOpcode() == ISD::SUB) {
13796 SDValue Sum = ShAmt1.getOperand(0);
13797 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13798 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13799 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13800 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13801 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13802 return DAG.getNode(Opc, DL, VT,
13804 DAG.getNode(ISD::TRUNCATE, DL,
13807 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13808 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13810 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13811 return DAG.getNode(Opc, DL, VT,
13812 N0.getOperand(0), N1.getOperand(0),
13813 DAG.getNode(ISD::TRUNCATE, DL,
13820 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13821 TargetLowering::DAGCombinerInfo &DCI,
13822 const X86Subtarget *Subtarget) {
13823 if (DCI.isBeforeLegalizeOps())
13826 EVT VT = N->getValueType(0);
13828 if (VT != MVT::i32 && VT != MVT::i64)
13831 // Create BLSMSK instructions by finding X ^ (X-1)
13832 SDValue N0 = N->getOperand(0);
13833 SDValue N1 = N->getOperand(1);
13834 DebugLoc DL = N->getDebugLoc();
13836 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13837 isAllOnes(N0.getOperand(1)))
13838 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13840 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13841 isAllOnes(N1.getOperand(1)))
13842 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13847 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13848 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13849 const X86Subtarget *Subtarget) {
13850 LoadSDNode *Ld = cast<LoadSDNode>(N);
13851 EVT RegVT = Ld->getValueType(0);
13852 EVT MemVT = Ld->getMemoryVT();
13853 DebugLoc dl = Ld->getDebugLoc();
13854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13856 ISD::LoadExtType Ext = Ld->getExtensionType();
13858 // If this is a vector EXT Load then attempt to optimize it using a
13859 // shuffle. We need SSE4 for the shuffles.
13860 // TODO: It is possible to support ZExt by zeroing the undef values
13861 // during the shuffle phase or after the shuffle.
13862 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13863 assert(MemVT != RegVT && "Cannot extend to the same type");
13864 assert(MemVT.isVector() && "Must load a vector from memory");
13866 unsigned NumElems = RegVT.getVectorNumElements();
13867 unsigned RegSz = RegVT.getSizeInBits();
13868 unsigned MemSz = MemVT.getSizeInBits();
13869 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13870 // All sizes must be a power of two
13871 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13873 // Attempt to load the original value using a single load op.
13874 // Find a scalar type which is equal to the loaded word size.
13875 MVT SclrLoadTy = MVT::i8;
13876 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13877 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13878 MVT Tp = (MVT::SimpleValueType)tp;
13879 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13885 // Proceed if a load word is found.
13886 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13888 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13889 RegSz/SclrLoadTy.getSizeInBits());
13891 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13892 RegSz/MemVT.getScalarType().getSizeInBits());
13893 // Can't shuffle using an illegal type.
13894 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13896 // Perform a single load.
13897 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13899 Ld->getPointerInfo(), Ld->isVolatile(),
13900 Ld->isNonTemporal(), Ld->isInvariant(),
13901 Ld->getAlignment());
13903 // Insert the word loaded into a vector.
13904 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13905 LoadUnitVecVT, ScalarLoad);
13907 // Bitcast the loaded value to a vector of the original element type, in
13908 // the size of the target vector type.
13909 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13910 unsigned SizeRatio = RegSz/MemSz;
13912 // Redistribute the loaded elements into the different locations.
13913 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13914 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13916 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13917 DAG.getUNDEF(SlicedVec.getValueType()),
13918 ShuffleVec.data());
13920 // Bitcast to the requested type.
13921 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13922 // Replace the original load with the new sequence
13923 // and return the new chain.
13924 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13925 return SDValue(ScalarLoad.getNode(), 1);
13931 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13932 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13933 const X86Subtarget *Subtarget) {
13934 StoreSDNode *St = cast<StoreSDNode>(N);
13935 EVT VT = St->getValue().getValueType();
13936 EVT StVT = St->getMemoryVT();
13937 DebugLoc dl = St->getDebugLoc();
13938 SDValue StoredVal = St->getOperand(1);
13939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13941 // If we are saving a concatenation of two XMM registers, perform two stores.
13942 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13943 // 128-bit ones. If in the future the cost becomes only one memory access the
13944 // first version would be better.
13945 if (VT.getSizeInBits() == 256 &&
13946 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13947 StoredVal.getNumOperands() == 2) {
13949 SDValue Value0 = StoredVal.getOperand(0);
13950 SDValue Value1 = StoredVal.getOperand(1);
13952 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13953 SDValue Ptr0 = St->getBasePtr();
13954 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13956 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13957 St->getPointerInfo(), St->isVolatile(),
13958 St->isNonTemporal(), St->getAlignment());
13959 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13960 St->getPointerInfo(), St->isVolatile(),
13961 St->isNonTemporal(), St->getAlignment());
13962 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13965 // Optimize trunc store (of multiple scalars) to shuffle and store.
13966 // First, pack all of the elements in one place. Next, store to memory
13967 // in fewer chunks.
13968 if (St->isTruncatingStore() && VT.isVector()) {
13969 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13970 unsigned NumElems = VT.getVectorNumElements();
13971 assert(StVT != VT && "Cannot truncate to the same type");
13972 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13973 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13975 // From, To sizes and ElemCount must be pow of two
13976 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13977 // We are going to use the original vector elt for storing.
13978 // Accumulated smaller vector elements must be a multiple of the store size.
13979 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13981 unsigned SizeRatio = FromSz / ToSz;
13983 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13985 // Create a type on which we perform the shuffle
13986 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13987 StVT.getScalarType(), NumElems*SizeRatio);
13989 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13991 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13992 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13993 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13995 // Can't shuffle using an illegal type
13996 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13998 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13999 DAG.getUNDEF(WideVec.getValueType()),
14000 ShuffleVec.data());
14001 // At this point all of the data is stored at the bottom of the
14002 // register. We now need to save it to mem.
14004 // Find the largest store unit
14005 MVT StoreType = MVT::i8;
14006 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14007 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14008 MVT Tp = (MVT::SimpleValueType)tp;
14009 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14013 // Bitcast the original vector into a vector of store-size units
14014 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14015 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14016 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14017 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14018 SmallVector<SDValue, 8> Chains;
14019 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14020 TLI.getPointerTy());
14021 SDValue Ptr = St->getBasePtr();
14023 // Perform one or more big stores into memory.
14024 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14025 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14026 StoreType, ShuffWide,
14027 DAG.getIntPtrConstant(i));
14028 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14029 St->getPointerInfo(), St->isVolatile(),
14030 St->isNonTemporal(), St->getAlignment());
14031 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14032 Chains.push_back(Ch);
14035 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14040 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14041 // the FP state in cases where an emms may be missing.
14042 // A preferable solution to the general problem is to figure out the right
14043 // places to insert EMMS. This qualifies as a quick hack.
14045 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14046 if (VT.getSizeInBits() != 64)
14049 const Function *F = DAG.getMachineFunction().getFunction();
14050 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14051 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14052 && Subtarget->hasXMMInt();
14053 if ((VT.isVector() ||
14054 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14055 isa<LoadSDNode>(St->getValue()) &&
14056 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14057 St->getChain().hasOneUse() && !St->isVolatile()) {
14058 SDNode* LdVal = St->getValue().getNode();
14059 LoadSDNode *Ld = 0;
14060 int TokenFactorIndex = -1;
14061 SmallVector<SDValue, 8> Ops;
14062 SDNode* ChainVal = St->getChain().getNode();
14063 // Must be a store of a load. We currently handle two cases: the load
14064 // is a direct child, and it's under an intervening TokenFactor. It is
14065 // possible to dig deeper under nested TokenFactors.
14066 if (ChainVal == LdVal)
14067 Ld = cast<LoadSDNode>(St->getChain());
14068 else if (St->getValue().hasOneUse() &&
14069 ChainVal->getOpcode() == ISD::TokenFactor) {
14070 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14071 if (ChainVal->getOperand(i).getNode() == LdVal) {
14072 TokenFactorIndex = i;
14073 Ld = cast<LoadSDNode>(St->getValue());
14075 Ops.push_back(ChainVal->getOperand(i));
14079 if (!Ld || !ISD::isNormalLoad(Ld))
14082 // If this is not the MMX case, i.e. we are just turning i64 load/store
14083 // into f64 load/store, avoid the transformation if there are multiple
14084 // uses of the loaded value.
14085 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14088 DebugLoc LdDL = Ld->getDebugLoc();
14089 DebugLoc StDL = N->getDebugLoc();
14090 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14091 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14093 if (Subtarget->is64Bit() || F64IsLegal) {
14094 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14095 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14096 Ld->getPointerInfo(), Ld->isVolatile(),
14097 Ld->isNonTemporal(), Ld->isInvariant(),
14098 Ld->getAlignment());
14099 SDValue NewChain = NewLd.getValue(1);
14100 if (TokenFactorIndex != -1) {
14101 Ops.push_back(NewChain);
14102 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14105 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14106 St->getPointerInfo(),
14107 St->isVolatile(), St->isNonTemporal(),
14108 St->getAlignment());
14111 // Otherwise, lower to two pairs of 32-bit loads / stores.
14112 SDValue LoAddr = Ld->getBasePtr();
14113 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14114 DAG.getConstant(4, MVT::i32));
14116 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14117 Ld->getPointerInfo(),
14118 Ld->isVolatile(), Ld->isNonTemporal(),
14119 Ld->isInvariant(), Ld->getAlignment());
14120 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14121 Ld->getPointerInfo().getWithOffset(4),
14122 Ld->isVolatile(), Ld->isNonTemporal(),
14124 MinAlign(Ld->getAlignment(), 4));
14126 SDValue NewChain = LoLd.getValue(1);
14127 if (TokenFactorIndex != -1) {
14128 Ops.push_back(LoLd);
14129 Ops.push_back(HiLd);
14130 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14134 LoAddr = St->getBasePtr();
14135 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14136 DAG.getConstant(4, MVT::i32));
14138 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14139 St->getPointerInfo(),
14140 St->isVolatile(), St->isNonTemporal(),
14141 St->getAlignment());
14142 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14143 St->getPointerInfo().getWithOffset(4),
14145 St->isNonTemporal(),
14146 MinAlign(St->getAlignment(), 4));
14147 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14152 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14153 /// and return the operands for the horizontal operation in LHS and RHS. A
14154 /// horizontal operation performs the binary operation on successive elements
14155 /// of its first operand, then on successive elements of its second operand,
14156 /// returning the resulting values in a vector. For example, if
14157 /// A = < float a0, float a1, float a2, float a3 >
14159 /// B = < float b0, float b1, float b2, float b3 >
14160 /// then the result of doing a horizontal operation on A and B is
14161 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14162 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14163 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14164 /// set to A, RHS to B, and the routine returns 'true'.
14165 /// Note that the binary operation should have the property that if one of the
14166 /// operands is UNDEF then the result is UNDEF.
14167 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14168 // Look for the following pattern: if
14169 // A = < float a0, float a1, float a2, float a3 >
14170 // B = < float b0, float b1, float b2, float b3 >
14172 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14173 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14174 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14175 // which is A horizontal-op B.
14177 // At least one of the operands should be a vector shuffle.
14178 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14179 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14182 EVT VT = LHS.getValueType();
14184 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14185 "Unsupported vector type for horizontal add/sub");
14187 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14188 // operate independently on 128-bit lanes.
14189 unsigned NumElts = VT.getVectorNumElements();
14190 unsigned NumLanes = VT.getSizeInBits()/128;
14191 unsigned NumLaneElts = NumElts / NumLanes;
14192 assert((NumLaneElts % 2 == 0) &&
14193 "Vector type should have an even number of elements in each lane");
14194 unsigned HalfLaneElts = NumLaneElts/2;
14196 // View LHS in the form
14197 // LHS = VECTOR_SHUFFLE A, B, LMask
14198 // If LHS is not a shuffle then pretend it is the shuffle
14199 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14200 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14203 SmallVector<int, 16> LMask(NumElts);
14204 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14205 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14206 A = LHS.getOperand(0);
14207 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14208 B = LHS.getOperand(1);
14209 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14211 if (LHS.getOpcode() != ISD::UNDEF)
14213 for (unsigned i = 0; i != NumElts; ++i)
14217 // Likewise, view RHS in the form
14218 // RHS = VECTOR_SHUFFLE C, D, RMask
14220 SmallVector<int, 16> RMask(NumElts);
14221 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14222 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14223 C = RHS.getOperand(0);
14224 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14225 D = RHS.getOperand(1);
14226 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14228 if (RHS.getOpcode() != ISD::UNDEF)
14230 for (unsigned i = 0; i != NumElts; ++i)
14234 // Check that the shuffles are both shuffling the same vectors.
14235 if (!(A == C && B == D) && !(A == D && B == C))
14238 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14239 if (!A.getNode() && !B.getNode())
14242 // If A and B occur in reverse order in RHS, then "swap" them (which means
14243 // rewriting the mask).
14245 CommuteVectorShuffleMask(RMask, NumElts);
14247 // At this point LHS and RHS are equivalent to
14248 // LHS = VECTOR_SHUFFLE A, B, LMask
14249 // RHS = VECTOR_SHUFFLE A, B, RMask
14250 // Check that the masks correspond to performing a horizontal operation.
14251 for (unsigned i = 0; i != NumElts; ++i) {
14252 int LIdx = LMask[i], RIdx = RMask[i];
14254 // Ignore any UNDEF components.
14255 if (LIdx < 0 || RIdx < 0 ||
14256 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14257 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14260 // Check that successive elements are being operated on. If not, this is
14261 // not a horizontal operation.
14262 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14263 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14264 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14265 if (!(LIdx == Index && RIdx == Index + 1) &&
14266 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14270 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14271 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14275 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14276 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14277 const X86Subtarget *Subtarget) {
14278 EVT VT = N->getValueType(0);
14279 SDValue LHS = N->getOperand(0);
14280 SDValue RHS = N->getOperand(1);
14282 // Try to synthesize horizontal adds from adds of shuffles.
14283 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14284 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14285 isHorizontalBinOp(LHS, RHS, true))
14286 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14290 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14291 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14292 const X86Subtarget *Subtarget) {
14293 EVT VT = N->getValueType(0);
14294 SDValue LHS = N->getOperand(0);
14295 SDValue RHS = N->getOperand(1);
14297 // Try to synthesize horizontal subs from subs of shuffles.
14298 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14299 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14300 isHorizontalBinOp(LHS, RHS, false))
14301 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14305 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14306 /// X86ISD::FXOR nodes.
14307 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14308 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14309 // F[X]OR(0.0, x) -> x
14310 // F[X]OR(x, 0.0) -> x
14311 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14312 if (C->getValueAPF().isPosZero())
14313 return N->getOperand(1);
14314 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14315 if (C->getValueAPF().isPosZero())
14316 return N->getOperand(0);
14320 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14321 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14322 // FAND(0.0, x) -> 0.0
14323 // FAND(x, 0.0) -> 0.0
14324 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14325 if (C->getValueAPF().isPosZero())
14326 return N->getOperand(0);
14327 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14328 if (C->getValueAPF().isPosZero())
14329 return N->getOperand(1);
14333 static SDValue PerformBTCombine(SDNode *N,
14335 TargetLowering::DAGCombinerInfo &DCI) {
14336 // BT ignores high bits in the bit index operand.
14337 SDValue Op1 = N->getOperand(1);
14338 if (Op1.hasOneUse()) {
14339 unsigned BitWidth = Op1.getValueSizeInBits();
14340 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14341 APInt KnownZero, KnownOne;
14342 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14343 !DCI.isBeforeLegalizeOps());
14344 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14345 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14346 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14347 DCI.CommitTargetLoweringOpt(TLO);
14352 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14353 SDValue Op = N->getOperand(0);
14354 if (Op.getOpcode() == ISD::BITCAST)
14355 Op = Op.getOperand(0);
14356 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14357 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14358 VT.getVectorElementType().getSizeInBits() ==
14359 OpVT.getVectorElementType().getSizeInBits()) {
14360 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14365 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14366 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14367 // (and (i32 x86isd::setcc_carry), 1)
14368 // This eliminates the zext. This transformation is necessary because
14369 // ISD::SETCC is always legalized to i8.
14370 DebugLoc dl = N->getDebugLoc();
14371 SDValue N0 = N->getOperand(0);
14372 EVT VT = N->getValueType(0);
14373 if (N0.getOpcode() == ISD::AND &&
14375 N0.getOperand(0).hasOneUse()) {
14376 SDValue N00 = N0.getOperand(0);
14377 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14380 if (!C || C->getZExtValue() != 1)
14382 return DAG.getNode(ISD::AND, dl, VT,
14383 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14384 N00.getOperand(0), N00.getOperand(1)),
14385 DAG.getConstant(1, VT));
14391 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14392 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14393 unsigned X86CC = N->getConstantOperandVal(0);
14394 SDValue EFLAG = N->getOperand(1);
14395 DebugLoc DL = N->getDebugLoc();
14397 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14398 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14400 if (X86CC == X86::COND_B)
14401 return DAG.getNode(ISD::AND, DL, MVT::i8,
14402 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14403 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14404 DAG.getConstant(1, MVT::i8));
14409 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14410 const X86TargetLowering *XTLI) {
14411 SDValue Op0 = N->getOperand(0);
14412 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14413 // a 32-bit target where SSE doesn't support i64->FP operations.
14414 if (Op0.getOpcode() == ISD::LOAD) {
14415 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14416 EVT VT = Ld->getValueType(0);
14417 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14418 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14419 !XTLI->getSubtarget()->is64Bit() &&
14420 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14421 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14422 Ld->getChain(), Op0, DAG);
14423 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14430 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14431 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14432 X86TargetLowering::DAGCombinerInfo &DCI) {
14433 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14434 // the result is either zero or one (depending on the input carry bit).
14435 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14436 if (X86::isZeroNode(N->getOperand(0)) &&
14437 X86::isZeroNode(N->getOperand(1)) &&
14438 // We don't have a good way to replace an EFLAGS use, so only do this when
14440 SDValue(N, 1).use_empty()) {
14441 DebugLoc DL = N->getDebugLoc();
14442 EVT VT = N->getValueType(0);
14443 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14444 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14445 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14446 DAG.getConstant(X86::COND_B,MVT::i8),
14448 DAG.getConstant(1, VT));
14449 return DCI.CombineTo(N, Res1, CarryOut);
14455 // fold (add Y, (sete X, 0)) -> adc 0, Y
14456 // (add Y, (setne X, 0)) -> sbb -1, Y
14457 // (sub (sete X, 0), Y) -> sbb 0, Y
14458 // (sub (setne X, 0), Y) -> adc -1, Y
14459 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14460 DebugLoc DL = N->getDebugLoc();
14462 // Look through ZExts.
14463 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14464 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14467 SDValue SetCC = Ext.getOperand(0);
14468 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14471 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14472 if (CC != X86::COND_E && CC != X86::COND_NE)
14475 SDValue Cmp = SetCC.getOperand(1);
14476 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14477 !X86::isZeroNode(Cmp.getOperand(1)) ||
14478 !Cmp.getOperand(0).getValueType().isInteger())
14481 SDValue CmpOp0 = Cmp.getOperand(0);
14482 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14483 DAG.getConstant(1, CmpOp0.getValueType()));
14485 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14486 if (CC == X86::COND_NE)
14487 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14488 DL, OtherVal.getValueType(), OtherVal,
14489 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14490 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14491 DL, OtherVal.getValueType(), OtherVal,
14492 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14495 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14496 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14497 const X86Subtarget *Subtarget) {
14498 EVT VT = N->getValueType(0);
14499 SDValue Op0 = N->getOperand(0);
14500 SDValue Op1 = N->getOperand(1);
14502 // Try to synthesize horizontal adds from adds of shuffles.
14503 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14504 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14505 isHorizontalBinOp(Op0, Op1, true))
14506 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14508 return OptimizeConditionalInDecrement(N, DAG);
14511 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14512 const X86Subtarget *Subtarget) {
14513 SDValue Op0 = N->getOperand(0);
14514 SDValue Op1 = N->getOperand(1);
14516 // X86 can't encode an immediate LHS of a sub. See if we can push the
14517 // negation into a preceding instruction.
14518 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14519 // If the RHS of the sub is a XOR with one use and a constant, invert the
14520 // immediate. Then add one to the LHS of the sub so we can turn
14521 // X-Y -> X+~Y+1, saving one register.
14522 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14523 isa<ConstantSDNode>(Op1.getOperand(1))) {
14524 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14525 EVT VT = Op0.getValueType();
14526 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14528 DAG.getConstant(~XorC, VT));
14529 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14530 DAG.getConstant(C->getAPIntValue()+1, VT));
14534 // Try to synthesize horizontal adds from adds of shuffles.
14535 EVT VT = N->getValueType(0);
14536 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14537 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14538 isHorizontalBinOp(Op0, Op1, true))
14539 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14541 return OptimizeConditionalInDecrement(N, DAG);
14544 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14545 DAGCombinerInfo &DCI) const {
14546 SelectionDAG &DAG = DCI.DAG;
14547 switch (N->getOpcode()) {
14549 case ISD::EXTRACT_VECTOR_ELT:
14550 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14552 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14553 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14554 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14555 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14556 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14557 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14560 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14561 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14562 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14563 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14564 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14565 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14566 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14567 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14568 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14570 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14571 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14572 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14573 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14574 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14575 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14576 case X86ISD::SHUFPS: // Handle all target specific shuffles
14577 case X86ISD::SHUFPD:
14578 case X86ISD::PALIGN:
14579 case X86ISD::UNPCKH:
14580 case X86ISD::UNPCKL:
14581 case X86ISD::MOVHLPS:
14582 case X86ISD::MOVLHPS:
14583 case X86ISD::PSHUFD:
14584 case X86ISD::PSHUFHW:
14585 case X86ISD::PSHUFLW:
14586 case X86ISD::MOVSS:
14587 case X86ISD::MOVSD:
14588 case X86ISD::VPERMILP:
14589 case X86ISD::VPERM2X128:
14590 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14596 /// isTypeDesirableForOp - Return true if the target has native support for
14597 /// the specified value type and it is 'desirable' to use the type for the
14598 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14599 /// instruction encodings are longer and some i16 instructions are slow.
14600 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14601 if (!isTypeLegal(VT))
14603 if (VT != MVT::i16)
14610 case ISD::SIGN_EXTEND:
14611 case ISD::ZERO_EXTEND:
14612 case ISD::ANY_EXTEND:
14625 /// IsDesirableToPromoteOp - This method query the target whether it is
14626 /// beneficial for dag combiner to promote the specified node. If true, it
14627 /// should return the desired promotion type by reference.
14628 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14629 EVT VT = Op.getValueType();
14630 if (VT != MVT::i16)
14633 bool Promote = false;
14634 bool Commute = false;
14635 switch (Op.getOpcode()) {
14638 LoadSDNode *LD = cast<LoadSDNode>(Op);
14639 // If the non-extending load has a single use and it's not live out, then it
14640 // might be folded.
14641 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14642 Op.hasOneUse()*/) {
14643 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14644 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14645 // The only case where we'd want to promote LOAD (rather then it being
14646 // promoted as an operand is when it's only use is liveout.
14647 if (UI->getOpcode() != ISD::CopyToReg)
14654 case ISD::SIGN_EXTEND:
14655 case ISD::ZERO_EXTEND:
14656 case ISD::ANY_EXTEND:
14661 SDValue N0 = Op.getOperand(0);
14662 // Look out for (store (shl (load), x)).
14663 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14676 SDValue N0 = Op.getOperand(0);
14677 SDValue N1 = Op.getOperand(1);
14678 if (!Commute && MayFoldLoad(N1))
14680 // Avoid disabling potential load folding opportunities.
14681 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14683 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14693 //===----------------------------------------------------------------------===//
14694 // X86 Inline Assembly Support
14695 //===----------------------------------------------------------------------===//
14698 // Helper to match a string separated by whitespace.
14699 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14700 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14702 for (unsigned i = 0, e = args.size(); i != e; ++i) {
14703 StringRef piece(*args[i]);
14704 if (!s.startswith(piece)) // Check if the piece matches.
14707 s = s.substr(piece.size());
14708 StringRef::size_type pos = s.find_first_not_of(" \t");
14709 if (pos == 0) // We matched a prefix.
14717 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14720 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14721 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14723 std::string AsmStr = IA->getAsmString();
14725 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14726 if (!Ty || Ty->getBitWidth() % 16 != 0)
14729 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14730 SmallVector<StringRef, 4> AsmPieces;
14731 SplitString(AsmStr, AsmPieces, ";\n");
14733 switch (AsmPieces.size()) {
14734 default: return false;
14736 // FIXME: this should verify that we are targeting a 486 or better. If not,
14737 // we will turn this bswap into something that will be lowered to logical
14738 // ops instead of emitting the bswap asm. For now, we don't support 486 or
14739 // lower so don't worry about this.
14741 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14742 matchAsm(AsmPieces[0], "bswapl", "$0") ||
14743 matchAsm(AsmPieces[0], "bswapq", "$0") ||
14744 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14745 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14746 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14747 // No need to check constraints, nothing other than the equivalent of
14748 // "=r,0" would be valid here.
14749 return IntrinsicLowering::LowerToByteSwap(CI);
14752 // rorw $$8, ${0:w} --> llvm.bswap.i16
14753 if (CI->getType()->isIntegerTy(16) &&
14754 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14755 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14756 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14758 const std::string &ConstraintsStr = IA->getConstraintString();
14759 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14760 std::sort(AsmPieces.begin(), AsmPieces.end());
14761 if (AsmPieces.size() == 4 &&
14762 AsmPieces[0] == "~{cc}" &&
14763 AsmPieces[1] == "~{dirflag}" &&
14764 AsmPieces[2] == "~{flags}" &&
14765 AsmPieces[3] == "~{fpsr}")
14766 return IntrinsicLowering::LowerToByteSwap(CI);
14770 if (CI->getType()->isIntegerTy(32) &&
14771 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14772 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14773 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14774 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14776 const std::string &ConstraintsStr = IA->getConstraintString();
14777 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14778 std::sort(AsmPieces.begin(), AsmPieces.end());
14779 if (AsmPieces.size() == 4 &&
14780 AsmPieces[0] == "~{cc}" &&
14781 AsmPieces[1] == "~{dirflag}" &&
14782 AsmPieces[2] == "~{flags}" &&
14783 AsmPieces[3] == "~{fpsr}")
14784 return IntrinsicLowering::LowerToByteSwap(CI);
14787 if (CI->getType()->isIntegerTy(64)) {
14788 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14789 if (Constraints.size() >= 2 &&
14790 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14791 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14792 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14793 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14794 matchAsm(AsmPieces[1], "bswap", "%edx") &&
14795 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14796 return IntrinsicLowering::LowerToByteSwap(CI);
14806 /// getConstraintType - Given a constraint letter, return the type of
14807 /// constraint it is for this target.
14808 X86TargetLowering::ConstraintType
14809 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14810 if (Constraint.size() == 1) {
14811 switch (Constraint[0]) {
14822 return C_RegisterClass;
14846 return TargetLowering::getConstraintType(Constraint);
14849 /// Examine constraint type and operand type and determine a weight value.
14850 /// This object must already have been set up with the operand type
14851 /// and the current alternative constraint selected.
14852 TargetLowering::ConstraintWeight
14853 X86TargetLowering::getSingleConstraintMatchWeight(
14854 AsmOperandInfo &info, const char *constraint) const {
14855 ConstraintWeight weight = CW_Invalid;
14856 Value *CallOperandVal = info.CallOperandVal;
14857 // If we don't have a value, we can't do a match,
14858 // but allow it at the lowest weight.
14859 if (CallOperandVal == NULL)
14861 Type *type = CallOperandVal->getType();
14862 // Look at the constraint type.
14863 switch (*constraint) {
14865 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14876 if (CallOperandVal->getType()->isIntegerTy())
14877 weight = CW_SpecificReg;
14882 if (type->isFloatingPointTy())
14883 weight = CW_SpecificReg;
14886 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14887 weight = CW_SpecificReg;
14891 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14892 weight = CW_Register;
14895 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14896 if (C->getZExtValue() <= 31)
14897 weight = CW_Constant;
14901 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14902 if (C->getZExtValue() <= 63)
14903 weight = CW_Constant;
14907 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14908 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14909 weight = CW_Constant;
14913 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14914 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14915 weight = CW_Constant;
14919 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14920 if (C->getZExtValue() <= 3)
14921 weight = CW_Constant;
14925 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14926 if (C->getZExtValue() <= 0xff)
14927 weight = CW_Constant;
14932 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14933 weight = CW_Constant;
14937 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14938 if ((C->getSExtValue() >= -0x80000000LL) &&
14939 (C->getSExtValue() <= 0x7fffffffLL))
14940 weight = CW_Constant;
14944 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14945 if (C->getZExtValue() <= 0xffffffff)
14946 weight = CW_Constant;
14953 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14954 /// with another that has more specific requirements based on the type of the
14955 /// corresponding operand.
14956 const char *X86TargetLowering::
14957 LowerXConstraint(EVT ConstraintVT) const {
14958 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14959 // 'f' like normal targets.
14960 if (ConstraintVT.isFloatingPoint()) {
14961 if (Subtarget->hasXMMInt())
14963 if (Subtarget->hasXMM())
14967 return TargetLowering::LowerXConstraint(ConstraintVT);
14970 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14971 /// vector. If it is invalid, don't add anything to Ops.
14972 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14973 std::string &Constraint,
14974 std::vector<SDValue>&Ops,
14975 SelectionDAG &DAG) const {
14976 SDValue Result(0, 0);
14978 // Only support length 1 constraints for now.
14979 if (Constraint.length() > 1) return;
14981 char ConstraintLetter = Constraint[0];
14982 switch (ConstraintLetter) {
14985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14986 if (C->getZExtValue() <= 31) {
14987 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14994 if (C->getZExtValue() <= 63) {
14995 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15002 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15003 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15010 if (C->getZExtValue() <= 255) {
15011 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15017 // 32-bit signed value
15018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15019 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15020 C->getSExtValue())) {
15021 // Widen to 64 bits here to get it sign extended.
15022 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15025 // FIXME gcc accepts some relocatable values here too, but only in certain
15026 // memory models; it's complicated.
15031 // 32-bit unsigned value
15032 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15033 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15034 C->getZExtValue())) {
15035 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15039 // FIXME gcc accepts some relocatable values here too, but only in certain
15040 // memory models; it's complicated.
15044 // Literal immediates are always ok.
15045 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15046 // Widen to 64 bits here to get it sign extended.
15047 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15051 // In any sort of PIC mode addresses need to be computed at runtime by
15052 // adding in a register or some sort of table lookup. These can't
15053 // be used as immediates.
15054 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15057 // If we are in non-pic codegen mode, we allow the address of a global (with
15058 // an optional displacement) to be used with 'i'.
15059 GlobalAddressSDNode *GA = 0;
15060 int64_t Offset = 0;
15062 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15064 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15065 Offset += GA->getOffset();
15067 } else if (Op.getOpcode() == ISD::ADD) {
15068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15069 Offset += C->getZExtValue();
15070 Op = Op.getOperand(0);
15073 } else if (Op.getOpcode() == ISD::SUB) {
15074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15075 Offset += -C->getZExtValue();
15076 Op = Op.getOperand(0);
15081 // Otherwise, this isn't something we can handle, reject it.
15085 const GlobalValue *GV = GA->getGlobal();
15086 // If we require an extra load to get this address, as in PIC mode, we
15087 // can't accept it.
15088 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15089 getTargetMachine())))
15092 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15093 GA->getValueType(0), Offset);
15098 if (Result.getNode()) {
15099 Ops.push_back(Result);
15102 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15105 std::pair<unsigned, const TargetRegisterClass*>
15106 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15108 // First, see if this is a constraint that directly corresponds to an LLVM
15110 if (Constraint.size() == 1) {
15111 // GCC Constraint Letters
15112 switch (Constraint[0]) {
15114 // TODO: Slight differences here in allocation order and leaving
15115 // RIP in the class. Do they matter any more here than they do
15116 // in the normal allocation?
15117 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15118 if (Subtarget->is64Bit()) {
15119 if (VT == MVT::i32 || VT == MVT::f32)
15120 return std::make_pair(0U, X86::GR32RegisterClass);
15121 else if (VT == MVT::i16)
15122 return std::make_pair(0U, X86::GR16RegisterClass);
15123 else if (VT == MVT::i8 || VT == MVT::i1)
15124 return std::make_pair(0U, X86::GR8RegisterClass);
15125 else if (VT == MVT::i64 || VT == MVT::f64)
15126 return std::make_pair(0U, X86::GR64RegisterClass);
15129 // 32-bit fallthrough
15130 case 'Q': // Q_REGS
15131 if (VT == MVT::i32 || VT == MVT::f32)
15132 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15133 else if (VT == MVT::i16)
15134 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15135 else if (VT == MVT::i8 || VT == MVT::i1)
15136 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15137 else if (VT == MVT::i64)
15138 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15140 case 'r': // GENERAL_REGS
15141 case 'l': // INDEX_REGS
15142 if (VT == MVT::i8 || VT == MVT::i1)
15143 return std::make_pair(0U, X86::GR8RegisterClass);
15144 if (VT == MVT::i16)
15145 return std::make_pair(0U, X86::GR16RegisterClass);
15146 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15147 return std::make_pair(0U, X86::GR32RegisterClass);
15148 return std::make_pair(0U, X86::GR64RegisterClass);
15149 case 'R': // LEGACY_REGS
15150 if (VT == MVT::i8 || VT == MVT::i1)
15151 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15152 if (VT == MVT::i16)
15153 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15154 if (VT == MVT::i32 || !Subtarget->is64Bit())
15155 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15156 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15157 case 'f': // FP Stack registers.
15158 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15159 // value to the correct fpstack register class.
15160 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15161 return std::make_pair(0U, X86::RFP32RegisterClass);
15162 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15163 return std::make_pair(0U, X86::RFP64RegisterClass);
15164 return std::make_pair(0U, X86::RFP80RegisterClass);
15165 case 'y': // MMX_REGS if MMX allowed.
15166 if (!Subtarget->hasMMX()) break;
15167 return std::make_pair(0U, X86::VR64RegisterClass);
15168 case 'Y': // SSE_REGS if SSE2 allowed
15169 if (!Subtarget->hasXMMInt()) break;
15171 case 'x': // SSE_REGS if SSE1 allowed
15172 if (!Subtarget->hasXMM()) break;
15174 switch (VT.getSimpleVT().SimpleTy) {
15176 // Scalar SSE types.
15179 return std::make_pair(0U, X86::FR32RegisterClass);
15182 return std::make_pair(0U, X86::FR64RegisterClass);
15190 return std::make_pair(0U, X86::VR128RegisterClass);
15196 // Use the default implementation in TargetLowering to convert the register
15197 // constraint into a member of a register class.
15198 std::pair<unsigned, const TargetRegisterClass*> Res;
15199 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15201 // Not found as a standard register?
15202 if (Res.second == 0) {
15203 // Map st(0) -> st(7) -> ST0
15204 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15205 tolower(Constraint[1]) == 's' &&
15206 tolower(Constraint[2]) == 't' &&
15207 Constraint[3] == '(' &&
15208 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15209 Constraint[5] == ')' &&
15210 Constraint[6] == '}') {
15212 Res.first = X86::ST0+Constraint[4]-'0';
15213 Res.second = X86::RFP80RegisterClass;
15217 // GCC allows "st(0)" to be called just plain "st".
15218 if (StringRef("{st}").equals_lower(Constraint)) {
15219 Res.first = X86::ST0;
15220 Res.second = X86::RFP80RegisterClass;
15225 if (StringRef("{flags}").equals_lower(Constraint)) {
15226 Res.first = X86::EFLAGS;
15227 Res.second = X86::CCRRegisterClass;
15231 // 'A' means EAX + EDX.
15232 if (Constraint == "A") {
15233 Res.first = X86::EAX;
15234 Res.second = X86::GR32_ADRegisterClass;
15240 // Otherwise, check to see if this is a register class of the wrong value
15241 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15242 // turn into {ax},{dx}.
15243 if (Res.second->hasType(VT))
15244 return Res; // Correct type already, nothing to do.
15246 // All of the single-register GCC register classes map their values onto
15247 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15248 // really want an 8-bit or 32-bit register, map to the appropriate register
15249 // class and return the appropriate register.
15250 if (Res.second == X86::GR16RegisterClass) {
15251 if (VT == MVT::i8) {
15252 unsigned DestReg = 0;
15253 switch (Res.first) {
15255 case X86::AX: DestReg = X86::AL; break;
15256 case X86::DX: DestReg = X86::DL; break;
15257 case X86::CX: DestReg = X86::CL; break;
15258 case X86::BX: DestReg = X86::BL; break;
15261 Res.first = DestReg;
15262 Res.second = X86::GR8RegisterClass;
15264 } else if (VT == MVT::i32) {
15265 unsigned DestReg = 0;
15266 switch (Res.first) {
15268 case X86::AX: DestReg = X86::EAX; break;
15269 case X86::DX: DestReg = X86::EDX; break;
15270 case X86::CX: DestReg = X86::ECX; break;
15271 case X86::BX: DestReg = X86::EBX; break;
15272 case X86::SI: DestReg = X86::ESI; break;
15273 case X86::DI: DestReg = X86::EDI; break;
15274 case X86::BP: DestReg = X86::EBP; break;
15275 case X86::SP: DestReg = X86::ESP; break;
15278 Res.first = DestReg;
15279 Res.second = X86::GR32RegisterClass;
15281 } else if (VT == MVT::i64) {
15282 unsigned DestReg = 0;
15283 switch (Res.first) {
15285 case X86::AX: DestReg = X86::RAX; break;
15286 case X86::DX: DestReg = X86::RDX; break;
15287 case X86::CX: DestReg = X86::RCX; break;
15288 case X86::BX: DestReg = X86::RBX; break;
15289 case X86::SI: DestReg = X86::RSI; break;
15290 case X86::DI: DestReg = X86::RDI; break;
15291 case X86::BP: DestReg = X86::RBP; break;
15292 case X86::SP: DestReg = X86::RSP; break;
15295 Res.first = DestReg;
15296 Res.second = X86::GR64RegisterClass;
15299 } else if (Res.second == X86::FR32RegisterClass ||
15300 Res.second == X86::FR64RegisterClass ||
15301 Res.second == X86::VR128RegisterClass) {
15302 // Handle references to XMM physical registers that got mapped into the
15303 // wrong class. This can happen with constraints like {xmm0} where the
15304 // target independent register mapper will just pick the first match it can
15305 // find, ignoring the required type.
15306 if (VT == MVT::f32)
15307 Res.second = X86::FR32RegisterClass;
15308 else if (VT == MVT::f64)
15309 Res.second = X86::FR64RegisterClass;
15310 else if (X86::VR128RegisterClass->hasType(VT))
15311 Res.second = X86::VR128RegisterClass;