1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/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 (!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);
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 (!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 if (Subtarget->hasBMI()) {
383 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
385 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
386 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
387 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
388 if (Subtarget->is64Bit())
389 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
392 if (Subtarget->hasLZCNT()) {
393 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
395 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
396 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
402 if (Subtarget->hasPOPCNT()) {
403 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
405 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
406 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
407 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
408 if (Subtarget->is64Bit())
409 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
412 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
413 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
415 // These should be promoted to a larger select which is supported.
416 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
417 // X86 wants to expand cmov itself.
418 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
419 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
420 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
423 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
426 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
429 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
430 if (Subtarget->is64Bit()) {
431 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
432 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
434 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
437 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
438 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
439 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
440 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
441 if (Subtarget->is64Bit())
442 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
444 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
445 if (Subtarget->is64Bit()) {
446 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
447 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
448 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
449 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
450 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
452 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
454 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
455 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
456 if (Subtarget->is64Bit()) {
457 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
458 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
459 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
462 if (Subtarget->hasXMM())
463 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
465 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
466 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
468 // On X86 and X86-64, atomic operations are lowered to locked instructions.
469 // Locked instructions, in turn, have implicit fence semantics (all memory
470 // operations are flushed before issuing the locked instruction, and they
471 // are not buffered), so we can fold away the common pattern of
472 // fence-atomic-fence.
473 setShouldFoldAtomicFences(true);
475 // Expand certain atomics
476 for (unsigned i = 0, e = 4; i != e; ++i) {
478 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
483 if (!Subtarget->is64Bit()) {
484 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
494 if (Subtarget->hasCmpxchg16b()) {
495 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
498 // FIXME - use subtarget debug flags
499 if (!Subtarget->isTargetDarwin() &&
500 !Subtarget->isTargetELF() &&
501 !Subtarget->isTargetCygMing()) {
502 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
505 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
507 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
509 if (Subtarget->is64Bit()) {
510 setExceptionPointerRegister(X86::RAX);
511 setExceptionSelectorRegister(X86::RDX);
513 setExceptionPointerRegister(X86::EAX);
514 setExceptionSelectorRegister(X86::EDX);
516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
519 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
522 setOperationAction(ISD::TRAP, MVT::Other, Legal);
524 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525 setOperationAction(ISD::VASTART , MVT::Other, Custom);
526 setOperationAction(ISD::VAEND , MVT::Other, Expand);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::VAARG , MVT::Other, Custom);
529 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
531 setOperationAction(ISD::VAARG , MVT::Other, Expand);
532 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
535 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
536 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
538 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540 MVT::i64 : MVT::i32, Custom);
541 else if (EnableSegmentedStacks)
542 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543 MVT::i64 : MVT::i32, Custom);
545 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546 MVT::i64 : MVT::i32, Expand);
548 if (!UseSoftFloat && X86ScalarSSEf64) {
549 // f32 and f64 use SSE.
550 // Set up the FP register classes.
551 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
554 // Use ANDPD to simulate FABS.
555 setOperationAction(ISD::FABS , MVT::f64, Custom);
556 setOperationAction(ISD::FABS , MVT::f32, Custom);
558 // Use XORP to simulate FNEG.
559 setOperationAction(ISD::FNEG , MVT::f64, Custom);
560 setOperationAction(ISD::FNEG , MVT::f32, Custom);
562 // Use ANDPD and ORPD to simulate FCOPYSIGN.
563 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566 // Lower this to FGETSIGNx86 plus an AND.
567 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
570 // We don't support sin/cos/fmod
571 setOperationAction(ISD::FSIN , MVT::f64, Expand);
572 setOperationAction(ISD::FCOS , MVT::f64, Expand);
573 setOperationAction(ISD::FSIN , MVT::f32, Expand);
574 setOperationAction(ISD::FCOS , MVT::f32, Expand);
576 // Expand FP immediates into loads from the stack, except for the special
578 addLegalFPImmediate(APFloat(+0.0)); // xorpd
579 addLegalFPImmediate(APFloat(+0.0f)); // xorps
580 } else if (!UseSoftFloat && X86ScalarSSEf32) {
581 // Use SSE for f32, x87 for f64.
582 // Set up the FP register classes.
583 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
586 // Use ANDPS to simulate FABS.
587 setOperationAction(ISD::FABS , MVT::f32, Custom);
589 // Use XORP to simulate FNEG.
590 setOperationAction(ISD::FNEG , MVT::f32, Custom);
592 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
594 // Use ANDPS and ORPS to simulate FCOPYSIGN.
595 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
598 // We don't support sin/cos/fmod
599 setOperationAction(ISD::FSIN , MVT::f32, Expand);
600 setOperationAction(ISD::FCOS , MVT::f32, Expand);
602 // Special cases we handle for FP constants.
603 addLegalFPImmediate(APFloat(+0.0f)); // xorps
604 addLegalFPImmediate(APFloat(+0.0)); // FLD0
605 addLegalFPImmediate(APFloat(+1.0)); // FLD1
606 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
610 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
611 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
613 } else if (!UseSoftFloat) {
614 // f32 and f64 in x87.
615 // Set up the FP register classes.
616 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
619 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
620 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
625 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
626 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
628 addLegalFPImmediate(APFloat(+0.0)); // FLD0
629 addLegalFPImmediate(APFloat(+1.0)); // FLD1
630 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
638 // We don't support FMA.
639 setOperationAction(ISD::FMA, MVT::f64, Expand);
640 setOperationAction(ISD::FMA, MVT::f32, Expand);
642 // Long double always uses X87.
644 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
646 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
648 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649 addLegalFPImmediate(TmpFlt); // FLD0
651 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
654 APFloat TmpFlt2(+1.0);
655 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
657 addLegalFPImmediate(TmpFlt2); // FLD1
658 TmpFlt2.changeSign();
659 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
663 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
667 setOperationAction(ISD::FMA, MVT::f80, Expand);
670 // Always use a library call for pow.
671 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
675 setOperationAction(ISD::FLOG, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681 // First set operation action for all vector types to either promote
682 // (for widening) or expand (for scalarization). Then we will selectively
683 // turn on ones that can be effectively codegen'd.
684 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
741 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743 setTruncStoreAction((MVT::SimpleValueType)VT,
744 (MVT::SimpleValueType)InnerVT, Expand);
745 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751 // with -msoft-float, disable use of MMX as well.
752 if (!UseSoftFloat && Subtarget->hasMMX()) {
753 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754 // No operations on x86mmx supported, everything uses intrinsics.
757 // MMX-sized vectors (other than x86mmx) are expected to be expanded
758 // into smaller operations.
759 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
760 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
761 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
762 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
763 setOperationAction(ISD::AND, MVT::v8i8, Expand);
764 setOperationAction(ISD::AND, MVT::v4i16, Expand);
765 setOperationAction(ISD::AND, MVT::v2i32, Expand);
766 setOperationAction(ISD::AND, MVT::v1i64, Expand);
767 setOperationAction(ISD::OR, MVT::v8i8, Expand);
768 setOperationAction(ISD::OR, MVT::v4i16, Expand);
769 setOperationAction(ISD::OR, MVT::v2i32, Expand);
770 setOperationAction(ISD::OR, MVT::v1i64, Expand);
771 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
781 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
782 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
783 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
789 if (!UseSoftFloat && Subtarget->hasXMM()) {
790 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
792 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
793 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
794 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
795 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
796 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
797 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
798 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
803 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
806 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
809 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810 // registers cannot be used even for integer operations.
811 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
816 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
817 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
818 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
819 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
833 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
850 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852 EVT VT = (MVT::SimpleValueType)i;
853 // Do not attempt to custom lower non-power-of-2 vectors
854 if (!isPowerOf2_32(VT.getVectorNumElements()))
856 // Do not attempt to custom lower non-128-bit vectors
857 if (!VT.is128BitVector())
859 setOperationAction(ISD::BUILD_VECTOR,
860 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE,
862 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
874 if (Subtarget->is64Bit()) {
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
879 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
884 // Do not attempt to promote non-128-bit vectors
885 if (!VT.is128BitVector())
888 setOperationAction(ISD::AND, SVT, Promote);
889 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
890 setOperationAction(ISD::OR, SVT, Promote);
891 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
892 setOperationAction(ISD::XOR, SVT, Promote);
893 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
894 setOperationAction(ISD::LOAD, SVT, Promote);
895 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
896 setOperationAction(ISD::SELECT, SVT, Promote);
897 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
900 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
902 // Custom lower v2i64 and v2f64 selects.
903 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
904 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
905 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
912 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
924 // FIXME: Do we need to handle scalar-to-vector here?
925 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
927 // Can turn SHL into an integer multiply.
928 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
929 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
931 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
932 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
933 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
934 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
935 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
937 // i8 and i16 vectors are custom , because the source register and source
938 // source memory operand types are not the same width. f32 vectors are
939 // custom since the immediate controlling the insert encodes additional
941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
946 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
951 if (Subtarget->is64Bit()) {
952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
953 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
957 if (Subtarget->hasXMMInt()) {
958 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
959 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
960 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
963 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
964 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
965 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
967 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
968 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
969 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
972 if (Subtarget->hasSSE42() || Subtarget->hasAVX())
973 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
975 if (!UseSoftFloat && Subtarget->hasAVX()) {
976 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
978 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
979 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
980 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
981 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
983 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
984 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
985 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
987 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
988 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
989 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
990 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
991 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
992 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
994 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
995 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
996 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
997 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
998 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
999 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1001 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1002 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1003 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1005 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1006 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1007 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1008 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1009 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1010 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1012 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1013 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1014 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1015 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1017 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1018 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1019 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1020 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1022 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1023 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1025 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1026 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1027 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1028 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1030 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1031 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1032 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1034 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1035 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1036 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1037 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1039 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1040 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1041 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1042 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1044 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1045 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1046 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1049 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1050 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1051 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1052 // Don't lower v32i8 because there is no 128-bit byte mul
1054 // Custom lower several nodes for 256-bit types.
1055 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1056 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1057 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1060 // Extract subvector is special because the value type
1061 // (result) is 128-bit but the source is 256-bit wide.
1062 if (VT.is128BitVector())
1063 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1065 // Do not attempt to custom lower other non-256-bit vectors
1066 if (!VT.is256BitVector())
1069 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1070 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1071 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1072 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1073 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1074 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1077 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1078 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1079 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1082 // Do not attempt to promote non-256-bit vectors
1083 if (!VT.is256BitVector())
1086 setOperationAction(ISD::AND, SVT, Promote);
1087 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1088 setOperationAction(ISD::OR, SVT, Promote);
1089 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1090 setOperationAction(ISD::XOR, SVT, Promote);
1091 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1092 setOperationAction(ISD::LOAD, SVT, Promote);
1093 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1094 setOperationAction(ISD::SELECT, SVT, Promote);
1095 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1099 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1100 // of this type with custom code.
1101 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1102 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1103 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1106 // We want to custom lower some of our intrinsics.
1107 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1110 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1111 // handle type legalization for these operations here.
1113 // FIXME: We really should do custom legalization for addition and
1114 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1115 // than generic legalization for 64-bit multiplication-with-overflow, though.
1116 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1117 // Add/Sub/Mul with overflow operations are custom lowered.
1119 setOperationAction(ISD::SADDO, VT, Custom);
1120 setOperationAction(ISD::UADDO, VT, Custom);
1121 setOperationAction(ISD::SSUBO, VT, Custom);
1122 setOperationAction(ISD::USUBO, VT, Custom);
1123 setOperationAction(ISD::SMULO, VT, Custom);
1124 setOperationAction(ISD::UMULO, VT, Custom);
1127 // There are no 8-bit 3-address imul/mul instructions
1128 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1129 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1131 if (!Subtarget->is64Bit()) {
1132 // These libcalls are not available in 32-bit.
1133 setLibcallName(RTLIB::SHL_I128, 0);
1134 setLibcallName(RTLIB::SRL_I128, 0);
1135 setLibcallName(RTLIB::SRA_I128, 0);
1138 // We have target-specific dag combine patterns for the following nodes:
1139 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1140 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1141 setTargetDAGCombine(ISD::BUILD_VECTOR);
1142 setTargetDAGCombine(ISD::VSELECT);
1143 setTargetDAGCombine(ISD::SELECT);
1144 setTargetDAGCombine(ISD::SHL);
1145 setTargetDAGCombine(ISD::SRA);
1146 setTargetDAGCombine(ISD::SRL);
1147 setTargetDAGCombine(ISD::OR);
1148 setTargetDAGCombine(ISD::AND);
1149 setTargetDAGCombine(ISD::ADD);
1150 setTargetDAGCombine(ISD::FADD);
1151 setTargetDAGCombine(ISD::FSUB);
1152 setTargetDAGCombine(ISD::SUB);
1153 setTargetDAGCombine(ISD::LOAD);
1154 setTargetDAGCombine(ISD::STORE);
1155 setTargetDAGCombine(ISD::ZERO_EXTEND);
1156 setTargetDAGCombine(ISD::SINT_TO_FP);
1157 if (Subtarget->is64Bit())
1158 setTargetDAGCombine(ISD::MUL);
1159 if (Subtarget->hasBMI())
1160 setTargetDAGCombine(ISD::XOR);
1162 computeRegisterProperties();
1164 // On Darwin, -Os means optimize for size without hurting performance,
1165 // do not reduce the limit.
1166 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1167 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1168 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1169 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1170 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1171 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1172 setPrefLoopAlignment(16);
1173 benefitFromCodePlacementOpt = true;
1175 setPrefFunctionAlignment(4);
1179 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1180 if (!VT.isVector()) return MVT::i8;
1181 return VT.changeVectorElementTypeToInteger();
1185 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1186 /// the desired ByVal argument alignment.
1187 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1190 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1191 if (VTy->getBitWidth() == 128)
1193 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1194 unsigned EltAlign = 0;
1195 getMaxByValAlign(ATy->getElementType(), EltAlign);
1196 if (EltAlign > MaxAlign)
1197 MaxAlign = EltAlign;
1198 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1199 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1200 unsigned EltAlign = 0;
1201 getMaxByValAlign(STy->getElementType(i), EltAlign);
1202 if (EltAlign > MaxAlign)
1203 MaxAlign = EltAlign;
1211 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1212 /// function arguments in the caller parameter area. For X86, aggregates
1213 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1214 /// are at 4-byte boundaries.
1215 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1216 if (Subtarget->is64Bit()) {
1217 // Max of 8 and alignment of type.
1218 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1225 if (Subtarget->hasXMM())
1226 getMaxByValAlign(Ty, Align);
1230 /// getOptimalMemOpType - Returns the target specific optimal type for load
1231 /// and store operations as a result of memset, memcpy, and memmove
1232 /// lowering. If DstAlign is zero that means it's safe to destination
1233 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1234 /// means there isn't a need to check it against alignment requirement,
1235 /// probably because the source does not need to be loaded. If
1236 /// 'IsZeroVal' is true, that means it's safe to return a
1237 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1238 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1239 /// constant so it does not need to be loaded.
1240 /// It returns EVT::Other if the type should be determined using generic
1241 /// target-independent logic.
1243 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1244 unsigned DstAlign, unsigned SrcAlign,
1247 MachineFunction &MF) const {
1248 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1249 // linux. This is because the stack realignment code can't handle certain
1250 // cases like PR2962. This should be removed when PR2962 is fixed.
1251 const Function *F = MF.getFunction();
1253 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1255 (Subtarget->isUnalignedMemAccessFast() ||
1256 ((DstAlign == 0 || DstAlign >= 16) &&
1257 (SrcAlign == 0 || SrcAlign >= 16))) &&
1258 Subtarget->getStackAlignment() >= 16) {
1259 if (Subtarget->hasAVX() &&
1260 Subtarget->getStackAlignment() >= 32)
1262 if (Subtarget->hasXMMInt())
1264 if (Subtarget->hasXMM())
1266 } else if (!MemcpyStrSrc && Size >= 8 &&
1267 !Subtarget->is64Bit() &&
1268 Subtarget->getStackAlignment() >= 8 &&
1269 Subtarget->hasXMMInt()) {
1270 // Do not use f64 to lower memcpy if source is string constant. It's
1271 // better to use i32 to avoid the loads.
1275 if (Subtarget->is64Bit() && Size >= 8)
1280 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1281 /// current function. The returned value is a member of the
1282 /// MachineJumpTableInfo::JTEntryKind enum.
1283 unsigned X86TargetLowering::getJumpTableEncoding() const {
1284 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1286 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1287 Subtarget->isPICStyleGOT())
1288 return MachineJumpTableInfo::EK_Custom32;
1290 // Otherwise, use the normal jump table encoding heuristics.
1291 return TargetLowering::getJumpTableEncoding();
1295 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1296 const MachineBasicBlock *MBB,
1297 unsigned uid,MCContext &Ctx) const{
1298 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1299 Subtarget->isPICStyleGOT());
1300 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1302 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1303 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1306 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1308 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1309 SelectionDAG &DAG) const {
1310 if (!Subtarget->is64Bit())
1311 // This doesn't have DebugLoc associated with it, but is not really the
1312 // same as a Register.
1313 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1317 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1318 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1320 const MCExpr *X86TargetLowering::
1321 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1322 MCContext &Ctx) const {
1323 // X86-64 uses RIP relative addressing based on the jump table label.
1324 if (Subtarget->isPICStyleRIPRel())
1325 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1327 // Otherwise, the reference is relative to the PIC base.
1328 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1331 // FIXME: Why this routine is here? Move to RegInfo!
1332 std::pair<const TargetRegisterClass*, uint8_t>
1333 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1334 const TargetRegisterClass *RRC = 0;
1336 switch (VT.getSimpleVT().SimpleTy) {
1338 return TargetLowering::findRepresentativeClass(VT);
1339 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1340 RRC = (Subtarget->is64Bit()
1341 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1344 RRC = X86::VR64RegisterClass;
1346 case MVT::f32: case MVT::f64:
1347 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1348 case MVT::v4f32: case MVT::v2f64:
1349 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1351 RRC = X86::VR128RegisterClass;
1354 return std::make_pair(RRC, Cost);
1357 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1358 unsigned &Offset) const {
1359 if (!Subtarget->isTargetLinux())
1362 if (Subtarget->is64Bit()) {
1363 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1365 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1378 //===----------------------------------------------------------------------===//
1379 // Return Value Calling Convention Implementation
1380 //===----------------------------------------------------------------------===//
1382 #include "X86GenCallingConv.inc"
1385 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1386 MachineFunction &MF, bool isVarArg,
1387 const SmallVectorImpl<ISD::OutputArg> &Outs,
1388 LLVMContext &Context) const {
1389 SmallVector<CCValAssign, 16> RVLocs;
1390 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1392 return CCInfo.CheckReturn(Outs, RetCC_X86);
1396 X86TargetLowering::LowerReturn(SDValue Chain,
1397 CallingConv::ID CallConv, bool isVarArg,
1398 const SmallVectorImpl<ISD::OutputArg> &Outs,
1399 const SmallVectorImpl<SDValue> &OutVals,
1400 DebugLoc dl, SelectionDAG &DAG) const {
1401 MachineFunction &MF = DAG.getMachineFunction();
1402 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1404 SmallVector<CCValAssign, 16> RVLocs;
1405 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1406 RVLocs, *DAG.getContext());
1407 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1409 // Add the regs to the liveout set for the function.
1410 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1411 for (unsigned i = 0; i != RVLocs.size(); ++i)
1412 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1413 MRI.addLiveOut(RVLocs[i].getLocReg());
1417 SmallVector<SDValue, 6> RetOps;
1418 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1419 // Operand #1 = Bytes To Pop
1420 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1423 // Copy the result values into the output registers.
1424 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1425 CCValAssign &VA = RVLocs[i];
1426 assert(VA.isRegLoc() && "Can only return in registers!");
1427 SDValue ValToCopy = OutVals[i];
1428 EVT ValVT = ValToCopy.getValueType();
1430 // If this is x86-64, and we disabled SSE, we can't return FP values,
1431 // or SSE or MMX vectors.
1432 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1433 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1434 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1435 report_fatal_error("SSE register return with SSE disabled");
1437 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1438 // llvm-gcc has never done it right and no one has noticed, so this
1439 // should be OK for now.
1440 if (ValVT == MVT::f64 &&
1441 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1442 report_fatal_error("SSE2 register return with SSE2 disabled");
1444 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1445 // the RET instruction and handled by the FP Stackifier.
1446 if (VA.getLocReg() == X86::ST0 ||
1447 VA.getLocReg() == X86::ST1) {
1448 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1449 // change the value to the FP stack register class.
1450 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1451 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1452 RetOps.push_back(ValToCopy);
1453 // Don't emit a copytoreg.
1457 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1458 // which is returned in RAX / RDX.
1459 if (Subtarget->is64Bit()) {
1460 if (ValVT == MVT::x86mmx) {
1461 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1462 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1463 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1465 // If we don't have SSE2 available, convert to v4f32 so the generated
1466 // register is legal.
1467 if (!Subtarget->hasXMMInt())
1468 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1473 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1474 Flag = Chain.getValue(1);
1477 // The x86-64 ABI for returning structs by value requires that we copy
1478 // the sret argument into %rax for the return. We saved the argument into
1479 // a virtual register in the entry block, so now we copy the value out
1481 if (Subtarget->is64Bit() &&
1482 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1483 MachineFunction &MF = DAG.getMachineFunction();
1484 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485 unsigned Reg = FuncInfo->getSRetReturnReg();
1487 "SRetReturnReg should have been set in LowerFormalArguments().");
1488 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1490 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1491 Flag = Chain.getValue(1);
1493 // RAX now acts like a return value.
1494 MRI.addLiveOut(X86::RAX);
1497 RetOps[0] = Chain; // Update chain.
1499 // Add the flag if we have it.
1501 RetOps.push_back(Flag);
1503 return DAG.getNode(X86ISD::RET_FLAG, dl,
1504 MVT::Other, &RetOps[0], RetOps.size());
1507 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1508 if (N->getNumValues() != 1)
1510 if (!N->hasNUsesOfValue(1, 0))
1513 SDNode *Copy = *N->use_begin();
1514 if (Copy->getOpcode() != ISD::CopyToReg &&
1515 Copy->getOpcode() != ISD::FP_EXTEND)
1518 bool HasRet = false;
1519 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1521 if (UI->getOpcode() != X86ISD::RET_FLAG)
1530 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1531 ISD::NodeType ExtendKind) const {
1533 // TODO: Is this also valid on 32-bit?
1534 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1535 ReturnMVT = MVT::i8;
1537 ReturnMVT = MVT::i32;
1539 EVT MinVT = getRegisterType(Context, ReturnMVT);
1540 return VT.bitsLT(MinVT) ? MinVT : VT;
1543 /// LowerCallResult - Lower the result values of a call into the
1544 /// appropriate copies out of appropriate physical registers.
1547 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1548 CallingConv::ID CallConv, bool isVarArg,
1549 const SmallVectorImpl<ISD::InputArg> &Ins,
1550 DebugLoc dl, SelectionDAG &DAG,
1551 SmallVectorImpl<SDValue> &InVals) const {
1553 // Assign locations to each value returned by this call.
1554 SmallVector<CCValAssign, 16> RVLocs;
1555 bool Is64Bit = Subtarget->is64Bit();
1556 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1557 getTargetMachine(), RVLocs, *DAG.getContext());
1558 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1560 // Copy all of the result registers out of their specified physreg.
1561 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1562 CCValAssign &VA = RVLocs[i];
1563 EVT CopyVT = VA.getValVT();
1565 // If this is x86-64, and we disabled SSE, we can't return FP values
1566 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1567 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1568 report_fatal_error("SSE register return with SSE disabled");
1573 // If this is a call to a function that returns an fp value on the floating
1574 // point stack, we must guarantee the the value is popped from the stack, so
1575 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1576 // if the return value is not used. We use the FpPOP_RETVAL instruction
1578 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1579 // If we prefer to use the value in xmm registers, copy it out as f80 and
1580 // use a truncate to move it from fp stack reg to xmm reg.
1581 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1582 SDValue Ops[] = { Chain, InFlag };
1583 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1584 MVT::Other, MVT::Glue, Ops, 2), 1);
1585 Val = Chain.getValue(0);
1587 // Round the f80 to the right size, which also moves it to the appropriate
1589 if (CopyVT != VA.getValVT())
1590 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1591 // This truncation won't change the value.
1592 DAG.getIntPtrConstant(1));
1594 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1595 CopyVT, InFlag).getValue(1);
1596 Val = Chain.getValue(0);
1598 InFlag = Chain.getValue(2);
1599 InVals.push_back(Val);
1606 //===----------------------------------------------------------------------===//
1607 // C & StdCall & Fast Calling Convention implementation
1608 //===----------------------------------------------------------------------===//
1609 // StdCall calling convention seems to be standard for many Windows' API
1610 // routines and around. It differs from C calling convention just a little:
1611 // callee should clean up the stack, not caller. Symbols should be also
1612 // decorated in some fancy way :) It doesn't support any vector arguments.
1613 // For info on fast calling convention see Fast Calling Convention (tail call)
1614 // implementation LowerX86_32FastCCCallTo.
1616 /// CallIsStructReturn - Determines whether a call uses struct return
1618 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1622 return Outs[0].Flags.isSRet();
1625 /// ArgsAreStructReturn - Determines whether a function uses struct
1626 /// return semantics.
1628 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1632 return Ins[0].Flags.isSRet();
1635 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1636 /// by "Src" to address "Dst" with size and alignment information specified by
1637 /// the specific parameter attribute. The copy will be passed as a byval
1638 /// function parameter.
1640 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1641 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1643 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1645 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1646 /*isVolatile*/false, /*AlwaysInline=*/true,
1647 MachinePointerInfo(), MachinePointerInfo());
1650 /// IsTailCallConvention - Return true if the calling convention is one that
1651 /// supports tail call optimization.
1652 static bool IsTailCallConvention(CallingConv::ID CC) {
1653 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1656 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1657 if (!CI->isTailCall())
1661 CallingConv::ID CalleeCC = CS.getCallingConv();
1662 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1668 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1669 /// a tailcall target by changing its ABI.
1670 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1671 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1675 X86TargetLowering::LowerMemArgument(SDValue Chain,
1676 CallingConv::ID CallConv,
1677 const SmallVectorImpl<ISD::InputArg> &Ins,
1678 DebugLoc dl, SelectionDAG &DAG,
1679 const CCValAssign &VA,
1680 MachineFrameInfo *MFI,
1682 // Create the nodes corresponding to a load from this parameter slot.
1683 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1684 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1685 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1688 // If value is passed by pointer we have address passed instead of the value
1690 if (VA.getLocInfo() == CCValAssign::Indirect)
1691 ValVT = VA.getLocVT();
1693 ValVT = VA.getValVT();
1695 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1696 // changed with more analysis.
1697 // In case of tail call optimization mark all arguments mutable. Since they
1698 // could be overwritten by lowering of arguments in case of a tail call.
1699 if (Flags.isByVal()) {
1700 unsigned Bytes = Flags.getByValSize();
1701 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1702 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1703 return DAG.getFrameIndex(FI, getPointerTy());
1705 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1706 VA.getLocMemOffset(), isImmutable);
1707 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1708 return DAG.getLoad(ValVT, dl, Chain, FIN,
1709 MachinePointerInfo::getFixedStack(FI),
1710 false, false, false, 0);
1715 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1716 CallingConv::ID CallConv,
1718 const SmallVectorImpl<ISD::InputArg> &Ins,
1721 SmallVectorImpl<SDValue> &InVals)
1723 MachineFunction &MF = DAG.getMachineFunction();
1724 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1726 const Function* Fn = MF.getFunction();
1727 if (Fn->hasExternalLinkage() &&
1728 Subtarget->isTargetCygMing() &&
1729 Fn->getName() == "main")
1730 FuncInfo->setForceFramePointer(true);
1732 MachineFrameInfo *MFI = MF.getFrameInfo();
1733 bool Is64Bit = Subtarget->is64Bit();
1734 bool IsWin64 = Subtarget->isTargetWin64();
1736 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1737 "Var args not supported with calling convention fastcc or ghc");
1739 // Assign locations to all of the incoming arguments.
1740 SmallVector<CCValAssign, 16> ArgLocs;
1741 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1742 ArgLocs, *DAG.getContext());
1744 // Allocate shadow area for Win64
1746 CCInfo.AllocateStack(32, 8);
1749 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1751 unsigned LastVal = ~0U;
1753 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1754 CCValAssign &VA = ArgLocs[i];
1755 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1757 assert(VA.getValNo() != LastVal &&
1758 "Don't support value assigned to multiple locs yet");
1760 LastVal = VA.getValNo();
1762 if (VA.isRegLoc()) {
1763 EVT RegVT = VA.getLocVT();
1764 TargetRegisterClass *RC = NULL;
1765 if (RegVT == MVT::i32)
1766 RC = X86::GR32RegisterClass;
1767 else if (Is64Bit && RegVT == MVT::i64)
1768 RC = X86::GR64RegisterClass;
1769 else if (RegVT == MVT::f32)
1770 RC = X86::FR32RegisterClass;
1771 else if (RegVT == MVT::f64)
1772 RC = X86::FR64RegisterClass;
1773 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1774 RC = X86::VR256RegisterClass;
1775 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1776 RC = X86::VR128RegisterClass;
1777 else if (RegVT == MVT::x86mmx)
1778 RC = X86::VR64RegisterClass;
1780 llvm_unreachable("Unknown argument type!");
1782 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1783 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1785 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1786 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1788 if (VA.getLocInfo() == CCValAssign::SExt)
1789 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1790 DAG.getValueType(VA.getValVT()));
1791 else if (VA.getLocInfo() == CCValAssign::ZExt)
1792 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1793 DAG.getValueType(VA.getValVT()));
1794 else if (VA.getLocInfo() == CCValAssign::BCvt)
1795 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1797 if (VA.isExtInLoc()) {
1798 // Handle MMX values passed in XMM regs.
1799 if (RegVT.isVector()) {
1800 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1803 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1806 assert(VA.isMemLoc());
1807 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1810 // If value is passed via pointer - do a load.
1811 if (VA.getLocInfo() == CCValAssign::Indirect)
1812 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1813 MachinePointerInfo(), false, false, false, 0);
1815 InVals.push_back(ArgValue);
1818 // The x86-64 ABI for returning structs by value requires that we copy
1819 // the sret argument into %rax for the return. Save the argument into
1820 // a virtual register so that we can access it from the return points.
1821 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1822 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 unsigned Reg = FuncInfo->getSRetReturnReg();
1825 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1826 FuncInfo->setSRetReturnReg(Reg);
1828 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1829 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1832 unsigned StackSize = CCInfo.getNextStackOffset();
1833 // Align stack specially for tail calls.
1834 if (FuncIsMadeTailCallSafe(CallConv))
1835 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1837 // If the function takes variable number of arguments, make a frame index for
1838 // the start of the first vararg value... for expansion of llvm.va_start.
1840 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1841 CallConv != CallingConv::X86_ThisCall)) {
1842 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1845 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1847 // FIXME: We should really autogenerate these arrays
1848 static const unsigned GPR64ArgRegsWin64[] = {
1849 X86::RCX, X86::RDX, X86::R8, X86::R9
1851 static const unsigned GPR64ArgRegs64Bit[] = {
1852 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1854 static const unsigned XMMArgRegs64Bit[] = {
1855 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1856 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1858 const unsigned *GPR64ArgRegs;
1859 unsigned NumXMMRegs = 0;
1862 // The XMM registers which might contain var arg parameters are shadowed
1863 // in their paired GPR. So we only need to save the GPR to their home
1865 TotalNumIntRegs = 4;
1866 GPR64ArgRegs = GPR64ArgRegsWin64;
1868 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1869 GPR64ArgRegs = GPR64ArgRegs64Bit;
1871 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1873 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1876 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1877 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1878 "SSE register cannot be used when SSE is disabled!");
1879 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1880 "SSE register cannot be used when SSE is disabled!");
1881 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1882 // Kernel mode asks for SSE to be disabled, so don't push them
1884 TotalNumXMMRegs = 0;
1887 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1888 // Get to the caller-allocated home save location. Add 8 to account
1889 // for the return address.
1890 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1891 FuncInfo->setRegSaveFrameIndex(
1892 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1893 // Fixup to set vararg frame on shadow area (4 x i64).
1895 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1897 // For X86-64, if there are vararg parameters that are passed via
1898 // registers, then we must store them to their spots on the stack so they
1899 // may be loaded by deferencing the result of va_next.
1900 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1901 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1902 FuncInfo->setRegSaveFrameIndex(
1903 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1907 // Store the integer parameter registers.
1908 SmallVector<SDValue, 8> MemOps;
1909 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1911 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1912 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1913 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1914 DAG.getIntPtrConstant(Offset));
1915 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1916 X86::GR64RegisterClass);
1917 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1919 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1920 MachinePointerInfo::getFixedStack(
1921 FuncInfo->getRegSaveFrameIndex(), Offset),
1923 MemOps.push_back(Store);
1927 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1928 // Now store the XMM (fp + vector) parameter registers.
1929 SmallVector<SDValue, 11> SaveXMMOps;
1930 SaveXMMOps.push_back(Chain);
1932 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1933 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1934 SaveXMMOps.push_back(ALVal);
1936 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1937 FuncInfo->getRegSaveFrameIndex()));
1938 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1939 FuncInfo->getVarArgsFPOffset()));
1941 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1942 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1943 X86::VR128RegisterClass);
1944 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1945 SaveXMMOps.push_back(Val);
1947 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1949 &SaveXMMOps[0], SaveXMMOps.size()));
1952 if (!MemOps.empty())
1953 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1954 &MemOps[0], MemOps.size());
1958 // Some CCs need callee pop.
1959 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1960 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1962 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1963 // If this is an sret function, the return should pop the hidden pointer.
1964 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1965 FuncInfo->setBytesToPopOnReturn(4);
1969 // RegSaveFrameIndex is X86-64 only.
1970 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1971 if (CallConv == CallingConv::X86_FastCall ||
1972 CallConv == CallingConv::X86_ThisCall)
1973 // fastcc functions can't have varargs.
1974 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1977 FuncInfo->setArgumentStackSize(StackSize);
1983 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1984 SDValue StackPtr, SDValue Arg,
1985 DebugLoc dl, SelectionDAG &DAG,
1986 const CCValAssign &VA,
1987 ISD::ArgFlagsTy Flags) const {
1988 unsigned LocMemOffset = VA.getLocMemOffset();
1989 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1990 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1991 if (Flags.isByVal())
1992 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1994 return DAG.getStore(Chain, dl, Arg, PtrOff,
1995 MachinePointerInfo::getStack(LocMemOffset),
1999 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2000 /// optimization is performed and it is required.
2002 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2003 SDValue &OutRetAddr, SDValue Chain,
2004 bool IsTailCall, bool Is64Bit,
2005 int FPDiff, DebugLoc dl) const {
2006 // Adjust the Return address stack slot.
2007 EVT VT = getPointerTy();
2008 OutRetAddr = getReturnAddressFrameIndex(DAG);
2010 // Load the "old" Return address.
2011 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2012 false, false, false, 0);
2013 return SDValue(OutRetAddr.getNode(), 1);
2016 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2017 /// optimization is performed and it is required (FPDiff!=0).
2019 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2020 SDValue Chain, SDValue RetAddrFrIdx,
2021 bool Is64Bit, int FPDiff, DebugLoc dl) {
2022 // Store the return address to the appropriate stack slot.
2023 if (!FPDiff) return Chain;
2024 // Calculate the new stack slot for the return address.
2025 int SlotSize = Is64Bit ? 8 : 4;
2026 int NewReturnAddrFI =
2027 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2028 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2029 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2030 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2031 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2037 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2038 CallingConv::ID CallConv, bool isVarArg,
2040 const SmallVectorImpl<ISD::OutputArg> &Outs,
2041 const SmallVectorImpl<SDValue> &OutVals,
2042 const SmallVectorImpl<ISD::InputArg> &Ins,
2043 DebugLoc dl, SelectionDAG &DAG,
2044 SmallVectorImpl<SDValue> &InVals) const {
2045 MachineFunction &MF = DAG.getMachineFunction();
2046 bool Is64Bit = Subtarget->is64Bit();
2047 bool IsWin64 = Subtarget->isTargetWin64();
2048 bool IsStructRet = CallIsStructReturn(Outs);
2049 bool IsSibcall = false;
2052 // Check if it's really possible to do a tail call.
2053 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2054 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2055 Outs, OutVals, Ins, DAG);
2057 // Sibcalls are automatically detected tailcalls which do not require
2059 if (!GuaranteedTailCallOpt && isTailCall)
2066 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2067 "Var args not supported with calling convention fastcc or ghc");
2069 // Analyze operands of the call, assigning locations to each operand.
2070 SmallVector<CCValAssign, 16> ArgLocs;
2071 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2072 ArgLocs, *DAG.getContext());
2074 // Allocate shadow area for Win64
2076 CCInfo.AllocateStack(32, 8);
2079 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2081 // Get a count of how many bytes are to be pushed on the stack.
2082 unsigned NumBytes = CCInfo.getNextStackOffset();
2084 // This is a sibcall. The memory operands are available in caller's
2085 // own caller's stack.
2087 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2088 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2091 if (isTailCall && !IsSibcall) {
2092 // Lower arguments at fp - stackoffset + fpdiff.
2093 unsigned NumBytesCallerPushed =
2094 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2095 FPDiff = NumBytesCallerPushed - NumBytes;
2097 // Set the delta of movement of the returnaddr stackslot.
2098 // But only set if delta is greater than previous delta.
2099 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2100 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2104 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2106 SDValue RetAddrFrIdx;
2107 // Load return address for tail calls.
2108 if (isTailCall && FPDiff)
2109 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2110 Is64Bit, FPDiff, dl);
2112 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2113 SmallVector<SDValue, 8> MemOpChains;
2116 // Walk the register/memloc assignments, inserting copies/loads. In the case
2117 // of tail call optimization arguments are handle later.
2118 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2119 CCValAssign &VA = ArgLocs[i];
2120 EVT RegVT = VA.getLocVT();
2121 SDValue Arg = OutVals[i];
2122 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2123 bool isByVal = Flags.isByVal();
2125 // Promote the value if needed.
2126 switch (VA.getLocInfo()) {
2127 default: llvm_unreachable("Unknown loc info!");
2128 case CCValAssign::Full: break;
2129 case CCValAssign::SExt:
2130 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2132 case CCValAssign::ZExt:
2133 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2135 case CCValAssign::AExt:
2136 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2137 // Special case: passing MMX values in XMM registers.
2138 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2139 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2140 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2142 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2144 case CCValAssign::BCvt:
2145 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2147 case CCValAssign::Indirect: {
2148 // Store the argument.
2149 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2150 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2151 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2152 MachinePointerInfo::getFixedStack(FI),
2159 if (VA.isRegLoc()) {
2160 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2161 if (isVarArg && IsWin64) {
2162 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2163 // shadow reg if callee is a varargs function.
2164 unsigned ShadowReg = 0;
2165 switch (VA.getLocReg()) {
2166 case X86::XMM0: ShadowReg = X86::RCX; break;
2167 case X86::XMM1: ShadowReg = X86::RDX; break;
2168 case X86::XMM2: ShadowReg = X86::R8; break;
2169 case X86::XMM3: ShadowReg = X86::R9; break;
2172 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2174 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2175 assert(VA.isMemLoc());
2176 if (StackPtr.getNode() == 0)
2177 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2178 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2179 dl, DAG, VA, Flags));
2183 if (!MemOpChains.empty())
2184 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2185 &MemOpChains[0], MemOpChains.size());
2187 // Build a sequence of copy-to-reg nodes chained together with token chain
2188 // and flag operands which copy the outgoing args into registers.
2190 // Tail call byval lowering might overwrite argument registers so in case of
2191 // tail call optimization the copies to registers are lowered later.
2193 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2194 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2195 RegsToPass[i].second, InFlag);
2196 InFlag = Chain.getValue(1);
2199 if (Subtarget->isPICStyleGOT()) {
2200 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2203 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2204 DAG.getNode(X86ISD::GlobalBaseReg,
2205 DebugLoc(), getPointerTy()),
2207 InFlag = Chain.getValue(1);
2209 // If we are tail calling and generating PIC/GOT style code load the
2210 // address of the callee into ECX. The value in ecx is used as target of
2211 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2212 // for tail calls on PIC/GOT architectures. Normally we would just put the
2213 // address of GOT into ebx and then call target@PLT. But for tail calls
2214 // ebx would be restored (since ebx is callee saved) before jumping to the
2217 // Note: The actual moving to ECX is done further down.
2218 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2219 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2220 !G->getGlobal()->hasProtectedVisibility())
2221 Callee = LowerGlobalAddress(Callee, DAG);
2222 else if (isa<ExternalSymbolSDNode>(Callee))
2223 Callee = LowerExternalSymbol(Callee, DAG);
2227 if (Is64Bit && isVarArg && !IsWin64) {
2228 // From AMD64 ABI document:
2229 // For calls that may call functions that use varargs or stdargs
2230 // (prototype-less calls or calls to functions containing ellipsis (...) in
2231 // the declaration) %al is used as hidden argument to specify the number
2232 // of SSE registers used. The contents of %al do not need to match exactly
2233 // the number of registers, but must be an ubound on the number of SSE
2234 // registers used and is in the range 0 - 8 inclusive.
2236 // Count the number of XMM registers allocated.
2237 static const unsigned XMMArgRegs[] = {
2238 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2239 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2241 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2242 assert((Subtarget->hasXMM() || !NumXMMRegs)
2243 && "SSE registers cannot be used when SSE is disabled");
2245 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2246 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2247 InFlag = Chain.getValue(1);
2251 // For tail calls lower the arguments to the 'real' stack slot.
2253 // Force all the incoming stack arguments to be loaded from the stack
2254 // before any new outgoing arguments are stored to the stack, because the
2255 // outgoing stack slots may alias the incoming argument stack slots, and
2256 // the alias isn't otherwise explicit. This is slightly more conservative
2257 // than necessary, because it means that each store effectively depends
2258 // on every argument instead of just those arguments it would clobber.
2259 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2261 SmallVector<SDValue, 8> MemOpChains2;
2264 // Do not flag preceding copytoreg stuff together with the following stuff.
2266 if (GuaranteedTailCallOpt) {
2267 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2268 CCValAssign &VA = ArgLocs[i];
2271 assert(VA.isMemLoc());
2272 SDValue Arg = OutVals[i];
2273 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2274 // Create frame index.
2275 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2276 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2277 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2278 FIN = DAG.getFrameIndex(FI, getPointerTy());
2280 if (Flags.isByVal()) {
2281 // Copy relative to framepointer.
2282 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2283 if (StackPtr.getNode() == 0)
2284 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2286 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2288 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2292 // Store relative to framepointer.
2293 MemOpChains2.push_back(
2294 DAG.getStore(ArgChain, dl, Arg, FIN,
2295 MachinePointerInfo::getFixedStack(FI),
2301 if (!MemOpChains2.empty())
2302 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2303 &MemOpChains2[0], MemOpChains2.size());
2305 // Copy arguments to their registers.
2306 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2307 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2308 RegsToPass[i].second, InFlag);
2309 InFlag = Chain.getValue(1);
2313 // Store the return address to the appropriate stack slot.
2314 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2318 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2319 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2320 // In the 64-bit large code model, we have to make all calls
2321 // through a register, since the call instruction's 32-bit
2322 // pc-relative offset may not be large enough to hold the whole
2324 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2325 // If the callee is a GlobalAddress node (quite common, every direct call
2326 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2329 // We should use extra load for direct calls to dllimported functions in
2331 const GlobalValue *GV = G->getGlobal();
2332 if (!GV->hasDLLImportLinkage()) {
2333 unsigned char OpFlags = 0;
2334 bool ExtraLoad = false;
2335 unsigned WrapperKind = ISD::DELETED_NODE;
2337 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2338 // external symbols most go through the PLT in PIC mode. If the symbol
2339 // has hidden or protected visibility, or if it is static or local, then
2340 // we don't need to use the PLT - we can directly call it.
2341 if (Subtarget->isTargetELF() &&
2342 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2343 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2344 OpFlags = X86II::MO_PLT;
2345 } else if (Subtarget->isPICStyleStubAny() &&
2346 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2347 (!Subtarget->getTargetTriple().isMacOSX() ||
2348 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2349 // PC-relative references to external symbols should go through $stub,
2350 // unless we're building with the leopard linker or later, which
2351 // automatically synthesizes these stubs.
2352 OpFlags = X86II::MO_DARWIN_STUB;
2353 } else if (Subtarget->isPICStyleRIPRel() &&
2354 isa<Function>(GV) &&
2355 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2356 // If the function is marked as non-lazy, generate an indirect call
2357 // which loads from the GOT directly. This avoids runtime overhead
2358 // at the cost of eager binding (and one extra byte of encoding).
2359 OpFlags = X86II::MO_GOTPCREL;
2360 WrapperKind = X86ISD::WrapperRIP;
2364 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2365 G->getOffset(), OpFlags);
2367 // Add a wrapper if needed.
2368 if (WrapperKind != ISD::DELETED_NODE)
2369 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2370 // Add extra indirection if needed.
2372 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2373 MachinePointerInfo::getGOT(),
2374 false, false, false, 0);
2376 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2377 unsigned char OpFlags = 0;
2379 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2380 // external symbols should go through the PLT.
2381 if (Subtarget->isTargetELF() &&
2382 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2383 OpFlags = X86II::MO_PLT;
2384 } else if (Subtarget->isPICStyleStubAny() &&
2385 (!Subtarget->getTargetTriple().isMacOSX() ||
2386 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2387 // PC-relative references to external symbols should go through $stub,
2388 // unless we're building with the leopard linker or later, which
2389 // automatically synthesizes these stubs.
2390 OpFlags = X86II::MO_DARWIN_STUB;
2393 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2397 // Returns a chain & a flag for retval copy to use.
2398 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2399 SmallVector<SDValue, 8> Ops;
2401 if (!IsSibcall && isTailCall) {
2402 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2403 DAG.getIntPtrConstant(0, true), InFlag);
2404 InFlag = Chain.getValue(1);
2407 Ops.push_back(Chain);
2408 Ops.push_back(Callee);
2411 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2413 // Add argument registers to the end of the list so that they are known live
2415 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2416 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2417 RegsToPass[i].second.getValueType()));
2419 // Add an implicit use GOT pointer in EBX.
2420 if (!isTailCall && Subtarget->isPICStyleGOT())
2421 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2423 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2424 if (Is64Bit && isVarArg && !IsWin64)
2425 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2427 if (InFlag.getNode())
2428 Ops.push_back(InFlag);
2432 //// If this is the first return lowered for this function, add the regs
2433 //// to the liveout set for the function.
2434 // This isn't right, although it's probably harmless on x86; liveouts
2435 // should be computed from returns not tail calls. Consider a void
2436 // function making a tail call to a function returning int.
2437 return DAG.getNode(X86ISD::TC_RETURN, dl,
2438 NodeTys, &Ops[0], Ops.size());
2441 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2442 InFlag = Chain.getValue(1);
2444 // Create the CALLSEQ_END node.
2445 unsigned NumBytesForCalleeToPush;
2446 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2447 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2448 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2449 // If this is a call to a struct-return function, the callee
2450 // pops the hidden struct pointer, so we have to push it back.
2451 // This is common for Darwin/X86, Linux & Mingw32 targets.
2452 NumBytesForCalleeToPush = 4;
2454 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2456 // Returns a flag for retval copy to use.
2458 Chain = DAG.getCALLSEQ_END(Chain,
2459 DAG.getIntPtrConstant(NumBytes, true),
2460 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2463 InFlag = Chain.getValue(1);
2466 // Handle result values, copying them out of physregs into vregs that we
2468 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2469 Ins, dl, DAG, InVals);
2473 //===----------------------------------------------------------------------===//
2474 // Fast Calling Convention (tail call) implementation
2475 //===----------------------------------------------------------------------===//
2477 // Like std call, callee cleans arguments, convention except that ECX is
2478 // reserved for storing the tail called function address. Only 2 registers are
2479 // free for argument passing (inreg). Tail call optimization is performed
2481 // * tailcallopt is enabled
2482 // * caller/callee are fastcc
2483 // On X86_64 architecture with GOT-style position independent code only local
2484 // (within module) calls are supported at the moment.
2485 // To keep the stack aligned according to platform abi the function
2486 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2487 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2488 // If a tail called function callee has more arguments than the caller the
2489 // caller needs to make sure that there is room to move the RETADDR to. This is
2490 // achieved by reserving an area the size of the argument delta right after the
2491 // original REtADDR, but before the saved framepointer or the spilled registers
2492 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2504 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2505 /// for a 16 byte align requirement.
2507 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2508 SelectionDAG& DAG) const {
2509 MachineFunction &MF = DAG.getMachineFunction();
2510 const TargetMachine &TM = MF.getTarget();
2511 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2512 unsigned StackAlignment = TFI.getStackAlignment();
2513 uint64_t AlignMask = StackAlignment - 1;
2514 int64_t Offset = StackSize;
2515 uint64_t SlotSize = TD->getPointerSize();
2516 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2517 // Number smaller than 12 so just add the difference.
2518 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2520 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2521 Offset = ((~AlignMask) & Offset) + StackAlignment +
2522 (StackAlignment-SlotSize);
2527 /// MatchingStackOffset - Return true if the given stack call argument is
2528 /// already available in the same position (relatively) of the caller's
2529 /// incoming argument stack.
2531 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2532 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2533 const X86InstrInfo *TII) {
2534 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2536 if (Arg.getOpcode() == ISD::CopyFromReg) {
2537 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2538 if (!TargetRegisterInfo::isVirtualRegister(VR))
2540 MachineInstr *Def = MRI->getVRegDef(VR);
2543 if (!Flags.isByVal()) {
2544 if (!TII->isLoadFromStackSlot(Def, FI))
2547 unsigned Opcode = Def->getOpcode();
2548 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2549 Def->getOperand(1).isFI()) {
2550 FI = Def->getOperand(1).getIndex();
2551 Bytes = Flags.getByValSize();
2555 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2556 if (Flags.isByVal())
2557 // ByVal argument is passed in as a pointer but it's now being
2558 // dereferenced. e.g.
2559 // define @foo(%struct.X* %A) {
2560 // tail call @bar(%struct.X* byval %A)
2563 SDValue Ptr = Ld->getBasePtr();
2564 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2567 FI = FINode->getIndex();
2568 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2569 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2570 FI = FINode->getIndex();
2571 Bytes = Flags.getByValSize();
2575 assert(FI != INT_MAX);
2576 if (!MFI->isFixedObjectIndex(FI))
2578 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2581 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2582 /// for tail call optimization. Targets which want to do tail call
2583 /// optimization should implement this function.
2585 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2586 CallingConv::ID CalleeCC,
2588 bool isCalleeStructRet,
2589 bool isCallerStructRet,
2590 const SmallVectorImpl<ISD::OutputArg> &Outs,
2591 const SmallVectorImpl<SDValue> &OutVals,
2592 const SmallVectorImpl<ISD::InputArg> &Ins,
2593 SelectionDAG& DAG) const {
2594 if (!IsTailCallConvention(CalleeCC) &&
2595 CalleeCC != CallingConv::C)
2598 // If -tailcallopt is specified, make fastcc functions tail-callable.
2599 const MachineFunction &MF = DAG.getMachineFunction();
2600 const Function *CallerF = DAG.getMachineFunction().getFunction();
2601 CallingConv::ID CallerCC = CallerF->getCallingConv();
2602 bool CCMatch = CallerCC == CalleeCC;
2604 if (GuaranteedTailCallOpt) {
2605 if (IsTailCallConvention(CalleeCC) && CCMatch)
2610 // Look for obvious safe cases to perform tail call optimization that do not
2611 // require ABI changes. This is what gcc calls sibcall.
2613 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2614 // emit a special epilogue.
2615 if (RegInfo->needsStackRealignment(MF))
2618 // Also avoid sibcall optimization if either caller or callee uses struct
2619 // return semantics.
2620 if (isCalleeStructRet || isCallerStructRet)
2623 // An stdcall caller is expected to clean up its arguments; the callee
2624 // isn't going to do that.
2625 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2628 // Do not sibcall optimize vararg calls unless all arguments are passed via
2630 if (isVarArg && !Outs.empty()) {
2632 // Optimizing for varargs on Win64 is unlikely to be safe without
2633 // additional testing.
2634 if (Subtarget->isTargetWin64())
2637 SmallVector<CCValAssign, 16> ArgLocs;
2638 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2639 getTargetMachine(), ArgLocs, *DAG.getContext());
2641 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2643 if (!ArgLocs[i].isRegLoc())
2647 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2648 // Therefore if it's not used by the call it is not safe to optimize this into
2650 bool Unused = false;
2651 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2658 SmallVector<CCValAssign, 16> RVLocs;
2659 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2660 getTargetMachine(), RVLocs, *DAG.getContext());
2661 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2662 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2663 CCValAssign &VA = RVLocs[i];
2664 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2669 // If the calling conventions do not match, then we'd better make sure the
2670 // results are returned in the same way as what the caller expects.
2672 SmallVector<CCValAssign, 16> RVLocs1;
2673 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2674 getTargetMachine(), RVLocs1, *DAG.getContext());
2675 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2677 SmallVector<CCValAssign, 16> RVLocs2;
2678 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2679 getTargetMachine(), RVLocs2, *DAG.getContext());
2680 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2682 if (RVLocs1.size() != RVLocs2.size())
2684 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2685 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2687 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2689 if (RVLocs1[i].isRegLoc()) {
2690 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2693 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2699 // If the callee takes no arguments then go on to check the results of the
2701 if (!Outs.empty()) {
2702 // Check if stack adjustment is needed. For now, do not do this if any
2703 // argument is passed on the stack.
2704 SmallVector<CCValAssign, 16> ArgLocs;
2705 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2706 getTargetMachine(), ArgLocs, *DAG.getContext());
2708 // Allocate shadow area for Win64
2709 if (Subtarget->isTargetWin64()) {
2710 CCInfo.AllocateStack(32, 8);
2713 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2714 if (CCInfo.getNextStackOffset()) {
2715 MachineFunction &MF = DAG.getMachineFunction();
2716 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2719 // Check if the arguments are already laid out in the right way as
2720 // the caller's fixed stack objects.
2721 MachineFrameInfo *MFI = MF.getFrameInfo();
2722 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2723 const X86InstrInfo *TII =
2724 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2725 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2726 CCValAssign &VA = ArgLocs[i];
2727 SDValue Arg = OutVals[i];
2728 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729 if (VA.getLocInfo() == CCValAssign::Indirect)
2731 if (!VA.isRegLoc()) {
2732 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2739 // If the tailcall address may be in a register, then make sure it's
2740 // possible to register allocate for it. In 32-bit, the call address can
2741 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2742 // callee-saved registers are restored. These happen to be the same
2743 // registers used to pass 'inreg' arguments so watch out for those.
2744 if (!Subtarget->is64Bit() &&
2745 !isa<GlobalAddressSDNode>(Callee) &&
2746 !isa<ExternalSymbolSDNode>(Callee)) {
2747 unsigned NumInRegs = 0;
2748 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2749 CCValAssign &VA = ArgLocs[i];
2752 unsigned Reg = VA.getLocReg();
2755 case X86::EAX: case X86::EDX: case X86::ECX:
2756 if (++NumInRegs == 3)
2768 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2769 return X86::createFastISel(funcInfo);
2773 //===----------------------------------------------------------------------===//
2774 // Other Lowering Hooks
2775 //===----------------------------------------------------------------------===//
2777 static bool MayFoldLoad(SDValue Op) {
2778 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2781 static bool MayFoldIntoStore(SDValue Op) {
2782 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2785 static bool isTargetShuffle(unsigned Opcode) {
2787 default: return false;
2788 case X86ISD::PSHUFD:
2789 case X86ISD::PSHUFHW:
2790 case X86ISD::PSHUFLW:
2791 case X86ISD::SHUFPD:
2792 case X86ISD::PALIGN:
2793 case X86ISD::SHUFPS:
2794 case X86ISD::MOVLHPS:
2795 case X86ISD::MOVLHPD:
2796 case X86ISD::MOVHLPS:
2797 case X86ISD::MOVLPS:
2798 case X86ISD::MOVLPD:
2799 case X86ISD::MOVSHDUP:
2800 case X86ISD::MOVSLDUP:
2801 case X86ISD::MOVDDUP:
2804 case X86ISD::UNPCKLPS:
2805 case X86ISD::UNPCKLPD:
2806 case X86ISD::VUNPCKLPSY:
2807 case X86ISD::VUNPCKLPDY:
2808 case X86ISD::PUNPCKLWD:
2809 case X86ISD::PUNPCKLBW:
2810 case X86ISD::PUNPCKLDQ:
2811 case X86ISD::PUNPCKLQDQ:
2812 case X86ISD::UNPCKHPS:
2813 case X86ISD::UNPCKHPD:
2814 case X86ISD::VUNPCKHPSY:
2815 case X86ISD::VUNPCKHPDY:
2816 case X86ISD::PUNPCKHWD:
2817 case X86ISD::PUNPCKHBW:
2818 case X86ISD::PUNPCKHDQ:
2819 case X86ISD::PUNPCKHQDQ:
2820 case X86ISD::VPERMILPS:
2821 case X86ISD::VPERMILPSY:
2822 case X86ISD::VPERMILPD:
2823 case X86ISD::VPERMILPDY:
2824 case X86ISD::VPERM2F128:
2830 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2831 SDValue V1, SelectionDAG &DAG) {
2833 default: llvm_unreachable("Unknown x86 shuffle node");
2834 case X86ISD::MOVSHDUP:
2835 case X86ISD::MOVSLDUP:
2836 case X86ISD::MOVDDUP:
2837 return DAG.getNode(Opc, dl, VT, V1);
2843 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2844 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2846 default: llvm_unreachable("Unknown x86 shuffle node");
2847 case X86ISD::PSHUFD:
2848 case X86ISD::PSHUFHW:
2849 case X86ISD::PSHUFLW:
2850 case X86ISD::VPERMILPS:
2851 case X86ISD::VPERMILPSY:
2852 case X86ISD::VPERMILPD:
2853 case X86ISD::VPERMILPDY:
2854 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2860 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2861 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2863 default: llvm_unreachable("Unknown x86 shuffle node");
2864 case X86ISD::PALIGN:
2865 case X86ISD::SHUFPD:
2866 case X86ISD::SHUFPS:
2867 case X86ISD::VPERM2F128:
2868 return DAG.getNode(Opc, dl, VT, V1, V2,
2869 DAG.getConstant(TargetMask, MVT::i8));
2874 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2875 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2877 default: llvm_unreachable("Unknown x86 shuffle node");
2878 case X86ISD::MOVLHPS:
2879 case X86ISD::MOVLHPD:
2880 case X86ISD::MOVHLPS:
2881 case X86ISD::MOVLPS:
2882 case X86ISD::MOVLPD:
2885 case X86ISD::UNPCKLPS:
2886 case X86ISD::UNPCKLPD:
2887 case X86ISD::VUNPCKLPSY:
2888 case X86ISD::VUNPCKLPDY:
2889 case X86ISD::PUNPCKLWD:
2890 case X86ISD::PUNPCKLBW:
2891 case X86ISD::PUNPCKLDQ:
2892 case X86ISD::PUNPCKLQDQ:
2893 case X86ISD::UNPCKHPS:
2894 case X86ISD::UNPCKHPD:
2895 case X86ISD::VUNPCKHPSY:
2896 case X86ISD::VUNPCKHPDY:
2897 case X86ISD::PUNPCKHWD:
2898 case X86ISD::PUNPCKHBW:
2899 case X86ISD::PUNPCKHDQ:
2900 case X86ISD::PUNPCKHQDQ:
2901 return DAG.getNode(Opc, dl, VT, V1, V2);
2906 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2907 MachineFunction &MF = DAG.getMachineFunction();
2908 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2909 int ReturnAddrIndex = FuncInfo->getRAIndex();
2911 if (ReturnAddrIndex == 0) {
2912 // Set up a frame object for the return address.
2913 uint64_t SlotSize = TD->getPointerSize();
2914 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2916 FuncInfo->setRAIndex(ReturnAddrIndex);
2919 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2923 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2924 bool hasSymbolicDisplacement) {
2925 // Offset should fit into 32 bit immediate field.
2926 if (!isInt<32>(Offset))
2929 // If we don't have a symbolic displacement - we don't have any extra
2931 if (!hasSymbolicDisplacement)
2934 // FIXME: Some tweaks might be needed for medium code model.
2935 if (M != CodeModel::Small && M != CodeModel::Kernel)
2938 // For small code model we assume that latest object is 16MB before end of 31
2939 // bits boundary. We may also accept pretty large negative constants knowing
2940 // that all objects are in the positive half of address space.
2941 if (M == CodeModel::Small && Offset < 16*1024*1024)
2944 // For kernel code model we know that all object resist in the negative half
2945 // of 32bits address space. We may not accept negative offsets, since they may
2946 // be just off and we may accept pretty large positive ones.
2947 if (M == CodeModel::Kernel && Offset > 0)
2953 /// isCalleePop - Determines whether the callee is required to pop its
2954 /// own arguments. Callee pop is necessary to support tail calls.
2955 bool X86::isCalleePop(CallingConv::ID CallingConv,
2956 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2960 switch (CallingConv) {
2963 case CallingConv::X86_StdCall:
2965 case CallingConv::X86_FastCall:
2967 case CallingConv::X86_ThisCall:
2969 case CallingConv::Fast:
2971 case CallingConv::GHC:
2976 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2977 /// specific condition code, returning the condition code and the LHS/RHS of the
2978 /// comparison to make.
2979 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2980 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2982 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2983 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2984 // X > -1 -> X == 0, jump !sign.
2985 RHS = DAG.getConstant(0, RHS.getValueType());
2986 return X86::COND_NS;
2987 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2988 // X < 0 -> X == 0, jump on sign.
2990 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2992 RHS = DAG.getConstant(0, RHS.getValueType());
2993 return X86::COND_LE;
2997 switch (SetCCOpcode) {
2998 default: llvm_unreachable("Invalid integer condition!");
2999 case ISD::SETEQ: return X86::COND_E;
3000 case ISD::SETGT: return X86::COND_G;
3001 case ISD::SETGE: return X86::COND_GE;
3002 case ISD::SETLT: return X86::COND_L;
3003 case ISD::SETLE: return X86::COND_LE;
3004 case ISD::SETNE: return X86::COND_NE;
3005 case ISD::SETULT: return X86::COND_B;
3006 case ISD::SETUGT: return X86::COND_A;
3007 case ISD::SETULE: return X86::COND_BE;
3008 case ISD::SETUGE: return X86::COND_AE;
3012 // First determine if it is required or is profitable to flip the operands.
3014 // If LHS is a foldable load, but RHS is not, flip the condition.
3015 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3016 !ISD::isNON_EXTLoad(RHS.getNode())) {
3017 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3018 std::swap(LHS, RHS);
3021 switch (SetCCOpcode) {
3027 std::swap(LHS, RHS);
3031 // On a floating point condition, the flags are set as follows:
3033 // 0 | 0 | 0 | X > Y
3034 // 0 | 0 | 1 | X < Y
3035 // 1 | 0 | 0 | X == Y
3036 // 1 | 1 | 1 | unordered
3037 switch (SetCCOpcode) {
3038 default: llvm_unreachable("Condcode should be pre-legalized away");
3040 case ISD::SETEQ: return X86::COND_E;
3041 case ISD::SETOLT: // flipped
3043 case ISD::SETGT: return X86::COND_A;
3044 case ISD::SETOLE: // flipped
3046 case ISD::SETGE: return X86::COND_AE;
3047 case ISD::SETUGT: // flipped
3049 case ISD::SETLT: return X86::COND_B;
3050 case ISD::SETUGE: // flipped
3052 case ISD::SETLE: return X86::COND_BE;
3054 case ISD::SETNE: return X86::COND_NE;
3055 case ISD::SETUO: return X86::COND_P;
3056 case ISD::SETO: return X86::COND_NP;
3058 case ISD::SETUNE: return X86::COND_INVALID;
3062 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3063 /// code. Current x86 isa includes the following FP cmov instructions:
3064 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3065 static bool hasFPCMov(unsigned X86CC) {
3081 /// isFPImmLegal - Returns true if the target can instruction select the
3082 /// specified FP immediate natively. If false, the legalizer will
3083 /// materialize the FP immediate as a load from a constant pool.
3084 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3085 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3086 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3092 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3093 /// the specified range (L, H].
3094 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3095 return (Val < 0) || (Val >= Low && Val < Hi);
3098 /// isUndefOrInRange - Return true if every element in Mask, begining
3099 /// from position Pos and ending in Pos+Size, falls within the specified
3100 /// range (L, L+Pos]. or is undef.
3101 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3102 int Pos, int Size, int Low, int Hi) {
3103 for (int i = Pos, e = Pos+Size; i != e; ++i)
3104 if (!isUndefOrInRange(Mask[i], Low, Hi))
3109 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3110 /// specified value.
3111 static bool isUndefOrEqual(int Val, int CmpVal) {
3112 if (Val < 0 || Val == CmpVal)
3117 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3118 /// from position Pos and ending in Pos+Size, falls within the specified
3119 /// sequential range (L, L+Pos]. or is undef.
3120 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3121 int Pos, int Size, int Low) {
3122 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3123 if (!isUndefOrEqual(Mask[i], Low))
3128 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3129 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3130 /// the second operand.
3131 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3132 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3133 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3134 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3135 return (Mask[0] < 2 && Mask[1] < 2);
3139 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3140 SmallVector<int, 8> M;
3142 return ::isPSHUFDMask(M, N->getValueType(0));
3145 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3146 /// is suitable for input to PSHUFHW.
3147 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148 if (VT != MVT::v8i16)
3151 // Lower quadword copied in order or undef.
3152 for (int i = 0; i != 4; ++i)
3153 if (Mask[i] >= 0 && Mask[i] != i)
3156 // Upper quadword shuffled.
3157 for (int i = 4; i != 8; ++i)
3158 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3164 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3165 SmallVector<int, 8> M;
3167 return ::isPSHUFHWMask(M, N->getValueType(0));
3170 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3171 /// is suitable for input to PSHUFLW.
3172 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3173 if (VT != MVT::v8i16)
3176 // Upper quadword copied in order.
3177 for (int i = 4; i != 8; ++i)
3178 if (Mask[i] >= 0 && Mask[i] != i)
3181 // Lower quadword shuffled.
3182 for (int i = 0; i != 4; ++i)
3189 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3190 SmallVector<int, 8> M;
3192 return ::isPSHUFLWMask(M, N->getValueType(0));
3195 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3196 /// is suitable for input to PALIGNR.
3197 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3198 bool hasSSSE3OrAVX) {
3199 int i, e = VT.getVectorNumElements();
3200 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3203 // Do not handle v2i64 / v2f64 shuffles with palignr.
3204 if (e < 4 || !hasSSSE3OrAVX)
3207 for (i = 0; i != e; ++i)
3211 // All undef, not a palignr.
3215 // Make sure we're shifting in the right direction.
3219 int s = Mask[i] - i;
3221 // Check the rest of the elements to see if they are consecutive.
3222 for (++i; i != e; ++i) {
3224 if (m >= 0 && m != s+i)
3230 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3231 /// specifies a shuffle of elements that is suitable for input to 256-bit
3233 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3234 const X86Subtarget *Subtarget) {
3235 int NumElems = VT.getVectorNumElements();
3237 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3243 // VSHUFPSY divides the resulting vector into 4 chunks.
3244 // The sources are also splitted into 4 chunks, and each destination
3245 // chunk must come from a different source chunk.
3247 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3248 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3250 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3251 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3253 int QuarterSize = NumElems/4;
3254 int HalfSize = QuarterSize*2;
3255 for (int i = 0; i < QuarterSize; ++i)
3256 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3258 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3259 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3262 // The mask of the second half must be the same as the first but with
3263 // the appropriate offsets. This works in the same way as VPERMILPS
3264 // works with masks.
3265 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3266 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3268 int FstHalfIdx = i-HalfSize;
3269 if (Mask[FstHalfIdx] < 0)
3271 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3274 for (int i = QuarterSize*3; i < NumElems; ++i) {
3275 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3277 int FstHalfIdx = i-HalfSize;
3278 if (Mask[FstHalfIdx] < 0)
3280 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3288 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3289 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3290 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3291 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3292 EVT VT = SVOp->getValueType(0);
3293 int NumElems = VT.getVectorNumElements();
3295 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3296 "Only supports v8i32 and v8f32 types");
3298 int HalfSize = NumElems/2;
3300 for (int i = 0; i != NumElems ; ++i) {
3301 if (SVOp->getMaskElt(i) < 0)
3303 // The mask of the first half must be equal to the second one.
3304 unsigned Shamt = (i%HalfSize)*2;
3305 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3306 Mask |= Elt << Shamt;
3312 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3313 /// specifies a shuffle of elements that is suitable for input to 256-bit
3314 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3315 /// version and the mask of the second half isn't binded with the first
3317 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3318 const X86Subtarget *Subtarget) {
3319 int NumElems = VT.getVectorNumElements();
3321 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3327 // VSHUFPSY divides the resulting vector into 4 chunks.
3328 // The sources are also splitted into 4 chunks, and each destination
3329 // chunk must come from a different source chunk.
3331 // SRC1 => X3 X2 X1 X0
3332 // SRC2 => Y3 Y2 Y1 Y0
3334 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3336 int QuarterSize = NumElems/4;
3337 int HalfSize = QuarterSize*2;
3338 for (int i = 0; i < QuarterSize; ++i)
3339 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3341 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3342 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3344 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3345 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3347 for (int i = QuarterSize*3; i < NumElems; ++i)
3348 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3354 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3355 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3356 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3357 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3358 EVT VT = SVOp->getValueType(0);
3359 int NumElems = VT.getVectorNumElements();
3361 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3362 "Only supports v4i64 and v4f64 types");
3364 int HalfSize = NumElems/2;
3366 for (int i = 0; i != NumElems ; ++i) {
3367 if (SVOp->getMaskElt(i) < 0)
3369 int Elt = SVOp->getMaskElt(i) % HalfSize;
3376 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3377 /// specifies a shuffle of elements that is suitable for input to 128-bit
3378 /// SHUFPS and SHUFPD.
3379 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3380 int NumElems = VT.getVectorNumElements();
3382 if (VT.getSizeInBits() != 128)
3385 if (NumElems != 2 && NumElems != 4)
3388 int Half = NumElems / 2;
3389 for (int i = 0; i < Half; ++i)
3390 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3392 for (int i = Half; i < NumElems; ++i)
3393 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3399 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3400 SmallVector<int, 8> M;
3402 return ::isSHUFPMask(M, N->getValueType(0));
3405 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3406 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3407 /// half elements to come from vector 1 (which would equal the dest.) and
3408 /// the upper half to come from vector 2.
3409 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3410 int NumElems = VT.getVectorNumElements();
3412 if (NumElems != 2 && NumElems != 4)
3415 int Half = NumElems / 2;
3416 for (int i = 0; i < Half; ++i)
3417 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3419 for (int i = Half; i < NumElems; ++i)
3420 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3425 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3426 SmallVector<int, 8> M;
3428 return isCommutedSHUFPMask(M, N->getValueType(0));
3431 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3432 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3433 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3434 EVT VT = N->getValueType(0);
3435 unsigned NumElems = VT.getVectorNumElements();
3437 if (VT.getSizeInBits() != 128)
3443 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3444 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3445 isUndefOrEqual(N->getMaskElt(1), 7) &&
3446 isUndefOrEqual(N->getMaskElt(2), 2) &&
3447 isUndefOrEqual(N->getMaskElt(3), 3);
3450 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3451 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3453 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3454 EVT VT = N->getValueType(0);
3455 unsigned NumElems = VT.getVectorNumElements();
3457 if (VT.getSizeInBits() != 128)
3463 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3464 isUndefOrEqual(N->getMaskElt(1), 3) &&
3465 isUndefOrEqual(N->getMaskElt(2), 2) &&
3466 isUndefOrEqual(N->getMaskElt(3), 3);
3469 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3470 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3471 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3472 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3474 if (NumElems != 2 && NumElems != 4)
3477 for (unsigned i = 0; i < NumElems/2; ++i)
3478 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3481 for (unsigned i = NumElems/2; i < NumElems; ++i)
3482 if (!isUndefOrEqual(N->getMaskElt(i), i))
3488 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3490 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3491 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3493 if ((NumElems != 2 && NumElems != 4)
3494 || N->getValueType(0).getSizeInBits() > 128)
3497 for (unsigned i = 0; i < NumElems/2; ++i)
3498 if (!isUndefOrEqual(N->getMaskElt(i), i))
3501 for (unsigned i = 0; i < NumElems/2; ++i)
3502 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3508 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3509 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3510 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3511 bool V2IsSplat = false) {
3512 int NumElts = VT.getVectorNumElements();
3514 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3515 "Unsupported vector type for unpckh");
3517 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3520 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3521 // independently on 128-bit lanes.
3522 unsigned NumLanes = VT.getSizeInBits()/128;
3523 unsigned NumLaneElts = NumElts/NumLanes;
3526 unsigned End = NumLaneElts;
3527 for (unsigned s = 0; s < NumLanes; ++s) {
3528 for (unsigned i = Start, j = s * NumLaneElts;
3532 int BitI1 = Mask[i+1];
3533 if (!isUndefOrEqual(BitI, j))
3536 if (!isUndefOrEqual(BitI1, NumElts))
3539 if (!isUndefOrEqual(BitI1, j + NumElts))
3543 // Process the next 128 bits.
3544 Start += NumLaneElts;
3551 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3552 SmallVector<int, 8> M;
3554 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3557 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3558 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3559 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3560 bool V2IsSplat = false) {
3561 int NumElts = VT.getVectorNumElements();
3563 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3564 "Unsupported vector type for unpckh");
3566 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3569 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3570 // independently on 128-bit lanes.
3571 unsigned NumLanes = VT.getSizeInBits()/128;
3572 unsigned NumLaneElts = NumElts/NumLanes;
3575 unsigned End = NumLaneElts;
3576 for (unsigned l = 0; l != NumLanes; ++l) {
3577 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3578 i != End; i += 2, ++j) {
3580 int BitI1 = Mask[i+1];
3581 if (!isUndefOrEqual(BitI, j))
3584 if (isUndefOrEqual(BitI1, NumElts))
3587 if (!isUndefOrEqual(BitI1, j+NumElts))
3591 // Process the next 128 bits.
3592 Start += NumLaneElts;
3598 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3599 SmallVector<int, 8> M;
3601 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3604 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3605 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3607 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3608 int NumElems = VT.getVectorNumElements();
3609 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3612 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3613 // FIXME: Need a better way to get rid of this, there's no latency difference
3614 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3615 // the former later. We should also remove the "_undef" special mask.
3616 if (NumElems == 4 && VT.getSizeInBits() == 256)
3619 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3620 // independently on 128-bit lanes.
3621 unsigned NumLanes = VT.getSizeInBits() / 128;
3622 unsigned NumLaneElts = NumElems / NumLanes;
3624 for (unsigned s = 0; s < NumLanes; ++s) {
3625 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3626 i != NumLaneElts * (s + 1);
3629 int BitI1 = Mask[i+1];
3631 if (!isUndefOrEqual(BitI, j))
3633 if (!isUndefOrEqual(BitI1, j))
3641 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3642 SmallVector<int, 8> M;
3644 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3647 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3648 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3650 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3651 int NumElems = VT.getVectorNumElements();
3652 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3655 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3657 int BitI1 = Mask[i+1];
3658 if (!isUndefOrEqual(BitI, j))
3660 if (!isUndefOrEqual(BitI1, j))
3666 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3667 SmallVector<int, 8> M;
3669 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3672 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3673 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3674 /// MOVSD, and MOVD, i.e. setting the lowest element.
3675 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3676 if (VT.getVectorElementType().getSizeInBits() < 32)
3679 int NumElts = VT.getVectorNumElements();
3681 if (!isUndefOrEqual(Mask[0], NumElts))
3684 for (int i = 1; i < NumElts; ++i)
3685 if (!isUndefOrEqual(Mask[i], i))
3691 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3692 SmallVector<int, 8> M;
3694 return ::isMOVLMask(M, N->getValueType(0));
3697 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3698 /// as permutations between 128-bit chunks or halves. As an example: this
3700 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3701 /// The first half comes from the second half of V1 and the second half from the
3702 /// the second half of V2.
3703 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3704 const X86Subtarget *Subtarget) {
3705 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3708 // The shuffle result is divided into half A and half B. In total the two
3709 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3710 // B must come from C, D, E or F.
3711 int HalfSize = VT.getVectorNumElements()/2;
3712 bool MatchA = false, MatchB = false;
3714 // Check if A comes from one of C, D, E, F.
3715 for (int Half = 0; Half < 4; ++Half) {
3716 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3722 // Check if B comes from one of C, D, E, F.
3723 for (int Half = 0; Half < 4; ++Half) {
3724 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3730 return MatchA && MatchB;
3733 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3734 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3735 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3736 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3737 EVT VT = SVOp->getValueType(0);
3739 int HalfSize = VT.getVectorNumElements()/2;
3741 int FstHalf = 0, SndHalf = 0;
3742 for (int i = 0; i < HalfSize; ++i) {
3743 if (SVOp->getMaskElt(i) > 0) {
3744 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3748 for (int i = HalfSize; i < HalfSize*2; ++i) {
3749 if (SVOp->getMaskElt(i) > 0) {
3750 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3755 return (FstHalf | (SndHalf << 4));
3758 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3759 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3760 /// Note that VPERMIL mask matching is different depending whether theunderlying
3761 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3762 /// to the same elements of the low, but to the higher half of the source.
3763 /// In VPERMILPD the two lanes could be shuffled independently of each other
3764 /// with the same restriction that lanes can't be crossed.
3765 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3766 const X86Subtarget *Subtarget) {
3767 int NumElts = VT.getVectorNumElements();
3768 int NumLanes = VT.getSizeInBits()/128;
3770 if (!Subtarget->hasAVX())
3773 // Only match 256-bit with 64-bit types
3774 if (VT.getSizeInBits() != 256 || NumElts != 4)
3777 // The mask on the high lane is independent of the low. Both can match
3778 // any element in inside its own lane, but can't cross.
3779 int LaneSize = NumElts/NumLanes;
3780 for (int l = 0; l < NumLanes; ++l)
3781 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3782 int LaneStart = l*LaneSize;
3783 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3790 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3791 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3792 /// Note that VPERMIL mask matching is different depending whether theunderlying
3793 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3794 /// to the same elements of the low, but to the higher half of the source.
3795 /// In VPERMILPD the two lanes could be shuffled independently of each other
3796 /// with the same restriction that lanes can't be crossed.
3797 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3798 const X86Subtarget *Subtarget) {
3799 unsigned NumElts = VT.getVectorNumElements();
3800 unsigned NumLanes = VT.getSizeInBits()/128;
3802 if (!Subtarget->hasAVX())
3805 // Only match 256-bit with 32-bit types
3806 if (VT.getSizeInBits() != 256 || NumElts != 8)
3809 // The mask on the high lane should be the same as the low. Actually,
3810 // they can differ if any of the corresponding index in a lane is undef
3811 // and the other stays in range.
3812 int LaneSize = NumElts/NumLanes;
3813 for (int i = 0; i < LaneSize; ++i) {
3814 int HighElt = i+LaneSize;
3815 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3816 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3818 if (!HighValid || !LowValid)
3820 if (Mask[i] < 0 || Mask[HighElt] < 0)
3822 if (Mask[HighElt]-Mask[i] != LaneSize)
3829 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3830 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3831 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3833 EVT VT = SVOp->getValueType(0);
3835 int NumElts = VT.getVectorNumElements();
3836 int NumLanes = VT.getSizeInBits()/128;
3837 int LaneSize = NumElts/NumLanes;
3839 // Although the mask is equal for both lanes do it twice to get the cases
3840 // where a mask will match because the same mask element is undef on the
3841 // first half but valid on the second. This would get pathological cases
3842 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3844 for (int l = 0; l < NumLanes; ++l) {
3845 for (int i = 0; i < LaneSize; ++i) {
3846 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3849 if (MaskElt >= LaneSize)
3850 MaskElt -= LaneSize;
3851 Mask |= MaskElt << (i*2);
3858 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3859 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3860 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3862 EVT VT = SVOp->getValueType(0);
3864 int NumElts = VT.getVectorNumElements();
3865 int NumLanes = VT.getSizeInBits()/128;
3868 int LaneSize = NumElts/NumLanes;
3869 for (int l = 0; l < NumLanes; ++l)
3870 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3871 int MaskElt = SVOp->getMaskElt(i);
3874 Mask |= (MaskElt-l*LaneSize) << i;
3880 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3881 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3882 /// element of vector 2 and the other elements to come from vector 1 in order.
3883 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3884 bool V2IsSplat = false, bool V2IsUndef = false) {
3885 int NumOps = VT.getVectorNumElements();
3886 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3889 if (!isUndefOrEqual(Mask[0], 0))
3892 for (int i = 1; i < NumOps; ++i)
3893 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3894 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3895 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3901 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3902 bool V2IsUndef = false) {
3903 SmallVector<int, 8> M;
3905 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3908 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3910 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3911 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3912 const X86Subtarget *Subtarget) {
3913 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3916 // The second vector must be undef
3917 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3920 EVT VT = N->getValueType(0);
3921 unsigned NumElems = VT.getVectorNumElements();
3923 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3924 (VT.getSizeInBits() == 256 && NumElems != 8))
3927 // "i+1" is the value the indexed mask element must have
3928 for (unsigned i = 0; i < NumElems; i += 2)
3929 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3930 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3936 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3938 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3939 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3940 const X86Subtarget *Subtarget) {
3941 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3944 // The second vector must be undef
3945 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3948 EVT VT = N->getValueType(0);
3949 unsigned NumElems = VT.getVectorNumElements();
3951 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3952 (VT.getSizeInBits() == 256 && NumElems != 8))
3955 // "i" is the value the indexed mask element must have
3956 for (unsigned i = 0; i < NumElems; i += 2)
3957 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3958 !isUndefOrEqual(N->getMaskElt(i+1), i))
3964 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3965 /// specifies a shuffle of elements that is suitable for input to 256-bit
3966 /// version of MOVDDUP.
3967 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3968 const X86Subtarget *Subtarget) {
3969 EVT VT = N->getValueType(0);
3970 int NumElts = VT.getVectorNumElements();
3971 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3973 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3974 !V2IsUndef || NumElts != 4)
3977 for (int i = 0; i != NumElts/2; ++i)
3978 if (!isUndefOrEqual(N->getMaskElt(i), 0))
3980 for (int i = NumElts/2; i != NumElts; ++i)
3981 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3986 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3987 /// specifies a shuffle of elements that is suitable for input to 128-bit
3988 /// version of MOVDDUP.
3989 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3990 EVT VT = N->getValueType(0);
3992 if (VT.getSizeInBits() != 128)
3995 int e = VT.getVectorNumElements() / 2;
3996 for (int i = 0; i < e; ++i)
3997 if (!isUndefOrEqual(N->getMaskElt(i), i))
3999 for (int i = 0; i < e; ++i)
4000 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4005 /// isVEXTRACTF128Index - Return true if the specified
4006 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4007 /// suitable for input to VEXTRACTF128.
4008 bool X86::isVEXTRACTF128Index(SDNode *N) {
4009 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4012 // The index should be aligned on a 128-bit boundary.
4014 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4016 unsigned VL = N->getValueType(0).getVectorNumElements();
4017 unsigned VBits = N->getValueType(0).getSizeInBits();
4018 unsigned ElSize = VBits / VL;
4019 bool Result = (Index * ElSize) % 128 == 0;
4024 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4027 bool X86::isVINSERTF128Index(SDNode *N) {
4028 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4031 // The index should be aligned on a 128-bit boundary.
4033 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4035 unsigned VL = N->getValueType(0).getVectorNumElements();
4036 unsigned VBits = N->getValueType(0).getSizeInBits();
4037 unsigned ElSize = VBits / VL;
4038 bool Result = (Index * ElSize) % 128 == 0;
4043 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4044 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4045 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4046 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4047 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4049 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4051 for (int i = 0; i < NumOperands; ++i) {
4052 int Val = SVOp->getMaskElt(NumOperands-i-1);
4053 if (Val < 0) Val = 0;
4054 if (Val >= NumOperands) Val -= NumOperands;
4056 if (i != NumOperands - 1)
4062 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4063 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4064 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4067 // 8 nodes, but we only care about the last 4.
4068 for (unsigned i = 7; i >= 4; --i) {
4069 int Val = SVOp->getMaskElt(i);
4078 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4080 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4083 // 8 nodes, but we only care about the first 4.
4084 for (int i = 3; i >= 0; --i) {
4085 int Val = SVOp->getMaskElt(i);
4094 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4096 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4097 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4098 EVT VVT = N->getValueType(0);
4099 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4103 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4104 Val = SVOp->getMaskElt(i);
4108 assert(Val - i > 0 && "PALIGNR imm should be positive");
4109 return (Val - i) * EltSize;
4112 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4113 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4115 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4116 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4117 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4120 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4122 EVT VecVT = N->getOperand(0).getValueType();
4123 EVT ElVT = VecVT.getVectorElementType();
4125 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4126 return Index / NumElemsPerChunk;
4129 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4130 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4132 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4133 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4134 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4137 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4139 EVT VecVT = N->getValueType(0);
4140 EVT ElVT = VecVT.getVectorElementType();
4142 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4143 return Index / NumElemsPerChunk;
4146 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4148 bool X86::isZeroNode(SDValue Elt) {
4149 return ((isa<ConstantSDNode>(Elt) &&
4150 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4151 (isa<ConstantFPSDNode>(Elt) &&
4152 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4155 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4156 /// their permute mask.
4157 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4158 SelectionDAG &DAG) {
4159 EVT VT = SVOp->getValueType(0);
4160 unsigned NumElems = VT.getVectorNumElements();
4161 SmallVector<int, 8> MaskVec;
4163 for (unsigned i = 0; i != NumElems; ++i) {
4164 int idx = SVOp->getMaskElt(i);
4166 MaskVec.push_back(idx);
4167 else if (idx < (int)NumElems)
4168 MaskVec.push_back(idx + NumElems);
4170 MaskVec.push_back(idx - NumElems);
4172 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4173 SVOp->getOperand(0), &MaskVec[0]);
4176 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4177 /// the two vector operands have swapped position.
4178 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4179 unsigned NumElems = VT.getVectorNumElements();
4180 for (unsigned i = 0; i != NumElems; ++i) {
4184 else if (idx < (int)NumElems)
4185 Mask[i] = idx + NumElems;
4187 Mask[i] = idx - NumElems;
4191 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4192 /// match movhlps. The lower half elements should come from upper half of
4193 /// V1 (and in order), and the upper half elements should come from the upper
4194 /// half of V2 (and in order).
4195 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4196 EVT VT = Op->getValueType(0);
4197 if (VT.getSizeInBits() != 128)
4199 if (VT.getVectorNumElements() != 4)
4201 for (unsigned i = 0, e = 2; i != e; ++i)
4202 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4204 for (unsigned i = 2; i != 4; ++i)
4205 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4210 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4211 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4213 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4214 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4216 N = N->getOperand(0).getNode();
4217 if (!ISD::isNON_EXTLoad(N))
4220 *LD = cast<LoadSDNode>(N);
4224 // Test whether the given value is a vector value which will be legalized
4226 static bool WillBeConstantPoolLoad(SDNode *N) {
4227 if (N->getOpcode() != ISD::BUILD_VECTOR)
4230 // Check for any non-constant elements.
4231 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4232 switch (N->getOperand(i).getNode()->getOpcode()) {
4234 case ISD::ConstantFP:
4241 // Vectors of all-zeros and all-ones are materialized with special
4242 // instructions rather than being loaded.
4243 return !ISD::isBuildVectorAllZeros(N) &&
4244 !ISD::isBuildVectorAllOnes(N);
4247 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4248 /// match movlp{s|d}. The lower half elements should come from lower half of
4249 /// V1 (and in order), and the upper half elements should come from the upper
4250 /// half of V2 (and in order). And since V1 will become the source of the
4251 /// MOVLP, it must be either a vector load or a scalar load to vector.
4252 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4253 ShuffleVectorSDNode *Op) {
4254 EVT VT = Op->getValueType(0);
4255 if (VT.getSizeInBits() != 128)
4258 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4260 // Is V2 is a vector load, don't do this transformation. We will try to use
4261 // load folding shufps op.
4262 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4265 unsigned NumElems = VT.getVectorNumElements();
4267 if (NumElems != 2 && NumElems != 4)
4269 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4270 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4272 for (unsigned i = NumElems/2; i != NumElems; ++i)
4273 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4278 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4280 static bool isSplatVector(SDNode *N) {
4281 if (N->getOpcode() != ISD::BUILD_VECTOR)
4284 SDValue SplatValue = N->getOperand(0);
4285 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4286 if (N->getOperand(i) != SplatValue)
4291 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4292 /// to an zero vector.
4293 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4294 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4295 SDValue V1 = N->getOperand(0);
4296 SDValue V2 = N->getOperand(1);
4297 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4298 for (unsigned i = 0; i != NumElems; ++i) {
4299 int Idx = N->getMaskElt(i);
4300 if (Idx >= (int)NumElems) {
4301 unsigned Opc = V2.getOpcode();
4302 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4304 if (Opc != ISD::BUILD_VECTOR ||
4305 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4307 } else if (Idx >= 0) {
4308 unsigned Opc = V1.getOpcode();
4309 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4311 if (Opc != ISD::BUILD_VECTOR ||
4312 !X86::isZeroNode(V1.getOperand(Idx)))
4319 /// getZeroVector - Returns a vector of specified type with all zero elements.
4321 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4323 assert(VT.isVector() && "Expected a vector type");
4325 // Always build SSE zero vectors as <4 x i32> bitcasted
4326 // to their dest type. This ensures they get CSE'd.
4328 if (VT.getSizeInBits() == 128) { // SSE
4329 if (HasXMMInt) { // SSE2
4330 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4331 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4333 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4334 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4336 } else if (VT.getSizeInBits() == 256) { // AVX
4337 // 256-bit logic and arithmetic instructions in AVX are
4338 // all floating-point, no support for integer ops. Default
4339 // to emitting fp zeroed vectors then.
4340 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4341 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4342 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4344 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4347 /// getOnesVector - Returns a vector of specified type with all bits set.
4348 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4349 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4350 /// original type, ensuring they get CSE'd.
4351 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4352 assert(VT.isVector() && "Expected a vector type");
4353 assert((VT.is128BitVector() || VT.is256BitVector())
4354 && "Expected a 128-bit or 256-bit vector type");
4356 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4357 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4358 Cst, Cst, Cst, Cst);
4360 if (VT.is256BitVector()) {
4361 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4362 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4363 Vec = Insert128BitVector(InsV, Vec,
4364 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4367 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4370 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4371 /// that point to V2 points to its first element.
4372 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4373 EVT VT = SVOp->getValueType(0);
4374 unsigned NumElems = VT.getVectorNumElements();
4376 bool Changed = false;
4377 SmallVector<int, 8> MaskVec;
4378 SVOp->getMask(MaskVec);
4380 for (unsigned i = 0; i != NumElems; ++i) {
4381 if (MaskVec[i] > (int)NumElems) {
4382 MaskVec[i] = NumElems;
4387 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4388 SVOp->getOperand(1), &MaskVec[0]);
4389 return SDValue(SVOp, 0);
4392 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4393 /// operation of specified width.
4394 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4396 unsigned NumElems = VT.getVectorNumElements();
4397 SmallVector<int, 8> Mask;
4398 Mask.push_back(NumElems);
4399 for (unsigned i = 1; i != NumElems; ++i)
4401 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4404 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4405 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4407 unsigned NumElems = VT.getVectorNumElements();
4408 SmallVector<int, 8> Mask;
4409 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4411 Mask.push_back(i + NumElems);
4413 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4416 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4417 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4419 unsigned NumElems = VT.getVectorNumElements();
4420 unsigned Half = NumElems/2;
4421 SmallVector<int, 8> Mask;
4422 for (unsigned i = 0; i != Half; ++i) {
4423 Mask.push_back(i + Half);
4424 Mask.push_back(i + NumElems + Half);
4426 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4429 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4430 // a generic shuffle instruction because the target has no such instructions.
4431 // Generate shuffles which repeat i16 and i8 several times until they can be
4432 // represented by v4f32 and then be manipulated by target suported shuffles.
4433 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4434 EVT VT = V.getValueType();
4435 int NumElems = VT.getVectorNumElements();
4436 DebugLoc dl = V.getDebugLoc();
4438 while (NumElems > 4) {
4439 if (EltNo < NumElems/2) {
4440 V = getUnpackl(DAG, dl, VT, V, V);
4442 V = getUnpackh(DAG, dl, VT, V, V);
4443 EltNo -= NumElems/2;
4450 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4451 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4452 EVT VT = V.getValueType();
4453 DebugLoc dl = V.getDebugLoc();
4454 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4455 && "Vector size not supported");
4457 if (VT.getSizeInBits() == 128) {
4458 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4459 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4460 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4463 // To use VPERMILPS to splat scalars, the second half of indicies must
4464 // refer to the higher part, which is a duplication of the lower one,
4465 // because VPERMILPS can only handle in-lane permutations.
4466 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4467 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4469 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4470 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4474 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4477 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4478 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4479 EVT SrcVT = SV->getValueType(0);
4480 SDValue V1 = SV->getOperand(0);
4481 DebugLoc dl = SV->getDebugLoc();
4483 int EltNo = SV->getSplatIndex();
4484 int NumElems = SrcVT.getVectorNumElements();
4485 unsigned Size = SrcVT.getSizeInBits();
4487 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4488 "Unknown how to promote splat for type");
4490 // Extract the 128-bit part containing the splat element and update
4491 // the splat element index when it refers to the higher register.
4493 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4494 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4496 EltNo -= NumElems/2;
4499 // All i16 and i8 vector types can't be used directly by a generic shuffle
4500 // instruction because the target has no such instruction. Generate shuffles
4501 // which repeat i16 and i8 several times until they fit in i32, and then can
4502 // be manipulated by target suported shuffles.
4503 EVT EltVT = SrcVT.getVectorElementType();
4504 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4505 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4507 // Recreate the 256-bit vector and place the same 128-bit vector
4508 // into the low and high part. This is necessary because we want
4509 // to use VPERM* to shuffle the vectors
4511 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4512 DAG.getConstant(0, MVT::i32), DAG, dl);
4513 V1 = Insert128BitVector(InsV, V1,
4514 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4517 return getLegalSplat(DAG, V1, EltNo);
4520 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4521 /// vector of zero or undef vector. This produces a shuffle where the low
4522 /// element of V2 is swizzled into the zero/undef vector, landing at element
4523 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4524 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4525 bool isZero, bool HasXMMInt,
4526 SelectionDAG &DAG) {
4527 EVT VT = V2.getValueType();
4529 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4530 unsigned NumElems = VT.getVectorNumElements();
4531 SmallVector<int, 16> MaskVec;
4532 for (unsigned i = 0; i != NumElems; ++i)
4533 // If this is the insertion idx, put the low elt of V2 here.
4534 MaskVec.push_back(i == Idx ? NumElems : i);
4535 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4538 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4539 /// element of the result of the vector shuffle.
4540 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4543 return SDValue(); // Limit search depth.
4545 SDValue V = SDValue(N, 0);
4546 EVT VT = V.getValueType();
4547 unsigned Opcode = V.getOpcode();
4549 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4550 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4551 Index = SV->getMaskElt(Index);
4554 return DAG.getUNDEF(VT.getVectorElementType());
4556 int NumElems = VT.getVectorNumElements();
4557 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4558 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4561 // Recurse into target specific vector shuffles to find scalars.
4562 if (isTargetShuffle(Opcode)) {
4563 int NumElems = VT.getVectorNumElements();
4564 SmallVector<unsigned, 16> ShuffleMask;
4568 case X86ISD::SHUFPS:
4569 case X86ISD::SHUFPD:
4570 ImmN = N->getOperand(N->getNumOperands()-1);
4571 DecodeSHUFPSMask(NumElems,
4572 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4575 case X86ISD::PUNPCKHBW:
4576 case X86ISD::PUNPCKHWD:
4577 case X86ISD::PUNPCKHDQ:
4578 case X86ISD::PUNPCKHQDQ:
4579 DecodePUNPCKHMask(NumElems, ShuffleMask);
4581 case X86ISD::UNPCKHPS:
4582 case X86ISD::UNPCKHPD:
4583 case X86ISD::VUNPCKHPSY:
4584 case X86ISD::VUNPCKHPDY:
4585 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4587 case X86ISD::PUNPCKLBW:
4588 case X86ISD::PUNPCKLWD:
4589 case X86ISD::PUNPCKLDQ:
4590 case X86ISD::PUNPCKLQDQ:
4591 DecodePUNPCKLMask(VT, ShuffleMask);
4593 case X86ISD::UNPCKLPS:
4594 case X86ISD::UNPCKLPD:
4595 case X86ISD::VUNPCKLPSY:
4596 case X86ISD::VUNPCKLPDY:
4597 DecodeUNPCKLPMask(VT, ShuffleMask);
4599 case X86ISD::MOVHLPS:
4600 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4602 case X86ISD::MOVLHPS:
4603 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4605 case X86ISD::PSHUFD:
4606 ImmN = N->getOperand(N->getNumOperands()-1);
4607 DecodePSHUFMask(NumElems,
4608 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4611 case X86ISD::PSHUFHW:
4612 ImmN = N->getOperand(N->getNumOperands()-1);
4613 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4616 case X86ISD::PSHUFLW:
4617 ImmN = N->getOperand(N->getNumOperands()-1);
4618 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4622 case X86ISD::MOVSD: {
4623 // The index 0 always comes from the first element of the second source,
4624 // this is why MOVSS and MOVSD are used in the first place. The other
4625 // elements come from the other positions of the first source vector.
4626 unsigned OpNum = (Index == 0) ? 1 : 0;
4627 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4630 case X86ISD::VPERMILPS:
4631 ImmN = N->getOperand(N->getNumOperands()-1);
4632 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4635 case X86ISD::VPERMILPSY:
4636 ImmN = N->getOperand(N->getNumOperands()-1);
4637 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4640 case X86ISD::VPERMILPD:
4641 ImmN = N->getOperand(N->getNumOperands()-1);
4642 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4645 case X86ISD::VPERMILPDY:
4646 ImmN = N->getOperand(N->getNumOperands()-1);
4647 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4650 case X86ISD::VPERM2F128:
4651 ImmN = N->getOperand(N->getNumOperands()-1);
4652 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4655 case X86ISD::MOVDDUP:
4656 case X86ISD::MOVLHPD:
4657 case X86ISD::MOVLPD:
4658 case X86ISD::MOVLPS:
4659 case X86ISD::MOVSHDUP:
4660 case X86ISD::MOVSLDUP:
4661 case X86ISD::PALIGN:
4662 return SDValue(); // Not yet implemented.
4664 assert(0 && "unknown target shuffle node");
4668 Index = ShuffleMask[Index];
4670 return DAG.getUNDEF(VT.getVectorElementType());
4672 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4673 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4677 // Actual nodes that may contain scalar elements
4678 if (Opcode == ISD::BITCAST) {
4679 V = V.getOperand(0);
4680 EVT SrcVT = V.getValueType();
4681 unsigned NumElems = VT.getVectorNumElements();
4683 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4687 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4688 return (Index == 0) ? V.getOperand(0)
4689 : DAG.getUNDEF(VT.getVectorElementType());
4691 if (V.getOpcode() == ISD::BUILD_VECTOR)
4692 return V.getOperand(Index);
4697 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4698 /// shuffle operation which come from a consecutively from a zero. The
4699 /// search can start in two different directions, from left or right.
4701 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4702 bool ZerosFromLeft, SelectionDAG &DAG) {
4705 while (i < NumElems) {
4706 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4707 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4708 if (!(Elt.getNode() &&
4709 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4717 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4718 /// MaskE correspond consecutively to elements from one of the vector operands,
4719 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4721 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4722 int OpIdx, int NumElems, unsigned &OpNum) {
4723 bool SeenV1 = false;
4724 bool SeenV2 = false;
4726 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4727 int Idx = SVOp->getMaskElt(i);
4728 // Ignore undef indicies
4737 // Only accept consecutive elements from the same vector
4738 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4742 OpNum = SeenV1 ? 0 : 1;
4746 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4747 /// logical left shift of a vector.
4748 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4749 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4750 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4751 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4752 false /* check zeros from right */, DAG);
4758 // Considering the elements in the mask that are not consecutive zeros,
4759 // check if they consecutively come from only one of the source vectors.
4761 // V1 = {X, A, B, C} 0
4763 // vector_shuffle V1, V2 <1, 2, 3, X>
4765 if (!isShuffleMaskConsecutive(SVOp,
4766 0, // Mask Start Index
4767 NumElems-NumZeros-1, // Mask End Index
4768 NumZeros, // Where to start looking in the src vector
4769 NumElems, // Number of elements in vector
4770 OpSrc)) // Which source operand ?
4775 ShVal = SVOp->getOperand(OpSrc);
4779 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4780 /// logical left shift of a vector.
4781 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4782 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4783 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4784 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4785 true /* check zeros from left */, DAG);
4791 // Considering the elements in the mask that are not consecutive zeros,
4792 // check if they consecutively come from only one of the source vectors.
4794 // 0 { A, B, X, X } = V2
4796 // vector_shuffle V1, V2 <X, X, 4, 5>
4798 if (!isShuffleMaskConsecutive(SVOp,
4799 NumZeros, // Mask Start Index
4800 NumElems-1, // Mask End Index
4801 0, // Where to start looking in the src vector
4802 NumElems, // Number of elements in vector
4803 OpSrc)) // Which source operand ?
4808 ShVal = SVOp->getOperand(OpSrc);
4812 /// isVectorShift - Returns true if the shuffle can be implemented as a
4813 /// logical left or right shift of a vector.
4814 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4815 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4816 // Although the logic below support any bitwidth size, there are no
4817 // shift instructions which handle more than 128-bit vectors.
4818 if (SVOp->getValueType(0).getSizeInBits() > 128)
4821 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4822 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4828 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4830 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4831 unsigned NumNonZero, unsigned NumZero,
4833 const TargetLowering &TLI) {
4837 DebugLoc dl = Op.getDebugLoc();
4840 for (unsigned i = 0; i < 16; ++i) {
4841 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4842 if (ThisIsNonZero && First) {
4844 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4846 V = DAG.getUNDEF(MVT::v8i16);
4851 SDValue ThisElt(0, 0), LastElt(0, 0);
4852 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4853 if (LastIsNonZero) {
4854 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4855 MVT::i16, Op.getOperand(i-1));
4857 if (ThisIsNonZero) {
4858 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4859 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4860 ThisElt, DAG.getConstant(8, MVT::i8));
4862 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4866 if (ThisElt.getNode())
4867 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4868 DAG.getIntPtrConstant(i/2));
4872 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4875 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4877 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4878 unsigned NumNonZero, unsigned NumZero,
4880 const TargetLowering &TLI) {
4884 DebugLoc dl = Op.getDebugLoc();
4887 for (unsigned i = 0; i < 8; ++i) {
4888 bool isNonZero = (NonZeros & (1 << i)) != 0;
4892 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4894 V = DAG.getUNDEF(MVT::v8i16);
4897 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4898 MVT::v8i16, V, Op.getOperand(i),
4899 DAG.getIntPtrConstant(i));
4906 /// getVShift - Return a vector logical shift node.
4908 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4909 unsigned NumBits, SelectionDAG &DAG,
4910 const TargetLowering &TLI, DebugLoc dl) {
4911 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4912 EVT ShVT = MVT::v2i64;
4913 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4914 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4915 return DAG.getNode(ISD::BITCAST, dl, VT,
4916 DAG.getNode(Opc, dl, ShVT, SrcOp,
4917 DAG.getConstant(NumBits,
4918 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4922 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4923 SelectionDAG &DAG) const {
4925 // Check if the scalar load can be widened into a vector load. And if
4926 // the address is "base + cst" see if the cst can be "absorbed" into
4927 // the shuffle mask.
4928 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4929 SDValue Ptr = LD->getBasePtr();
4930 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4932 EVT PVT = LD->getValueType(0);
4933 if (PVT != MVT::i32 && PVT != MVT::f32)
4938 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4939 FI = FINode->getIndex();
4941 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4942 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4943 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4944 Offset = Ptr.getConstantOperandVal(1);
4945 Ptr = Ptr.getOperand(0);
4950 // FIXME: 256-bit vector instructions don't require a strict alignment,
4951 // improve this code to support it better.
4952 unsigned RequiredAlign = VT.getSizeInBits()/8;
4953 SDValue Chain = LD->getChain();
4954 // Make sure the stack object alignment is at least 16 or 32.
4955 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4956 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4957 if (MFI->isFixedObjectIndex(FI)) {
4958 // Can't change the alignment. FIXME: It's possible to compute
4959 // the exact stack offset and reference FI + adjust offset instead.
4960 // If someone *really* cares about this. That's the way to implement it.
4963 MFI->setObjectAlignment(FI, RequiredAlign);
4967 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4968 // Ptr + (Offset & ~15).
4971 if ((Offset % RequiredAlign) & 3)
4973 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4975 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4976 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4978 int EltNo = (Offset - StartOffset) >> 2;
4979 int NumElems = VT.getVectorNumElements();
4981 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4982 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4983 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4984 LD->getPointerInfo().getWithOffset(StartOffset),
4985 false, false, false, 0);
4987 // Canonicalize it to a v4i32 or v8i32 shuffle.
4988 SmallVector<int, 8> Mask;
4989 for (int i = 0; i < NumElems; ++i)
4990 Mask.push_back(EltNo);
4992 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4993 return DAG.getNode(ISD::BITCAST, dl, NVT,
4994 DAG.getVectorShuffle(CanonVT, dl, V1,
4995 DAG.getUNDEF(CanonVT),&Mask[0]));
5001 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5002 /// vector of type 'VT', see if the elements can be replaced by a single large
5003 /// load which has the same value as a build_vector whose operands are 'elts'.
5005 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5007 /// FIXME: we'd also like to handle the case where the last elements are zero
5008 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5009 /// There's even a handy isZeroNode for that purpose.
5010 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5011 DebugLoc &DL, SelectionDAG &DAG) {
5012 EVT EltVT = VT.getVectorElementType();
5013 unsigned NumElems = Elts.size();
5015 LoadSDNode *LDBase = NULL;
5016 unsigned LastLoadedElt = -1U;
5018 // For each element in the initializer, see if we've found a load or an undef.
5019 // If we don't find an initial load element, or later load elements are
5020 // non-consecutive, bail out.
5021 for (unsigned i = 0; i < NumElems; ++i) {
5022 SDValue Elt = Elts[i];
5024 if (!Elt.getNode() ||
5025 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5028 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5030 LDBase = cast<LoadSDNode>(Elt.getNode());
5034 if (Elt.getOpcode() == ISD::UNDEF)
5037 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5038 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5043 // If we have found an entire vector of loads and undefs, then return a large
5044 // load of the entire vector width starting at the base pointer. If we found
5045 // consecutive loads for the low half, generate a vzext_load node.
5046 if (LastLoadedElt == NumElems - 1) {
5047 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5048 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5049 LDBase->getPointerInfo(),
5050 LDBase->isVolatile(), LDBase->isNonTemporal(),
5051 LDBase->isInvariant(), 0);
5052 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5053 LDBase->getPointerInfo(),
5054 LDBase->isVolatile(), LDBase->isNonTemporal(),
5055 LDBase->isInvariant(), LDBase->getAlignment());
5056 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5057 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5058 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5059 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5061 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5062 LDBase->getPointerInfo(),
5063 LDBase->getAlignment(),
5064 false/*isVolatile*/, true/*ReadMem*/,
5066 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5072 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5073 DebugLoc dl = Op.getDebugLoc();
5075 EVT VT = Op.getValueType();
5076 EVT ExtVT = VT.getVectorElementType();
5077 unsigned NumElems = Op.getNumOperands();
5079 // Vectors containing all zeros can be matched by pxor and xorps later
5080 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5081 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5082 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5083 if (Op.getValueType() == MVT::v4i32 ||
5084 Op.getValueType() == MVT::v8i32)
5087 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5090 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5091 // vectors or broken into v4i32 operations on 256-bit vectors.
5092 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5093 if (Op.getValueType() == MVT::v4i32)
5096 return getOnesVector(Op.getValueType(), DAG, dl);
5099 unsigned EVTBits = ExtVT.getSizeInBits();
5101 unsigned NumZero = 0;
5102 unsigned NumNonZero = 0;
5103 unsigned NonZeros = 0;
5104 bool IsAllConstants = true;
5105 SmallSet<SDValue, 8> Values;
5106 for (unsigned i = 0; i < NumElems; ++i) {
5107 SDValue Elt = Op.getOperand(i);
5108 if (Elt.getOpcode() == ISD::UNDEF)
5111 if (Elt.getOpcode() != ISD::Constant &&
5112 Elt.getOpcode() != ISD::ConstantFP)
5113 IsAllConstants = false;
5114 if (X86::isZeroNode(Elt))
5117 NonZeros |= (1 << i);
5122 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5123 if (NumNonZero == 0)
5124 return DAG.getUNDEF(VT);
5126 // Special case for single non-zero, non-undef, element.
5127 if (NumNonZero == 1) {
5128 unsigned Idx = CountTrailingZeros_32(NonZeros);
5129 SDValue Item = Op.getOperand(Idx);
5131 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5132 // the value are obviously zero, truncate the value to i32 and do the
5133 // insertion that way. Only do this if the value is non-constant or if the
5134 // value is a constant being inserted into element 0. It is cheaper to do
5135 // a constant pool load than it is to do a movd + shuffle.
5136 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5137 (!IsAllConstants || Idx == 0)) {
5138 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5140 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5141 EVT VecVT = MVT::v4i32;
5142 unsigned VecElts = 4;
5144 // Truncate the value (which may itself be a constant) to i32, and
5145 // convert it to a vector with movd (S2V+shuffle to zero extend).
5146 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5147 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5148 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5149 Subtarget->hasXMMInt(), DAG);
5151 // Now we have our 32-bit value zero extended in the low element of
5152 // a vector. If Idx != 0, swizzle it into place.
5154 SmallVector<int, 4> Mask;
5155 Mask.push_back(Idx);
5156 for (unsigned i = 1; i != VecElts; ++i)
5158 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5159 DAG.getUNDEF(Item.getValueType()),
5162 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5166 // If we have a constant or non-constant insertion into the low element of
5167 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5168 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5169 // depending on what the source datatype is.
5172 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5173 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5174 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5175 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5176 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5177 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5179 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5180 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5181 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5182 EVT MiddleVT = MVT::v4i32;
5183 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5184 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5185 Subtarget->hasXMMInt(), DAG);
5186 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5190 // Is it a vector logical left shift?
5191 if (NumElems == 2 && Idx == 1 &&
5192 X86::isZeroNode(Op.getOperand(0)) &&
5193 !X86::isZeroNode(Op.getOperand(1))) {
5194 unsigned NumBits = VT.getSizeInBits();
5195 return getVShift(true, VT,
5196 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5197 VT, Op.getOperand(1)),
5198 NumBits/2, DAG, *this, dl);
5201 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5204 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5205 // is a non-constant being inserted into an element other than the low one,
5206 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5207 // movd/movss) to move this into the low element, then shuffle it into
5209 if (EVTBits == 32) {
5210 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5212 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5213 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5214 Subtarget->hasXMMInt(), DAG);
5215 SmallVector<int, 8> MaskVec;
5216 for (unsigned i = 0; i < NumElems; i++)
5217 MaskVec.push_back(i == Idx ? 0 : 1);
5218 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5222 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5223 if (Values.size() == 1) {
5224 if (EVTBits == 32) {
5225 // Instead of a shuffle like this:
5226 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5227 // Check if it's possible to issue this instead.
5228 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5229 unsigned Idx = CountTrailingZeros_32(NonZeros);
5230 SDValue Item = Op.getOperand(Idx);
5231 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5232 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5237 // A vector full of immediates; various special cases are already
5238 // handled, so this is best done with a single constant-pool load.
5242 // For AVX-length vectors, build the individual 128-bit pieces and use
5243 // shuffles to put them in place.
5244 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5245 SmallVector<SDValue, 32> V;
5246 for (unsigned i = 0; i < NumElems; ++i)
5247 V.push_back(Op.getOperand(i));
5249 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5251 // Build both the lower and upper subvector.
5252 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5253 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5256 // Recreate the wider vector with the lower and upper part.
5257 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5258 DAG.getConstant(0, MVT::i32), DAG, dl);
5259 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5263 // Let legalizer expand 2-wide build_vectors.
5264 if (EVTBits == 64) {
5265 if (NumNonZero == 1) {
5266 // One half is zero or undef.
5267 unsigned Idx = CountTrailingZeros_32(NonZeros);
5268 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5269 Op.getOperand(Idx));
5270 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5271 Subtarget->hasXMMInt(), DAG);
5276 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5277 if (EVTBits == 8 && NumElems == 16) {
5278 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5280 if (V.getNode()) return V;
5283 if (EVTBits == 16 && NumElems == 8) {
5284 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5286 if (V.getNode()) return V;
5289 // If element VT is == 32 bits, turn it into a number of shuffles.
5290 SmallVector<SDValue, 8> V;
5292 if (NumElems == 4 && NumZero > 0) {
5293 for (unsigned i = 0; i < 4; ++i) {
5294 bool isZero = !(NonZeros & (1 << i));
5296 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5298 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5301 for (unsigned i = 0; i < 2; ++i) {
5302 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5305 V[i] = V[i*2]; // Must be a zero vector.
5308 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5311 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5314 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5319 SmallVector<int, 8> MaskVec;
5320 bool Reverse = (NonZeros & 0x3) == 2;
5321 for (unsigned i = 0; i < 2; ++i)
5322 MaskVec.push_back(Reverse ? 1-i : i);
5323 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5324 for (unsigned i = 0; i < 2; ++i)
5325 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5326 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5329 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5330 // Check for a build vector of consecutive loads.
5331 for (unsigned i = 0; i < NumElems; ++i)
5332 V[i] = Op.getOperand(i);
5334 // Check for elements which are consecutive loads.
5335 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5339 // For SSE 4.1, use insertps to put the high elements into the low element.
5340 if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5342 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5343 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5345 Result = DAG.getUNDEF(VT);
5347 for (unsigned i = 1; i < NumElems; ++i) {
5348 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5349 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5350 Op.getOperand(i), DAG.getIntPtrConstant(i));
5355 // Otherwise, expand into a number of unpckl*, start by extending each of
5356 // our (non-undef) elements to the full vector width with the element in the
5357 // bottom slot of the vector (which generates no code for SSE).
5358 for (unsigned i = 0; i < NumElems; ++i) {
5359 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5360 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5362 V[i] = DAG.getUNDEF(VT);
5365 // Next, we iteratively mix elements, e.g. for v4f32:
5366 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5367 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5368 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5369 unsigned EltStride = NumElems >> 1;
5370 while (EltStride != 0) {
5371 for (unsigned i = 0; i < EltStride; ++i) {
5372 // If V[i+EltStride] is undef and this is the first round of mixing,
5373 // then it is safe to just drop this shuffle: V[i] is already in the
5374 // right place, the one element (since it's the first round) being
5375 // inserted as undef can be dropped. This isn't safe for successive
5376 // rounds because they will permute elements within both vectors.
5377 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5378 EltStride == NumElems/2)
5381 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5390 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5391 // them in a MMX register. This is better than doing a stack convert.
5392 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5393 DebugLoc dl = Op.getDebugLoc();
5394 EVT ResVT = Op.getValueType();
5396 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5397 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5399 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5400 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5401 InVec = Op.getOperand(1);
5402 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5403 unsigned NumElts = ResVT.getVectorNumElements();
5404 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5405 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5406 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5408 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5409 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5410 Mask[0] = 0; Mask[1] = 2;
5411 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5413 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5416 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5417 // to create 256-bit vectors from two other 128-bit ones.
5418 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5419 DebugLoc dl = Op.getDebugLoc();
5420 EVT ResVT = Op.getValueType();
5422 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5424 SDValue V1 = Op.getOperand(0);
5425 SDValue V2 = Op.getOperand(1);
5426 unsigned NumElems = ResVT.getVectorNumElements();
5428 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5429 DAG.getConstant(0, MVT::i32), DAG, dl);
5430 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5435 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5436 EVT ResVT = Op.getValueType();
5438 assert(Op.getNumOperands() == 2);
5439 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5440 "Unsupported CONCAT_VECTORS for value type");
5442 // We support concatenate two MMX registers and place them in a MMX register.
5443 // This is better than doing a stack convert.
5444 if (ResVT.is128BitVector())
5445 return LowerMMXCONCAT_VECTORS(Op, DAG);
5447 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5448 // from two other 128-bit ones.
5449 return LowerAVXCONCAT_VECTORS(Op, DAG);
5452 // v8i16 shuffles - Prefer shuffles in the following order:
5453 // 1. [all] pshuflw, pshufhw, optional move
5454 // 2. [ssse3] 1 x pshufb
5455 // 3. [ssse3] 2 x pshufb + 1 x por
5456 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5458 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5459 SelectionDAG &DAG) const {
5460 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5461 SDValue V1 = SVOp->getOperand(0);
5462 SDValue V2 = SVOp->getOperand(1);
5463 DebugLoc dl = SVOp->getDebugLoc();
5464 SmallVector<int, 8> MaskVals;
5466 // Determine if more than 1 of the words in each of the low and high quadwords
5467 // of the result come from the same quadword of one of the two inputs. Undef
5468 // mask values count as coming from any quadword, for better codegen.
5469 unsigned LoQuad[] = { 0, 0, 0, 0 };
5470 unsigned HiQuad[] = { 0, 0, 0, 0 };
5471 BitVector InputQuads(4);
5472 for (unsigned i = 0; i < 8; ++i) {
5473 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5474 int EltIdx = SVOp->getMaskElt(i);
5475 MaskVals.push_back(EltIdx);
5484 InputQuads.set(EltIdx / 4);
5487 int BestLoQuad = -1;
5488 unsigned MaxQuad = 1;
5489 for (unsigned i = 0; i < 4; ++i) {
5490 if (LoQuad[i] > MaxQuad) {
5492 MaxQuad = LoQuad[i];
5496 int BestHiQuad = -1;
5498 for (unsigned i = 0; i < 4; ++i) {
5499 if (HiQuad[i] > MaxQuad) {
5501 MaxQuad = HiQuad[i];
5505 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5506 // of the two input vectors, shuffle them into one input vector so only a
5507 // single pshufb instruction is necessary. If There are more than 2 input
5508 // quads, disable the next transformation since it does not help SSSE3.
5509 bool V1Used = InputQuads[0] || InputQuads[1];
5510 bool V2Used = InputQuads[2] || InputQuads[3];
5511 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5512 if (InputQuads.count() == 2 && V1Used && V2Used) {
5513 BestLoQuad = InputQuads.find_first();
5514 BestHiQuad = InputQuads.find_next(BestLoQuad);
5516 if (InputQuads.count() > 2) {
5522 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5523 // the shuffle mask. If a quad is scored as -1, that means that it contains
5524 // words from all 4 input quadwords.
5526 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5527 SmallVector<int, 8> MaskV;
5528 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5529 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5530 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5531 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5532 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5533 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5535 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5536 // source words for the shuffle, to aid later transformations.
5537 bool AllWordsInNewV = true;
5538 bool InOrder[2] = { true, true };
5539 for (unsigned i = 0; i != 8; ++i) {
5540 int idx = MaskVals[i];
5542 InOrder[i/4] = false;
5543 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5545 AllWordsInNewV = false;
5549 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5550 if (AllWordsInNewV) {
5551 for (int i = 0; i != 8; ++i) {
5552 int idx = MaskVals[i];
5555 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5556 if ((idx != i) && idx < 4)
5558 if ((idx != i) && idx > 3)
5567 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5568 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5569 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5570 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5571 unsigned TargetMask = 0;
5572 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5573 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5574 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5575 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5576 V1 = NewV.getOperand(0);
5577 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5581 // If we have SSSE3, and all words of the result are from 1 input vector,
5582 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5583 // is present, fall back to case 4.
5584 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5585 SmallVector<SDValue,16> pshufbMask;
5587 // If we have elements from both input vectors, set the high bit of the
5588 // shuffle mask element to zero out elements that come from V2 in the V1
5589 // mask, and elements that come from V1 in the V2 mask, so that the two
5590 // results can be OR'd together.
5591 bool TwoInputs = V1Used && V2Used;
5592 for (unsigned i = 0; i != 8; ++i) {
5593 int EltIdx = MaskVals[i] * 2;
5594 if (TwoInputs && (EltIdx >= 16)) {
5595 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5596 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5599 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5600 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5602 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5603 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5604 DAG.getNode(ISD::BUILD_VECTOR, dl,
5605 MVT::v16i8, &pshufbMask[0], 16));
5607 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5609 // Calculate the shuffle mask for the second input, shuffle it, and
5610 // OR it with the first shuffled input.
5612 for (unsigned i = 0; i != 8; ++i) {
5613 int EltIdx = MaskVals[i] * 2;
5615 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5616 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5619 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5620 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5622 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5623 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5624 DAG.getNode(ISD::BUILD_VECTOR, dl,
5625 MVT::v16i8, &pshufbMask[0], 16));
5626 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5627 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5630 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5631 // and update MaskVals with new element order.
5632 BitVector InOrder(8);
5633 if (BestLoQuad >= 0) {
5634 SmallVector<int, 8> MaskV;
5635 for (int i = 0; i != 4; ++i) {
5636 int idx = MaskVals[i];
5638 MaskV.push_back(-1);
5640 } else if ((idx / 4) == BestLoQuad) {
5641 MaskV.push_back(idx & 3);
5644 MaskV.push_back(-1);
5647 for (unsigned i = 4; i != 8; ++i)
5649 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5652 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5653 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5654 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5656 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5660 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5661 // and update MaskVals with the new element order.
5662 if (BestHiQuad >= 0) {
5663 SmallVector<int, 8> MaskV;
5664 for (unsigned i = 0; i != 4; ++i)
5666 for (unsigned i = 4; i != 8; ++i) {
5667 int idx = MaskVals[i];
5669 MaskV.push_back(-1);
5671 } else if ((idx / 4) == BestHiQuad) {
5672 MaskV.push_back((idx & 3) + 4);
5675 MaskV.push_back(-1);
5678 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5681 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5682 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5683 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5685 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5689 // In case BestHi & BestLo were both -1, which means each quadword has a word
5690 // from each of the four input quadwords, calculate the InOrder bitvector now
5691 // before falling through to the insert/extract cleanup.
5692 if (BestLoQuad == -1 && BestHiQuad == -1) {
5694 for (int i = 0; i != 8; ++i)
5695 if (MaskVals[i] < 0 || MaskVals[i] == i)
5699 // The other elements are put in the right place using pextrw and pinsrw.
5700 for (unsigned i = 0; i != 8; ++i) {
5703 int EltIdx = MaskVals[i];
5706 SDValue ExtOp = (EltIdx < 8)
5707 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5708 DAG.getIntPtrConstant(EltIdx))
5709 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5710 DAG.getIntPtrConstant(EltIdx - 8));
5711 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5712 DAG.getIntPtrConstant(i));
5717 // v16i8 shuffles - Prefer shuffles in the following order:
5718 // 1. [ssse3] 1 x pshufb
5719 // 2. [ssse3] 2 x pshufb + 1 x por
5720 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5722 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5724 const X86TargetLowering &TLI) {
5725 SDValue V1 = SVOp->getOperand(0);
5726 SDValue V2 = SVOp->getOperand(1);
5727 DebugLoc dl = SVOp->getDebugLoc();
5728 SmallVector<int, 16> MaskVals;
5729 SVOp->getMask(MaskVals);
5731 // If we have SSSE3, case 1 is generated when all result bytes come from
5732 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5733 // present, fall back to case 3.
5734 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5737 for (unsigned i = 0; i < 16; ++i) {
5738 int EltIdx = MaskVals[i];
5747 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5748 if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5749 SmallVector<SDValue,16> pshufbMask;
5751 // If all result elements are from one input vector, then only translate
5752 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5754 // Otherwise, we have elements from both input vectors, and must zero out
5755 // elements that come from V2 in the first mask, and V1 in the second mask
5756 // so that we can OR them together.
5757 bool TwoInputs = !(V1Only || V2Only);
5758 for (unsigned i = 0; i != 16; ++i) {
5759 int EltIdx = MaskVals[i];
5760 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5761 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5764 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5766 // If all the elements are from V2, assign it to V1 and return after
5767 // building the first pshufb.
5770 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5771 DAG.getNode(ISD::BUILD_VECTOR, dl,
5772 MVT::v16i8, &pshufbMask[0], 16));
5776 // Calculate the shuffle mask for the second input, shuffle it, and
5777 // OR it with the first shuffled input.
5779 for (unsigned i = 0; i != 16; ++i) {
5780 int EltIdx = MaskVals[i];
5782 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5785 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5787 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5788 DAG.getNode(ISD::BUILD_VECTOR, dl,
5789 MVT::v16i8, &pshufbMask[0], 16));
5790 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5793 // No SSSE3 - Calculate in place words and then fix all out of place words
5794 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5795 // the 16 different words that comprise the two doublequadword input vectors.
5796 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5797 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5798 SDValue NewV = V2Only ? V2 : V1;
5799 for (int i = 0; i != 8; ++i) {
5800 int Elt0 = MaskVals[i*2];
5801 int Elt1 = MaskVals[i*2+1];
5803 // This word of the result is all undef, skip it.
5804 if (Elt0 < 0 && Elt1 < 0)
5807 // This word of the result is already in the correct place, skip it.
5808 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5810 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5813 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5814 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5817 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5818 // using a single extract together, load it and store it.
5819 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5820 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5821 DAG.getIntPtrConstant(Elt1 / 2));
5822 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5823 DAG.getIntPtrConstant(i));
5827 // If Elt1 is defined, extract it from the appropriate source. If the
5828 // source byte is not also odd, shift the extracted word left 8 bits
5829 // otherwise clear the bottom 8 bits if we need to do an or.
5831 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5832 DAG.getIntPtrConstant(Elt1 / 2));
5833 if ((Elt1 & 1) == 0)
5834 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5836 TLI.getShiftAmountTy(InsElt.getValueType())));
5838 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5839 DAG.getConstant(0xFF00, MVT::i16));
5841 // If Elt0 is defined, extract it from the appropriate source. If the
5842 // source byte is not also even, shift the extracted word right 8 bits. If
5843 // Elt1 was also defined, OR the extracted values together before
5844 // inserting them in the result.
5846 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5847 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5848 if ((Elt0 & 1) != 0)
5849 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5851 TLI.getShiftAmountTy(InsElt0.getValueType())));
5853 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5854 DAG.getConstant(0x00FF, MVT::i16));
5855 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5858 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5859 DAG.getIntPtrConstant(i));
5861 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5864 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5865 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5866 /// done when every pair / quad of shuffle mask elements point to elements in
5867 /// the right sequence. e.g.
5868 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5870 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5871 SelectionDAG &DAG, DebugLoc dl) {
5872 EVT VT = SVOp->getValueType(0);
5873 SDValue V1 = SVOp->getOperand(0);
5874 SDValue V2 = SVOp->getOperand(1);
5875 unsigned NumElems = VT.getVectorNumElements();
5876 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5878 switch (VT.getSimpleVT().SimpleTy) {
5879 default: assert(false && "Unexpected!");
5880 case MVT::v4f32: NewVT = MVT::v2f64; break;
5881 case MVT::v4i32: NewVT = MVT::v2i64; break;
5882 case MVT::v8i16: NewVT = MVT::v4i32; break;
5883 case MVT::v16i8: NewVT = MVT::v4i32; break;
5886 int Scale = NumElems / NewWidth;
5887 SmallVector<int, 8> MaskVec;
5888 for (unsigned i = 0; i < NumElems; i += Scale) {
5890 for (int j = 0; j < Scale; ++j) {
5891 int EltIdx = SVOp->getMaskElt(i+j);
5895 StartIdx = EltIdx - (EltIdx % Scale);
5896 if (EltIdx != StartIdx + j)
5900 MaskVec.push_back(-1);
5902 MaskVec.push_back(StartIdx / Scale);
5905 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5906 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5907 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5910 /// getVZextMovL - Return a zero-extending vector move low node.
5912 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5913 SDValue SrcOp, SelectionDAG &DAG,
5914 const X86Subtarget *Subtarget, DebugLoc dl) {
5915 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5916 LoadSDNode *LD = NULL;
5917 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5918 LD = dyn_cast<LoadSDNode>(SrcOp);
5920 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5922 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5923 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5924 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5925 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5926 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5928 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5929 return DAG.getNode(ISD::BITCAST, dl, VT,
5930 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5931 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5939 return DAG.getNode(ISD::BITCAST, dl, VT,
5940 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5941 DAG.getNode(ISD::BITCAST, dl,
5945 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5946 /// shuffle node referes to only one lane in the sources.
5947 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5948 EVT VT = SVOp->getValueType(0);
5949 int NumElems = VT.getVectorNumElements();
5950 int HalfSize = NumElems/2;
5951 SmallVector<int, 16> M;
5953 bool MatchA = false, MatchB = false;
5955 for (int l = 0; l < NumElems*2; l += HalfSize) {
5956 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5962 for (int l = 0; l < NumElems*2; l += HalfSize) {
5963 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5969 return MatchA && MatchB;
5972 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5973 /// which could not be matched by any known target speficic shuffle
5975 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5976 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5977 // If each half of a vector shuffle node referes to only one lane in the
5978 // source vectors, extract each used 128-bit lane and shuffle them using
5979 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5980 // the work to the legalizer.
5981 DebugLoc dl = SVOp->getDebugLoc();
5982 EVT VT = SVOp->getValueType(0);
5983 int NumElems = VT.getVectorNumElements();
5984 int HalfSize = NumElems/2;
5986 // Extract the reference for each half
5987 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5988 int FstVecOpNum = 0, SndVecOpNum = 0;
5989 for (int i = 0; i < HalfSize; ++i) {
5990 int Elt = SVOp->getMaskElt(i);
5991 if (SVOp->getMaskElt(i) < 0)
5993 FstVecOpNum = Elt/NumElems;
5994 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5997 for (int i = HalfSize; i < NumElems; ++i) {
5998 int Elt = SVOp->getMaskElt(i);
5999 if (SVOp->getMaskElt(i) < 0)
6001 SndVecOpNum = Elt/NumElems;
6002 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6006 // Extract the subvectors
6007 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6008 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6009 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6010 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6012 // Generate 128-bit shuffles
6013 SmallVector<int, 16> MaskV1, MaskV2;
6014 for (int i = 0; i < HalfSize; ++i) {
6015 int Elt = SVOp->getMaskElt(i);
6016 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6018 for (int i = HalfSize; i < NumElems; ++i) {
6019 int Elt = SVOp->getMaskElt(i);
6020 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6023 EVT NVT = V1.getValueType();
6024 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6025 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6027 // Concatenate the result back
6028 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6029 DAG.getConstant(0, MVT::i32), DAG, dl);
6030 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6037 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6038 /// 4 elements, and match them with several different shuffle types.
6040 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6041 SDValue V1 = SVOp->getOperand(0);
6042 SDValue V2 = SVOp->getOperand(1);
6043 DebugLoc dl = SVOp->getDebugLoc();
6044 EVT VT = SVOp->getValueType(0);
6046 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6048 SmallVector<std::pair<int, int>, 8> Locs;
6050 SmallVector<int, 8> Mask1(4U, -1);
6051 SmallVector<int, 8> PermMask;
6052 SVOp->getMask(PermMask);
6056 for (unsigned i = 0; i != 4; ++i) {
6057 int Idx = PermMask[i];
6059 Locs[i] = std::make_pair(-1, -1);
6061 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6063 Locs[i] = std::make_pair(0, NumLo);
6067 Locs[i] = std::make_pair(1, NumHi);
6069 Mask1[2+NumHi] = Idx;
6075 if (NumLo <= 2 && NumHi <= 2) {
6076 // If no more than two elements come from either vector. This can be
6077 // implemented with two shuffles. First shuffle gather the elements.
6078 // The second shuffle, which takes the first shuffle as both of its
6079 // vector operands, put the elements into the right order.
6080 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6082 SmallVector<int, 8> Mask2(4U, -1);
6084 for (unsigned i = 0; i != 4; ++i) {
6085 if (Locs[i].first == -1)
6088 unsigned Idx = (i < 2) ? 0 : 4;
6089 Idx += Locs[i].first * 2 + Locs[i].second;
6094 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6095 } else if (NumLo == 3 || NumHi == 3) {
6096 // Otherwise, we must have three elements from one vector, call it X, and
6097 // one element from the other, call it Y. First, use a shufps to build an
6098 // intermediate vector with the one element from Y and the element from X
6099 // that will be in the same half in the final destination (the indexes don't
6100 // matter). Then, use a shufps to build the final vector, taking the half
6101 // containing the element from Y from the intermediate, and the other half
6104 // Normalize it so the 3 elements come from V1.
6105 CommuteVectorShuffleMask(PermMask, VT);
6109 // Find the element from V2.
6111 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6112 int Val = PermMask[HiIndex];
6119 Mask1[0] = PermMask[HiIndex];
6121 Mask1[2] = PermMask[HiIndex^1];
6123 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6126 Mask1[0] = PermMask[0];
6127 Mask1[1] = PermMask[1];
6128 Mask1[2] = HiIndex & 1 ? 6 : 4;
6129 Mask1[3] = HiIndex & 1 ? 4 : 6;
6130 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6132 Mask1[0] = HiIndex & 1 ? 2 : 0;
6133 Mask1[1] = HiIndex & 1 ? 0 : 2;
6134 Mask1[2] = PermMask[2];
6135 Mask1[3] = PermMask[3];
6140 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6144 // Break it into (shuffle shuffle_hi, shuffle_lo).
6147 SmallVector<int,8> LoMask(4U, -1);
6148 SmallVector<int,8> HiMask(4U, -1);
6150 SmallVector<int,8> *MaskPtr = &LoMask;
6151 unsigned MaskIdx = 0;
6154 for (unsigned i = 0; i != 4; ++i) {
6161 int Idx = PermMask[i];
6163 Locs[i] = std::make_pair(-1, -1);
6164 } else if (Idx < 4) {
6165 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6166 (*MaskPtr)[LoIdx] = Idx;
6169 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6170 (*MaskPtr)[HiIdx] = Idx;
6175 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6176 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6177 SmallVector<int, 8> MaskOps;
6178 for (unsigned i = 0; i != 4; ++i) {
6179 if (Locs[i].first == -1) {
6180 MaskOps.push_back(-1);
6182 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6183 MaskOps.push_back(Idx);
6186 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6189 static bool MayFoldVectorLoad(SDValue V) {
6190 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6191 V = V.getOperand(0);
6192 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6193 V = V.getOperand(0);
6194 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6195 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6196 // BUILD_VECTOR (load), undef
6197 V = V.getOperand(0);
6203 // FIXME: the version above should always be used. Since there's
6204 // a bug where several vector shuffles can't be folded because the
6205 // DAG is not updated during lowering and a node claims to have two
6206 // uses while it only has one, use this version, and let isel match
6207 // another instruction if the load really happens to have more than
6208 // one use. Remove this version after this bug get fixed.
6209 // rdar://8434668, PR8156
6210 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6211 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6212 V = V.getOperand(0);
6213 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6214 V = V.getOperand(0);
6215 if (ISD::isNormalLoad(V.getNode()))
6220 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6221 /// a vector extract, and if both can be later optimized into a single load.
6222 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6223 /// here because otherwise a target specific shuffle node is going to be
6224 /// emitted for this shuffle, and the optimization not done.
6225 /// FIXME: This is probably not the best approach, but fix the problem
6226 /// until the right path is decided.
6228 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6229 const TargetLowering &TLI) {
6230 EVT VT = V.getValueType();
6231 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6233 // Be sure that the vector shuffle is present in a pattern like this:
6234 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6238 SDNode *N = *V.getNode()->use_begin();
6239 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6242 SDValue EltNo = N->getOperand(1);
6243 if (!isa<ConstantSDNode>(EltNo))
6246 // If the bit convert changed the number of elements, it is unsafe
6247 // to examine the mask.
6248 bool HasShuffleIntoBitcast = false;
6249 if (V.getOpcode() == ISD::BITCAST) {
6250 EVT SrcVT = V.getOperand(0).getValueType();
6251 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6253 V = V.getOperand(0);
6254 HasShuffleIntoBitcast = true;
6257 // Select the input vector, guarding against out of range extract vector.
6258 unsigned NumElems = VT.getVectorNumElements();
6259 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6260 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6261 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6263 // Skip one more bit_convert if necessary
6264 if (V.getOpcode() == ISD::BITCAST)
6265 V = V.getOperand(0);
6267 if (ISD::isNormalLoad(V.getNode())) {
6268 // Is the original load suitable?
6269 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6271 // FIXME: avoid the multi-use bug that is preventing lots of
6272 // of foldings to be detected, this is still wrong of course, but
6273 // give the temporary desired behavior, and if it happens that
6274 // the load has real more uses, during isel it will not fold, and
6275 // will generate poor code.
6276 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6279 if (!HasShuffleIntoBitcast)
6282 // If there's a bitcast before the shuffle, check if the load type and
6283 // alignment is valid.
6284 unsigned Align = LN0->getAlignment();
6286 TLI.getTargetData()->getABITypeAlignment(
6287 VT.getTypeForEVT(*DAG.getContext()));
6289 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6297 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6298 EVT VT = Op.getValueType();
6300 // Canonizalize to v2f64.
6301 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6302 return DAG.getNode(ISD::BITCAST, dl, VT,
6303 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6308 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6310 SDValue V1 = Op.getOperand(0);
6311 SDValue V2 = Op.getOperand(1);
6312 EVT VT = Op.getValueType();
6314 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6316 if (HasXMMInt && VT == MVT::v2f64)
6317 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6319 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6320 return DAG.getNode(ISD::BITCAST, dl, VT,
6321 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6322 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6323 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6327 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6328 SDValue V1 = Op.getOperand(0);
6329 SDValue V2 = Op.getOperand(1);
6330 EVT VT = Op.getValueType();
6332 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6333 "unsupported shuffle type");
6335 if (V2.getOpcode() == ISD::UNDEF)
6339 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6342 static inline unsigned getSHUFPOpcode(EVT VT) {
6343 switch(VT.getSimpleVT().SimpleTy) {
6344 case MVT::v8i32: // Use fp unit for int unpack.
6346 case MVT::v4i32: // Use fp unit for int unpack.
6347 case MVT::v4f32: return X86ISD::SHUFPS;
6348 case MVT::v4i64: // Use fp unit for int unpack.
6350 case MVT::v2i64: // Use fp unit for int unpack.
6351 case MVT::v2f64: return X86ISD::SHUFPD;
6353 llvm_unreachable("Unknown type for shufp*");
6359 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6360 SDValue V1 = Op.getOperand(0);
6361 SDValue V2 = Op.getOperand(1);
6362 EVT VT = Op.getValueType();
6363 unsigned NumElems = VT.getVectorNumElements();
6365 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6366 // operand of these instructions is only memory, so check if there's a
6367 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6369 bool CanFoldLoad = false;
6371 // Trivial case, when V2 comes from a load.
6372 if (MayFoldVectorLoad(V2))
6375 // When V1 is a load, it can be folded later into a store in isel, example:
6376 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6378 // (MOVLPSmr addr:$src1, VR128:$src2)
6379 // So, recognize this potential and also use MOVLPS or MOVLPD
6380 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6383 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6385 if (HasXMMInt && NumElems == 2)
6386 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6389 // If we don't care about the second element, procede to use movss.
6390 if (SVOp->getMaskElt(1) != -1)
6391 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6394 // movl and movlp will both match v2i64, but v2i64 is never matched by
6395 // movl earlier because we make it strict to avoid messing with the movlp load
6396 // folding logic (see the code above getMOVLP call). Match it here then,
6397 // this is horrible, but will stay like this until we move all shuffle
6398 // matching to x86 specific nodes. Note that for the 1st condition all
6399 // types are matched with movsd.
6401 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6402 // as to remove this logic from here, as much as possible
6403 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6404 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6405 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6408 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6410 // Invert the operand order and use SHUFPS to match it.
6411 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6412 X86::getShuffleSHUFImmediate(SVOp), DAG);
6415 static inline unsigned getUNPCKLOpcode(EVT VT) {
6416 switch(VT.getSimpleVT().SimpleTy) {
6417 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6418 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6419 case MVT::v4f32: return X86ISD::UNPCKLPS;
6420 case MVT::v2f64: return X86ISD::UNPCKLPD;
6421 case MVT::v8i32: // Use fp unit for int unpack.
6422 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6423 case MVT::v4i64: // Use fp unit for int unpack.
6424 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6425 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6426 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6428 llvm_unreachable("Unknown type for unpckl");
6433 static inline unsigned getUNPCKHOpcode(EVT VT) {
6434 switch(VT.getSimpleVT().SimpleTy) {
6435 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6436 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6437 case MVT::v4f32: return X86ISD::UNPCKHPS;
6438 case MVT::v2f64: return X86ISD::UNPCKHPD;
6439 case MVT::v8i32: // Use fp unit for int unpack.
6440 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6441 case MVT::v4i64: // Use fp unit for int unpack.
6442 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6443 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6444 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6446 llvm_unreachable("Unknown type for unpckh");
6451 static inline unsigned getVPERMILOpcode(EVT VT) {
6452 switch(VT.getSimpleVT().SimpleTy) {
6454 case MVT::v4f32: return X86ISD::VPERMILPS;
6456 case MVT::v2f64: return X86ISD::VPERMILPD;
6458 case MVT::v8f32: return X86ISD::VPERMILPSY;
6460 case MVT::v4f64: return X86ISD::VPERMILPDY;
6462 llvm_unreachable("Unknown type for vpermil");
6467 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6468 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6469 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6470 static bool isVectorBroadcast(SDValue &Op) {
6471 EVT VT = Op.getValueType();
6472 bool Is256 = VT.getSizeInBits() == 256;
6474 assert((VT.getSizeInBits() == 128 || Is256) &&
6475 "Unsupported type for vbroadcast node");
6478 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6479 V = V.getOperand(0);
6481 if (Is256 && !(V.hasOneUse() &&
6482 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6483 V.getOperand(0).getOpcode() == ISD::UNDEF))
6487 V = V.getOperand(1);
6492 // Check the source scalar_to_vector type. 256-bit broadcasts are
6493 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6494 // for 32-bit scalars.
6495 if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6498 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6499 if (ScalarSize != 32 && ScalarSize != 64)
6501 if (!Is256 && ScalarSize == 64)
6504 V = V.getOperand(0);
6505 if (!MayFoldLoad(V))
6508 // Return the load node
6514 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6515 const TargetLowering &TLI,
6516 const X86Subtarget *Subtarget) {
6517 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6518 EVT VT = Op.getValueType();
6519 DebugLoc dl = Op.getDebugLoc();
6520 SDValue V1 = Op.getOperand(0);
6521 SDValue V2 = Op.getOperand(1);
6523 if (isZeroShuffle(SVOp))
6524 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6526 // Handle splat operations
6527 if (SVOp->isSplat()) {
6528 unsigned NumElem = VT.getVectorNumElements();
6529 int Size = VT.getSizeInBits();
6530 // Special case, this is the only place now where it's allowed to return
6531 // a vector_shuffle operation without using a target specific node, because
6532 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6533 // this be moved to DAGCombine instead?
6534 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6537 // Use vbroadcast whenever the splat comes from a foldable load
6538 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6539 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6541 // Handle splats by matching through known shuffle masks
6542 if ((Size == 128 && NumElem <= 4) ||
6543 (Size == 256 && NumElem < 8))
6546 // All remaning splats are promoted to target supported vector shuffles.
6547 return PromoteSplat(SVOp, DAG);
6550 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6552 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6553 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6554 if (NewOp.getNode())
6555 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6556 } else if ((VT == MVT::v4i32 ||
6557 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6558 // FIXME: Figure out a cleaner way to do this.
6559 // Try to make use of movq to zero out the top part.
6560 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6561 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6562 if (NewOp.getNode()) {
6563 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6564 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6565 DAG, Subtarget, dl);
6567 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6568 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6569 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6570 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6571 DAG, Subtarget, dl);
6578 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6579 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6580 SDValue V1 = Op.getOperand(0);
6581 SDValue V2 = Op.getOperand(1);
6582 EVT VT = Op.getValueType();
6583 DebugLoc dl = Op.getDebugLoc();
6584 unsigned NumElems = VT.getVectorNumElements();
6585 bool isMMX = VT.getSizeInBits() == 64;
6586 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6587 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6588 bool V1IsSplat = false;
6589 bool V2IsSplat = false;
6590 bool HasXMMInt = Subtarget->hasXMMInt();
6591 MachineFunction &MF = DAG.getMachineFunction();
6592 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6594 // Shuffle operations on MMX not supported.
6598 // Vector shuffle lowering takes 3 steps:
6600 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6601 // narrowing and commutation of operands should be handled.
6602 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6604 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6605 // so the shuffle can be broken into other shuffles and the legalizer can
6606 // try the lowering again.
6608 // The general ideia is that no vector_shuffle operation should be left to
6609 // be matched during isel, all of them must be converted to a target specific
6612 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6613 // narrowing and commutation of operands should be handled. The actual code
6614 // doesn't include all of those, work in progress...
6615 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6616 if (NewOp.getNode())
6619 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6620 // unpckh_undef). Only use pshufd if speed is more important than size.
6621 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6622 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6623 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6624 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6626 if (X86::isMOVDDUPMask(SVOp) &&
6627 (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6628 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6629 return getMOVDDup(Op, dl, V1, DAG);
6631 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6632 return getMOVHighToLow(Op, dl, DAG);
6634 // Use to match splats
6635 if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6636 (VT == MVT::v2f64 || VT == MVT::v2i64))
6637 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6639 if (X86::isPSHUFDMask(SVOp)) {
6640 // The actual implementation will match the mask in the if above and then
6641 // during isel it can match several different instructions, not only pshufd
6642 // as its name says, sad but true, emulate the behavior for now...
6643 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6644 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6646 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6648 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6649 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6651 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6655 // Check if this can be converted into a logical shift.
6656 bool isLeft = false;
6659 bool isShift = getSubtarget()->hasXMMInt() &&
6660 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6661 if (isShift && ShVal.hasOneUse()) {
6662 // If the shifted value has multiple uses, it may be cheaper to use
6663 // v_set0 + movlhps or movhlps, etc.
6664 EVT EltVT = VT.getVectorElementType();
6665 ShAmt *= EltVT.getSizeInBits();
6666 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6669 if (X86::isMOVLMask(SVOp)) {
6672 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6673 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6674 if (!X86::isMOVLPMask(SVOp)) {
6675 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6676 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6678 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6679 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6683 // FIXME: fold these into legal mask.
6684 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6685 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6687 if (X86::isMOVHLPSMask(SVOp))
6688 return getMOVHighToLow(Op, dl, DAG);
6690 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6691 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6693 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6694 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6696 if (X86::isMOVLPMask(SVOp))
6697 return getMOVLP(Op, dl, DAG, HasXMMInt);
6699 if (ShouldXformToMOVHLPS(SVOp) ||
6700 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6701 return CommuteVectorShuffle(SVOp, DAG);
6704 // No better options. Use a vshl / vsrl.
6705 EVT EltVT = VT.getVectorElementType();
6706 ShAmt *= EltVT.getSizeInBits();
6707 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6710 bool Commuted = false;
6711 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6712 // 1,1,1,1 -> v8i16 though.
6713 V1IsSplat = isSplatVector(V1.getNode());
6714 V2IsSplat = isSplatVector(V2.getNode());
6716 // Canonicalize the splat or undef, if present, to be on the RHS.
6717 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6718 Op = CommuteVectorShuffle(SVOp, DAG);
6719 SVOp = cast<ShuffleVectorSDNode>(Op);
6720 V1 = SVOp->getOperand(0);
6721 V2 = SVOp->getOperand(1);
6722 std::swap(V1IsSplat, V2IsSplat);
6723 std::swap(V1IsUndef, V2IsUndef);
6727 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6728 // Shuffling low element of v1 into undef, just return v1.
6731 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6732 // the instruction selector will not match, so get a canonical MOVL with
6733 // swapped operands to undo the commute.
6734 return getMOVL(DAG, dl, VT, V2, V1);
6737 if (X86::isUNPCKLMask(SVOp))
6738 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6740 if (X86::isUNPCKHMask(SVOp))
6741 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6744 // Normalize mask so all entries that point to V2 points to its first
6745 // element then try to match unpck{h|l} again. If match, return a
6746 // new vector_shuffle with the corrected mask.
6747 SDValue NewMask = NormalizeMask(SVOp, DAG);
6748 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6749 if (NSVOp != SVOp) {
6750 if (X86::isUNPCKLMask(NSVOp, true)) {
6752 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6759 // Commute is back and try unpck* again.
6760 // FIXME: this seems wrong.
6761 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6762 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6764 if (X86::isUNPCKLMask(NewSVOp))
6765 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6767 if (X86::isUNPCKHMask(NewSVOp))
6768 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6771 // Normalize the node to match x86 shuffle ops if needed
6772 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6773 return CommuteVectorShuffle(SVOp, DAG);
6775 // The checks below are all present in isShuffleMaskLegal, but they are
6776 // inlined here right now to enable us to directly emit target specific
6777 // nodes, and remove one by one until they don't return Op anymore.
6778 SmallVector<int, 16> M;
6781 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6782 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6783 X86::getShufflePALIGNRImmediate(SVOp),
6786 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6787 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6788 if (VT == MVT::v2f64)
6789 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6790 if (VT == MVT::v2i64)
6791 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6794 if (isPSHUFHWMask(M, VT))
6795 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6796 X86::getShufflePSHUFHWImmediate(SVOp),
6799 if (isPSHUFLWMask(M, VT))
6800 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6801 X86::getShufflePSHUFLWImmediate(SVOp),
6804 if (isSHUFPMask(M, VT))
6805 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6806 X86::getShuffleSHUFImmediate(SVOp), DAG);
6808 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6809 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6810 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6811 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6813 //===--------------------------------------------------------------------===//
6814 // Generate target specific nodes for 128 or 256-bit shuffles only
6815 // supported in the AVX instruction set.
6818 // Handle VMOVDDUPY permutations
6819 if (isMOVDDUPYMask(SVOp, Subtarget))
6820 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6822 // Handle VPERMILPS* permutations
6823 if (isVPERMILPSMask(M, VT, Subtarget))
6824 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6825 getShuffleVPERMILPSImmediate(SVOp), DAG);
6827 // Handle VPERMILPD* permutations
6828 if (isVPERMILPDMask(M, VT, Subtarget))
6829 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6830 getShuffleVPERMILPDImmediate(SVOp), DAG);
6832 // Handle VPERM2F128 permutations
6833 if (isVPERM2F128Mask(M, VT, Subtarget))
6834 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6835 getShuffleVPERM2F128Immediate(SVOp), DAG);
6837 // Handle VSHUFPSY permutations
6838 if (isVSHUFPSYMask(M, VT, Subtarget))
6839 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6840 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6842 // Handle VSHUFPDY permutations
6843 if (isVSHUFPDYMask(M, VT, Subtarget))
6844 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6845 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6847 //===--------------------------------------------------------------------===//
6848 // Since no target specific shuffle was selected for this generic one,
6849 // lower it into other known shuffles. FIXME: this isn't true yet, but
6850 // this is the plan.
6853 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6854 if (VT == MVT::v8i16) {
6855 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6856 if (NewOp.getNode())
6860 if (VT == MVT::v16i8) {
6861 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6862 if (NewOp.getNode())
6866 // Handle all 128-bit wide vectors with 4 elements, and match them with
6867 // several different shuffle types.
6868 if (NumElems == 4 && VT.getSizeInBits() == 128)
6869 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6871 // Handle general 256-bit shuffles
6872 if (VT.is256BitVector())
6873 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6879 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6880 SelectionDAG &DAG) const {
6881 EVT VT = Op.getValueType();
6882 DebugLoc dl = Op.getDebugLoc();
6884 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6887 if (VT.getSizeInBits() == 8) {
6888 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6889 Op.getOperand(0), Op.getOperand(1));
6890 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6891 DAG.getValueType(VT));
6892 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6893 } else if (VT.getSizeInBits() == 16) {
6894 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6895 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6897 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6898 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6899 DAG.getNode(ISD::BITCAST, dl,
6903 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6904 Op.getOperand(0), Op.getOperand(1));
6905 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6906 DAG.getValueType(VT));
6907 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6908 } else if (VT == MVT::f32) {
6909 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6910 // the result back to FR32 register. It's only worth matching if the
6911 // result has a single use which is a store or a bitcast to i32. And in
6912 // the case of a store, it's not worth it if the index is a constant 0,
6913 // because a MOVSSmr can be used instead, which is smaller and faster.
6914 if (!Op.hasOneUse())
6916 SDNode *User = *Op.getNode()->use_begin();
6917 if ((User->getOpcode() != ISD::STORE ||
6918 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6919 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6920 (User->getOpcode() != ISD::BITCAST ||
6921 User->getValueType(0) != MVT::i32))
6923 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6924 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6927 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6928 } else if (VT == MVT::i32) {
6929 // ExtractPS works with constant index.
6930 if (isa<ConstantSDNode>(Op.getOperand(1)))
6938 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6939 SelectionDAG &DAG) const {
6940 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6943 SDValue Vec = Op.getOperand(0);
6944 EVT VecVT = Vec.getValueType();
6946 // If this is a 256-bit vector result, first extract the 128-bit vector and
6947 // then extract the element from the 128-bit vector.
6948 if (VecVT.getSizeInBits() == 256) {
6949 DebugLoc dl = Op.getNode()->getDebugLoc();
6950 unsigned NumElems = VecVT.getVectorNumElements();
6951 SDValue Idx = Op.getOperand(1);
6952 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6954 // Get the 128-bit vector.
6955 bool Upper = IdxVal >= NumElems/2;
6956 Vec = Extract128BitVector(Vec,
6957 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6959 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6960 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6963 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6965 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6966 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6971 EVT VT = Op.getValueType();
6972 DebugLoc dl = Op.getDebugLoc();
6973 // TODO: handle v16i8.
6974 if (VT.getSizeInBits() == 16) {
6975 SDValue Vec = Op.getOperand(0);
6976 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6978 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6979 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6980 DAG.getNode(ISD::BITCAST, dl,
6983 // Transform it so it match pextrw which produces a 32-bit result.
6984 EVT EltVT = MVT::i32;
6985 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6986 Op.getOperand(0), Op.getOperand(1));
6987 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6988 DAG.getValueType(VT));
6989 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6990 } else if (VT.getSizeInBits() == 32) {
6991 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6995 // SHUFPS the element to the lowest double word, then movss.
6996 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6997 EVT VVT = Op.getOperand(0).getValueType();
6998 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6999 DAG.getUNDEF(VVT), Mask);
7000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7001 DAG.getIntPtrConstant(0));
7002 } else if (VT.getSizeInBits() == 64) {
7003 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7004 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7005 // to match extract_elt for f64.
7006 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7010 // UNPCKHPD the element to the lowest double word, then movsd.
7011 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7012 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7013 int Mask[2] = { 1, -1 };
7014 EVT VVT = Op.getOperand(0).getValueType();
7015 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7016 DAG.getUNDEF(VVT), Mask);
7017 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7018 DAG.getIntPtrConstant(0));
7025 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7026 SelectionDAG &DAG) const {
7027 EVT VT = Op.getValueType();
7028 EVT EltVT = VT.getVectorElementType();
7029 DebugLoc dl = Op.getDebugLoc();
7031 SDValue N0 = Op.getOperand(0);
7032 SDValue N1 = Op.getOperand(1);
7033 SDValue N2 = Op.getOperand(2);
7035 if (VT.getSizeInBits() == 256)
7038 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7039 isa<ConstantSDNode>(N2)) {
7041 if (VT == MVT::v8i16)
7042 Opc = X86ISD::PINSRW;
7043 else if (VT == MVT::v16i8)
7044 Opc = X86ISD::PINSRB;
7046 Opc = X86ISD::PINSRB;
7048 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7050 if (N1.getValueType() != MVT::i32)
7051 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7052 if (N2.getValueType() != MVT::i32)
7053 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7054 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7055 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7056 // Bits [7:6] of the constant are the source select. This will always be
7057 // zero here. The DAG Combiner may combine an extract_elt index into these
7058 // bits. For example (insert (extract, 3), 2) could be matched by putting
7059 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7060 // Bits [5:4] of the constant are the destination select. This is the
7061 // value of the incoming immediate.
7062 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7063 // combine either bitwise AND or insert of float 0.0 to set these bits.
7064 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7065 // Create this as a scalar to vector..
7066 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7067 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7068 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7069 // PINSR* works with constant index.
7076 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7077 EVT VT = Op.getValueType();
7078 EVT EltVT = VT.getVectorElementType();
7080 DebugLoc dl = Op.getDebugLoc();
7081 SDValue N0 = Op.getOperand(0);
7082 SDValue N1 = Op.getOperand(1);
7083 SDValue N2 = Op.getOperand(2);
7085 // If this is a 256-bit vector result, first extract the 128-bit vector,
7086 // insert the element into the extracted half and then place it back.
7087 if (VT.getSizeInBits() == 256) {
7088 if (!isa<ConstantSDNode>(N2))
7091 // Get the desired 128-bit vector half.
7092 unsigned NumElems = VT.getVectorNumElements();
7093 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7094 bool Upper = IdxVal >= NumElems/2;
7095 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7096 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7098 // Insert the element into the desired half.
7099 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7100 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7102 // Insert the changed part back to the 256-bit vector
7103 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7106 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7107 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7109 if (EltVT == MVT::i8)
7112 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7113 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7114 // as its second argument.
7115 if (N1.getValueType() != MVT::i32)
7116 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7117 if (N2.getValueType() != MVT::i32)
7118 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7119 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7125 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7126 LLVMContext *Context = DAG.getContext();
7127 DebugLoc dl = Op.getDebugLoc();
7128 EVT OpVT = Op.getValueType();
7130 // If this is a 256-bit vector result, first insert into a 128-bit
7131 // vector and then insert into the 256-bit vector.
7132 if (OpVT.getSizeInBits() > 128) {
7133 // Insert into a 128-bit vector.
7134 EVT VT128 = EVT::getVectorVT(*Context,
7135 OpVT.getVectorElementType(),
7136 OpVT.getVectorNumElements() / 2);
7138 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7140 // Insert the 128-bit vector.
7141 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7142 DAG.getConstant(0, MVT::i32),
7146 if (Op.getValueType() == MVT::v1i64 &&
7147 Op.getOperand(0).getValueType() == MVT::i64)
7148 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7150 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7151 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7152 "Expected an SSE type!");
7153 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7154 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7157 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7158 // a simple subregister reference or explicit instructions to grab
7159 // upper bits of a vector.
7161 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7162 if (Subtarget->hasAVX()) {
7163 DebugLoc dl = Op.getNode()->getDebugLoc();
7164 SDValue Vec = Op.getNode()->getOperand(0);
7165 SDValue Idx = Op.getNode()->getOperand(1);
7167 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7168 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7169 return Extract128BitVector(Vec, Idx, DAG, dl);
7175 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7176 // simple superregister reference or explicit instructions to insert
7177 // the upper bits of a vector.
7179 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7180 if (Subtarget->hasAVX()) {
7181 DebugLoc dl = Op.getNode()->getDebugLoc();
7182 SDValue Vec = Op.getNode()->getOperand(0);
7183 SDValue SubVec = Op.getNode()->getOperand(1);
7184 SDValue Idx = Op.getNode()->getOperand(2);
7186 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7187 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7188 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7194 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7195 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7196 // one of the above mentioned nodes. It has to be wrapped because otherwise
7197 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7198 // be used to form addressing mode. These wrapped nodes will be selected
7201 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7202 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7204 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7206 unsigned char OpFlag = 0;
7207 unsigned WrapperKind = X86ISD::Wrapper;
7208 CodeModel::Model M = getTargetMachine().getCodeModel();
7210 if (Subtarget->isPICStyleRIPRel() &&
7211 (M == CodeModel::Small || M == CodeModel::Kernel))
7212 WrapperKind = X86ISD::WrapperRIP;
7213 else if (Subtarget->isPICStyleGOT())
7214 OpFlag = X86II::MO_GOTOFF;
7215 else if (Subtarget->isPICStyleStubPIC())
7216 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7218 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7220 CP->getOffset(), OpFlag);
7221 DebugLoc DL = CP->getDebugLoc();
7222 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7223 // With PIC, the address is actually $g + Offset.
7225 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7226 DAG.getNode(X86ISD::GlobalBaseReg,
7227 DebugLoc(), getPointerTy()),
7234 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7235 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7237 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7239 unsigned char OpFlag = 0;
7240 unsigned WrapperKind = X86ISD::Wrapper;
7241 CodeModel::Model M = getTargetMachine().getCodeModel();
7243 if (Subtarget->isPICStyleRIPRel() &&
7244 (M == CodeModel::Small || M == CodeModel::Kernel))
7245 WrapperKind = X86ISD::WrapperRIP;
7246 else if (Subtarget->isPICStyleGOT())
7247 OpFlag = X86II::MO_GOTOFF;
7248 else if (Subtarget->isPICStyleStubPIC())
7249 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7251 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7253 DebugLoc DL = JT->getDebugLoc();
7254 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7256 // With PIC, the address is actually $g + Offset.
7258 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7259 DAG.getNode(X86ISD::GlobalBaseReg,
7260 DebugLoc(), getPointerTy()),
7267 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7268 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7270 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7272 unsigned char OpFlag = 0;
7273 unsigned WrapperKind = X86ISD::Wrapper;
7274 CodeModel::Model M = getTargetMachine().getCodeModel();
7276 if (Subtarget->isPICStyleRIPRel() &&
7277 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7278 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7279 OpFlag = X86II::MO_GOTPCREL;
7280 WrapperKind = X86ISD::WrapperRIP;
7281 } else if (Subtarget->isPICStyleGOT()) {
7282 OpFlag = X86II::MO_GOT;
7283 } else if (Subtarget->isPICStyleStubPIC()) {
7284 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7285 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7286 OpFlag = X86II::MO_DARWIN_NONLAZY;
7289 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7291 DebugLoc DL = Op.getDebugLoc();
7292 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7295 // With PIC, the address is actually $g + Offset.
7296 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7297 !Subtarget->is64Bit()) {
7298 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7299 DAG.getNode(X86ISD::GlobalBaseReg,
7300 DebugLoc(), getPointerTy()),
7304 // For symbols that require a load from a stub to get the address, emit the
7306 if (isGlobalStubReference(OpFlag))
7307 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7308 MachinePointerInfo::getGOT(), false, false, false, 0);
7314 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7315 // Create the TargetBlockAddressAddress node.
7316 unsigned char OpFlags =
7317 Subtarget->ClassifyBlockAddressReference();
7318 CodeModel::Model M = getTargetMachine().getCodeModel();
7319 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7320 DebugLoc dl = Op.getDebugLoc();
7321 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7322 /*isTarget=*/true, OpFlags);
7324 if (Subtarget->isPICStyleRIPRel() &&
7325 (M == CodeModel::Small || M == CodeModel::Kernel))
7326 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7328 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7330 // With PIC, the address is actually $g + Offset.
7331 if (isGlobalRelativeToPICBase(OpFlags)) {
7332 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7333 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7341 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7343 SelectionDAG &DAG) const {
7344 // Create the TargetGlobalAddress node, folding in the constant
7345 // offset if it is legal.
7346 unsigned char OpFlags =
7347 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7348 CodeModel::Model M = getTargetMachine().getCodeModel();
7350 if (OpFlags == X86II::MO_NO_FLAG &&
7351 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7352 // A direct static reference to a global.
7353 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7356 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7359 if (Subtarget->isPICStyleRIPRel() &&
7360 (M == CodeModel::Small || M == CodeModel::Kernel))
7361 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7363 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7365 // With PIC, the address is actually $g + Offset.
7366 if (isGlobalRelativeToPICBase(OpFlags)) {
7367 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7368 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7372 // For globals that require a load from a stub to get the address, emit the
7374 if (isGlobalStubReference(OpFlags))
7375 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7376 MachinePointerInfo::getGOT(), false, false, false, 0);
7378 // If there was a non-zero offset that we didn't fold, create an explicit
7381 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7382 DAG.getConstant(Offset, getPointerTy()));
7388 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7389 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7390 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7391 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7395 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7396 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7397 unsigned char OperandFlags) {
7398 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7399 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7400 DebugLoc dl = GA->getDebugLoc();
7401 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7402 GA->getValueType(0),
7406 SDValue Ops[] = { Chain, TGA, *InFlag };
7407 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7409 SDValue Ops[] = { Chain, TGA };
7410 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7413 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7414 MFI->setAdjustsStack(true);
7416 SDValue Flag = Chain.getValue(1);
7417 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7420 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7422 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7425 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7426 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7427 DAG.getNode(X86ISD::GlobalBaseReg,
7428 DebugLoc(), PtrVT), InFlag);
7429 InFlag = Chain.getValue(1);
7431 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7434 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7436 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7438 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7439 X86::RAX, X86II::MO_TLSGD);
7442 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7443 // "local exec" model.
7444 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7445 const EVT PtrVT, TLSModel::Model model,
7447 DebugLoc dl = GA->getDebugLoc();
7449 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7450 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7451 is64Bit ? 257 : 256));
7453 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7454 DAG.getIntPtrConstant(0),
7455 MachinePointerInfo(Ptr),
7456 false, false, false, 0);
7458 unsigned char OperandFlags = 0;
7459 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7461 unsigned WrapperKind = X86ISD::Wrapper;
7462 if (model == TLSModel::LocalExec) {
7463 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7464 } else if (is64Bit) {
7465 assert(model == TLSModel::InitialExec);
7466 OperandFlags = X86II::MO_GOTTPOFF;
7467 WrapperKind = X86ISD::WrapperRIP;
7469 assert(model == TLSModel::InitialExec);
7470 OperandFlags = X86II::MO_INDNTPOFF;
7473 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7475 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7476 GA->getValueType(0),
7477 GA->getOffset(), OperandFlags);
7478 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7480 if (model == TLSModel::InitialExec)
7481 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7482 MachinePointerInfo::getGOT(), false, false, false, 0);
7484 // The address of the thread local variable is the add of the thread
7485 // pointer with the offset of the variable.
7486 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7490 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7492 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7493 const GlobalValue *GV = GA->getGlobal();
7495 if (Subtarget->isTargetELF()) {
7496 // TODO: implement the "local dynamic" model
7497 // TODO: implement the "initial exec"model for pic executables
7499 // If GV is an alias then use the aliasee for determining
7500 // thread-localness.
7501 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7502 GV = GA->resolveAliasedGlobal(false);
7504 TLSModel::Model model
7505 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7508 case TLSModel::GeneralDynamic:
7509 case TLSModel::LocalDynamic: // not implemented
7510 if (Subtarget->is64Bit())
7511 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7512 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7514 case TLSModel::InitialExec:
7515 case TLSModel::LocalExec:
7516 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7517 Subtarget->is64Bit());
7519 } else if (Subtarget->isTargetDarwin()) {
7520 // Darwin only has one model of TLS. Lower to that.
7521 unsigned char OpFlag = 0;
7522 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7523 X86ISD::WrapperRIP : X86ISD::Wrapper;
7525 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7527 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7528 !Subtarget->is64Bit();
7530 OpFlag = X86II::MO_TLVP_PIC_BASE;
7532 OpFlag = X86II::MO_TLVP;
7533 DebugLoc DL = Op.getDebugLoc();
7534 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7535 GA->getValueType(0),
7536 GA->getOffset(), OpFlag);
7537 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7539 // With PIC32, the address is actually $g + Offset.
7541 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7542 DAG.getNode(X86ISD::GlobalBaseReg,
7543 DebugLoc(), getPointerTy()),
7546 // Lowering the machine isd will make sure everything is in the right
7548 SDValue Chain = DAG.getEntryNode();
7549 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7550 SDValue Args[] = { Chain, Offset };
7551 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7553 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7554 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7555 MFI->setAdjustsStack(true);
7557 // And our return value (tls address) is in the standard call return value
7559 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7560 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7565 "TLS not implemented for this target.");
7567 llvm_unreachable("Unreachable");
7572 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7573 /// take a 2 x i32 value to shift plus a shift amount.
7574 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7575 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7576 EVT VT = Op.getValueType();
7577 unsigned VTBits = VT.getSizeInBits();
7578 DebugLoc dl = Op.getDebugLoc();
7579 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7580 SDValue ShOpLo = Op.getOperand(0);
7581 SDValue ShOpHi = Op.getOperand(1);
7582 SDValue ShAmt = Op.getOperand(2);
7583 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7584 DAG.getConstant(VTBits - 1, MVT::i8))
7585 : DAG.getConstant(0, VT);
7588 if (Op.getOpcode() == ISD::SHL_PARTS) {
7589 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7590 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7592 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7593 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7596 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7597 DAG.getConstant(VTBits, MVT::i8));
7598 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7599 AndNode, DAG.getConstant(0, MVT::i8));
7602 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7603 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7604 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7606 if (Op.getOpcode() == ISD::SHL_PARTS) {
7607 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7608 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7610 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7611 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7614 SDValue Ops[2] = { Lo, Hi };
7615 return DAG.getMergeValues(Ops, 2, dl);
7618 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7619 SelectionDAG &DAG) const {
7620 EVT SrcVT = Op.getOperand(0).getValueType();
7622 if (SrcVT.isVector())
7625 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7626 "Unknown SINT_TO_FP to lower!");
7628 // These are really Legal; return the operand so the caller accepts it as
7630 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7632 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7633 Subtarget->is64Bit()) {
7637 DebugLoc dl = Op.getDebugLoc();
7638 unsigned Size = SrcVT.getSizeInBits()/8;
7639 MachineFunction &MF = DAG.getMachineFunction();
7640 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7641 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7642 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7644 MachinePointerInfo::getFixedStack(SSFI),
7646 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7649 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7651 SelectionDAG &DAG) const {
7653 DebugLoc DL = Op.getDebugLoc();
7655 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7657 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7659 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7661 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7663 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7664 MachineMemOperand *MMO;
7666 int SSFI = FI->getIndex();
7668 DAG.getMachineFunction()
7669 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7670 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7672 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7673 StackSlot = StackSlot.getOperand(1);
7675 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7676 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7678 Tys, Ops, array_lengthof(Ops),
7682 Chain = Result.getValue(1);
7683 SDValue InFlag = Result.getValue(2);
7685 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7686 // shouldn't be necessary except that RFP cannot be live across
7687 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7688 MachineFunction &MF = DAG.getMachineFunction();
7689 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7690 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7691 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7692 Tys = DAG.getVTList(MVT::Other);
7694 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7696 MachineMemOperand *MMO =
7697 DAG.getMachineFunction()
7698 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7699 MachineMemOperand::MOStore, SSFISize, SSFISize);
7701 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7702 Ops, array_lengthof(Ops),
7703 Op.getValueType(), MMO);
7704 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7705 MachinePointerInfo::getFixedStack(SSFI),
7706 false, false, false, 0);
7712 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7713 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7714 SelectionDAG &DAG) const {
7715 // This algorithm is not obvious. Here it is in C code, more or less:
7717 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7718 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7719 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7721 // Copy ints to xmm registers.
7722 __m128i xh = _mm_cvtsi32_si128( hi );
7723 __m128i xl = _mm_cvtsi32_si128( lo );
7725 // Combine into low half of a single xmm register.
7726 __m128i x = _mm_unpacklo_epi32( xh, xl );
7730 // Merge in appropriate exponents to give the integer bits the right
7732 x = _mm_unpacklo_epi32( x, exp );
7734 // Subtract away the biases to deal with the IEEE-754 double precision
7736 d = _mm_sub_pd( (__m128d) x, bias );
7738 // All conversions up to here are exact. The correctly rounded result is
7739 // calculated using the current rounding mode using the following
7741 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7742 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7743 // store doesn't really need to be here (except
7744 // maybe to zero the other double)
7749 DebugLoc dl = Op.getDebugLoc();
7750 LLVMContext *Context = DAG.getContext();
7752 // Build some magic constants.
7753 std::vector<Constant*> CV0;
7754 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7755 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7756 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7757 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7758 Constant *C0 = ConstantVector::get(CV0);
7759 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7761 std::vector<Constant*> CV1;
7763 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7765 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7766 Constant *C1 = ConstantVector::get(CV1);
7767 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7769 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7770 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7772 DAG.getIntPtrConstant(1)));
7773 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7774 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7776 DAG.getIntPtrConstant(0)));
7777 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7778 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7779 MachinePointerInfo::getConstantPool(),
7780 false, false, false, 16);
7781 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7782 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7783 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7784 MachinePointerInfo::getConstantPool(),
7785 false, false, false, 16);
7786 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7788 // Add the halves; easiest way is to swap them into another reg first.
7789 int ShufMask[2] = { 1, -1 };
7790 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7791 DAG.getUNDEF(MVT::v2f64), ShufMask);
7792 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7793 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7794 DAG.getIntPtrConstant(0));
7797 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7798 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7799 SelectionDAG &DAG) const {
7800 DebugLoc dl = Op.getDebugLoc();
7801 // FP constant to bias correct the final result.
7802 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7805 // Load the 32-bit value into an XMM register.
7806 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7809 // Zero out the upper parts of the register.
7810 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7813 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7814 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7815 DAG.getIntPtrConstant(0));
7817 // Or the load with the bias.
7818 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7819 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7820 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7822 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7823 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7824 MVT::v2f64, Bias)));
7825 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7826 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7827 DAG.getIntPtrConstant(0));
7829 // Subtract the bias.
7830 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7832 // Handle final rounding.
7833 EVT DestVT = Op.getValueType();
7835 if (DestVT.bitsLT(MVT::f64)) {
7836 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7837 DAG.getIntPtrConstant(0));
7838 } else if (DestVT.bitsGT(MVT::f64)) {
7839 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7842 // Handle final rounding.
7846 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7847 SelectionDAG &DAG) const {
7848 SDValue N0 = Op.getOperand(0);
7849 DebugLoc dl = Op.getDebugLoc();
7851 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7852 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7853 // the optimization here.
7854 if (DAG.SignBitIsZero(N0))
7855 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7857 EVT SrcVT = N0.getValueType();
7858 EVT DstVT = Op.getValueType();
7859 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7860 return LowerUINT_TO_FP_i64(Op, DAG);
7861 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7862 return LowerUINT_TO_FP_i32(Op, DAG);
7864 // Make a 64-bit buffer, and use it to build an FILD.
7865 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7866 if (SrcVT == MVT::i32) {
7867 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7868 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7869 getPointerTy(), StackSlot, WordOff);
7870 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7871 StackSlot, MachinePointerInfo(),
7873 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7874 OffsetSlot, MachinePointerInfo(),
7876 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7880 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7881 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7882 StackSlot, MachinePointerInfo(),
7884 // For i64 source, we need to add the appropriate power of 2 if the input
7885 // was negative. This is the same as the optimization in
7886 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7887 // we must be careful to do the computation in x87 extended precision, not
7888 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7889 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7890 MachineMemOperand *MMO =
7891 DAG.getMachineFunction()
7892 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7893 MachineMemOperand::MOLoad, 8, 8);
7895 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7896 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7897 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7900 APInt FF(32, 0x5F800000ULL);
7902 // Check whether the sign bit is set.
7903 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7904 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7907 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7908 SDValue FudgePtr = DAG.getConstantPool(
7909 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7912 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7913 SDValue Zero = DAG.getIntPtrConstant(0);
7914 SDValue Four = DAG.getIntPtrConstant(4);
7915 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7917 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7919 // Load the value out, extending it from f32 to f80.
7920 // FIXME: Avoid the extend by constructing the right constant pool?
7921 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7922 FudgePtr, MachinePointerInfo::getConstantPool(),
7923 MVT::f32, false, false, 4);
7924 // Extend everything to 80 bits to force it to be done on x87.
7925 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7926 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7929 std::pair<SDValue,SDValue> X86TargetLowering::
7930 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7931 DebugLoc DL = Op.getDebugLoc();
7933 EVT DstTy = Op.getValueType();
7936 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7940 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7941 DstTy.getSimpleVT() >= MVT::i16 &&
7942 "Unknown FP_TO_SINT to lower!");
7944 // These are really Legal.
7945 if (DstTy == MVT::i32 &&
7946 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7947 return std::make_pair(SDValue(), SDValue());
7948 if (Subtarget->is64Bit() &&
7949 DstTy == MVT::i64 &&
7950 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7951 return std::make_pair(SDValue(), SDValue());
7953 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7955 MachineFunction &MF = DAG.getMachineFunction();
7956 unsigned MemSize = DstTy.getSizeInBits()/8;
7957 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7958 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963 switch (DstTy.getSimpleVT().SimpleTy) {
7964 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7965 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7966 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7967 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7970 SDValue Chain = DAG.getEntryNode();
7971 SDValue Value = Op.getOperand(0);
7972 EVT TheVT = Op.getOperand(0).getValueType();
7973 if (isScalarFPTypeInSSEReg(TheVT)) {
7974 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7975 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7976 MachinePointerInfo::getFixedStack(SSFI),
7978 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7980 Chain, StackSlot, DAG.getValueType(TheVT)
7983 MachineMemOperand *MMO =
7984 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7985 MachineMemOperand::MOLoad, MemSize, MemSize);
7986 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7988 Chain = Value.getValue(1);
7989 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7990 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7993 MachineMemOperand *MMO =
7994 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7995 MachineMemOperand::MOStore, MemSize, MemSize);
7997 // Build the FP_TO_INT*_IN_MEM
7998 SDValue Ops[] = { Chain, Value, StackSlot };
7999 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8000 Ops, 3, DstTy, MMO);
8002 return std::make_pair(FIST, StackSlot);
8005 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8006 SelectionDAG &DAG) const {
8007 if (Op.getValueType().isVector())
8010 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8011 SDValue FIST = Vals.first, StackSlot = Vals.second;
8012 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8013 if (FIST.getNode() == 0) return Op;
8016 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8017 FIST, StackSlot, MachinePointerInfo(),
8018 false, false, false, 0);
8021 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8022 SelectionDAG &DAG) const {
8023 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8024 SDValue FIST = Vals.first, StackSlot = Vals.second;
8025 assert(FIST.getNode() && "Unexpected failure");
8028 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8029 FIST, StackSlot, MachinePointerInfo(),
8030 false, false, false, 0);
8033 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8034 SelectionDAG &DAG) const {
8035 LLVMContext *Context = DAG.getContext();
8036 DebugLoc dl = Op.getDebugLoc();
8037 EVT VT = Op.getValueType();
8040 EltVT = VT.getVectorElementType();
8041 std::vector<Constant*> CV;
8042 if (EltVT == MVT::f64) {
8043 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8047 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8053 Constant *C = ConstantVector::get(CV);
8054 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8055 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8056 MachinePointerInfo::getConstantPool(),
8057 false, false, false, 16);
8058 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8061 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8062 LLVMContext *Context = DAG.getContext();
8063 DebugLoc dl = Op.getDebugLoc();
8064 EVT VT = Op.getValueType();
8067 EltVT = VT.getVectorElementType();
8068 std::vector<Constant*> CV;
8069 if (EltVT == MVT::f64) {
8070 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8074 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8080 Constant *C = ConstantVector::get(CV);
8081 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8082 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8083 MachinePointerInfo::getConstantPool(),
8084 false, false, false, 16);
8085 if (VT.isVector()) {
8086 return DAG.getNode(ISD::BITCAST, dl, VT,
8087 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8088 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8090 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8092 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8096 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8097 LLVMContext *Context = DAG.getContext();
8098 SDValue Op0 = Op.getOperand(0);
8099 SDValue Op1 = Op.getOperand(1);
8100 DebugLoc dl = Op.getDebugLoc();
8101 EVT VT = Op.getValueType();
8102 EVT SrcVT = Op1.getValueType();
8104 // If second operand is smaller, extend it first.
8105 if (SrcVT.bitsLT(VT)) {
8106 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8109 // And if it is bigger, shrink it first.
8110 if (SrcVT.bitsGT(VT)) {
8111 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8115 // At this point the operands and the result should have the same
8116 // type, and that won't be f80 since that is not custom lowered.
8118 // First get the sign bit of second operand.
8119 std::vector<Constant*> CV;
8120 if (SrcVT == MVT::f64) {
8121 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8122 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8124 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8125 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8126 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8127 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8129 Constant *C = ConstantVector::get(CV);
8130 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8131 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8132 MachinePointerInfo::getConstantPool(),
8133 false, false, false, 16);
8134 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8136 // Shift sign bit right or left if the two operands have different types.
8137 if (SrcVT.bitsGT(VT)) {
8138 // Op0 is MVT::f32, Op1 is MVT::f64.
8139 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8140 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8141 DAG.getConstant(32, MVT::i32));
8142 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8143 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8144 DAG.getIntPtrConstant(0));
8147 // Clear first operand sign bit.
8149 if (VT == MVT::f64) {
8150 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8151 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8153 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8154 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8155 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8156 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8158 C = ConstantVector::get(CV);
8159 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8160 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8161 MachinePointerInfo::getConstantPool(),
8162 false, false, false, 16);
8163 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8165 // Or the value with the sign bit.
8166 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8169 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8170 SDValue N0 = Op.getOperand(0);
8171 DebugLoc dl = Op.getDebugLoc();
8172 EVT VT = Op.getValueType();
8174 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8175 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8176 DAG.getConstant(1, VT));
8177 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8180 /// Emit nodes that will be selected as "test Op0,Op0", or something
8182 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8183 SelectionDAG &DAG) const {
8184 DebugLoc dl = Op.getDebugLoc();
8186 // CF and OF aren't always set the way we want. Determine which
8187 // of these we need.
8188 bool NeedCF = false;
8189 bool NeedOF = false;
8192 case X86::COND_A: case X86::COND_AE:
8193 case X86::COND_B: case X86::COND_BE:
8196 case X86::COND_G: case X86::COND_GE:
8197 case X86::COND_L: case X86::COND_LE:
8198 case X86::COND_O: case X86::COND_NO:
8203 // See if we can use the EFLAGS value from the operand instead of
8204 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8205 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8206 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8207 // Emit a CMP with 0, which is the TEST pattern.
8208 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8209 DAG.getConstant(0, Op.getValueType()));
8211 unsigned Opcode = 0;
8212 unsigned NumOperands = 0;
8213 switch (Op.getNode()->getOpcode()) {
8215 // Due to an isel shortcoming, be conservative if this add is likely to be
8216 // selected as part of a load-modify-store instruction. When the root node
8217 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8218 // uses of other nodes in the match, such as the ADD in this case. This
8219 // leads to the ADD being left around and reselected, with the result being
8220 // two adds in the output. Alas, even if none our users are stores, that
8221 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8222 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8223 // climbing the DAG back to the root, and it doesn't seem to be worth the
8225 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8226 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8227 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8230 if (ConstantSDNode *C =
8231 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8232 // An add of one will be selected as an INC.
8233 if (C->getAPIntValue() == 1) {
8234 Opcode = X86ISD::INC;
8239 // An add of negative one (subtract of one) will be selected as a DEC.
8240 if (C->getAPIntValue().isAllOnesValue()) {
8241 Opcode = X86ISD::DEC;
8247 // Otherwise use a regular EFLAGS-setting add.
8248 Opcode = X86ISD::ADD;
8252 // If the primary and result isn't used, don't bother using X86ISD::AND,
8253 // because a TEST instruction will be better.
8254 bool NonFlagUse = false;
8255 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8256 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8258 unsigned UOpNo = UI.getOperandNo();
8259 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8260 // Look pass truncate.
8261 UOpNo = User->use_begin().getOperandNo();
8262 User = *User->use_begin();
8265 if (User->getOpcode() != ISD::BRCOND &&
8266 User->getOpcode() != ISD::SETCC &&
8267 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8280 // Due to the ISEL shortcoming noted above, be conservative if this op is
8281 // likely to be selected as part of a load-modify-store instruction.
8282 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8283 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8284 if (UI->getOpcode() == ISD::STORE)
8287 // Otherwise use a regular EFLAGS-setting instruction.
8288 switch (Op.getNode()->getOpcode()) {
8289 default: llvm_unreachable("unexpected operator!");
8290 case ISD::SUB: Opcode = X86ISD::SUB; break;
8291 case ISD::OR: Opcode = X86ISD::OR; break;
8292 case ISD::XOR: Opcode = X86ISD::XOR; break;
8293 case ISD::AND: Opcode = X86ISD::AND; break;
8305 return SDValue(Op.getNode(), 1);
8312 // Emit a CMP with 0, which is the TEST pattern.
8313 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8314 DAG.getConstant(0, Op.getValueType()));
8316 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8317 SmallVector<SDValue, 4> Ops;
8318 for (unsigned i = 0; i != NumOperands; ++i)
8319 Ops.push_back(Op.getOperand(i));
8321 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8322 DAG.ReplaceAllUsesWith(Op, New);
8323 return SDValue(New.getNode(), 1);
8326 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8328 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8329 SelectionDAG &DAG) const {
8330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8331 if (C->getAPIntValue() == 0)
8332 return EmitTest(Op0, X86CC, DAG);
8334 DebugLoc dl = Op0.getDebugLoc();
8335 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8338 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8339 /// if it's possible.
8340 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8341 DebugLoc dl, SelectionDAG &DAG) const {
8342 SDValue Op0 = And.getOperand(0);
8343 SDValue Op1 = And.getOperand(1);
8344 if (Op0.getOpcode() == ISD::TRUNCATE)
8345 Op0 = Op0.getOperand(0);
8346 if (Op1.getOpcode() == ISD::TRUNCATE)
8347 Op1 = Op1.getOperand(0);
8350 if (Op1.getOpcode() == ISD::SHL)
8351 std::swap(Op0, Op1);
8352 if (Op0.getOpcode() == ISD::SHL) {
8353 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8354 if (And00C->getZExtValue() == 1) {
8355 // If we looked past a truncate, check that it's only truncating away
8357 unsigned BitWidth = Op0.getValueSizeInBits();
8358 unsigned AndBitWidth = And.getValueSizeInBits();
8359 if (BitWidth > AndBitWidth) {
8360 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8361 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8362 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8366 RHS = Op0.getOperand(1);
8368 } else if (Op1.getOpcode() == ISD::Constant) {
8369 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8370 SDValue AndLHS = Op0;
8371 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8372 LHS = AndLHS.getOperand(0);
8373 RHS = AndLHS.getOperand(1);
8377 if (LHS.getNode()) {
8378 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8379 // instruction. Since the shift amount is in-range-or-undefined, we know
8380 // that doing a bittest on the i32 value is ok. We extend to i32 because
8381 // the encoding for the i16 version is larger than the i32 version.
8382 // Also promote i16 to i32 for performance / code size reason.
8383 if (LHS.getValueType() == MVT::i8 ||
8384 LHS.getValueType() == MVT::i16)
8385 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8387 // If the operand types disagree, extend the shift amount to match. Since
8388 // BT ignores high bits (like shifts) we can use anyextend.
8389 if (LHS.getValueType() != RHS.getValueType())
8390 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8392 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8393 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8394 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8395 DAG.getConstant(Cond, MVT::i8), BT);
8401 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8403 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8405 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8406 SDValue Op0 = Op.getOperand(0);
8407 SDValue Op1 = Op.getOperand(1);
8408 DebugLoc dl = Op.getDebugLoc();
8409 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8411 // Optimize to BT if possible.
8412 // Lower (X & (1 << N)) == 0 to BT(X, N).
8413 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8414 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8415 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8416 Op1.getOpcode() == ISD::Constant &&
8417 cast<ConstantSDNode>(Op1)->isNullValue() &&
8418 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8419 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8420 if (NewSetCC.getNode())
8424 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8426 if (Op1.getOpcode() == ISD::Constant &&
8427 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8428 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8429 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8431 // If the input is a setcc, then reuse the input setcc or use a new one with
8432 // the inverted condition.
8433 if (Op0.getOpcode() == X86ISD::SETCC) {
8434 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8435 bool Invert = (CC == ISD::SETNE) ^
8436 cast<ConstantSDNode>(Op1)->isNullValue();
8437 if (!Invert) return Op0;
8439 CCode = X86::GetOppositeBranchCondition(CCode);
8440 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8441 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8445 bool isFP = Op1.getValueType().isFloatingPoint();
8446 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8447 if (X86CC == X86::COND_INVALID)
8450 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8451 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8452 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8455 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8456 // ones, and then concatenate the result back.
8457 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8458 EVT VT = Op.getValueType();
8460 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8461 "Unsupported value type for operation");
8463 int NumElems = VT.getVectorNumElements();
8464 DebugLoc dl = Op.getDebugLoc();
8465 SDValue CC = Op.getOperand(2);
8466 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8467 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8469 // Extract the LHS vectors
8470 SDValue LHS = Op.getOperand(0);
8471 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8472 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8474 // Extract the RHS vectors
8475 SDValue RHS = Op.getOperand(1);
8476 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8477 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8479 // Issue the operation on the smaller types and concatenate the result back
8480 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8481 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8482 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8483 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8484 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8488 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8490 SDValue Op0 = Op.getOperand(0);
8491 SDValue Op1 = Op.getOperand(1);
8492 SDValue CC = Op.getOperand(2);
8493 EVT VT = Op.getValueType();
8494 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8495 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8496 DebugLoc dl = Op.getDebugLoc();
8500 EVT EltVT = Op0.getValueType().getVectorElementType();
8501 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8503 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8506 // SSE Condition code mapping:
8515 switch (SetCCOpcode) {
8518 case ISD::SETEQ: SSECC = 0; break;
8520 case ISD::SETGT: Swap = true; // Fallthrough
8522 case ISD::SETOLT: SSECC = 1; break;
8524 case ISD::SETGE: Swap = true; // Fallthrough
8526 case ISD::SETOLE: SSECC = 2; break;
8527 case ISD::SETUO: SSECC = 3; break;
8529 case ISD::SETNE: SSECC = 4; break;
8530 case ISD::SETULE: Swap = true;
8531 case ISD::SETUGE: SSECC = 5; break;
8532 case ISD::SETULT: Swap = true;
8533 case ISD::SETUGT: SSECC = 6; break;
8534 case ISD::SETO: SSECC = 7; break;
8537 std::swap(Op0, Op1);
8539 // In the two special cases we can't handle, emit two comparisons.
8541 if (SetCCOpcode == ISD::SETUEQ) {
8543 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8544 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8545 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8547 else if (SetCCOpcode == ISD::SETONE) {
8549 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8550 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8551 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8553 llvm_unreachable("Illegal FP comparison");
8555 // Handle all other FP comparisons here.
8556 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8559 // Break 256-bit integer vector compare into smaller ones.
8560 if (!isFP && VT.getSizeInBits() == 256)
8561 return Lower256IntVSETCC(Op, DAG);
8563 // We are handling one of the integer comparisons here. Since SSE only has
8564 // GT and EQ comparisons for integer, swapping operands and multiple
8565 // operations may be required for some comparisons.
8566 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8567 bool Swap = false, Invert = false, FlipSigns = false;
8569 switch (VT.getSimpleVT().SimpleTy) {
8571 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8572 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8573 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8574 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8577 switch (SetCCOpcode) {
8579 case ISD::SETNE: Invert = true;
8580 case ISD::SETEQ: Opc = EQOpc; break;
8581 case ISD::SETLT: Swap = true;
8582 case ISD::SETGT: Opc = GTOpc; break;
8583 case ISD::SETGE: Swap = true;
8584 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8585 case ISD::SETULT: Swap = true;
8586 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8587 case ISD::SETUGE: Swap = true;
8588 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8591 std::swap(Op0, Op1);
8593 // Check that the operation in question is available (most are plain SSE2,
8594 // but PCMPGTQ and PCMPEQQ have different requirements).
8595 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8597 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8600 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8601 // bits of the inputs before performing those operations.
8603 EVT EltVT = VT.getVectorElementType();
8604 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8606 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8607 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8609 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8610 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8613 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8615 // If the logical-not of the result is required, perform that now.
8617 Result = DAG.getNOT(dl, Result, VT);
8622 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8623 static bool isX86LogicalCmp(SDValue Op) {
8624 unsigned Opc = Op.getNode()->getOpcode();
8625 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8627 if (Op.getResNo() == 1 &&
8628 (Opc == X86ISD::ADD ||
8629 Opc == X86ISD::SUB ||
8630 Opc == X86ISD::ADC ||
8631 Opc == X86ISD::SBB ||
8632 Opc == X86ISD::SMUL ||
8633 Opc == X86ISD::UMUL ||
8634 Opc == X86ISD::INC ||
8635 Opc == X86ISD::DEC ||
8636 Opc == X86ISD::OR ||
8637 Opc == X86ISD::XOR ||
8638 Opc == X86ISD::AND))
8641 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8647 static bool isZero(SDValue V) {
8648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8649 return C && C->isNullValue();
8652 static bool isAllOnes(SDValue V) {
8653 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8654 return C && C->isAllOnesValue();
8657 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8658 bool addTest = true;
8659 SDValue Cond = Op.getOperand(0);
8660 SDValue Op1 = Op.getOperand(1);
8661 SDValue Op2 = Op.getOperand(2);
8662 DebugLoc DL = Op.getDebugLoc();
8665 if (Cond.getOpcode() == ISD::SETCC) {
8666 SDValue NewCond = LowerSETCC(Cond, DAG);
8667 if (NewCond.getNode())
8671 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8672 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8673 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8674 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8675 if (Cond.getOpcode() == X86ISD::SETCC &&
8676 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8677 isZero(Cond.getOperand(1).getOperand(1))) {
8678 SDValue Cmp = Cond.getOperand(1);
8680 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8682 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8683 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8684 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8686 SDValue CmpOp0 = Cmp.getOperand(0);
8687 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8688 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8690 SDValue Res = // Res = 0 or -1.
8691 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8692 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8694 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8695 Res = DAG.getNOT(DL, Res, Res.getValueType());
8697 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8698 if (N2C == 0 || !N2C->isNullValue())
8699 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8704 // Look past (and (setcc_carry (cmp ...)), 1).
8705 if (Cond.getOpcode() == ISD::AND &&
8706 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8707 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8708 if (C && C->getAPIntValue() == 1)
8709 Cond = Cond.getOperand(0);
8712 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8713 // setting operand in place of the X86ISD::SETCC.
8714 unsigned CondOpcode = Cond.getOpcode();
8715 if (CondOpcode == X86ISD::SETCC ||
8716 CondOpcode == X86ISD::SETCC_CARRY) {
8717 CC = Cond.getOperand(0);
8719 SDValue Cmp = Cond.getOperand(1);
8720 unsigned Opc = Cmp.getOpcode();
8721 EVT VT = Op.getValueType();
8723 bool IllegalFPCMov = false;
8724 if (VT.isFloatingPoint() && !VT.isVector() &&
8725 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8726 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8728 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8729 Opc == X86ISD::BT) { // FIXME
8733 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8734 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8735 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8736 Cond.getOperand(0).getValueType() != MVT::i8)) {
8737 SDValue LHS = Cond.getOperand(0);
8738 SDValue RHS = Cond.getOperand(1);
8742 switch (CondOpcode) {
8743 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8744 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8745 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8746 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8747 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8748 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8749 default: llvm_unreachable("unexpected overflowing operator");
8751 if (CondOpcode == ISD::UMULO)
8752 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8755 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8757 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8759 if (CondOpcode == ISD::UMULO)
8760 Cond = X86Op.getValue(2);
8762 Cond = X86Op.getValue(1);
8764 CC = DAG.getConstant(X86Cond, MVT::i8);
8769 // Look pass the truncate.
8770 if (Cond.getOpcode() == ISD::TRUNCATE)
8771 Cond = Cond.getOperand(0);
8773 // We know the result of AND is compared against zero. Try to match
8775 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8776 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8777 if (NewSetCC.getNode()) {
8778 CC = NewSetCC.getOperand(0);
8779 Cond = NewSetCC.getOperand(1);
8786 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8787 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8790 // a < b ? -1 : 0 -> RES = ~setcc_carry
8791 // a < b ? 0 : -1 -> RES = setcc_carry
8792 // a >= b ? -1 : 0 -> RES = setcc_carry
8793 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8794 if (Cond.getOpcode() == X86ISD::CMP) {
8795 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8797 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8798 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8799 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8800 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8801 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8802 return DAG.getNOT(DL, Res, Res.getValueType());
8807 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8808 // condition is true.
8809 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8810 SDValue Ops[] = { Op2, Op1, CC, Cond };
8811 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8814 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8815 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8816 // from the AND / OR.
8817 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8818 Opc = Op.getOpcode();
8819 if (Opc != ISD::OR && Opc != ISD::AND)
8821 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8822 Op.getOperand(0).hasOneUse() &&
8823 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8824 Op.getOperand(1).hasOneUse());
8827 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8828 // 1 and that the SETCC node has a single use.
8829 static bool isXor1OfSetCC(SDValue Op) {
8830 if (Op.getOpcode() != ISD::XOR)
8832 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8833 if (N1C && N1C->getAPIntValue() == 1) {
8834 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8835 Op.getOperand(0).hasOneUse();
8840 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8841 bool addTest = true;
8842 SDValue Chain = Op.getOperand(0);
8843 SDValue Cond = Op.getOperand(1);
8844 SDValue Dest = Op.getOperand(2);
8845 DebugLoc dl = Op.getDebugLoc();
8847 bool Inverted = false;
8849 if (Cond.getOpcode() == ISD::SETCC) {
8850 // Check for setcc([su]{add,sub,mul}o == 0).
8851 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8852 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8853 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8854 Cond.getOperand(0).getResNo() == 1 &&
8855 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8856 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8857 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8858 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8859 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8860 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8862 Cond = Cond.getOperand(0);
8864 SDValue NewCond = LowerSETCC(Cond, DAG);
8865 if (NewCond.getNode())
8870 // FIXME: LowerXALUO doesn't handle these!!
8871 else if (Cond.getOpcode() == X86ISD::ADD ||
8872 Cond.getOpcode() == X86ISD::SUB ||
8873 Cond.getOpcode() == X86ISD::SMUL ||
8874 Cond.getOpcode() == X86ISD::UMUL)
8875 Cond = LowerXALUO(Cond, DAG);
8878 // Look pass (and (setcc_carry (cmp ...)), 1).
8879 if (Cond.getOpcode() == ISD::AND &&
8880 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8881 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8882 if (C && C->getAPIntValue() == 1)
8883 Cond = Cond.getOperand(0);
8886 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8887 // setting operand in place of the X86ISD::SETCC.
8888 unsigned CondOpcode = Cond.getOpcode();
8889 if (CondOpcode == X86ISD::SETCC ||
8890 CondOpcode == X86ISD::SETCC_CARRY) {
8891 CC = Cond.getOperand(0);
8893 SDValue Cmp = Cond.getOperand(1);
8894 unsigned Opc = Cmp.getOpcode();
8895 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8896 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8900 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8904 // These can only come from an arithmetic instruction with overflow,
8905 // e.g. SADDO, UADDO.
8906 Cond = Cond.getNode()->getOperand(1);
8912 CondOpcode = Cond.getOpcode();
8913 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8914 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8915 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8916 Cond.getOperand(0).getValueType() != MVT::i8)) {
8917 SDValue LHS = Cond.getOperand(0);
8918 SDValue RHS = Cond.getOperand(1);
8922 switch (CondOpcode) {
8923 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8924 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8925 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8926 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8927 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8928 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8929 default: llvm_unreachable("unexpected overflowing operator");
8932 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8933 if (CondOpcode == ISD::UMULO)
8934 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8937 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8939 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8941 if (CondOpcode == ISD::UMULO)
8942 Cond = X86Op.getValue(2);
8944 Cond = X86Op.getValue(1);
8946 CC = DAG.getConstant(X86Cond, MVT::i8);
8950 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8951 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8952 if (CondOpc == ISD::OR) {
8953 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8954 // two branches instead of an explicit OR instruction with a
8956 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8957 isX86LogicalCmp(Cmp)) {
8958 CC = Cond.getOperand(0).getOperand(0);
8959 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8960 Chain, Dest, CC, Cmp);
8961 CC = Cond.getOperand(1).getOperand(0);
8965 } else { // ISD::AND
8966 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8967 // two branches instead of an explicit AND instruction with a
8968 // separate test. However, we only do this if this block doesn't
8969 // have a fall-through edge, because this requires an explicit
8970 // jmp when the condition is false.
8971 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8972 isX86LogicalCmp(Cmp) &&
8973 Op.getNode()->hasOneUse()) {
8974 X86::CondCode CCode =
8975 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8976 CCode = X86::GetOppositeBranchCondition(CCode);
8977 CC = DAG.getConstant(CCode, MVT::i8);
8978 SDNode *User = *Op.getNode()->use_begin();
8979 // Look for an unconditional branch following this conditional branch.
8980 // We need this because we need to reverse the successors in order
8981 // to implement FCMP_OEQ.
8982 if (User->getOpcode() == ISD::BR) {
8983 SDValue FalseBB = User->getOperand(1);
8985 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8986 assert(NewBR == User);
8990 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8991 Chain, Dest, CC, Cmp);
8992 X86::CondCode CCode =
8993 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8994 CCode = X86::GetOppositeBranchCondition(CCode);
8995 CC = DAG.getConstant(CCode, MVT::i8);
9001 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9002 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9003 // It should be transformed during dag combiner except when the condition
9004 // is set by a arithmetics with overflow node.
9005 X86::CondCode CCode =
9006 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9007 CCode = X86::GetOppositeBranchCondition(CCode);
9008 CC = DAG.getConstant(CCode, MVT::i8);
9009 Cond = Cond.getOperand(0).getOperand(1);
9011 } else if (Cond.getOpcode() == ISD::SETCC &&
9012 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9013 // For FCMP_OEQ, we can emit
9014 // two branches instead of an explicit AND instruction with a
9015 // separate test. However, we only do this if this block doesn't
9016 // have a fall-through edge, because this requires an explicit
9017 // jmp when the condition is false.
9018 if (Op.getNode()->hasOneUse()) {
9019 SDNode *User = *Op.getNode()->use_begin();
9020 // Look for an unconditional branch following this conditional branch.
9021 // We need this because we need to reverse the successors in order
9022 // to implement FCMP_OEQ.
9023 if (User->getOpcode() == ISD::BR) {
9024 SDValue FalseBB = User->getOperand(1);
9026 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9027 assert(NewBR == User);
9031 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9032 Cond.getOperand(0), Cond.getOperand(1));
9033 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9034 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9035 Chain, Dest, CC, Cmp);
9036 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9041 } else if (Cond.getOpcode() == ISD::SETCC &&
9042 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9043 // For FCMP_UNE, we can emit
9044 // two branches instead of an explicit AND instruction with a
9045 // separate test. However, we only do this if this block doesn't
9046 // have a fall-through edge, because this requires an explicit
9047 // jmp when the condition is false.
9048 if (Op.getNode()->hasOneUse()) {
9049 SDNode *User = *Op.getNode()->use_begin();
9050 // Look for an unconditional branch following this conditional branch.
9051 // We need this because we need to reverse the successors in order
9052 // to implement FCMP_UNE.
9053 if (User->getOpcode() == ISD::BR) {
9054 SDValue FalseBB = User->getOperand(1);
9056 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9057 assert(NewBR == User);
9060 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9061 Cond.getOperand(0), Cond.getOperand(1));
9062 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9063 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9064 Chain, Dest, CC, Cmp);
9065 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9075 // Look pass the truncate.
9076 if (Cond.getOpcode() == ISD::TRUNCATE)
9077 Cond = Cond.getOperand(0);
9079 // We know the result of AND is compared against zero. Try to match
9081 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9082 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9083 if (NewSetCC.getNode()) {
9084 CC = NewSetCC.getOperand(0);
9085 Cond = NewSetCC.getOperand(1);
9092 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9093 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9095 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9096 Chain, Dest, CC, Cond);
9100 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9101 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9102 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9103 // that the guard pages used by the OS virtual memory manager are allocated in
9104 // correct sequence.
9106 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9107 SelectionDAG &DAG) const {
9108 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9109 EnableSegmentedStacks) &&
9110 "This should be used only on Windows targets or when segmented stacks "
9112 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9113 DebugLoc dl = Op.getDebugLoc();
9116 SDValue Chain = Op.getOperand(0);
9117 SDValue Size = Op.getOperand(1);
9118 // FIXME: Ensure alignment here
9120 bool Is64Bit = Subtarget->is64Bit();
9121 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9123 if (EnableSegmentedStacks) {
9124 MachineFunction &MF = DAG.getMachineFunction();
9125 MachineRegisterInfo &MRI = MF.getRegInfo();
9128 // The 64 bit implementation of segmented stacks needs to clobber both r10
9129 // r11. This makes it impossible to use it along with nested parameters.
9130 const Function *F = MF.getFunction();
9132 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9134 if (I->hasNestAttr())
9135 report_fatal_error("Cannot use segmented stacks with functions that "
9136 "have nested arguments.");
9139 const TargetRegisterClass *AddrRegClass =
9140 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9141 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9142 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9143 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9144 DAG.getRegister(Vreg, SPTy));
9145 SDValue Ops1[2] = { Value, Chain };
9146 return DAG.getMergeValues(Ops1, 2, dl);
9149 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9151 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9152 Flag = Chain.getValue(1);
9153 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9155 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9156 Flag = Chain.getValue(1);
9158 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9160 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9161 return DAG.getMergeValues(Ops1, 2, dl);
9165 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9166 MachineFunction &MF = DAG.getMachineFunction();
9167 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9169 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9170 DebugLoc DL = Op.getDebugLoc();
9172 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9173 // vastart just stores the address of the VarArgsFrameIndex slot into the
9174 // memory location argument.
9175 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9177 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9178 MachinePointerInfo(SV), false, false, 0);
9182 // gp_offset (0 - 6 * 8)
9183 // fp_offset (48 - 48 + 8 * 16)
9184 // overflow_arg_area (point to parameters coming in memory).
9186 SmallVector<SDValue, 8> MemOps;
9187 SDValue FIN = Op.getOperand(1);
9189 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9190 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9192 FIN, MachinePointerInfo(SV), false, false, 0);
9193 MemOps.push_back(Store);
9196 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9197 FIN, DAG.getIntPtrConstant(4));
9198 Store = DAG.getStore(Op.getOperand(0), DL,
9199 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9201 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9202 MemOps.push_back(Store);
9204 // Store ptr to overflow_arg_area
9205 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9206 FIN, DAG.getIntPtrConstant(4));
9207 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9209 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9210 MachinePointerInfo(SV, 8),
9212 MemOps.push_back(Store);
9214 // Store ptr to reg_save_area.
9215 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9216 FIN, DAG.getIntPtrConstant(8));
9217 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9219 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9220 MachinePointerInfo(SV, 16), false, false, 0);
9221 MemOps.push_back(Store);
9222 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9223 &MemOps[0], MemOps.size());
9226 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9227 assert(Subtarget->is64Bit() &&
9228 "LowerVAARG only handles 64-bit va_arg!");
9229 assert((Subtarget->isTargetLinux() ||
9230 Subtarget->isTargetDarwin()) &&
9231 "Unhandled target in LowerVAARG");
9232 assert(Op.getNode()->getNumOperands() == 4);
9233 SDValue Chain = Op.getOperand(0);
9234 SDValue SrcPtr = Op.getOperand(1);
9235 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9236 unsigned Align = Op.getConstantOperandVal(3);
9237 DebugLoc dl = Op.getDebugLoc();
9239 EVT ArgVT = Op.getNode()->getValueType(0);
9240 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9241 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9244 // Decide which area this value should be read from.
9245 // TODO: Implement the AMD64 ABI in its entirety. This simple
9246 // selection mechanism works only for the basic types.
9247 if (ArgVT == MVT::f80) {
9248 llvm_unreachable("va_arg for f80 not yet implemented");
9249 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9250 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9251 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9252 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9254 llvm_unreachable("Unhandled argument type in LowerVAARG");
9258 // Sanity Check: Make sure using fp_offset makes sense.
9259 assert(!UseSoftFloat &&
9260 !(DAG.getMachineFunction()
9261 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9262 Subtarget->hasXMM());
9265 // Insert VAARG_64 node into the DAG
9266 // VAARG_64 returns two values: Variable Argument Address, Chain
9267 SmallVector<SDValue, 11> InstOps;
9268 InstOps.push_back(Chain);
9269 InstOps.push_back(SrcPtr);
9270 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9271 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9272 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9273 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9274 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9275 VTs, &InstOps[0], InstOps.size(),
9277 MachinePointerInfo(SV),
9282 Chain = VAARG.getValue(1);
9284 // Load the next argument and return it
9285 return DAG.getLoad(ArgVT, dl,
9288 MachinePointerInfo(),
9289 false, false, false, 0);
9292 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9293 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9294 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9295 SDValue Chain = Op.getOperand(0);
9296 SDValue DstPtr = Op.getOperand(1);
9297 SDValue SrcPtr = Op.getOperand(2);
9298 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9299 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9300 DebugLoc DL = Op.getDebugLoc();
9302 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9303 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9305 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9309 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9310 DebugLoc dl = Op.getDebugLoc();
9311 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9313 default: return SDValue(); // Don't custom lower most intrinsics.
9314 // Comparison intrinsics.
9315 case Intrinsic::x86_sse_comieq_ss:
9316 case Intrinsic::x86_sse_comilt_ss:
9317 case Intrinsic::x86_sse_comile_ss:
9318 case Intrinsic::x86_sse_comigt_ss:
9319 case Intrinsic::x86_sse_comige_ss:
9320 case Intrinsic::x86_sse_comineq_ss:
9321 case Intrinsic::x86_sse_ucomieq_ss:
9322 case Intrinsic::x86_sse_ucomilt_ss:
9323 case Intrinsic::x86_sse_ucomile_ss:
9324 case Intrinsic::x86_sse_ucomigt_ss:
9325 case Intrinsic::x86_sse_ucomige_ss:
9326 case Intrinsic::x86_sse_ucomineq_ss:
9327 case Intrinsic::x86_sse2_comieq_sd:
9328 case Intrinsic::x86_sse2_comilt_sd:
9329 case Intrinsic::x86_sse2_comile_sd:
9330 case Intrinsic::x86_sse2_comigt_sd:
9331 case Intrinsic::x86_sse2_comige_sd:
9332 case Intrinsic::x86_sse2_comineq_sd:
9333 case Intrinsic::x86_sse2_ucomieq_sd:
9334 case Intrinsic::x86_sse2_ucomilt_sd:
9335 case Intrinsic::x86_sse2_ucomile_sd:
9336 case Intrinsic::x86_sse2_ucomigt_sd:
9337 case Intrinsic::x86_sse2_ucomige_sd:
9338 case Intrinsic::x86_sse2_ucomineq_sd: {
9340 ISD::CondCode CC = ISD::SETCC_INVALID;
9343 case Intrinsic::x86_sse_comieq_ss:
9344 case Intrinsic::x86_sse2_comieq_sd:
9348 case Intrinsic::x86_sse_comilt_ss:
9349 case Intrinsic::x86_sse2_comilt_sd:
9353 case Intrinsic::x86_sse_comile_ss:
9354 case Intrinsic::x86_sse2_comile_sd:
9358 case Intrinsic::x86_sse_comigt_ss:
9359 case Intrinsic::x86_sse2_comigt_sd:
9363 case Intrinsic::x86_sse_comige_ss:
9364 case Intrinsic::x86_sse2_comige_sd:
9368 case Intrinsic::x86_sse_comineq_ss:
9369 case Intrinsic::x86_sse2_comineq_sd:
9373 case Intrinsic::x86_sse_ucomieq_ss:
9374 case Intrinsic::x86_sse2_ucomieq_sd:
9375 Opc = X86ISD::UCOMI;
9378 case Intrinsic::x86_sse_ucomilt_ss:
9379 case Intrinsic::x86_sse2_ucomilt_sd:
9380 Opc = X86ISD::UCOMI;
9383 case Intrinsic::x86_sse_ucomile_ss:
9384 case Intrinsic::x86_sse2_ucomile_sd:
9385 Opc = X86ISD::UCOMI;
9388 case Intrinsic::x86_sse_ucomigt_ss:
9389 case Intrinsic::x86_sse2_ucomigt_sd:
9390 Opc = X86ISD::UCOMI;
9393 case Intrinsic::x86_sse_ucomige_ss:
9394 case Intrinsic::x86_sse2_ucomige_sd:
9395 Opc = X86ISD::UCOMI;
9398 case Intrinsic::x86_sse_ucomineq_ss:
9399 case Intrinsic::x86_sse2_ucomineq_sd:
9400 Opc = X86ISD::UCOMI;
9405 SDValue LHS = Op.getOperand(1);
9406 SDValue RHS = Op.getOperand(2);
9407 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9408 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9409 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9410 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9411 DAG.getConstant(X86CC, MVT::i8), Cond);
9412 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9414 // Arithmetic intrinsics.
9415 case Intrinsic::x86_sse3_hadd_ps:
9416 case Intrinsic::x86_sse3_hadd_pd:
9417 case Intrinsic::x86_avx_hadd_ps_256:
9418 case Intrinsic::x86_avx_hadd_pd_256:
9419 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9420 Op.getOperand(1), Op.getOperand(2));
9421 case Intrinsic::x86_sse3_hsub_ps:
9422 case Intrinsic::x86_sse3_hsub_pd:
9423 case Intrinsic::x86_avx_hsub_ps_256:
9424 case Intrinsic::x86_avx_hsub_pd_256:
9425 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9426 Op.getOperand(1), Op.getOperand(2));
9427 // ptest and testp intrinsics. The intrinsic these come from are designed to
9428 // return an integer value, not just an instruction so lower it to the ptest
9429 // or testp pattern and a setcc for the result.
9430 case Intrinsic::x86_sse41_ptestz:
9431 case Intrinsic::x86_sse41_ptestc:
9432 case Intrinsic::x86_sse41_ptestnzc:
9433 case Intrinsic::x86_avx_ptestz_256:
9434 case Intrinsic::x86_avx_ptestc_256:
9435 case Intrinsic::x86_avx_ptestnzc_256:
9436 case Intrinsic::x86_avx_vtestz_ps:
9437 case Intrinsic::x86_avx_vtestc_ps:
9438 case Intrinsic::x86_avx_vtestnzc_ps:
9439 case Intrinsic::x86_avx_vtestz_pd:
9440 case Intrinsic::x86_avx_vtestc_pd:
9441 case Intrinsic::x86_avx_vtestnzc_pd:
9442 case Intrinsic::x86_avx_vtestz_ps_256:
9443 case Intrinsic::x86_avx_vtestc_ps_256:
9444 case Intrinsic::x86_avx_vtestnzc_ps_256:
9445 case Intrinsic::x86_avx_vtestz_pd_256:
9446 case Intrinsic::x86_avx_vtestc_pd_256:
9447 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9448 bool IsTestPacked = false;
9451 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9452 case Intrinsic::x86_avx_vtestz_ps:
9453 case Intrinsic::x86_avx_vtestz_pd:
9454 case Intrinsic::x86_avx_vtestz_ps_256:
9455 case Intrinsic::x86_avx_vtestz_pd_256:
9456 IsTestPacked = true; // Fallthrough
9457 case Intrinsic::x86_sse41_ptestz:
9458 case Intrinsic::x86_avx_ptestz_256:
9460 X86CC = X86::COND_E;
9462 case Intrinsic::x86_avx_vtestc_ps:
9463 case Intrinsic::x86_avx_vtestc_pd:
9464 case Intrinsic::x86_avx_vtestc_ps_256:
9465 case Intrinsic::x86_avx_vtestc_pd_256:
9466 IsTestPacked = true; // Fallthrough
9467 case Intrinsic::x86_sse41_ptestc:
9468 case Intrinsic::x86_avx_ptestc_256:
9470 X86CC = X86::COND_B;
9472 case Intrinsic::x86_avx_vtestnzc_ps:
9473 case Intrinsic::x86_avx_vtestnzc_pd:
9474 case Intrinsic::x86_avx_vtestnzc_ps_256:
9475 case Intrinsic::x86_avx_vtestnzc_pd_256:
9476 IsTestPacked = true; // Fallthrough
9477 case Intrinsic::x86_sse41_ptestnzc:
9478 case Intrinsic::x86_avx_ptestnzc_256:
9480 X86CC = X86::COND_A;
9484 SDValue LHS = Op.getOperand(1);
9485 SDValue RHS = Op.getOperand(2);
9486 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9487 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9488 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9489 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9490 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9493 // Fix vector shift instructions where the last operand is a non-immediate
9495 case Intrinsic::x86_sse2_pslli_w:
9496 case Intrinsic::x86_sse2_pslli_d:
9497 case Intrinsic::x86_sse2_pslli_q:
9498 case Intrinsic::x86_sse2_psrli_w:
9499 case Intrinsic::x86_sse2_psrli_d:
9500 case Intrinsic::x86_sse2_psrli_q:
9501 case Intrinsic::x86_sse2_psrai_w:
9502 case Intrinsic::x86_sse2_psrai_d:
9503 case Intrinsic::x86_mmx_pslli_w:
9504 case Intrinsic::x86_mmx_pslli_d:
9505 case Intrinsic::x86_mmx_pslli_q:
9506 case Intrinsic::x86_mmx_psrli_w:
9507 case Intrinsic::x86_mmx_psrli_d:
9508 case Intrinsic::x86_mmx_psrli_q:
9509 case Intrinsic::x86_mmx_psrai_w:
9510 case Intrinsic::x86_mmx_psrai_d: {
9511 SDValue ShAmt = Op.getOperand(2);
9512 if (isa<ConstantSDNode>(ShAmt))
9515 unsigned NewIntNo = 0;
9516 EVT ShAmtVT = MVT::v4i32;
9518 case Intrinsic::x86_sse2_pslli_w:
9519 NewIntNo = Intrinsic::x86_sse2_psll_w;
9521 case Intrinsic::x86_sse2_pslli_d:
9522 NewIntNo = Intrinsic::x86_sse2_psll_d;
9524 case Intrinsic::x86_sse2_pslli_q:
9525 NewIntNo = Intrinsic::x86_sse2_psll_q;
9527 case Intrinsic::x86_sse2_psrli_w:
9528 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9530 case Intrinsic::x86_sse2_psrli_d:
9531 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9533 case Intrinsic::x86_sse2_psrli_q:
9534 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9536 case Intrinsic::x86_sse2_psrai_w:
9537 NewIntNo = Intrinsic::x86_sse2_psra_w;
9539 case Intrinsic::x86_sse2_psrai_d:
9540 NewIntNo = Intrinsic::x86_sse2_psra_d;
9543 ShAmtVT = MVT::v2i32;
9545 case Intrinsic::x86_mmx_pslli_w:
9546 NewIntNo = Intrinsic::x86_mmx_psll_w;
9548 case Intrinsic::x86_mmx_pslli_d:
9549 NewIntNo = Intrinsic::x86_mmx_psll_d;
9551 case Intrinsic::x86_mmx_pslli_q:
9552 NewIntNo = Intrinsic::x86_mmx_psll_q;
9554 case Intrinsic::x86_mmx_psrli_w:
9555 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9557 case Intrinsic::x86_mmx_psrli_d:
9558 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9560 case Intrinsic::x86_mmx_psrli_q:
9561 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9563 case Intrinsic::x86_mmx_psrai_w:
9564 NewIntNo = Intrinsic::x86_mmx_psra_w;
9566 case Intrinsic::x86_mmx_psrai_d:
9567 NewIntNo = Intrinsic::x86_mmx_psra_d;
9569 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9575 // The vector shift intrinsics with scalars uses 32b shift amounts but
9576 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9580 ShOps[1] = DAG.getConstant(0, MVT::i32);
9581 if (ShAmtVT == MVT::v4i32) {
9582 ShOps[2] = DAG.getUNDEF(MVT::i32);
9583 ShOps[3] = DAG.getUNDEF(MVT::i32);
9584 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9586 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9587 // FIXME this must be lowered to get rid of the invalid type.
9590 EVT VT = Op.getValueType();
9591 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9592 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9593 DAG.getConstant(NewIntNo, MVT::i32),
9594 Op.getOperand(1), ShAmt);
9599 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9600 SelectionDAG &DAG) const {
9601 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9602 MFI->setReturnAddressIsTaken(true);
9604 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9605 DebugLoc dl = Op.getDebugLoc();
9608 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9610 DAG.getConstant(TD->getPointerSize(),
9611 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9612 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9613 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9615 MachinePointerInfo(), false, false, false, 0);
9618 // Just load the return address.
9619 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9620 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9621 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9624 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9625 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9626 MFI->setFrameAddressIsTaken(true);
9628 EVT VT = Op.getValueType();
9629 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9630 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9631 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9632 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9634 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9635 MachinePointerInfo(),
9636 false, false, false, 0);
9640 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9641 SelectionDAG &DAG) const {
9642 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9646 MachineFunction &MF = DAG.getMachineFunction();
9647 SDValue Chain = Op.getOperand(0);
9648 SDValue Offset = Op.getOperand(1);
9649 SDValue Handler = Op.getOperand(2);
9650 DebugLoc dl = Op.getDebugLoc();
9652 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9653 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9655 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9657 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9658 DAG.getIntPtrConstant(TD->getPointerSize()));
9659 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9660 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9662 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9663 MF.getRegInfo().addLiveOut(StoreAddrReg);
9665 return DAG.getNode(X86ISD::EH_RETURN, dl,
9667 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9670 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9671 SelectionDAG &DAG) const {
9672 return Op.getOperand(0);
9675 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9676 SelectionDAG &DAG) const {
9677 SDValue Root = Op.getOperand(0);
9678 SDValue Trmp = Op.getOperand(1); // trampoline
9679 SDValue FPtr = Op.getOperand(2); // nested function
9680 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9681 DebugLoc dl = Op.getDebugLoc();
9683 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9685 if (Subtarget->is64Bit()) {
9686 SDValue OutChains[6];
9688 // Large code-model.
9689 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9690 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9692 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9693 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9695 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9697 // Load the pointer to the nested function into R11.
9698 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9699 SDValue Addr = Trmp;
9700 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9701 Addr, MachinePointerInfo(TrmpAddr),
9704 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9705 DAG.getConstant(2, MVT::i64));
9706 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9707 MachinePointerInfo(TrmpAddr, 2),
9710 // Load the 'nest' parameter value into R10.
9711 // R10 is specified in X86CallingConv.td
9712 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9713 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9714 DAG.getConstant(10, MVT::i64));
9715 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9716 Addr, MachinePointerInfo(TrmpAddr, 10),
9719 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9720 DAG.getConstant(12, MVT::i64));
9721 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9722 MachinePointerInfo(TrmpAddr, 12),
9725 // Jump to the nested function.
9726 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9727 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9728 DAG.getConstant(20, MVT::i64));
9729 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9730 Addr, MachinePointerInfo(TrmpAddr, 20),
9733 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9734 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9735 DAG.getConstant(22, MVT::i64));
9736 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9737 MachinePointerInfo(TrmpAddr, 22),
9740 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9742 const Function *Func =
9743 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9744 CallingConv::ID CC = Func->getCallingConv();
9749 llvm_unreachable("Unsupported calling convention");
9750 case CallingConv::C:
9751 case CallingConv::X86_StdCall: {
9752 // Pass 'nest' parameter in ECX.
9753 // Must be kept in sync with X86CallingConv.td
9756 // Check that ECX wasn't needed by an 'inreg' parameter.
9757 FunctionType *FTy = Func->getFunctionType();
9758 const AttrListPtr &Attrs = Func->getAttributes();
9760 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9761 unsigned InRegCount = 0;
9764 for (FunctionType::param_iterator I = FTy->param_begin(),
9765 E = FTy->param_end(); I != E; ++I, ++Idx)
9766 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9767 // FIXME: should only count parameters that are lowered to integers.
9768 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9770 if (InRegCount > 2) {
9771 report_fatal_error("Nest register in use - reduce number of inreg"
9777 case CallingConv::X86_FastCall:
9778 case CallingConv::X86_ThisCall:
9779 case CallingConv::Fast:
9780 // Pass 'nest' parameter in EAX.
9781 // Must be kept in sync with X86CallingConv.td
9786 SDValue OutChains[4];
9789 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9790 DAG.getConstant(10, MVT::i32));
9791 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9793 // This is storing the opcode for MOV32ri.
9794 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9795 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9796 OutChains[0] = DAG.getStore(Root, dl,
9797 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9798 Trmp, MachinePointerInfo(TrmpAddr),
9801 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9802 DAG.getConstant(1, MVT::i32));
9803 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9804 MachinePointerInfo(TrmpAddr, 1),
9807 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9808 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9809 DAG.getConstant(5, MVT::i32));
9810 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9811 MachinePointerInfo(TrmpAddr, 5),
9814 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9815 DAG.getConstant(6, MVT::i32));
9816 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9817 MachinePointerInfo(TrmpAddr, 6),
9820 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9824 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9825 SelectionDAG &DAG) const {
9827 The rounding mode is in bits 11:10 of FPSR, and has the following
9834 FLT_ROUNDS, on the other hand, expects the following:
9841 To perform the conversion, we do:
9842 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9845 MachineFunction &MF = DAG.getMachineFunction();
9846 const TargetMachine &TM = MF.getTarget();
9847 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9848 unsigned StackAlignment = TFI.getStackAlignment();
9849 EVT VT = Op.getValueType();
9850 DebugLoc DL = Op.getDebugLoc();
9852 // Save FP Control Word to stack slot
9853 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9854 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9857 MachineMemOperand *MMO =
9858 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9859 MachineMemOperand::MOStore, 2, 2);
9861 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9862 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9863 DAG.getVTList(MVT::Other),
9864 Ops, 2, MVT::i16, MMO);
9866 // Load FP Control Word from stack slot
9867 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9868 MachinePointerInfo(), false, false, false, 0);
9870 // Transform as necessary
9872 DAG.getNode(ISD::SRL, DL, MVT::i16,
9873 DAG.getNode(ISD::AND, DL, MVT::i16,
9874 CWD, DAG.getConstant(0x800, MVT::i16)),
9875 DAG.getConstant(11, MVT::i8));
9877 DAG.getNode(ISD::SRL, DL, MVT::i16,
9878 DAG.getNode(ISD::AND, DL, MVT::i16,
9879 CWD, DAG.getConstant(0x400, MVT::i16)),
9880 DAG.getConstant(9, MVT::i8));
9883 DAG.getNode(ISD::AND, DL, MVT::i16,
9884 DAG.getNode(ISD::ADD, DL, MVT::i16,
9885 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9886 DAG.getConstant(1, MVT::i16)),
9887 DAG.getConstant(3, MVT::i16));
9890 return DAG.getNode((VT.getSizeInBits() < 16 ?
9891 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9894 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9895 EVT VT = Op.getValueType();
9897 unsigned NumBits = VT.getSizeInBits();
9898 DebugLoc dl = Op.getDebugLoc();
9900 Op = Op.getOperand(0);
9901 if (VT == MVT::i8) {
9902 // Zero extend to i32 since there is not an i8 bsr.
9904 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9907 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9908 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9909 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9911 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9914 DAG.getConstant(NumBits+NumBits-1, OpVT),
9915 DAG.getConstant(X86::COND_E, MVT::i8),
9918 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9920 // Finally xor with NumBits-1.
9921 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9924 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9928 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9929 EVT VT = Op.getValueType();
9931 unsigned NumBits = VT.getSizeInBits();
9932 DebugLoc dl = Op.getDebugLoc();
9934 Op = Op.getOperand(0);
9935 if (VT == MVT::i8) {
9937 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9940 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9941 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9942 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9944 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9947 DAG.getConstant(NumBits, OpVT),
9948 DAG.getConstant(X86::COND_E, MVT::i8),
9951 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9954 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9958 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9959 // ones, and then concatenate the result back.
9960 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9961 EVT VT = Op.getValueType();
9963 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9964 "Unsupported value type for operation");
9966 int NumElems = VT.getVectorNumElements();
9967 DebugLoc dl = Op.getDebugLoc();
9968 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9969 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9971 // Extract the LHS vectors
9972 SDValue LHS = Op.getOperand(0);
9973 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9974 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9976 // Extract the RHS vectors
9977 SDValue RHS = Op.getOperand(1);
9978 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9979 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9981 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9982 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9984 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9985 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9986 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9989 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9990 assert(Op.getValueType().getSizeInBits() == 256 &&
9991 Op.getValueType().isInteger() &&
9992 "Only handle AVX 256-bit vector integer operation");
9993 return Lower256IntArith(Op, DAG);
9996 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9997 assert(Op.getValueType().getSizeInBits() == 256 &&
9998 Op.getValueType().isInteger() &&
9999 "Only handle AVX 256-bit vector integer operation");
10000 return Lower256IntArith(Op, DAG);
10003 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10004 EVT VT = Op.getValueType();
10006 // Decompose 256-bit ops into smaller 128-bit ops.
10007 if (VT.getSizeInBits() == 256)
10008 return Lower256IntArith(Op, DAG);
10010 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10011 DebugLoc dl = Op.getDebugLoc();
10013 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10014 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10015 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10016 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10017 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10019 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10020 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10021 // return AloBlo + AloBhi + AhiBlo;
10023 SDValue A = Op.getOperand(0);
10024 SDValue B = Op.getOperand(1);
10026 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10027 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10028 A, DAG.getConstant(32, MVT::i32));
10029 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10030 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10031 B, DAG.getConstant(32, MVT::i32));
10032 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10033 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10035 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10036 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10038 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10039 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10041 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10042 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10043 AloBhi, DAG.getConstant(32, MVT::i32));
10044 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10045 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10046 AhiBlo, DAG.getConstant(32, MVT::i32));
10047 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10048 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10052 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10054 EVT VT = Op.getValueType();
10055 DebugLoc dl = Op.getDebugLoc();
10056 SDValue R = Op.getOperand(0);
10057 SDValue Amt = Op.getOperand(1);
10058 LLVMContext *Context = DAG.getContext();
10060 if (!Subtarget->hasXMMInt())
10063 // Decompose 256-bit shifts into smaller 128-bit shifts.
10064 if (VT.getSizeInBits() == 256) {
10065 int NumElems = VT.getVectorNumElements();
10066 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10067 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10069 // Extract the two vectors
10070 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10071 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10074 // Recreate the shift amount vectors
10075 SDValue Amt1, Amt2;
10076 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10077 // Constant shift amount
10078 SmallVector<SDValue, 4> Amt1Csts;
10079 SmallVector<SDValue, 4> Amt2Csts;
10080 for (int i = 0; i < NumElems/2; ++i)
10081 Amt1Csts.push_back(Amt->getOperand(i));
10082 for (int i = NumElems/2; i < NumElems; ++i)
10083 Amt2Csts.push_back(Amt->getOperand(i));
10085 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10086 &Amt1Csts[0], NumElems/2);
10087 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10088 &Amt2Csts[0], NumElems/2);
10090 // Variable shift amount
10091 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10092 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10096 // Issue new vector shifts for the smaller types
10097 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10098 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10100 // Concatenate the result back
10101 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10104 // Optimize shl/srl/sra with constant shift amount.
10105 if (isSplatVector(Amt.getNode())) {
10106 SDValue SclrAmt = Amt->getOperand(0);
10107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10108 uint64_t ShiftAmt = C->getZExtValue();
10110 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10111 // Make a large shift.
10113 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10114 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10115 R, DAG.getConstant(ShiftAmt, MVT::i32));
10116 // Zero out the rightmost bits.
10117 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10119 return DAG.getNode(ISD::AND, dl, VT, SHL,
10120 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10123 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10124 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10125 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10126 R, DAG.getConstant(ShiftAmt, MVT::i32));
10128 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10129 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10130 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10131 R, DAG.getConstant(ShiftAmt, MVT::i32));
10133 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10134 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10135 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10136 R, DAG.getConstant(ShiftAmt, MVT::i32));
10138 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10139 // Make a large shift.
10141 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10142 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10143 R, DAG.getConstant(ShiftAmt, MVT::i32));
10144 // Zero out the leftmost bits.
10145 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10147 return DAG.getNode(ISD::AND, dl, VT, SRL,
10148 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10151 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10152 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10153 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10154 R, DAG.getConstant(ShiftAmt, MVT::i32));
10156 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10157 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10158 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10159 R, DAG.getConstant(ShiftAmt, MVT::i32));
10161 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10162 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10163 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10164 R, DAG.getConstant(ShiftAmt, MVT::i32));
10166 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10167 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10168 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10169 R, DAG.getConstant(ShiftAmt, MVT::i32));
10171 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10172 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10173 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10174 R, DAG.getConstant(ShiftAmt, MVT::i32));
10176 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10177 if (ShiftAmt == 7) {
10178 // R s>> 7 === R s< 0
10179 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10180 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10183 // R s>> a === ((R u>> a) ^ m) - m
10184 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10185 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10187 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10188 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10189 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10195 // Lower SHL with variable shift amount.
10196 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10197 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10198 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10199 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10201 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10203 std::vector<Constant*> CV(4, CI);
10204 Constant *C = ConstantVector::get(CV);
10205 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10206 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10207 MachinePointerInfo::getConstantPool(),
10208 false, false, false, 16);
10210 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10211 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10212 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10213 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10215 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10217 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10218 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10219 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10221 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10222 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10224 std::vector<Constant*> CVM1(16, CM1);
10225 std::vector<Constant*> CVM2(16, CM2);
10226 Constant *C = ConstantVector::get(CVM1);
10227 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10228 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10229 MachinePointerInfo::getConstantPool(),
10230 false, false, false, 16);
10232 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10233 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10234 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10235 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10236 DAG.getConstant(4, MVT::i32));
10237 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10239 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10241 C = ConstantVector::get(CVM2);
10242 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10243 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10244 MachinePointerInfo::getConstantPool(),
10245 false, false, false, 16);
10247 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10248 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10249 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10250 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10251 DAG.getConstant(2, MVT::i32));
10252 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10254 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10256 // return pblendv(r, r+r, a);
10257 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10258 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10264 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10265 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10266 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10267 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10268 // has only one use.
10269 SDNode *N = Op.getNode();
10270 SDValue LHS = N->getOperand(0);
10271 SDValue RHS = N->getOperand(1);
10272 unsigned BaseOp = 0;
10274 DebugLoc DL = Op.getDebugLoc();
10275 switch (Op.getOpcode()) {
10276 default: llvm_unreachable("Unknown ovf instruction!");
10278 // A subtract of one will be selected as a INC. Note that INC doesn't
10279 // set CF, so we can't do this for UADDO.
10280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10282 BaseOp = X86ISD::INC;
10283 Cond = X86::COND_O;
10286 BaseOp = X86ISD::ADD;
10287 Cond = X86::COND_O;
10290 BaseOp = X86ISD::ADD;
10291 Cond = X86::COND_B;
10294 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10295 // set CF, so we can't do this for USUBO.
10296 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10298 BaseOp = X86ISD::DEC;
10299 Cond = X86::COND_O;
10302 BaseOp = X86ISD::SUB;
10303 Cond = X86::COND_O;
10306 BaseOp = X86ISD::SUB;
10307 Cond = X86::COND_B;
10310 BaseOp = X86ISD::SMUL;
10311 Cond = X86::COND_O;
10313 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10314 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10316 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10319 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10320 DAG.getConstant(X86::COND_O, MVT::i32),
10321 SDValue(Sum.getNode(), 2));
10323 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10327 // Also sets EFLAGS.
10328 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10329 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10332 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10333 DAG.getConstant(Cond, MVT::i32),
10334 SDValue(Sum.getNode(), 1));
10336 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10339 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10340 DebugLoc dl = Op.getDebugLoc();
10341 SDNode* Node = Op.getNode();
10342 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10343 EVT VT = Node->getValueType(0);
10344 if (Subtarget->hasXMMInt() && VT.isVector()) {
10345 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10346 ExtraVT.getScalarType().getSizeInBits();
10347 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10349 unsigned SHLIntrinsicsID = 0;
10350 unsigned SRAIntrinsicsID = 0;
10351 switch (VT.getSimpleVT().SimpleTy) {
10355 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10356 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10360 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10361 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10366 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10367 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10368 Node->getOperand(0), ShAmt);
10370 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10371 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10379 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10380 DebugLoc dl = Op.getDebugLoc();
10382 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10383 // There isn't any reason to disable it if the target processor supports it.
10384 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10385 SDValue Chain = Op.getOperand(0);
10386 SDValue Zero = DAG.getConstant(0, MVT::i32);
10388 DAG.getRegister(X86::ESP, MVT::i32), // Base
10389 DAG.getTargetConstant(1, MVT::i8), // Scale
10390 DAG.getRegister(0, MVT::i32), // Index
10391 DAG.getTargetConstant(0, MVT::i32), // Disp
10392 DAG.getRegister(0, MVT::i32), // Segment.
10397 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10398 array_lengthof(Ops));
10399 return SDValue(Res, 0);
10402 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10404 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10406 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10407 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10408 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10409 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10411 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10412 if (!Op1 && !Op2 && !Op3 && Op4)
10413 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10415 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10416 if (Op1 && !Op2 && !Op3 && !Op4)
10417 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10419 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10421 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10424 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10425 SelectionDAG &DAG) const {
10426 DebugLoc dl = Op.getDebugLoc();
10427 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10428 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10429 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10430 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10432 // The only fence that needs an instruction is a sequentially-consistent
10433 // cross-thread fence.
10434 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10435 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10436 // no-sse2). There isn't any reason to disable it if the target processor
10438 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10439 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10441 SDValue Chain = Op.getOperand(0);
10442 SDValue Zero = DAG.getConstant(0, MVT::i32);
10444 DAG.getRegister(X86::ESP, MVT::i32), // Base
10445 DAG.getTargetConstant(1, MVT::i8), // Scale
10446 DAG.getRegister(0, MVT::i32), // Index
10447 DAG.getTargetConstant(0, MVT::i32), // Disp
10448 DAG.getRegister(0, MVT::i32), // Segment.
10453 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10454 array_lengthof(Ops));
10455 return SDValue(Res, 0);
10458 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10459 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10463 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10464 EVT T = Op.getValueType();
10465 DebugLoc DL = Op.getDebugLoc();
10468 switch(T.getSimpleVT().SimpleTy) {
10470 assert(false && "Invalid value type!");
10471 case MVT::i8: Reg = X86::AL; size = 1; break;
10472 case MVT::i16: Reg = X86::AX; size = 2; break;
10473 case MVT::i32: Reg = X86::EAX; size = 4; break;
10475 assert(Subtarget->is64Bit() && "Node not type legal!");
10476 Reg = X86::RAX; size = 8;
10479 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10480 Op.getOperand(2), SDValue());
10481 SDValue Ops[] = { cpIn.getValue(0),
10484 DAG.getTargetConstant(size, MVT::i8),
10485 cpIn.getValue(1) };
10486 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10487 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10488 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10491 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10495 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10496 SelectionDAG &DAG) const {
10497 assert(Subtarget->is64Bit() && "Result not type legalized?");
10498 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10499 SDValue TheChain = Op.getOperand(0);
10500 DebugLoc dl = Op.getDebugLoc();
10501 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10502 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10503 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10505 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10506 DAG.getConstant(32, MVT::i8));
10508 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10511 return DAG.getMergeValues(Ops, 2, dl);
10514 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10515 SelectionDAG &DAG) const {
10516 EVT SrcVT = Op.getOperand(0).getValueType();
10517 EVT DstVT = Op.getValueType();
10518 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10519 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10520 assert((DstVT == MVT::i64 ||
10521 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10522 "Unexpected custom BITCAST");
10523 // i64 <=> MMX conversions are Legal.
10524 if (SrcVT==MVT::i64 && DstVT.isVector())
10526 if (DstVT==MVT::i64 && SrcVT.isVector())
10528 // MMX <=> MMX conversions are Legal.
10529 if (SrcVT.isVector() && DstVT.isVector())
10531 // All other conversions need to be expanded.
10535 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10536 SDNode *Node = Op.getNode();
10537 DebugLoc dl = Node->getDebugLoc();
10538 EVT T = Node->getValueType(0);
10539 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10540 DAG.getConstant(0, T), Node->getOperand(2));
10541 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10542 cast<AtomicSDNode>(Node)->getMemoryVT(),
10543 Node->getOperand(0),
10544 Node->getOperand(1), negOp,
10545 cast<AtomicSDNode>(Node)->getSrcValue(),
10546 cast<AtomicSDNode>(Node)->getAlignment(),
10547 cast<AtomicSDNode>(Node)->getOrdering(),
10548 cast<AtomicSDNode>(Node)->getSynchScope());
10551 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10552 SDNode *Node = Op.getNode();
10553 DebugLoc dl = Node->getDebugLoc();
10554 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10556 // Convert seq_cst store -> xchg
10557 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10558 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10559 // (The only way to get a 16-byte store is cmpxchg16b)
10560 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10561 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10562 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10563 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10564 cast<AtomicSDNode>(Node)->getMemoryVT(),
10565 Node->getOperand(0),
10566 Node->getOperand(1), Node->getOperand(2),
10567 cast<AtomicSDNode>(Node)->getMemOperand(),
10568 cast<AtomicSDNode>(Node)->getOrdering(),
10569 cast<AtomicSDNode>(Node)->getSynchScope());
10570 return Swap.getValue(1);
10572 // Other atomic stores have a simple pattern.
10576 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10577 EVT VT = Op.getNode()->getValueType(0);
10579 // Let legalize expand this if it isn't a legal type yet.
10580 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10583 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10586 bool ExtraOp = false;
10587 switch (Op.getOpcode()) {
10588 default: assert(0 && "Invalid code");
10589 case ISD::ADDC: Opc = X86ISD::ADD; break;
10590 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10591 case ISD::SUBC: Opc = X86ISD::SUB; break;
10592 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10596 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10598 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10599 Op.getOperand(1), Op.getOperand(2));
10602 /// LowerOperation - Provide custom lowering hooks for some operations.
10604 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10605 switch (Op.getOpcode()) {
10606 default: llvm_unreachable("Should not custom lower this!");
10607 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10608 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10609 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10610 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10611 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10612 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10613 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10614 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10615 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10616 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10617 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10618 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10619 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10620 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10621 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10622 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10623 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10624 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10625 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10626 case ISD::SHL_PARTS:
10627 case ISD::SRA_PARTS:
10628 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10629 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10630 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10631 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10632 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10633 case ISD::FABS: return LowerFABS(Op, DAG);
10634 case ISD::FNEG: return LowerFNEG(Op, DAG);
10635 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10636 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10637 case ISD::SETCC: return LowerSETCC(Op, DAG);
10638 case ISD::SELECT: return LowerSELECT(Op, DAG);
10639 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10640 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10641 case ISD::VASTART: return LowerVASTART(Op, DAG);
10642 case ISD::VAARG: return LowerVAARG(Op, DAG);
10643 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10644 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10645 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10646 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10647 case ISD::FRAME_TO_ARGS_OFFSET:
10648 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10649 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10650 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10651 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10652 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10653 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10654 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10655 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10656 case ISD::MUL: return LowerMUL(Op, DAG);
10659 case ISD::SHL: return LowerShift(Op, DAG);
10665 case ISD::UMULO: return LowerXALUO(Op, DAG);
10666 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10667 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10671 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10672 case ISD::ADD: return LowerADD(Op, DAG);
10673 case ISD::SUB: return LowerSUB(Op, DAG);
10677 static void ReplaceATOMIC_LOAD(SDNode *Node,
10678 SmallVectorImpl<SDValue> &Results,
10679 SelectionDAG &DAG) {
10680 DebugLoc dl = Node->getDebugLoc();
10681 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10683 // Convert wide load -> cmpxchg8b/cmpxchg16b
10684 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10685 // (The only way to get a 16-byte load is cmpxchg16b)
10686 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10687 SDValue Zero = DAG.getConstant(0, VT);
10688 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10689 Node->getOperand(0),
10690 Node->getOperand(1), Zero, Zero,
10691 cast<AtomicSDNode>(Node)->getMemOperand(),
10692 cast<AtomicSDNode>(Node)->getOrdering(),
10693 cast<AtomicSDNode>(Node)->getSynchScope());
10694 Results.push_back(Swap.getValue(0));
10695 Results.push_back(Swap.getValue(1));
10698 void X86TargetLowering::
10699 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10700 SelectionDAG &DAG, unsigned NewOp) const {
10701 DebugLoc dl = Node->getDebugLoc();
10702 assert (Node->getValueType(0) == MVT::i64 &&
10703 "Only know how to expand i64 atomics");
10705 SDValue Chain = Node->getOperand(0);
10706 SDValue In1 = Node->getOperand(1);
10707 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10708 Node->getOperand(2), DAG.getIntPtrConstant(0));
10709 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10710 Node->getOperand(2), DAG.getIntPtrConstant(1));
10711 SDValue Ops[] = { Chain, In1, In2L, In2H };
10712 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10714 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10715 cast<MemSDNode>(Node)->getMemOperand());
10716 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10717 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10718 Results.push_back(Result.getValue(2));
10721 /// ReplaceNodeResults - Replace a node with an illegal result type
10722 /// with a new node built out of custom code.
10723 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10724 SmallVectorImpl<SDValue>&Results,
10725 SelectionDAG &DAG) const {
10726 DebugLoc dl = N->getDebugLoc();
10727 switch (N->getOpcode()) {
10729 assert(false && "Do not know how to custom type legalize this operation!");
10731 case ISD::SIGN_EXTEND_INREG:
10736 // We don't want to expand or promote these.
10738 case ISD::FP_TO_SINT: {
10739 std::pair<SDValue,SDValue> Vals =
10740 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10741 SDValue FIST = Vals.first, StackSlot = Vals.second;
10742 if (FIST.getNode() != 0) {
10743 EVT VT = N->getValueType(0);
10744 // Return a load from the stack slot.
10745 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10746 MachinePointerInfo(),
10747 false, false, false, 0));
10751 case ISD::READCYCLECOUNTER: {
10752 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10753 SDValue TheChain = N->getOperand(0);
10754 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10755 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10757 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10759 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10760 SDValue Ops[] = { eax, edx };
10761 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10762 Results.push_back(edx.getValue(1));
10765 case ISD::ATOMIC_CMP_SWAP: {
10766 EVT T = N->getValueType(0);
10767 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10768 bool Regs64bit = T == MVT::i128;
10769 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10770 SDValue cpInL, cpInH;
10771 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10772 DAG.getConstant(0, HalfT));
10773 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10774 DAG.getConstant(1, HalfT));
10775 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10776 Regs64bit ? X86::RAX : X86::EAX,
10778 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10779 Regs64bit ? X86::RDX : X86::EDX,
10780 cpInH, cpInL.getValue(1));
10781 SDValue swapInL, swapInH;
10782 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10783 DAG.getConstant(0, HalfT));
10784 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10785 DAG.getConstant(1, HalfT));
10786 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10787 Regs64bit ? X86::RBX : X86::EBX,
10788 swapInL, cpInH.getValue(1));
10789 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10790 Regs64bit ? X86::RCX : X86::ECX,
10791 swapInH, swapInL.getValue(1));
10792 SDValue Ops[] = { swapInH.getValue(0),
10794 swapInH.getValue(1) };
10795 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10796 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10797 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10798 X86ISD::LCMPXCHG8_DAG;
10799 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10801 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10802 Regs64bit ? X86::RAX : X86::EAX,
10803 HalfT, Result.getValue(1));
10804 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10805 Regs64bit ? X86::RDX : X86::EDX,
10806 HalfT, cpOutL.getValue(2));
10807 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10808 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10809 Results.push_back(cpOutH.getValue(1));
10812 case ISD::ATOMIC_LOAD_ADD:
10813 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10815 case ISD::ATOMIC_LOAD_AND:
10816 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10818 case ISD::ATOMIC_LOAD_NAND:
10819 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10821 case ISD::ATOMIC_LOAD_OR:
10822 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10824 case ISD::ATOMIC_LOAD_SUB:
10825 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10827 case ISD::ATOMIC_LOAD_XOR:
10828 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10830 case ISD::ATOMIC_SWAP:
10831 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10833 case ISD::ATOMIC_LOAD:
10834 ReplaceATOMIC_LOAD(N, Results, DAG);
10838 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10840 default: return NULL;
10841 case X86ISD::BSF: return "X86ISD::BSF";
10842 case X86ISD::BSR: return "X86ISD::BSR";
10843 case X86ISD::SHLD: return "X86ISD::SHLD";
10844 case X86ISD::SHRD: return "X86ISD::SHRD";
10845 case X86ISD::FAND: return "X86ISD::FAND";
10846 case X86ISD::FOR: return "X86ISD::FOR";
10847 case X86ISD::FXOR: return "X86ISD::FXOR";
10848 case X86ISD::FSRL: return "X86ISD::FSRL";
10849 case X86ISD::FILD: return "X86ISD::FILD";
10850 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10851 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10852 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10853 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10854 case X86ISD::FLD: return "X86ISD::FLD";
10855 case X86ISD::FST: return "X86ISD::FST";
10856 case X86ISD::CALL: return "X86ISD::CALL";
10857 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10858 case X86ISD::BT: return "X86ISD::BT";
10859 case X86ISD::CMP: return "X86ISD::CMP";
10860 case X86ISD::COMI: return "X86ISD::COMI";
10861 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10862 case X86ISD::SETCC: return "X86ISD::SETCC";
10863 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10864 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10865 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10866 case X86ISD::CMOV: return "X86ISD::CMOV";
10867 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10868 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10869 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10870 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10871 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10872 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10873 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10874 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10875 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10876 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10877 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10878 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10879 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10880 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10881 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10882 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10883 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10884 case X86ISD::FMAX: return "X86ISD::FMAX";
10885 case X86ISD::FMIN: return "X86ISD::FMIN";
10886 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10887 case X86ISD::FRCP: return "X86ISD::FRCP";
10888 case X86ISD::FHADD: return "X86ISD::FHADD";
10889 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10890 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10891 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10892 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10893 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10894 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10895 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10896 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10897 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10898 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10899 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10900 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10901 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10902 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10903 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10904 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10905 case X86ISD::VSHL: return "X86ISD::VSHL";
10906 case X86ISD::VSRL: return "X86ISD::VSRL";
10907 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10908 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10909 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10910 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10911 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10912 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10913 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10914 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10915 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10916 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10917 case X86ISD::ADD: return "X86ISD::ADD";
10918 case X86ISD::SUB: return "X86ISD::SUB";
10919 case X86ISD::ADC: return "X86ISD::ADC";
10920 case X86ISD::SBB: return "X86ISD::SBB";
10921 case X86ISD::SMUL: return "X86ISD::SMUL";
10922 case X86ISD::UMUL: return "X86ISD::UMUL";
10923 case X86ISD::INC: return "X86ISD::INC";
10924 case X86ISD::DEC: return "X86ISD::DEC";
10925 case X86ISD::OR: return "X86ISD::OR";
10926 case X86ISD::XOR: return "X86ISD::XOR";
10927 case X86ISD::AND: return "X86ISD::AND";
10928 case X86ISD::ANDN: return "X86ISD::ANDN";
10929 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10930 case X86ISD::PTEST: return "X86ISD::PTEST";
10931 case X86ISD::TESTP: return "X86ISD::TESTP";
10932 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10933 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10934 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10935 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10936 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10937 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10938 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10939 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10940 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10941 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10942 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10943 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10944 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10945 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10946 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10947 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10948 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10949 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10950 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10951 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10952 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10953 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
10954 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
10955 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
10956 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
10957 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
10958 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
10959 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
10960 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
10961 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
10962 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
10963 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
10964 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
10965 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
10966 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10967 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
10968 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
10969 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
10970 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
10971 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
10972 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10973 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10974 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10975 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10976 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
10980 // isLegalAddressingMode - Return true if the addressing mode represented
10981 // by AM is legal for this target, for a load/store of the specified type.
10982 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10984 // X86 supports extremely general addressing modes.
10985 CodeModel::Model M = getTargetMachine().getCodeModel();
10986 Reloc::Model R = getTargetMachine().getRelocationModel();
10988 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10989 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10994 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10996 // If a reference to this global requires an extra load, we can't fold it.
10997 if (isGlobalStubReference(GVFlags))
11000 // If BaseGV requires a register for the PIC base, we cannot also have a
11001 // BaseReg specified.
11002 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11005 // If lower 4G is not available, then we must use rip-relative addressing.
11006 if ((M != CodeModel::Small || R != Reloc::Static) &&
11007 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11011 switch (AM.Scale) {
11017 // These scales always work.
11022 // These scales are formed with basereg+scalereg. Only accept if there is
11027 default: // Other stuff never works.
11035 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11036 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11038 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11039 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11040 if (NumBits1 <= NumBits2)
11045 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11046 if (!VT1.isInteger() || !VT2.isInteger())
11048 unsigned NumBits1 = VT1.getSizeInBits();
11049 unsigned NumBits2 = VT2.getSizeInBits();
11050 if (NumBits1 <= NumBits2)
11055 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11056 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11057 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11060 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11061 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11062 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11065 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11066 // i16 instructions are longer (0x66 prefix) and potentially slower.
11067 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11070 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11071 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11072 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11073 /// are assumed to be legal.
11075 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11077 // Very little shuffling can be done for 64-bit vectors right now.
11078 if (VT.getSizeInBits() == 64)
11079 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11081 // FIXME: pshufb, blends, shifts.
11082 return (VT.getVectorNumElements() == 2 ||
11083 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11084 isMOVLMask(M, VT) ||
11085 isSHUFPMask(M, VT) ||
11086 isPSHUFDMask(M, VT) ||
11087 isPSHUFHWMask(M, VT) ||
11088 isPSHUFLWMask(M, VT) ||
11089 isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11090 isUNPCKLMask(M, VT) ||
11091 isUNPCKHMask(M, VT) ||
11092 isUNPCKL_v_undef_Mask(M, VT) ||
11093 isUNPCKH_v_undef_Mask(M, VT));
11097 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11099 unsigned NumElts = VT.getVectorNumElements();
11100 // FIXME: This collection of masks seems suspect.
11103 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11104 return (isMOVLMask(Mask, VT) ||
11105 isCommutedMOVLMask(Mask, VT, true) ||
11106 isSHUFPMask(Mask, VT) ||
11107 isCommutedSHUFPMask(Mask, VT));
11112 //===----------------------------------------------------------------------===//
11113 // X86 Scheduler Hooks
11114 //===----------------------------------------------------------------------===//
11116 // private utility function
11117 MachineBasicBlock *
11118 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11119 MachineBasicBlock *MBB,
11126 TargetRegisterClass *RC,
11127 bool invSrc) const {
11128 // For the atomic bitwise operator, we generate
11131 // ld t1 = [bitinstr.addr]
11132 // op t2 = t1, [bitinstr.val]
11134 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11136 // fallthrough -->nextMBB
11137 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11138 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11139 MachineFunction::iterator MBBIter = MBB;
11142 /// First build the CFG
11143 MachineFunction *F = MBB->getParent();
11144 MachineBasicBlock *thisMBB = MBB;
11145 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11146 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11147 F->insert(MBBIter, newMBB);
11148 F->insert(MBBIter, nextMBB);
11150 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11151 nextMBB->splice(nextMBB->begin(), thisMBB,
11152 llvm::next(MachineBasicBlock::iterator(bInstr)),
11154 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11156 // Update thisMBB to fall through to newMBB
11157 thisMBB->addSuccessor(newMBB);
11159 // newMBB jumps to itself and fall through to nextMBB
11160 newMBB->addSuccessor(nextMBB);
11161 newMBB->addSuccessor(newMBB);
11163 // Insert instructions into newMBB based on incoming instruction
11164 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11165 "unexpected number of operands");
11166 DebugLoc dl = bInstr->getDebugLoc();
11167 MachineOperand& destOper = bInstr->getOperand(0);
11168 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11169 int numArgs = bInstr->getNumOperands() - 1;
11170 for (int i=0; i < numArgs; ++i)
11171 argOpers[i] = &bInstr->getOperand(i+1);
11173 // x86 address has 4 operands: base, index, scale, and displacement
11174 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11175 int valArgIndx = lastAddrIndx + 1;
11177 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11178 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11179 for (int i=0; i <= lastAddrIndx; ++i)
11180 (*MIB).addOperand(*argOpers[i]);
11182 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11184 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11189 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11190 assert((argOpers[valArgIndx]->isReg() ||
11191 argOpers[valArgIndx]->isImm()) &&
11192 "invalid operand");
11193 if (argOpers[valArgIndx]->isReg())
11194 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11196 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11198 (*MIB).addOperand(*argOpers[valArgIndx]);
11200 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11203 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11204 for (int i=0; i <= lastAddrIndx; ++i)
11205 (*MIB).addOperand(*argOpers[i]);
11207 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11208 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11209 bInstr->memoperands_end());
11211 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11212 MIB.addReg(EAXreg);
11215 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11217 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11221 // private utility function: 64 bit atomics on 32 bit host.
11222 MachineBasicBlock *
11223 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11224 MachineBasicBlock *MBB,
11229 bool invSrc) const {
11230 // For the atomic bitwise operator, we generate
11231 // thisMBB (instructions are in pairs, except cmpxchg8b)
11232 // ld t1,t2 = [bitinstr.addr]
11234 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11235 // op t5, t6 <- out1, out2, [bitinstr.val]
11236 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11237 // mov ECX, EBX <- t5, t6
11238 // mov EAX, EDX <- t1, t2
11239 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11240 // mov t3, t4 <- EAX, EDX
11242 // result in out1, out2
11243 // fallthrough -->nextMBB
11245 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11246 const unsigned LoadOpc = X86::MOV32rm;
11247 const unsigned NotOpc = X86::NOT32r;
11248 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11249 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11250 MachineFunction::iterator MBBIter = MBB;
11253 /// First build the CFG
11254 MachineFunction *F = MBB->getParent();
11255 MachineBasicBlock *thisMBB = MBB;
11256 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11257 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11258 F->insert(MBBIter, newMBB);
11259 F->insert(MBBIter, nextMBB);
11261 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11262 nextMBB->splice(nextMBB->begin(), thisMBB,
11263 llvm::next(MachineBasicBlock::iterator(bInstr)),
11265 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11267 // Update thisMBB to fall through to newMBB
11268 thisMBB->addSuccessor(newMBB);
11270 // newMBB jumps to itself and fall through to nextMBB
11271 newMBB->addSuccessor(nextMBB);
11272 newMBB->addSuccessor(newMBB);
11274 DebugLoc dl = bInstr->getDebugLoc();
11275 // Insert instructions into newMBB based on incoming instruction
11276 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11277 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11278 "unexpected number of operands");
11279 MachineOperand& dest1Oper = bInstr->getOperand(0);
11280 MachineOperand& dest2Oper = bInstr->getOperand(1);
11281 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11282 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11283 argOpers[i] = &bInstr->getOperand(i+2);
11285 // We use some of the operands multiple times, so conservatively just
11286 // clear any kill flags that might be present.
11287 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11288 argOpers[i]->setIsKill(false);
11291 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11292 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11294 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11295 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11296 for (int i=0; i <= lastAddrIndx; ++i)
11297 (*MIB).addOperand(*argOpers[i]);
11298 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11299 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11300 // add 4 to displacement.
11301 for (int i=0; i <= lastAddrIndx-2; ++i)
11302 (*MIB).addOperand(*argOpers[i]);
11303 MachineOperand newOp3 = *(argOpers[3]);
11304 if (newOp3.isImm())
11305 newOp3.setImm(newOp3.getImm()+4);
11307 newOp3.setOffset(newOp3.getOffset()+4);
11308 (*MIB).addOperand(newOp3);
11309 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11311 // t3/4 are defined later, at the bottom of the loop
11312 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11313 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11314 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11315 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11316 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11317 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11319 // The subsequent operations should be using the destination registers of
11320 //the PHI instructions.
11322 t1 = F->getRegInfo().createVirtualRegister(RC);
11323 t2 = F->getRegInfo().createVirtualRegister(RC);
11324 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11325 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11327 t1 = dest1Oper.getReg();
11328 t2 = dest2Oper.getReg();
11331 int valArgIndx = lastAddrIndx + 1;
11332 assert((argOpers[valArgIndx]->isReg() ||
11333 argOpers[valArgIndx]->isImm()) &&
11334 "invalid operand");
11335 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11336 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11337 if (argOpers[valArgIndx]->isReg())
11338 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11340 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11341 if (regOpcL != X86::MOV32rr)
11343 (*MIB).addOperand(*argOpers[valArgIndx]);
11344 assert(argOpers[valArgIndx + 1]->isReg() ==
11345 argOpers[valArgIndx]->isReg());
11346 assert(argOpers[valArgIndx + 1]->isImm() ==
11347 argOpers[valArgIndx]->isImm());
11348 if (argOpers[valArgIndx + 1]->isReg())
11349 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11351 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11352 if (regOpcH != X86::MOV32rr)
11354 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11356 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11358 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11361 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11363 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11366 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11367 for (int i=0; i <= lastAddrIndx; ++i)
11368 (*MIB).addOperand(*argOpers[i]);
11370 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11371 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11372 bInstr->memoperands_end());
11374 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11375 MIB.addReg(X86::EAX);
11376 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11377 MIB.addReg(X86::EDX);
11380 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11382 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11386 // private utility function
11387 MachineBasicBlock *
11388 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11389 MachineBasicBlock *MBB,
11390 unsigned cmovOpc) const {
11391 // For the atomic min/max operator, we generate
11394 // ld t1 = [min/max.addr]
11395 // mov t2 = [min/max.val]
11397 // cmov[cond] t2 = t1
11399 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11401 // fallthrough -->nextMBB
11403 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11404 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11405 MachineFunction::iterator MBBIter = MBB;
11408 /// First build the CFG
11409 MachineFunction *F = MBB->getParent();
11410 MachineBasicBlock *thisMBB = MBB;
11411 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11412 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11413 F->insert(MBBIter, newMBB);
11414 F->insert(MBBIter, nextMBB);
11416 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11417 nextMBB->splice(nextMBB->begin(), thisMBB,
11418 llvm::next(MachineBasicBlock::iterator(mInstr)),
11420 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11422 // Update thisMBB to fall through to newMBB
11423 thisMBB->addSuccessor(newMBB);
11425 // newMBB jumps to newMBB and fall through to nextMBB
11426 newMBB->addSuccessor(nextMBB);
11427 newMBB->addSuccessor(newMBB);
11429 DebugLoc dl = mInstr->getDebugLoc();
11430 // Insert instructions into newMBB based on incoming instruction
11431 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11432 "unexpected number of operands");
11433 MachineOperand& destOper = mInstr->getOperand(0);
11434 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11435 int numArgs = mInstr->getNumOperands() - 1;
11436 for (int i=0; i < numArgs; ++i)
11437 argOpers[i] = &mInstr->getOperand(i+1);
11439 // x86 address has 4 operands: base, index, scale, and displacement
11440 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11441 int valArgIndx = lastAddrIndx + 1;
11443 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11444 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11445 for (int i=0; i <= lastAddrIndx; ++i)
11446 (*MIB).addOperand(*argOpers[i]);
11448 // We only support register and immediate values
11449 assert((argOpers[valArgIndx]->isReg() ||
11450 argOpers[valArgIndx]->isImm()) &&
11451 "invalid operand");
11453 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11454 if (argOpers[valArgIndx]->isReg())
11455 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11457 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11458 (*MIB).addOperand(*argOpers[valArgIndx]);
11460 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11463 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11468 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11469 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11473 // Cmp and exchange if none has modified the memory location
11474 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11475 for (int i=0; i <= lastAddrIndx; ++i)
11476 (*MIB).addOperand(*argOpers[i]);
11478 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11479 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11480 mInstr->memoperands_end());
11482 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11483 MIB.addReg(X86::EAX);
11486 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11488 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11492 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11493 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11494 // in the .td file.
11495 MachineBasicBlock *
11496 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11497 unsigned numArgs, bool memArg) const {
11498 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11499 "Target must have SSE4.2 or AVX features enabled");
11501 DebugLoc dl = MI->getDebugLoc();
11502 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11504 if (!Subtarget->hasAVX()) {
11506 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11508 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11511 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11513 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11516 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11517 for (unsigned i = 0; i < numArgs; ++i) {
11518 MachineOperand &Op = MI->getOperand(i+1);
11519 if (!(Op.isReg() && Op.isImplicit()))
11520 MIB.addOperand(Op);
11522 BuildMI(*BB, MI, dl,
11523 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11524 MI->getOperand(0).getReg())
11525 .addReg(X86::XMM0);
11527 MI->eraseFromParent();
11531 MachineBasicBlock *
11532 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11533 DebugLoc dl = MI->getDebugLoc();
11534 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11536 // Address into RAX/EAX, other two args into ECX, EDX.
11537 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11538 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11539 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11540 for (int i = 0; i < X86::AddrNumOperands; ++i)
11541 MIB.addOperand(MI->getOperand(i));
11543 unsigned ValOps = X86::AddrNumOperands;
11544 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11545 .addReg(MI->getOperand(ValOps).getReg());
11546 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11547 .addReg(MI->getOperand(ValOps+1).getReg());
11549 // The instruction doesn't actually take any operands though.
11550 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11552 MI->eraseFromParent(); // The pseudo is gone now.
11556 MachineBasicBlock *
11557 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11558 DebugLoc dl = MI->getDebugLoc();
11559 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11561 // First arg in ECX, the second in EAX.
11562 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11563 .addReg(MI->getOperand(0).getReg());
11564 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11565 .addReg(MI->getOperand(1).getReg());
11567 // The instruction doesn't actually take any operands though.
11568 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11570 MI->eraseFromParent(); // The pseudo is gone now.
11574 MachineBasicBlock *
11575 X86TargetLowering::EmitVAARG64WithCustomInserter(
11577 MachineBasicBlock *MBB) const {
11578 // Emit va_arg instruction on X86-64.
11580 // Operands to this pseudo-instruction:
11581 // 0 ) Output : destination address (reg)
11582 // 1-5) Input : va_list address (addr, i64mem)
11583 // 6 ) ArgSize : Size (in bytes) of vararg type
11584 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11585 // 8 ) Align : Alignment of type
11586 // 9 ) EFLAGS (implicit-def)
11588 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11589 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11591 unsigned DestReg = MI->getOperand(0).getReg();
11592 MachineOperand &Base = MI->getOperand(1);
11593 MachineOperand &Scale = MI->getOperand(2);
11594 MachineOperand &Index = MI->getOperand(3);
11595 MachineOperand &Disp = MI->getOperand(4);
11596 MachineOperand &Segment = MI->getOperand(5);
11597 unsigned ArgSize = MI->getOperand(6).getImm();
11598 unsigned ArgMode = MI->getOperand(7).getImm();
11599 unsigned Align = MI->getOperand(8).getImm();
11601 // Memory Reference
11602 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11603 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11604 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11606 // Machine Information
11607 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11608 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11609 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11610 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11611 DebugLoc DL = MI->getDebugLoc();
11613 // struct va_list {
11616 // i64 overflow_area (address)
11617 // i64 reg_save_area (address)
11619 // sizeof(va_list) = 24
11620 // alignment(va_list) = 8
11622 unsigned TotalNumIntRegs = 6;
11623 unsigned TotalNumXMMRegs = 8;
11624 bool UseGPOffset = (ArgMode == 1);
11625 bool UseFPOffset = (ArgMode == 2);
11626 unsigned MaxOffset = TotalNumIntRegs * 8 +
11627 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11629 /* Align ArgSize to a multiple of 8 */
11630 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11631 bool NeedsAlign = (Align > 8);
11633 MachineBasicBlock *thisMBB = MBB;
11634 MachineBasicBlock *overflowMBB;
11635 MachineBasicBlock *offsetMBB;
11636 MachineBasicBlock *endMBB;
11638 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11639 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11640 unsigned OffsetReg = 0;
11642 if (!UseGPOffset && !UseFPOffset) {
11643 // If we only pull from the overflow region, we don't create a branch.
11644 // We don't need to alter control flow.
11645 OffsetDestReg = 0; // unused
11646 OverflowDestReg = DestReg;
11649 overflowMBB = thisMBB;
11652 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11653 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11654 // If not, pull from overflow_area. (branch to overflowMBB)
11659 // offsetMBB overflowMBB
11664 // Registers for the PHI in endMBB
11665 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11666 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11668 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11669 MachineFunction *MF = MBB->getParent();
11670 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11671 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11672 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11674 MachineFunction::iterator MBBIter = MBB;
11677 // Insert the new basic blocks
11678 MF->insert(MBBIter, offsetMBB);
11679 MF->insert(MBBIter, overflowMBB);
11680 MF->insert(MBBIter, endMBB);
11682 // Transfer the remainder of MBB and its successor edges to endMBB.
11683 endMBB->splice(endMBB->begin(), thisMBB,
11684 llvm::next(MachineBasicBlock::iterator(MI)),
11686 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11688 // Make offsetMBB and overflowMBB successors of thisMBB
11689 thisMBB->addSuccessor(offsetMBB);
11690 thisMBB->addSuccessor(overflowMBB);
11692 // endMBB is a successor of both offsetMBB and overflowMBB
11693 offsetMBB->addSuccessor(endMBB);
11694 overflowMBB->addSuccessor(endMBB);
11696 // Load the offset value into a register
11697 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11698 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11702 .addDisp(Disp, UseFPOffset ? 4 : 0)
11703 .addOperand(Segment)
11704 .setMemRefs(MMOBegin, MMOEnd);
11706 // Check if there is enough room left to pull this argument.
11707 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11709 .addImm(MaxOffset + 8 - ArgSizeA8);
11711 // Branch to "overflowMBB" if offset >= max
11712 // Fall through to "offsetMBB" otherwise
11713 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11714 .addMBB(overflowMBB);
11717 // In offsetMBB, emit code to use the reg_save_area.
11719 assert(OffsetReg != 0);
11721 // Read the reg_save_area address.
11722 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11723 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11728 .addOperand(Segment)
11729 .setMemRefs(MMOBegin, MMOEnd);
11731 // Zero-extend the offset
11732 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11733 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11736 .addImm(X86::sub_32bit);
11738 // Add the offset to the reg_save_area to get the final address.
11739 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11740 .addReg(OffsetReg64)
11741 .addReg(RegSaveReg);
11743 // Compute the offset for the next argument
11744 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11745 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11747 .addImm(UseFPOffset ? 16 : 8);
11749 // Store it back into the va_list.
11750 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11754 .addDisp(Disp, UseFPOffset ? 4 : 0)
11755 .addOperand(Segment)
11756 .addReg(NextOffsetReg)
11757 .setMemRefs(MMOBegin, MMOEnd);
11760 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11765 // Emit code to use overflow area
11768 // Load the overflow_area address into a register.
11769 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11770 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11775 .addOperand(Segment)
11776 .setMemRefs(MMOBegin, MMOEnd);
11778 // If we need to align it, do so. Otherwise, just copy the address
11779 // to OverflowDestReg.
11781 // Align the overflow address
11782 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11783 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11785 // aligned_addr = (addr + (align-1)) & ~(align-1)
11786 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11787 .addReg(OverflowAddrReg)
11790 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11792 .addImm(~(uint64_t)(Align-1));
11794 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11795 .addReg(OverflowAddrReg);
11798 // Compute the next overflow address after this argument.
11799 // (the overflow address should be kept 8-byte aligned)
11800 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11801 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11802 .addReg(OverflowDestReg)
11803 .addImm(ArgSizeA8);
11805 // Store the new overflow address.
11806 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11811 .addOperand(Segment)
11812 .addReg(NextAddrReg)
11813 .setMemRefs(MMOBegin, MMOEnd);
11815 // If we branched, emit the PHI to the front of endMBB.
11817 BuildMI(*endMBB, endMBB->begin(), DL,
11818 TII->get(X86::PHI), DestReg)
11819 .addReg(OffsetDestReg).addMBB(offsetMBB)
11820 .addReg(OverflowDestReg).addMBB(overflowMBB);
11823 // Erase the pseudo instruction
11824 MI->eraseFromParent();
11829 MachineBasicBlock *
11830 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11832 MachineBasicBlock *MBB) const {
11833 // Emit code to save XMM registers to the stack. The ABI says that the
11834 // number of registers to save is given in %al, so it's theoretically
11835 // possible to do an indirect jump trick to avoid saving all of them,
11836 // however this code takes a simpler approach and just executes all
11837 // of the stores if %al is non-zero. It's less code, and it's probably
11838 // easier on the hardware branch predictor, and stores aren't all that
11839 // expensive anyway.
11841 // Create the new basic blocks. One block contains all the XMM stores,
11842 // and one block is the final destination regardless of whether any
11843 // stores were performed.
11844 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11845 MachineFunction *F = MBB->getParent();
11846 MachineFunction::iterator MBBIter = MBB;
11848 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11849 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11850 F->insert(MBBIter, XMMSaveMBB);
11851 F->insert(MBBIter, EndMBB);
11853 // Transfer the remainder of MBB and its successor edges to EndMBB.
11854 EndMBB->splice(EndMBB->begin(), MBB,
11855 llvm::next(MachineBasicBlock::iterator(MI)),
11857 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11859 // The original block will now fall through to the XMM save block.
11860 MBB->addSuccessor(XMMSaveMBB);
11861 // The XMMSaveMBB will fall through to the end block.
11862 XMMSaveMBB->addSuccessor(EndMBB);
11864 // Now add the instructions.
11865 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11866 DebugLoc DL = MI->getDebugLoc();
11868 unsigned CountReg = MI->getOperand(0).getReg();
11869 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11870 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11872 if (!Subtarget->isTargetWin64()) {
11873 // If %al is 0, branch around the XMM save block.
11874 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11875 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11876 MBB->addSuccessor(EndMBB);
11879 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11880 // In the XMM save block, save all the XMM argument registers.
11881 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11882 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11883 MachineMemOperand *MMO =
11884 F->getMachineMemOperand(
11885 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11886 MachineMemOperand::MOStore,
11887 /*Size=*/16, /*Align=*/16);
11888 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11889 .addFrameIndex(RegSaveFrameIndex)
11890 .addImm(/*Scale=*/1)
11891 .addReg(/*IndexReg=*/0)
11892 .addImm(/*Disp=*/Offset)
11893 .addReg(/*Segment=*/0)
11894 .addReg(MI->getOperand(i).getReg())
11895 .addMemOperand(MMO);
11898 MI->eraseFromParent(); // The pseudo instruction is gone now.
11903 MachineBasicBlock *
11904 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11905 MachineBasicBlock *BB) const {
11906 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11907 DebugLoc DL = MI->getDebugLoc();
11909 // To "insert" a SELECT_CC instruction, we actually have to insert the
11910 // diamond control-flow pattern. The incoming instruction knows the
11911 // destination vreg to set, the condition code register to branch on, the
11912 // true/false values to select between, and a branch opcode to use.
11913 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11914 MachineFunction::iterator It = BB;
11920 // cmpTY ccX, r1, r2
11922 // fallthrough --> copy0MBB
11923 MachineBasicBlock *thisMBB = BB;
11924 MachineFunction *F = BB->getParent();
11925 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11926 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11927 F->insert(It, copy0MBB);
11928 F->insert(It, sinkMBB);
11930 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11931 // live into the sink and copy blocks.
11932 if (!MI->killsRegister(X86::EFLAGS)) {
11933 copy0MBB->addLiveIn(X86::EFLAGS);
11934 sinkMBB->addLiveIn(X86::EFLAGS);
11937 // Transfer the remainder of BB and its successor edges to sinkMBB.
11938 sinkMBB->splice(sinkMBB->begin(), BB,
11939 llvm::next(MachineBasicBlock::iterator(MI)),
11941 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11943 // Add the true and fallthrough blocks as its successors.
11944 BB->addSuccessor(copy0MBB);
11945 BB->addSuccessor(sinkMBB);
11947 // Create the conditional branch instruction.
11949 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11950 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11953 // %FalseValue = ...
11954 // # fallthrough to sinkMBB
11955 copy0MBB->addSuccessor(sinkMBB);
11958 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11960 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11961 TII->get(X86::PHI), MI->getOperand(0).getReg())
11962 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11963 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11965 MI->eraseFromParent(); // The pseudo instruction is gone now.
11969 MachineBasicBlock *
11970 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11971 bool Is64Bit) const {
11972 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11973 DebugLoc DL = MI->getDebugLoc();
11974 MachineFunction *MF = BB->getParent();
11975 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11977 assert(EnableSegmentedStacks);
11979 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11980 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11983 // ... [Till the alloca]
11984 // If stacklet is not large enough, jump to mallocMBB
11987 // Allocate by subtracting from RSP
11988 // Jump to continueMBB
11991 // Allocate by call to runtime
11995 // [rest of original BB]
11998 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11999 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12000 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12002 MachineRegisterInfo &MRI = MF->getRegInfo();
12003 const TargetRegisterClass *AddrRegClass =
12004 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12006 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12007 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12008 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12009 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12010 sizeVReg = MI->getOperand(1).getReg(),
12011 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12013 MachineFunction::iterator MBBIter = BB;
12016 MF->insert(MBBIter, bumpMBB);
12017 MF->insert(MBBIter, mallocMBB);
12018 MF->insert(MBBIter, continueMBB);
12020 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12021 (MachineBasicBlock::iterator(MI)), BB->end());
12022 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12024 // Add code to the main basic block to check if the stack limit has been hit,
12025 // and if so, jump to mallocMBB otherwise to bumpMBB.
12026 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12027 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12028 .addReg(tmpSPVReg).addReg(sizeVReg);
12029 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12030 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12031 .addReg(SPLimitVReg);
12032 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12034 // bumpMBB simply decreases the stack pointer, since we know the current
12035 // stacklet has enough space.
12036 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12037 .addReg(SPLimitVReg);
12038 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12039 .addReg(SPLimitVReg);
12040 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12042 // Calls into a routine in libgcc to allocate more space from the heap.
12044 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12046 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12047 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12049 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12051 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12052 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12053 .addExternalSymbol("__morestack_allocate_stack_space");
12057 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12060 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12061 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12062 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12064 // Set up the CFG correctly.
12065 BB->addSuccessor(bumpMBB);
12066 BB->addSuccessor(mallocMBB);
12067 mallocMBB->addSuccessor(continueMBB);
12068 bumpMBB->addSuccessor(continueMBB);
12070 // Take care of the PHI nodes.
12071 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12072 MI->getOperand(0).getReg())
12073 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12074 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12076 // Delete the original pseudo instruction.
12077 MI->eraseFromParent();
12080 return continueMBB;
12083 MachineBasicBlock *
12084 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12085 MachineBasicBlock *BB) const {
12086 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12087 DebugLoc DL = MI->getDebugLoc();
12089 assert(!Subtarget->isTargetEnvMacho());
12091 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12092 // non-trivial part is impdef of ESP.
12094 if (Subtarget->isTargetWin64()) {
12095 if (Subtarget->isTargetCygMing()) {
12096 // ___chkstk(Mingw64):
12097 // Clobbers R10, R11, RAX and EFLAGS.
12099 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12100 .addExternalSymbol("___chkstk")
12101 .addReg(X86::RAX, RegState::Implicit)
12102 .addReg(X86::RSP, RegState::Implicit)
12103 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12104 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12105 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12107 // __chkstk(MSVCRT): does not update stack pointer.
12108 // Clobbers R10, R11 and EFLAGS.
12109 // FIXME: RAX(allocated size) might be reused and not killed.
12110 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12111 .addExternalSymbol("__chkstk")
12112 .addReg(X86::RAX, RegState::Implicit)
12113 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12114 // RAX has the offset to subtracted from RSP.
12115 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12120 const char *StackProbeSymbol =
12121 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12123 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12124 .addExternalSymbol(StackProbeSymbol)
12125 .addReg(X86::EAX, RegState::Implicit)
12126 .addReg(X86::ESP, RegState::Implicit)
12127 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12128 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12129 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12132 MI->eraseFromParent(); // The pseudo instruction is gone now.
12136 MachineBasicBlock *
12137 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12138 MachineBasicBlock *BB) const {
12139 // This is pretty easy. We're taking the value that we received from
12140 // our load from the relocation, sticking it in either RDI (x86-64)
12141 // or EAX and doing an indirect call. The return value will then
12142 // be in the normal return register.
12143 const X86InstrInfo *TII
12144 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12145 DebugLoc DL = MI->getDebugLoc();
12146 MachineFunction *F = BB->getParent();
12148 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12149 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12151 if (Subtarget->is64Bit()) {
12152 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12153 TII->get(X86::MOV64rm), X86::RDI)
12155 .addImm(0).addReg(0)
12156 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12157 MI->getOperand(3).getTargetFlags())
12159 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12160 addDirectMem(MIB, X86::RDI);
12161 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12162 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12163 TII->get(X86::MOV32rm), X86::EAX)
12165 .addImm(0).addReg(0)
12166 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12167 MI->getOperand(3).getTargetFlags())
12169 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12170 addDirectMem(MIB, X86::EAX);
12172 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12173 TII->get(X86::MOV32rm), X86::EAX)
12174 .addReg(TII->getGlobalBaseReg(F))
12175 .addImm(0).addReg(0)
12176 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12177 MI->getOperand(3).getTargetFlags())
12179 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12180 addDirectMem(MIB, X86::EAX);
12183 MI->eraseFromParent(); // The pseudo instruction is gone now.
12187 MachineBasicBlock *
12188 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12189 MachineBasicBlock *BB) const {
12190 switch (MI->getOpcode()) {
12191 default: assert(0 && "Unexpected instr type to insert");
12192 case X86::TAILJMPd64:
12193 case X86::TAILJMPr64:
12194 case X86::TAILJMPm64:
12195 assert(0 && "TAILJMP64 would not be touched here.");
12196 case X86::TCRETURNdi64:
12197 case X86::TCRETURNri64:
12198 case X86::TCRETURNmi64:
12199 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12200 // On AMD64, additional defs should be added before register allocation.
12201 if (!Subtarget->isTargetWin64()) {
12202 MI->addRegisterDefined(X86::RSI);
12203 MI->addRegisterDefined(X86::RDI);
12204 MI->addRegisterDefined(X86::XMM6);
12205 MI->addRegisterDefined(X86::XMM7);
12206 MI->addRegisterDefined(X86::XMM8);
12207 MI->addRegisterDefined(X86::XMM9);
12208 MI->addRegisterDefined(X86::XMM10);
12209 MI->addRegisterDefined(X86::XMM11);
12210 MI->addRegisterDefined(X86::XMM12);
12211 MI->addRegisterDefined(X86::XMM13);
12212 MI->addRegisterDefined(X86::XMM14);
12213 MI->addRegisterDefined(X86::XMM15);
12216 case X86::WIN_ALLOCA:
12217 return EmitLoweredWinAlloca(MI, BB);
12218 case X86::SEG_ALLOCA_32:
12219 return EmitLoweredSegAlloca(MI, BB, false);
12220 case X86::SEG_ALLOCA_64:
12221 return EmitLoweredSegAlloca(MI, BB, true);
12222 case X86::TLSCall_32:
12223 case X86::TLSCall_64:
12224 return EmitLoweredTLSCall(MI, BB);
12225 case X86::CMOV_GR8:
12226 case X86::CMOV_FR32:
12227 case X86::CMOV_FR64:
12228 case X86::CMOV_V4F32:
12229 case X86::CMOV_V2F64:
12230 case X86::CMOV_V2I64:
12231 case X86::CMOV_V8F32:
12232 case X86::CMOV_V4F64:
12233 case X86::CMOV_V4I64:
12234 case X86::CMOV_GR16:
12235 case X86::CMOV_GR32:
12236 case X86::CMOV_RFP32:
12237 case X86::CMOV_RFP64:
12238 case X86::CMOV_RFP80:
12239 return EmitLoweredSelect(MI, BB);
12241 case X86::FP32_TO_INT16_IN_MEM:
12242 case X86::FP32_TO_INT32_IN_MEM:
12243 case X86::FP32_TO_INT64_IN_MEM:
12244 case X86::FP64_TO_INT16_IN_MEM:
12245 case X86::FP64_TO_INT32_IN_MEM:
12246 case X86::FP64_TO_INT64_IN_MEM:
12247 case X86::FP80_TO_INT16_IN_MEM:
12248 case X86::FP80_TO_INT32_IN_MEM:
12249 case X86::FP80_TO_INT64_IN_MEM: {
12250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12251 DebugLoc DL = MI->getDebugLoc();
12253 // Change the floating point control register to use "round towards zero"
12254 // mode when truncating to an integer value.
12255 MachineFunction *F = BB->getParent();
12256 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12257 addFrameReference(BuildMI(*BB, MI, DL,
12258 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12260 // Load the old value of the high byte of the control word...
12262 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12263 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12266 // Set the high part to be round to zero...
12267 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12270 // Reload the modified control word now...
12271 addFrameReference(BuildMI(*BB, MI, DL,
12272 TII->get(X86::FLDCW16m)), CWFrameIdx);
12274 // Restore the memory image of control word to original value
12275 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12278 // Get the X86 opcode to use.
12280 switch (MI->getOpcode()) {
12281 default: llvm_unreachable("illegal opcode!");
12282 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12283 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12284 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12285 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12286 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12287 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12288 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12289 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12290 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12294 MachineOperand &Op = MI->getOperand(0);
12296 AM.BaseType = X86AddressMode::RegBase;
12297 AM.Base.Reg = Op.getReg();
12299 AM.BaseType = X86AddressMode::FrameIndexBase;
12300 AM.Base.FrameIndex = Op.getIndex();
12302 Op = MI->getOperand(1);
12304 AM.Scale = Op.getImm();
12305 Op = MI->getOperand(2);
12307 AM.IndexReg = Op.getImm();
12308 Op = MI->getOperand(3);
12309 if (Op.isGlobal()) {
12310 AM.GV = Op.getGlobal();
12312 AM.Disp = Op.getImm();
12314 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12315 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12317 // Reload the original control word now.
12318 addFrameReference(BuildMI(*BB, MI, DL,
12319 TII->get(X86::FLDCW16m)), CWFrameIdx);
12321 MI->eraseFromParent(); // The pseudo instruction is gone now.
12324 // String/text processing lowering.
12325 case X86::PCMPISTRM128REG:
12326 case X86::VPCMPISTRM128REG:
12327 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12328 case X86::PCMPISTRM128MEM:
12329 case X86::VPCMPISTRM128MEM:
12330 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12331 case X86::PCMPESTRM128REG:
12332 case X86::VPCMPESTRM128REG:
12333 return EmitPCMP(MI, BB, 5, false /* in mem */);
12334 case X86::PCMPESTRM128MEM:
12335 case X86::VPCMPESTRM128MEM:
12336 return EmitPCMP(MI, BB, 5, true /* in mem */);
12338 // Thread synchronization.
12340 return EmitMonitor(MI, BB);
12342 return EmitMwait(MI, BB);
12344 // Atomic Lowering.
12345 case X86::ATOMAND32:
12346 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12347 X86::AND32ri, X86::MOV32rm,
12349 X86::NOT32r, X86::EAX,
12350 X86::GR32RegisterClass);
12351 case X86::ATOMOR32:
12352 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12353 X86::OR32ri, X86::MOV32rm,
12355 X86::NOT32r, X86::EAX,
12356 X86::GR32RegisterClass);
12357 case X86::ATOMXOR32:
12358 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12359 X86::XOR32ri, X86::MOV32rm,
12361 X86::NOT32r, X86::EAX,
12362 X86::GR32RegisterClass);
12363 case X86::ATOMNAND32:
12364 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12365 X86::AND32ri, X86::MOV32rm,
12367 X86::NOT32r, X86::EAX,
12368 X86::GR32RegisterClass, true);
12369 case X86::ATOMMIN32:
12370 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12371 case X86::ATOMMAX32:
12372 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12373 case X86::ATOMUMIN32:
12374 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12375 case X86::ATOMUMAX32:
12376 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12378 case X86::ATOMAND16:
12379 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12380 X86::AND16ri, X86::MOV16rm,
12382 X86::NOT16r, X86::AX,
12383 X86::GR16RegisterClass);
12384 case X86::ATOMOR16:
12385 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12386 X86::OR16ri, X86::MOV16rm,
12388 X86::NOT16r, X86::AX,
12389 X86::GR16RegisterClass);
12390 case X86::ATOMXOR16:
12391 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12392 X86::XOR16ri, X86::MOV16rm,
12394 X86::NOT16r, X86::AX,
12395 X86::GR16RegisterClass);
12396 case X86::ATOMNAND16:
12397 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12398 X86::AND16ri, X86::MOV16rm,
12400 X86::NOT16r, X86::AX,
12401 X86::GR16RegisterClass, true);
12402 case X86::ATOMMIN16:
12403 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12404 case X86::ATOMMAX16:
12405 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12406 case X86::ATOMUMIN16:
12407 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12408 case X86::ATOMUMAX16:
12409 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12411 case X86::ATOMAND8:
12412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12413 X86::AND8ri, X86::MOV8rm,
12415 X86::NOT8r, X86::AL,
12416 X86::GR8RegisterClass);
12418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12419 X86::OR8ri, X86::MOV8rm,
12421 X86::NOT8r, X86::AL,
12422 X86::GR8RegisterClass);
12423 case X86::ATOMXOR8:
12424 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12425 X86::XOR8ri, X86::MOV8rm,
12427 X86::NOT8r, X86::AL,
12428 X86::GR8RegisterClass);
12429 case X86::ATOMNAND8:
12430 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12431 X86::AND8ri, X86::MOV8rm,
12433 X86::NOT8r, X86::AL,
12434 X86::GR8RegisterClass, true);
12435 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12436 // This group is for 64-bit host.
12437 case X86::ATOMAND64:
12438 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12439 X86::AND64ri32, X86::MOV64rm,
12441 X86::NOT64r, X86::RAX,
12442 X86::GR64RegisterClass);
12443 case X86::ATOMOR64:
12444 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12445 X86::OR64ri32, X86::MOV64rm,
12447 X86::NOT64r, X86::RAX,
12448 X86::GR64RegisterClass);
12449 case X86::ATOMXOR64:
12450 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12451 X86::XOR64ri32, X86::MOV64rm,
12453 X86::NOT64r, X86::RAX,
12454 X86::GR64RegisterClass);
12455 case X86::ATOMNAND64:
12456 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12457 X86::AND64ri32, X86::MOV64rm,
12459 X86::NOT64r, X86::RAX,
12460 X86::GR64RegisterClass, true);
12461 case X86::ATOMMIN64:
12462 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12463 case X86::ATOMMAX64:
12464 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12465 case X86::ATOMUMIN64:
12466 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12467 case X86::ATOMUMAX64:
12468 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12470 // This group does 64-bit operations on a 32-bit host.
12471 case X86::ATOMAND6432:
12472 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12473 X86::AND32rr, X86::AND32rr,
12474 X86::AND32ri, X86::AND32ri,
12476 case X86::ATOMOR6432:
12477 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12478 X86::OR32rr, X86::OR32rr,
12479 X86::OR32ri, X86::OR32ri,
12481 case X86::ATOMXOR6432:
12482 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12483 X86::XOR32rr, X86::XOR32rr,
12484 X86::XOR32ri, X86::XOR32ri,
12486 case X86::ATOMNAND6432:
12487 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12488 X86::AND32rr, X86::AND32rr,
12489 X86::AND32ri, X86::AND32ri,
12491 case X86::ATOMADD6432:
12492 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12493 X86::ADD32rr, X86::ADC32rr,
12494 X86::ADD32ri, X86::ADC32ri,
12496 case X86::ATOMSUB6432:
12497 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12498 X86::SUB32rr, X86::SBB32rr,
12499 X86::SUB32ri, X86::SBB32ri,
12501 case X86::ATOMSWAP6432:
12502 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12503 X86::MOV32rr, X86::MOV32rr,
12504 X86::MOV32ri, X86::MOV32ri,
12506 case X86::VASTART_SAVE_XMM_REGS:
12507 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12509 case X86::VAARG_64:
12510 return EmitVAARG64WithCustomInserter(MI, BB);
12514 //===----------------------------------------------------------------------===//
12515 // X86 Optimization Hooks
12516 //===----------------------------------------------------------------------===//
12518 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12522 const SelectionDAG &DAG,
12523 unsigned Depth) const {
12524 unsigned Opc = Op.getOpcode();
12525 assert((Opc >= ISD::BUILTIN_OP_END ||
12526 Opc == ISD::INTRINSIC_WO_CHAIN ||
12527 Opc == ISD::INTRINSIC_W_CHAIN ||
12528 Opc == ISD::INTRINSIC_VOID) &&
12529 "Should use MaskedValueIsZero if you don't know whether Op"
12530 " is a target node!");
12532 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12546 // These nodes' second result is a boolean.
12547 if (Op.getResNo() == 0)
12550 case X86ISD::SETCC:
12551 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12552 Mask.getBitWidth() - 1);
12554 case ISD::INTRINSIC_WO_CHAIN: {
12555 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12556 unsigned NumLoBits = 0;
12559 case Intrinsic::x86_sse_movmsk_ps:
12560 case Intrinsic::x86_avx_movmsk_ps_256:
12561 case Intrinsic::x86_sse2_movmsk_pd:
12562 case Intrinsic::x86_avx_movmsk_pd_256:
12563 case Intrinsic::x86_mmx_pmovmskb:
12564 case Intrinsic::x86_sse2_pmovmskb_128: {
12565 // High bits of movmskp{s|d}, pmovmskb are known zero.
12567 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12568 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12569 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12570 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12571 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12572 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12574 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12575 Mask.getBitWidth() - NumLoBits);
12584 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12585 unsigned Depth) const {
12586 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12587 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12588 return Op.getValueType().getScalarType().getSizeInBits();
12594 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12595 /// node is a GlobalAddress + offset.
12596 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12597 const GlobalValue* &GA,
12598 int64_t &Offset) const {
12599 if (N->getOpcode() == X86ISD::Wrapper) {
12600 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12601 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12602 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12606 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12609 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12610 /// same as extracting the high 128-bit part of 256-bit vector and then
12611 /// inserting the result into the low part of a new 256-bit vector
12612 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12613 EVT VT = SVOp->getValueType(0);
12614 int NumElems = VT.getVectorNumElements();
12616 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12617 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12618 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12619 SVOp->getMaskElt(j) >= 0)
12625 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12626 /// same as extracting the low 128-bit part of 256-bit vector and then
12627 /// inserting the result into the high part of a new 256-bit vector
12628 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12629 EVT VT = SVOp->getValueType(0);
12630 int NumElems = VT.getVectorNumElements();
12632 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12633 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12634 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12635 SVOp->getMaskElt(j) >= 0)
12641 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12642 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12643 TargetLowering::DAGCombinerInfo &DCI) {
12644 DebugLoc dl = N->getDebugLoc();
12645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12646 SDValue V1 = SVOp->getOperand(0);
12647 SDValue V2 = SVOp->getOperand(1);
12648 EVT VT = SVOp->getValueType(0);
12649 int NumElems = VT.getVectorNumElements();
12651 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12652 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12656 // V UNDEF BUILD_VECTOR UNDEF
12658 // CONCAT_VECTOR CONCAT_VECTOR
12661 // RESULT: V + zero extended
12663 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12664 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12665 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12668 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12671 // To match the shuffle mask, the first half of the mask should
12672 // be exactly the first vector, and all the rest a splat with the
12673 // first element of the second one.
12674 for (int i = 0; i < NumElems/2; ++i)
12675 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12676 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12679 // Emit a zeroed vector and insert the desired subvector on its
12681 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12682 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12683 DAG.getConstant(0, MVT::i32), DAG, dl);
12684 return DCI.CombineTo(N, InsV);
12687 //===--------------------------------------------------------------------===//
12688 // Combine some shuffles into subvector extracts and inserts:
12691 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12692 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12693 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12695 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12696 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12697 return DCI.CombineTo(N, InsV);
12700 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12701 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12702 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12703 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12704 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12705 return DCI.CombineTo(N, InsV);
12711 /// PerformShuffleCombine - Performs several different shuffle combines.
12712 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12713 TargetLowering::DAGCombinerInfo &DCI,
12714 const X86Subtarget *Subtarget) {
12715 DebugLoc dl = N->getDebugLoc();
12716 EVT VT = N->getValueType(0);
12718 // Don't create instructions with illegal types after legalize types has run.
12719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12720 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12723 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12724 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12725 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12726 return PerformShuffleCombine256(N, DAG, DCI);
12728 // Only handle 128 wide vector from here on.
12729 if (VT.getSizeInBits() != 128)
12732 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12733 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12734 // consecutive, non-overlapping, and in the right order.
12735 SmallVector<SDValue, 16> Elts;
12736 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12737 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12739 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12742 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12743 /// generation and convert it from being a bunch of shuffles and extracts
12744 /// to a simple store and scalar loads to extract the elements.
12745 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12746 const TargetLowering &TLI) {
12747 SDValue InputVector = N->getOperand(0);
12749 // Only operate on vectors of 4 elements, where the alternative shuffling
12750 // gets to be more expensive.
12751 if (InputVector.getValueType() != MVT::v4i32)
12754 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12755 // single use which is a sign-extend or zero-extend, and all elements are
12757 SmallVector<SDNode *, 4> Uses;
12758 unsigned ExtractedElements = 0;
12759 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12760 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12761 if (UI.getUse().getResNo() != InputVector.getResNo())
12764 SDNode *Extract = *UI;
12765 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12768 if (Extract->getValueType(0) != MVT::i32)
12770 if (!Extract->hasOneUse())
12772 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12773 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12775 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12778 // Record which element was extracted.
12779 ExtractedElements |=
12780 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12782 Uses.push_back(Extract);
12785 // If not all the elements were used, this may not be worthwhile.
12786 if (ExtractedElements != 15)
12789 // Ok, we've now decided to do the transformation.
12790 DebugLoc dl = InputVector.getDebugLoc();
12792 // Store the value to a temporary stack slot.
12793 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12794 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12795 MachinePointerInfo(), false, false, 0);
12797 // Replace each use (extract) with a load of the appropriate element.
12798 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12799 UE = Uses.end(); UI != UE; ++UI) {
12800 SDNode *Extract = *UI;
12802 // cOMpute the element's address.
12803 SDValue Idx = Extract->getOperand(1);
12805 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12806 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12807 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12809 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12810 StackPtr, OffsetVal);
12812 // Load the scalar.
12813 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12814 ScalarAddr, MachinePointerInfo(),
12815 false, false, false, 0);
12817 // Replace the exact with the load.
12818 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12821 // The replacement was made in place; don't return anything.
12825 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12827 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12828 const X86Subtarget *Subtarget) {
12829 DebugLoc DL = N->getDebugLoc();
12830 SDValue Cond = N->getOperand(0);
12831 // Get the LHS/RHS of the select.
12832 SDValue LHS = N->getOperand(1);
12833 SDValue RHS = N->getOperand(2);
12834 EVT VT = LHS.getValueType();
12836 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12837 // instructions match the semantics of the common C idiom x<y?x:y but not
12838 // x<=y?x:y, because of how they handle negative zero (which can be
12839 // ignored in unsafe-math mode).
12840 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12841 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12842 (Subtarget->hasXMMInt() ||
12843 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12844 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12846 unsigned Opcode = 0;
12847 // Check for x CC y ? x : y.
12848 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12849 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12853 // Converting this to a min would handle NaNs incorrectly, and swapping
12854 // the operands would cause it to handle comparisons between positive
12855 // and negative zero incorrectly.
12856 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12857 if (!UnsafeFPMath &&
12858 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12860 std::swap(LHS, RHS);
12862 Opcode = X86ISD::FMIN;
12865 // Converting this to a min would handle comparisons between positive
12866 // and negative zero incorrectly.
12867 if (!UnsafeFPMath &&
12868 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12870 Opcode = X86ISD::FMIN;
12873 // Converting this to a min would handle both negative zeros and NaNs
12874 // incorrectly, but we can swap the operands to fix both.
12875 std::swap(LHS, RHS);
12879 Opcode = X86ISD::FMIN;
12883 // Converting this to a max would handle comparisons between positive
12884 // and negative zero incorrectly.
12885 if (!UnsafeFPMath &&
12886 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12888 Opcode = X86ISD::FMAX;
12891 // Converting this to a max would handle NaNs incorrectly, and swapping
12892 // the operands would cause it to handle comparisons between positive
12893 // and negative zero incorrectly.
12894 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12895 if (!UnsafeFPMath &&
12896 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12898 std::swap(LHS, RHS);
12900 Opcode = X86ISD::FMAX;
12903 // Converting this to a max would handle both negative zeros and NaNs
12904 // incorrectly, but we can swap the operands to fix both.
12905 std::swap(LHS, RHS);
12909 Opcode = X86ISD::FMAX;
12912 // Check for x CC y ? y : x -- a min/max with reversed arms.
12913 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12914 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12918 // Converting this to a min would handle comparisons between positive
12919 // and negative zero incorrectly, and swapping the operands would
12920 // cause it to handle NaNs incorrectly.
12921 if (!UnsafeFPMath &&
12922 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12923 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12925 std::swap(LHS, RHS);
12927 Opcode = X86ISD::FMIN;
12930 // Converting this to a min would handle NaNs incorrectly.
12931 if (!UnsafeFPMath &&
12932 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12934 Opcode = X86ISD::FMIN;
12937 // Converting this to a min would handle both negative zeros and NaNs
12938 // incorrectly, but we can swap the operands to fix both.
12939 std::swap(LHS, RHS);
12943 Opcode = X86ISD::FMIN;
12947 // Converting this to a max would handle NaNs incorrectly.
12948 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12950 Opcode = X86ISD::FMAX;
12953 // Converting this to a max would handle comparisons between positive
12954 // and negative zero incorrectly, and swapping the operands would
12955 // cause it to handle NaNs incorrectly.
12956 if (!UnsafeFPMath &&
12957 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12958 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12960 std::swap(LHS, RHS);
12962 Opcode = X86ISD::FMAX;
12965 // Converting this to a max would handle both negative zeros and NaNs
12966 // incorrectly, but we can swap the operands to fix both.
12967 std::swap(LHS, RHS);
12971 Opcode = X86ISD::FMAX;
12977 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12980 // If this is a select between two integer constants, try to do some
12982 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12983 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12984 // Don't do this for crazy integer types.
12985 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12986 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12987 // so that TrueC (the true value) is larger than FalseC.
12988 bool NeedsCondInvert = false;
12990 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12991 // Efficiently invertible.
12992 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12993 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12994 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12995 NeedsCondInvert = true;
12996 std::swap(TrueC, FalseC);
12999 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13000 if (FalseC->getAPIntValue() == 0 &&
13001 TrueC->getAPIntValue().isPowerOf2()) {
13002 if (NeedsCondInvert) // Invert the condition if needed.
13003 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13004 DAG.getConstant(1, Cond.getValueType()));
13006 // Zero extend the condition if needed.
13007 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13009 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13010 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13011 DAG.getConstant(ShAmt, MVT::i8));
13014 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13015 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13016 if (NeedsCondInvert) // Invert the condition if needed.
13017 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13018 DAG.getConstant(1, Cond.getValueType()));
13020 // Zero extend the condition if needed.
13021 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13022 FalseC->getValueType(0), Cond);
13023 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13024 SDValue(FalseC, 0));
13027 // Optimize cases that will turn into an LEA instruction. This requires
13028 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13029 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13030 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13031 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13033 bool isFastMultiplier = false;
13035 switch ((unsigned char)Diff) {
13037 case 1: // result = add base, cond
13038 case 2: // result = lea base( , cond*2)
13039 case 3: // result = lea base(cond, cond*2)
13040 case 4: // result = lea base( , cond*4)
13041 case 5: // result = lea base(cond, cond*4)
13042 case 8: // result = lea base( , cond*8)
13043 case 9: // result = lea base(cond, cond*8)
13044 isFastMultiplier = true;
13049 if (isFastMultiplier) {
13050 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13051 if (NeedsCondInvert) // Invert the condition if needed.
13052 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13053 DAG.getConstant(1, Cond.getValueType()));
13055 // Zero extend the condition if needed.
13056 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13058 // Scale the condition by the difference.
13060 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13061 DAG.getConstant(Diff, Cond.getValueType()));
13063 // Add the base if non-zero.
13064 if (FalseC->getAPIntValue() != 0)
13065 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13066 SDValue(FalseC, 0));
13076 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13077 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13078 TargetLowering::DAGCombinerInfo &DCI) {
13079 DebugLoc DL = N->getDebugLoc();
13081 // If the flag operand isn't dead, don't touch this CMOV.
13082 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13085 SDValue FalseOp = N->getOperand(0);
13086 SDValue TrueOp = N->getOperand(1);
13087 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13088 SDValue Cond = N->getOperand(3);
13089 if (CC == X86::COND_E || CC == X86::COND_NE) {
13090 switch (Cond.getOpcode()) {
13094 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13095 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13096 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13100 // If this is a select between two integer constants, try to do some
13101 // optimizations. Note that the operands are ordered the opposite of SELECT
13103 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13104 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13105 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13106 // larger than FalseC (the false value).
13107 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13108 CC = X86::GetOppositeBranchCondition(CC);
13109 std::swap(TrueC, FalseC);
13112 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13113 // This is efficient for any integer data type (including i8/i16) and
13115 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13116 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13117 DAG.getConstant(CC, MVT::i8), Cond);
13119 // Zero extend the condition if needed.
13120 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13122 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13123 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13124 DAG.getConstant(ShAmt, MVT::i8));
13125 if (N->getNumValues() == 2) // Dead flag value?
13126 return DCI.CombineTo(N, Cond, SDValue());
13130 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13131 // for any integer data type, including i8/i16.
13132 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13133 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13134 DAG.getConstant(CC, MVT::i8), Cond);
13136 // Zero extend the condition if needed.
13137 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13138 FalseC->getValueType(0), Cond);
13139 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13140 SDValue(FalseC, 0));
13142 if (N->getNumValues() == 2) // Dead flag value?
13143 return DCI.CombineTo(N, Cond, SDValue());
13147 // Optimize cases that will turn into an LEA instruction. This requires
13148 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13149 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13150 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13151 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13153 bool isFastMultiplier = false;
13155 switch ((unsigned char)Diff) {
13157 case 1: // result = add base, cond
13158 case 2: // result = lea base( , cond*2)
13159 case 3: // result = lea base(cond, cond*2)
13160 case 4: // result = lea base( , cond*4)
13161 case 5: // result = lea base(cond, cond*4)
13162 case 8: // result = lea base( , cond*8)
13163 case 9: // result = lea base(cond, cond*8)
13164 isFastMultiplier = true;
13169 if (isFastMultiplier) {
13170 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13171 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13172 DAG.getConstant(CC, MVT::i8), Cond);
13173 // Zero extend the condition if needed.
13174 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13176 // Scale the condition by the difference.
13178 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13179 DAG.getConstant(Diff, Cond.getValueType()));
13181 // Add the base if non-zero.
13182 if (FalseC->getAPIntValue() != 0)
13183 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13184 SDValue(FalseC, 0));
13185 if (N->getNumValues() == 2) // Dead flag value?
13186 return DCI.CombineTo(N, Cond, SDValue());
13196 /// PerformMulCombine - Optimize a single multiply with constant into two
13197 /// in order to implement it with two cheaper instructions, e.g.
13198 /// LEA + SHL, LEA + LEA.
13199 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13200 TargetLowering::DAGCombinerInfo &DCI) {
13201 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13204 EVT VT = N->getValueType(0);
13205 if (VT != MVT::i64)
13208 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13211 uint64_t MulAmt = C->getZExtValue();
13212 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13215 uint64_t MulAmt1 = 0;
13216 uint64_t MulAmt2 = 0;
13217 if ((MulAmt % 9) == 0) {
13219 MulAmt2 = MulAmt / 9;
13220 } else if ((MulAmt % 5) == 0) {
13222 MulAmt2 = MulAmt / 5;
13223 } else if ((MulAmt % 3) == 0) {
13225 MulAmt2 = MulAmt / 3;
13228 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13229 DebugLoc DL = N->getDebugLoc();
13231 if (isPowerOf2_64(MulAmt2) &&
13232 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13233 // If second multiplifer is pow2, issue it first. We want the multiply by
13234 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13236 std::swap(MulAmt1, MulAmt2);
13239 if (isPowerOf2_64(MulAmt1))
13240 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13241 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13243 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13244 DAG.getConstant(MulAmt1, VT));
13246 if (isPowerOf2_64(MulAmt2))
13247 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13248 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13250 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13251 DAG.getConstant(MulAmt2, VT));
13253 // Do not add new nodes to DAG combiner worklist.
13254 DCI.CombineTo(N, NewMul, false);
13259 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13260 SDValue N0 = N->getOperand(0);
13261 SDValue N1 = N->getOperand(1);
13262 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13263 EVT VT = N0.getValueType();
13265 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13266 // since the result of setcc_c is all zero's or all ones.
13267 if (VT.isInteger() && !VT.isVector() &&
13268 N1C && N0.getOpcode() == ISD::AND &&
13269 N0.getOperand(1).getOpcode() == ISD::Constant) {
13270 SDValue N00 = N0.getOperand(0);
13271 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13272 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13273 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13274 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13275 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13276 APInt ShAmt = N1C->getAPIntValue();
13277 Mask = Mask.shl(ShAmt);
13279 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13280 N00, DAG.getConstant(Mask, VT));
13285 // Hardware support for vector shifts is sparse which makes us scalarize the
13286 // vector operations in many cases. Also, on sandybridge ADD is faster than
13288 // (shl V, 1) -> add V,V
13289 if (isSplatVector(N1.getNode())) {
13290 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13292 // We shift all of the values by one. In many cases we do not have
13293 // hardware support for this operation. This is better expressed as an ADD
13295 if (N1C && (1 == N1C->getZExtValue())) {
13296 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13303 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13305 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13306 const X86Subtarget *Subtarget) {
13307 EVT VT = N->getValueType(0);
13308 if (N->getOpcode() == ISD::SHL) {
13309 SDValue V = PerformSHLCombine(N, DAG);
13310 if (V.getNode()) return V;
13313 // On X86 with SSE2 support, we can transform this to a vector shift if
13314 // all elements are shifted by the same amount. We can't do this in legalize
13315 // because the a constant vector is typically transformed to a constant pool
13316 // so we have no knowledge of the shift amount.
13317 if (!Subtarget->hasXMMInt())
13320 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13323 SDValue ShAmtOp = N->getOperand(1);
13324 EVT EltVT = VT.getVectorElementType();
13325 DebugLoc DL = N->getDebugLoc();
13326 SDValue BaseShAmt = SDValue();
13327 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13328 unsigned NumElts = VT.getVectorNumElements();
13330 for (; i != NumElts; ++i) {
13331 SDValue Arg = ShAmtOp.getOperand(i);
13332 if (Arg.getOpcode() == ISD::UNDEF) continue;
13336 for (; i != NumElts; ++i) {
13337 SDValue Arg = ShAmtOp.getOperand(i);
13338 if (Arg.getOpcode() == ISD::UNDEF) continue;
13339 if (Arg != BaseShAmt) {
13343 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13344 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13345 SDValue InVec = ShAmtOp.getOperand(0);
13346 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13347 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13349 for (; i != NumElts; ++i) {
13350 SDValue Arg = InVec.getOperand(i);
13351 if (Arg.getOpcode() == ISD::UNDEF) continue;
13355 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13357 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13358 if (C->getZExtValue() == SplatIdx)
13359 BaseShAmt = InVec.getOperand(1);
13362 if (BaseShAmt.getNode() == 0)
13363 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13364 DAG.getIntPtrConstant(0));
13368 // The shift amount is an i32.
13369 if (EltVT.bitsGT(MVT::i32))
13370 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13371 else if (EltVT.bitsLT(MVT::i32))
13372 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13374 // The shift amount is identical so we can do a vector shift.
13375 SDValue ValOp = N->getOperand(0);
13376 switch (N->getOpcode()) {
13378 llvm_unreachable("Unknown shift opcode!");
13381 if (VT == MVT::v2i64)
13382 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13383 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13385 if (VT == MVT::v4i32)
13386 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13387 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13389 if (VT == MVT::v8i16)
13390 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13391 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13395 if (VT == MVT::v4i32)
13396 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13397 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13399 if (VT == MVT::v8i16)
13400 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13401 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13405 if (VT == MVT::v2i64)
13406 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13407 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13409 if (VT == MVT::v4i32)
13410 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13411 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13413 if (VT == MVT::v8i16)
13414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13415 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13423 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13424 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13425 // and friends. Likewise for OR -> CMPNEQSS.
13426 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13427 TargetLowering::DAGCombinerInfo &DCI,
13428 const X86Subtarget *Subtarget) {
13431 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13432 // we're requiring SSE2 for both.
13433 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13434 SDValue N0 = N->getOperand(0);
13435 SDValue N1 = N->getOperand(1);
13436 SDValue CMP0 = N0->getOperand(1);
13437 SDValue CMP1 = N1->getOperand(1);
13438 DebugLoc DL = N->getDebugLoc();
13440 // The SETCCs should both refer to the same CMP.
13441 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13444 SDValue CMP00 = CMP0->getOperand(0);
13445 SDValue CMP01 = CMP0->getOperand(1);
13446 EVT VT = CMP00.getValueType();
13448 if (VT == MVT::f32 || VT == MVT::f64) {
13449 bool ExpectingFlags = false;
13450 // Check for any users that want flags:
13451 for (SDNode::use_iterator UI = N->use_begin(),
13453 !ExpectingFlags && UI != UE; ++UI)
13454 switch (UI->getOpcode()) {
13459 ExpectingFlags = true;
13461 case ISD::CopyToReg:
13462 case ISD::SIGN_EXTEND:
13463 case ISD::ZERO_EXTEND:
13464 case ISD::ANY_EXTEND:
13468 if (!ExpectingFlags) {
13469 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13470 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13472 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13473 X86::CondCode tmp = cc0;
13478 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13479 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13480 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13481 X86ISD::NodeType NTOperator = is64BitFP ?
13482 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13483 // FIXME: need symbolic constants for these magic numbers.
13484 // See X86ATTInstPrinter.cpp:printSSECC().
13485 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13486 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13487 DAG.getConstant(x86cc, MVT::i8));
13488 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13490 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13491 DAG.getConstant(1, MVT::i32));
13492 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13493 return OneBitOfTruth;
13501 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13502 /// so it can be folded inside ANDNP.
13503 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13504 EVT VT = N->getValueType(0);
13506 // Match direct AllOnes for 128 and 256-bit vectors
13507 if (ISD::isBuildVectorAllOnes(N))
13510 // Look through a bit convert.
13511 if (N->getOpcode() == ISD::BITCAST)
13512 N = N->getOperand(0).getNode();
13514 // Sometimes the operand may come from a insert_subvector building a 256-bit
13516 if (VT.getSizeInBits() == 256 &&
13517 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13518 SDValue V1 = N->getOperand(0);
13519 SDValue V2 = N->getOperand(1);
13521 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13522 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13523 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13524 ISD::isBuildVectorAllOnes(V2.getNode()))
13531 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13532 TargetLowering::DAGCombinerInfo &DCI,
13533 const X86Subtarget *Subtarget) {
13534 if (DCI.isBeforeLegalizeOps())
13537 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13541 EVT VT = N->getValueType(0);
13543 // Create ANDN, BLSI, and BLSR instructions
13544 // BLSI is X & (-X)
13545 // BLSR is X & (X-1)
13546 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13547 SDValue N0 = N->getOperand(0);
13548 SDValue N1 = N->getOperand(1);
13549 DebugLoc DL = N->getDebugLoc();
13551 // Check LHS for not
13552 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13553 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13554 // Check RHS for not
13555 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13556 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13558 // Check LHS for neg
13559 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13560 isZero(N0.getOperand(0)))
13561 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13563 // Check RHS for neg
13564 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13565 isZero(N1.getOperand(0)))
13566 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13568 // Check LHS for X-1
13569 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13570 isAllOnes(N0.getOperand(1)))
13571 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13573 // Check RHS for X-1
13574 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13575 isAllOnes(N1.getOperand(1)))
13576 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13581 // Want to form ANDNP nodes:
13582 // 1) In the hopes of then easily combining them with OR and AND nodes
13583 // to form PBLEND/PSIGN.
13584 // 2) To match ANDN packed intrinsics
13585 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13588 SDValue N0 = N->getOperand(0);
13589 SDValue N1 = N->getOperand(1);
13590 DebugLoc DL = N->getDebugLoc();
13592 // Check LHS for vnot
13593 if (N0.getOpcode() == ISD::XOR &&
13594 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13595 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13596 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13598 // Check RHS for vnot
13599 if (N1.getOpcode() == ISD::XOR &&
13600 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13601 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13602 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13607 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13608 TargetLowering::DAGCombinerInfo &DCI,
13609 const X86Subtarget *Subtarget) {
13610 if (DCI.isBeforeLegalizeOps())
13613 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13617 EVT VT = N->getValueType(0);
13618 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13621 SDValue N0 = N->getOperand(0);
13622 SDValue N1 = N->getOperand(1);
13624 // look for psign/blend
13625 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13626 if (VT == MVT::v2i64) {
13627 // Canonicalize pandn to RHS
13628 if (N0.getOpcode() == X86ISD::ANDNP)
13630 // or (and (m, x), (pandn m, y))
13631 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13632 SDValue Mask = N1.getOperand(0);
13633 SDValue X = N1.getOperand(1);
13635 if (N0.getOperand(0) == Mask)
13636 Y = N0.getOperand(1);
13637 if (N0.getOperand(1) == Mask)
13638 Y = N0.getOperand(0);
13640 // Check to see if the mask appeared in both the AND and ANDNP and
13644 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13645 if (Mask.getOpcode() != ISD::BITCAST ||
13646 X.getOpcode() != ISD::BITCAST ||
13647 Y.getOpcode() != ISD::BITCAST)
13650 // Look through mask bitcast.
13651 Mask = Mask.getOperand(0);
13652 EVT MaskVT = Mask.getValueType();
13654 // Validate that the Mask operand is a vector sra node. The sra node
13655 // will be an intrinsic.
13656 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13659 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13660 // there is no psrai.b
13661 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13662 case Intrinsic::x86_sse2_psrai_w:
13663 case Intrinsic::x86_sse2_psrai_d:
13665 default: return SDValue();
13668 // Check that the SRA is all signbits.
13669 SDValue SraC = Mask.getOperand(2);
13670 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13671 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13672 if ((SraAmt + 1) != EltBits)
13675 DebugLoc DL = N->getDebugLoc();
13677 // Now we know we at least have a plendvb with the mask val. See if
13678 // we can form a psignb/w/d.
13679 // psign = x.type == y.type == mask.type && y = sub(0, x);
13680 X = X.getOperand(0);
13681 Y = Y.getOperand(0);
13682 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13683 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13684 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13687 case 8: Opc = X86ISD::PSIGNB; break;
13688 case 16: Opc = X86ISD::PSIGNW; break;
13689 case 32: Opc = X86ISD::PSIGND; break;
13693 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13694 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13697 // PBLENDVB only available on SSE 4.1
13698 if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13701 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13702 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13703 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13704 Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13705 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13710 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13711 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13713 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13715 if (!N0.hasOneUse() || !N1.hasOneUse())
13718 SDValue ShAmt0 = N0.getOperand(1);
13719 if (ShAmt0.getValueType() != MVT::i8)
13721 SDValue ShAmt1 = N1.getOperand(1);
13722 if (ShAmt1.getValueType() != MVT::i8)
13724 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13725 ShAmt0 = ShAmt0.getOperand(0);
13726 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13727 ShAmt1 = ShAmt1.getOperand(0);
13729 DebugLoc DL = N->getDebugLoc();
13730 unsigned Opc = X86ISD::SHLD;
13731 SDValue Op0 = N0.getOperand(0);
13732 SDValue Op1 = N1.getOperand(0);
13733 if (ShAmt0.getOpcode() == ISD::SUB) {
13734 Opc = X86ISD::SHRD;
13735 std::swap(Op0, Op1);
13736 std::swap(ShAmt0, ShAmt1);
13739 unsigned Bits = VT.getSizeInBits();
13740 if (ShAmt1.getOpcode() == ISD::SUB) {
13741 SDValue Sum = ShAmt1.getOperand(0);
13742 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13743 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13744 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13745 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13746 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13747 return DAG.getNode(Opc, DL, VT,
13749 DAG.getNode(ISD::TRUNCATE, DL,
13752 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13753 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13755 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13756 return DAG.getNode(Opc, DL, VT,
13757 N0.getOperand(0), N1.getOperand(0),
13758 DAG.getNode(ISD::TRUNCATE, DL,
13765 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13766 TargetLowering::DAGCombinerInfo &DCI,
13767 const X86Subtarget *Subtarget) {
13768 if (DCI.isBeforeLegalizeOps())
13771 EVT VT = N->getValueType(0);
13773 if (VT != MVT::i32 && VT != MVT::i64)
13776 // Create BLSMSK instructions by finding X ^ (X-1)
13777 SDValue N0 = N->getOperand(0);
13778 SDValue N1 = N->getOperand(1);
13779 DebugLoc DL = N->getDebugLoc();
13781 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13782 isAllOnes(N0.getOperand(1)))
13783 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13785 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13786 isAllOnes(N1.getOperand(1)))
13787 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13792 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13793 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13794 const X86Subtarget *Subtarget) {
13795 LoadSDNode *Ld = cast<LoadSDNode>(N);
13796 EVT RegVT = Ld->getValueType(0);
13797 EVT MemVT = Ld->getMemoryVT();
13798 DebugLoc dl = Ld->getDebugLoc();
13799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13801 ISD::LoadExtType Ext = Ld->getExtensionType();
13803 // If this is a vector EXT Load then attempt to optimize it using a
13804 // shuffle. We need SSE4 for the shuffles.
13805 // TODO: It is possible to support ZExt by zeroing the undef values
13806 // during the shuffle phase or after the shuffle.
13807 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13808 assert(MemVT != RegVT && "Cannot extend to the same type");
13809 assert(MemVT.isVector() && "Must load a vector from memory");
13811 unsigned NumElems = RegVT.getVectorNumElements();
13812 unsigned RegSz = RegVT.getSizeInBits();
13813 unsigned MemSz = MemVT.getSizeInBits();
13814 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13815 // All sizes must be a power of two
13816 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13818 // Attempt to load the original value using a single load op.
13819 // Find a scalar type which is equal to the loaded word size.
13820 MVT SclrLoadTy = MVT::i8;
13821 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13822 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13823 MVT Tp = (MVT::SimpleValueType)tp;
13824 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13830 // Proceed if a load word is found.
13831 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13833 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13834 RegSz/SclrLoadTy.getSizeInBits());
13836 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13837 RegSz/MemVT.getScalarType().getSizeInBits());
13838 // Can't shuffle using an illegal type.
13839 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13841 // Perform a single load.
13842 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13844 Ld->getPointerInfo(), Ld->isVolatile(),
13845 Ld->isNonTemporal(), Ld->isInvariant(),
13846 Ld->getAlignment());
13848 // Insert the word loaded into a vector.
13849 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13850 LoadUnitVecVT, ScalarLoad);
13852 // Bitcast the loaded value to a vector of the original element type, in
13853 // the size of the target vector type.
13854 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13855 unsigned SizeRatio = RegSz/MemSz;
13857 // Redistribute the loaded elements into the different locations.
13858 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13859 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13861 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13862 DAG.getUNDEF(SlicedVec.getValueType()),
13863 ShuffleVec.data());
13865 // Bitcast to the requested type.
13866 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13867 // Replace the original load with the new sequence
13868 // and return the new chain.
13869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13870 return SDValue(ScalarLoad.getNode(), 1);
13876 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13877 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13878 const X86Subtarget *Subtarget) {
13879 StoreSDNode *St = cast<StoreSDNode>(N);
13880 EVT VT = St->getValue().getValueType();
13881 EVT StVT = St->getMemoryVT();
13882 DebugLoc dl = St->getDebugLoc();
13883 SDValue StoredVal = St->getOperand(1);
13884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13886 // If we are saving a concatination of two XMM registers, perform two stores.
13887 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13888 // 128-bit ones. If in the future the cost becomes only one memory access the
13889 // first version would be better.
13890 if (VT.getSizeInBits() == 256 &&
13891 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13892 StoredVal.getNumOperands() == 2) {
13894 SDValue Value0 = StoredVal.getOperand(0);
13895 SDValue Value1 = StoredVal.getOperand(1);
13897 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13898 SDValue Ptr0 = St->getBasePtr();
13899 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13901 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13902 St->getPointerInfo(), St->isVolatile(),
13903 St->isNonTemporal(), St->getAlignment());
13904 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13905 St->getPointerInfo(), St->isVolatile(),
13906 St->isNonTemporal(), St->getAlignment());
13907 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13910 // Optimize trunc store (of multiple scalars) to shuffle and store.
13911 // First, pack all of the elements in one place. Next, store to memory
13912 // in fewer chunks.
13913 if (St->isTruncatingStore() && VT.isVector()) {
13914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13915 unsigned NumElems = VT.getVectorNumElements();
13916 assert(StVT != VT && "Cannot truncate to the same type");
13917 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13918 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13920 // From, To sizes and ElemCount must be pow of two
13921 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13922 // We are going to use the original vector elt for storing.
13923 // Accumulated smaller vector elements must be a multiple of the store size.
13924 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13926 unsigned SizeRatio = FromSz / ToSz;
13928 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13930 // Create a type on which we perform the shuffle
13931 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13932 StVT.getScalarType(), NumElems*SizeRatio);
13934 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13936 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13937 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13938 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13940 // Can't shuffle using an illegal type
13941 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13943 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13944 DAG.getUNDEF(WideVec.getValueType()),
13945 ShuffleVec.data());
13946 // At this point all of the data is stored at the bottom of the
13947 // register. We now need to save it to mem.
13949 // Find the largest store unit
13950 MVT StoreType = MVT::i8;
13951 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13952 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13953 MVT Tp = (MVT::SimpleValueType)tp;
13954 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13958 // Bitcast the original vector into a vector of store-size units
13959 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13960 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13961 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13962 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13963 SmallVector<SDValue, 8> Chains;
13964 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13965 TLI.getPointerTy());
13966 SDValue Ptr = St->getBasePtr();
13968 // Perform one or more big stores into memory.
13969 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13970 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13971 StoreType, ShuffWide,
13972 DAG.getIntPtrConstant(i));
13973 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13974 St->getPointerInfo(), St->isVolatile(),
13975 St->isNonTemporal(), St->getAlignment());
13976 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13977 Chains.push_back(Ch);
13980 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13985 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
13986 // the FP state in cases where an emms may be missing.
13987 // A preferable solution to the general problem is to figure out the right
13988 // places to insert EMMS. This qualifies as a quick hack.
13990 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13991 if (VT.getSizeInBits() != 64)
13994 const Function *F = DAG.getMachineFunction().getFunction();
13995 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13996 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13997 && Subtarget->hasXMMInt();
13998 if ((VT.isVector() ||
13999 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14000 isa<LoadSDNode>(St->getValue()) &&
14001 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14002 St->getChain().hasOneUse() && !St->isVolatile()) {
14003 SDNode* LdVal = St->getValue().getNode();
14004 LoadSDNode *Ld = 0;
14005 int TokenFactorIndex = -1;
14006 SmallVector<SDValue, 8> Ops;
14007 SDNode* ChainVal = St->getChain().getNode();
14008 // Must be a store of a load. We currently handle two cases: the load
14009 // is a direct child, and it's under an intervening TokenFactor. It is
14010 // possible to dig deeper under nested TokenFactors.
14011 if (ChainVal == LdVal)
14012 Ld = cast<LoadSDNode>(St->getChain());
14013 else if (St->getValue().hasOneUse() &&
14014 ChainVal->getOpcode() == ISD::TokenFactor) {
14015 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14016 if (ChainVal->getOperand(i).getNode() == LdVal) {
14017 TokenFactorIndex = i;
14018 Ld = cast<LoadSDNode>(St->getValue());
14020 Ops.push_back(ChainVal->getOperand(i));
14024 if (!Ld || !ISD::isNormalLoad(Ld))
14027 // If this is not the MMX case, i.e. we are just turning i64 load/store
14028 // into f64 load/store, avoid the transformation if there are multiple
14029 // uses of the loaded value.
14030 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14033 DebugLoc LdDL = Ld->getDebugLoc();
14034 DebugLoc StDL = N->getDebugLoc();
14035 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14036 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14038 if (Subtarget->is64Bit() || F64IsLegal) {
14039 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14040 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14041 Ld->getPointerInfo(), Ld->isVolatile(),
14042 Ld->isNonTemporal(), Ld->isInvariant(),
14043 Ld->getAlignment());
14044 SDValue NewChain = NewLd.getValue(1);
14045 if (TokenFactorIndex != -1) {
14046 Ops.push_back(NewChain);
14047 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14050 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14051 St->getPointerInfo(),
14052 St->isVolatile(), St->isNonTemporal(),
14053 St->getAlignment());
14056 // Otherwise, lower to two pairs of 32-bit loads / stores.
14057 SDValue LoAddr = Ld->getBasePtr();
14058 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14059 DAG.getConstant(4, MVT::i32));
14061 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14062 Ld->getPointerInfo(),
14063 Ld->isVolatile(), Ld->isNonTemporal(),
14064 Ld->isInvariant(), Ld->getAlignment());
14065 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14066 Ld->getPointerInfo().getWithOffset(4),
14067 Ld->isVolatile(), Ld->isNonTemporal(),
14069 MinAlign(Ld->getAlignment(), 4));
14071 SDValue NewChain = LoLd.getValue(1);
14072 if (TokenFactorIndex != -1) {
14073 Ops.push_back(LoLd);
14074 Ops.push_back(HiLd);
14075 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14079 LoAddr = St->getBasePtr();
14080 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14081 DAG.getConstant(4, MVT::i32));
14083 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14084 St->getPointerInfo(),
14085 St->isVolatile(), St->isNonTemporal(),
14086 St->getAlignment());
14087 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14088 St->getPointerInfo().getWithOffset(4),
14090 St->isNonTemporal(),
14091 MinAlign(St->getAlignment(), 4));
14092 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14097 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14098 /// and return the operands for the horizontal operation in LHS and RHS. A
14099 /// horizontal operation performs the binary operation on successive elements
14100 /// of its first operand, then on successive elements of its second operand,
14101 /// returning the resulting values in a vector. For example, if
14102 /// A = < float a0, float a1, float a2, float a3 >
14104 /// B = < float b0, float b1, float b2, float b3 >
14105 /// then the result of doing a horizontal operation on A and B is
14106 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14107 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14108 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14109 /// set to A, RHS to B, and the routine returns 'true'.
14110 /// Note that the binary operation should have the property that if one of the
14111 /// operands is UNDEF then the result is UNDEF.
14112 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14113 // Look for the following pattern: if
14114 // A = < float a0, float a1, float a2, float a3 >
14115 // B = < float b0, float b1, float b2, float b3 >
14117 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14118 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14119 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14120 // which is A horizontal-op B.
14122 // At least one of the operands should be a vector shuffle.
14123 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14124 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14127 EVT VT = LHS.getValueType();
14128 unsigned N = VT.getVectorNumElements();
14130 // View LHS in the form
14131 // LHS = VECTOR_SHUFFLE A, B, LMask
14132 // If LHS is not a shuffle then pretend it is the shuffle
14133 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14134 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14137 SmallVector<int, 8> LMask(N);
14138 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14139 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14140 A = LHS.getOperand(0);
14141 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14142 B = LHS.getOperand(1);
14143 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14145 if (LHS.getOpcode() != ISD::UNDEF)
14147 for (unsigned i = 0; i != N; ++i)
14151 // Likewise, view RHS in the form
14152 // RHS = VECTOR_SHUFFLE C, D, RMask
14154 SmallVector<int, 8> RMask(N);
14155 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14156 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14157 C = RHS.getOperand(0);
14158 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14159 D = RHS.getOperand(1);
14160 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14162 if (RHS.getOpcode() != ISD::UNDEF)
14164 for (unsigned i = 0; i != N; ++i)
14168 // Check that the shuffles are both shuffling the same vectors.
14169 if (!(A == C && B == D) && !(A == D && B == C))
14172 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14173 if (!A.getNode() && !B.getNode())
14176 // If A and B occur in reverse order in RHS, then "swap" them (which means
14177 // rewriting the mask).
14179 for (unsigned i = 0; i != N; ++i) {
14180 unsigned Idx = RMask[i];
14183 else if (Idx < 2*N)
14187 // At this point LHS and RHS are equivalent to
14188 // LHS = VECTOR_SHUFFLE A, B, LMask
14189 // RHS = VECTOR_SHUFFLE A, B, RMask
14190 // Check that the masks correspond to performing a horizontal operation.
14191 for (unsigned i = 0; i != N; ++i) {
14192 unsigned LIdx = LMask[i], RIdx = RMask[i];
14194 // Ignore any UNDEF components.
14195 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14196 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14199 // Check that successive elements are being operated on. If not, this is
14200 // not a horizontal operation.
14201 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14202 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14206 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14207 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14211 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14212 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14213 const X86Subtarget *Subtarget) {
14214 EVT VT = N->getValueType(0);
14215 SDValue LHS = N->getOperand(0);
14216 SDValue RHS = N->getOperand(1);
14218 // Try to synthesize horizontal adds from adds of shuffles.
14219 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14220 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14221 isHorizontalBinOp(LHS, RHS, true))
14222 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14226 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14227 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14228 const X86Subtarget *Subtarget) {
14229 EVT VT = N->getValueType(0);
14230 SDValue LHS = N->getOperand(0);
14231 SDValue RHS = N->getOperand(1);
14233 // Try to synthesize horizontal subs from subs of shuffles.
14234 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14235 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14236 isHorizontalBinOp(LHS, RHS, false))
14237 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14241 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14242 /// X86ISD::FXOR nodes.
14243 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14244 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14245 // F[X]OR(0.0, x) -> x
14246 // F[X]OR(x, 0.0) -> x
14247 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14248 if (C->getValueAPF().isPosZero())
14249 return N->getOperand(1);
14250 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14251 if (C->getValueAPF().isPosZero())
14252 return N->getOperand(0);
14256 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14257 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14258 // FAND(0.0, x) -> 0.0
14259 // FAND(x, 0.0) -> 0.0
14260 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14261 if (C->getValueAPF().isPosZero())
14262 return N->getOperand(0);
14263 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14264 if (C->getValueAPF().isPosZero())
14265 return N->getOperand(1);
14269 static SDValue PerformBTCombine(SDNode *N,
14271 TargetLowering::DAGCombinerInfo &DCI) {
14272 // BT ignores high bits in the bit index operand.
14273 SDValue Op1 = N->getOperand(1);
14274 if (Op1.hasOneUse()) {
14275 unsigned BitWidth = Op1.getValueSizeInBits();
14276 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14277 APInt KnownZero, KnownOne;
14278 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14279 !DCI.isBeforeLegalizeOps());
14280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14281 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14282 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14283 DCI.CommitTargetLoweringOpt(TLO);
14288 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14289 SDValue Op = N->getOperand(0);
14290 if (Op.getOpcode() == ISD::BITCAST)
14291 Op = Op.getOperand(0);
14292 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14293 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14294 VT.getVectorElementType().getSizeInBits() ==
14295 OpVT.getVectorElementType().getSizeInBits()) {
14296 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14301 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14302 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14303 // (and (i32 x86isd::setcc_carry), 1)
14304 // This eliminates the zext. This transformation is necessary because
14305 // ISD::SETCC is always legalized to i8.
14306 DebugLoc dl = N->getDebugLoc();
14307 SDValue N0 = N->getOperand(0);
14308 EVT VT = N->getValueType(0);
14309 if (N0.getOpcode() == ISD::AND &&
14311 N0.getOperand(0).hasOneUse()) {
14312 SDValue N00 = N0.getOperand(0);
14313 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14315 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14316 if (!C || C->getZExtValue() != 1)
14318 return DAG.getNode(ISD::AND, dl, VT,
14319 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14320 N00.getOperand(0), N00.getOperand(1)),
14321 DAG.getConstant(1, VT));
14327 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14328 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14329 unsigned X86CC = N->getConstantOperandVal(0);
14330 SDValue EFLAG = N->getOperand(1);
14331 DebugLoc DL = N->getDebugLoc();
14333 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14334 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14336 if (X86CC == X86::COND_B)
14337 return DAG.getNode(ISD::AND, DL, MVT::i8,
14338 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14339 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14340 DAG.getConstant(1, MVT::i8));
14345 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14346 const X86TargetLowering *XTLI) {
14347 SDValue Op0 = N->getOperand(0);
14348 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14349 // a 32-bit target where SSE doesn't support i64->FP operations.
14350 if (Op0.getOpcode() == ISD::LOAD) {
14351 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14352 EVT VT = Ld->getValueType(0);
14353 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14354 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14355 !XTLI->getSubtarget()->is64Bit() &&
14356 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14357 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14358 Ld->getChain(), Op0, DAG);
14359 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14366 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14367 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14368 X86TargetLowering::DAGCombinerInfo &DCI) {
14369 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14370 // the result is either zero or one (depending on the input carry bit).
14371 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14372 if (X86::isZeroNode(N->getOperand(0)) &&
14373 X86::isZeroNode(N->getOperand(1)) &&
14374 // We don't have a good way to replace an EFLAGS use, so only do this when
14376 SDValue(N, 1).use_empty()) {
14377 DebugLoc DL = N->getDebugLoc();
14378 EVT VT = N->getValueType(0);
14379 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14380 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14381 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14382 DAG.getConstant(X86::COND_B,MVT::i8),
14384 DAG.getConstant(1, VT));
14385 return DCI.CombineTo(N, Res1, CarryOut);
14391 // fold (add Y, (sete X, 0)) -> adc 0, Y
14392 // (add Y, (setne X, 0)) -> sbb -1, Y
14393 // (sub (sete X, 0), Y) -> sbb 0, Y
14394 // (sub (setne X, 0), Y) -> adc -1, Y
14395 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14396 DebugLoc DL = N->getDebugLoc();
14398 // Look through ZExts.
14399 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14400 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14403 SDValue SetCC = Ext.getOperand(0);
14404 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14407 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14408 if (CC != X86::COND_E && CC != X86::COND_NE)
14411 SDValue Cmp = SetCC.getOperand(1);
14412 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14413 !X86::isZeroNode(Cmp.getOperand(1)) ||
14414 !Cmp.getOperand(0).getValueType().isInteger())
14417 SDValue CmpOp0 = Cmp.getOperand(0);
14418 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14419 DAG.getConstant(1, CmpOp0.getValueType()));
14421 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14422 if (CC == X86::COND_NE)
14423 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14424 DL, OtherVal.getValueType(), OtherVal,
14425 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14426 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14427 DL, OtherVal.getValueType(), OtherVal,
14428 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14431 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14432 SDValue Op0 = N->getOperand(0);
14433 SDValue Op1 = N->getOperand(1);
14435 // X86 can't encode an immediate LHS of a sub. See if we can push the
14436 // negation into a preceding instruction.
14437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14438 // If the RHS of the sub is a XOR with one use and a constant, invert the
14439 // immediate. Then add one to the LHS of the sub so we can turn
14440 // X-Y -> X+~Y+1, saving one register.
14441 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14442 isa<ConstantSDNode>(Op1.getOperand(1))) {
14443 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14444 EVT VT = Op0.getValueType();
14445 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14447 DAG.getConstant(~XorC, VT));
14448 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14449 DAG.getConstant(C->getAPIntValue()+1, VT));
14453 return OptimizeConditionalInDecrement(N, DAG);
14456 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14457 DAGCombinerInfo &DCI) const {
14458 SelectionDAG &DAG = DCI.DAG;
14459 switch (N->getOpcode()) {
14461 case ISD::EXTRACT_VECTOR_ELT:
14462 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14464 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14465 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14466 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
14467 case ISD::SUB: return PerformSubCombine(N, DAG);
14468 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14469 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14472 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14473 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14474 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14475 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14476 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14477 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14478 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14479 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14480 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14482 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14483 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14484 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14485 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14486 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14487 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14488 case X86ISD::SHUFPS: // Handle all target specific shuffles
14489 case X86ISD::SHUFPD:
14490 case X86ISD::PALIGN:
14491 case X86ISD::PUNPCKHBW:
14492 case X86ISD::PUNPCKHWD:
14493 case X86ISD::PUNPCKHDQ:
14494 case X86ISD::PUNPCKHQDQ:
14495 case X86ISD::UNPCKHPS:
14496 case X86ISD::UNPCKHPD:
14497 case X86ISD::VUNPCKHPSY:
14498 case X86ISD::VUNPCKHPDY:
14499 case X86ISD::PUNPCKLBW:
14500 case X86ISD::PUNPCKLWD:
14501 case X86ISD::PUNPCKLDQ:
14502 case X86ISD::PUNPCKLQDQ:
14503 case X86ISD::UNPCKLPS:
14504 case X86ISD::UNPCKLPD:
14505 case X86ISD::VUNPCKLPSY:
14506 case X86ISD::VUNPCKLPDY:
14507 case X86ISD::MOVHLPS:
14508 case X86ISD::MOVLHPS:
14509 case X86ISD::PSHUFD:
14510 case X86ISD::PSHUFHW:
14511 case X86ISD::PSHUFLW:
14512 case X86ISD::MOVSS:
14513 case X86ISD::MOVSD:
14514 case X86ISD::VPERMILPS:
14515 case X86ISD::VPERMILPSY:
14516 case X86ISD::VPERMILPD:
14517 case X86ISD::VPERMILPDY:
14518 case X86ISD::VPERM2F128:
14519 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14525 /// isTypeDesirableForOp - Return true if the target has native support for
14526 /// the specified value type and it is 'desirable' to use the type for the
14527 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14528 /// instruction encodings are longer and some i16 instructions are slow.
14529 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14530 if (!isTypeLegal(VT))
14532 if (VT != MVT::i16)
14539 case ISD::SIGN_EXTEND:
14540 case ISD::ZERO_EXTEND:
14541 case ISD::ANY_EXTEND:
14554 /// IsDesirableToPromoteOp - This method query the target whether it is
14555 /// beneficial for dag combiner to promote the specified node. If true, it
14556 /// should return the desired promotion type by reference.
14557 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14558 EVT VT = Op.getValueType();
14559 if (VT != MVT::i16)
14562 bool Promote = false;
14563 bool Commute = false;
14564 switch (Op.getOpcode()) {
14567 LoadSDNode *LD = cast<LoadSDNode>(Op);
14568 // If the non-extending load has a single use and it's not live out, then it
14569 // might be folded.
14570 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14571 Op.hasOneUse()*/) {
14572 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14573 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14574 // The only case where we'd want to promote LOAD (rather then it being
14575 // promoted as an operand is when it's only use is liveout.
14576 if (UI->getOpcode() != ISD::CopyToReg)
14583 case ISD::SIGN_EXTEND:
14584 case ISD::ZERO_EXTEND:
14585 case ISD::ANY_EXTEND:
14590 SDValue N0 = Op.getOperand(0);
14591 // Look out for (store (shl (load), x)).
14592 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14605 SDValue N0 = Op.getOperand(0);
14606 SDValue N1 = Op.getOperand(1);
14607 if (!Commute && MayFoldLoad(N1))
14609 // Avoid disabling potential load folding opportunities.
14610 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14612 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14622 //===----------------------------------------------------------------------===//
14623 // X86 Inline Assembly Support
14624 //===----------------------------------------------------------------------===//
14626 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14627 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14629 std::string AsmStr = IA->getAsmString();
14631 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14632 SmallVector<StringRef, 4> AsmPieces;
14633 SplitString(AsmStr, AsmPieces, ";\n");
14635 switch (AsmPieces.size()) {
14636 default: return false;
14638 AsmStr = AsmPieces[0];
14640 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14642 // FIXME: this should verify that we are targeting a 486 or better. If not,
14643 // we will turn this bswap into something that will be lowered to logical ops
14644 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14645 // so don't worry about this.
14647 if (AsmPieces.size() == 2 &&
14648 (AsmPieces[0] == "bswap" ||
14649 AsmPieces[0] == "bswapq" ||
14650 AsmPieces[0] == "bswapl") &&
14651 (AsmPieces[1] == "$0" ||
14652 AsmPieces[1] == "${0:q}")) {
14653 // No need to check constraints, nothing other than the equivalent of
14654 // "=r,0" would be valid here.
14655 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14656 if (!Ty || Ty->getBitWidth() % 16 != 0)
14658 return IntrinsicLowering::LowerToByteSwap(CI);
14660 // rorw $$8, ${0:w} --> llvm.bswap.i16
14661 if (CI->getType()->isIntegerTy(16) &&
14662 AsmPieces.size() == 3 &&
14663 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14664 AsmPieces[1] == "$$8," &&
14665 AsmPieces[2] == "${0:w}" &&
14666 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14668 const std::string &ConstraintsStr = IA->getConstraintString();
14669 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14670 std::sort(AsmPieces.begin(), AsmPieces.end());
14671 if (AsmPieces.size() == 4 &&
14672 AsmPieces[0] == "~{cc}" &&
14673 AsmPieces[1] == "~{dirflag}" &&
14674 AsmPieces[2] == "~{flags}" &&
14675 AsmPieces[3] == "~{fpsr}") {
14676 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14677 if (!Ty || Ty->getBitWidth() % 16 != 0)
14679 return IntrinsicLowering::LowerToByteSwap(CI);
14684 if (CI->getType()->isIntegerTy(32) &&
14685 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14686 SmallVector<StringRef, 4> Words;
14687 SplitString(AsmPieces[0], Words, " \t,");
14688 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14689 Words[2] == "${0:w}") {
14691 SplitString(AsmPieces[1], Words, " \t,");
14692 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14693 Words[2] == "$0") {
14695 SplitString(AsmPieces[2], Words, " \t,");
14696 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14697 Words[2] == "${0:w}") {
14699 const std::string &ConstraintsStr = IA->getConstraintString();
14700 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14701 std::sort(AsmPieces.begin(), AsmPieces.end());
14702 if (AsmPieces.size() == 4 &&
14703 AsmPieces[0] == "~{cc}" &&
14704 AsmPieces[1] == "~{dirflag}" &&
14705 AsmPieces[2] == "~{flags}" &&
14706 AsmPieces[3] == "~{fpsr}") {
14707 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14708 if (!Ty || Ty->getBitWidth() % 16 != 0)
14710 return IntrinsicLowering::LowerToByteSwap(CI);
14717 if (CI->getType()->isIntegerTy(64)) {
14718 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14719 if (Constraints.size() >= 2 &&
14720 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14721 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14722 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14723 SmallVector<StringRef, 4> Words;
14724 SplitString(AsmPieces[0], Words, " \t");
14725 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14727 SplitString(AsmPieces[1], Words, " \t");
14728 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14730 SplitString(AsmPieces[2], Words, " \t,");
14731 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14732 Words[2] == "%edx") {
14733 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14734 if (!Ty || Ty->getBitWidth() % 16 != 0)
14736 return IntrinsicLowering::LowerToByteSwap(CI);
14749 /// getConstraintType - Given a constraint letter, return the type of
14750 /// constraint it is for this target.
14751 X86TargetLowering::ConstraintType
14752 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14753 if (Constraint.size() == 1) {
14754 switch (Constraint[0]) {
14765 return C_RegisterClass;
14789 return TargetLowering::getConstraintType(Constraint);
14792 /// Examine constraint type and operand type and determine a weight value.
14793 /// This object must already have been set up with the operand type
14794 /// and the current alternative constraint selected.
14795 TargetLowering::ConstraintWeight
14796 X86TargetLowering::getSingleConstraintMatchWeight(
14797 AsmOperandInfo &info, const char *constraint) const {
14798 ConstraintWeight weight = CW_Invalid;
14799 Value *CallOperandVal = info.CallOperandVal;
14800 // If we don't have a value, we can't do a match,
14801 // but allow it at the lowest weight.
14802 if (CallOperandVal == NULL)
14804 Type *type = CallOperandVal->getType();
14805 // Look at the constraint type.
14806 switch (*constraint) {
14808 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14819 if (CallOperandVal->getType()->isIntegerTy())
14820 weight = CW_SpecificReg;
14825 if (type->isFloatingPointTy())
14826 weight = CW_SpecificReg;
14829 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14830 weight = CW_SpecificReg;
14834 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14835 weight = CW_Register;
14838 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14839 if (C->getZExtValue() <= 31)
14840 weight = CW_Constant;
14844 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14845 if (C->getZExtValue() <= 63)
14846 weight = CW_Constant;
14850 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14851 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14852 weight = CW_Constant;
14856 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14857 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14858 weight = CW_Constant;
14862 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14863 if (C->getZExtValue() <= 3)
14864 weight = CW_Constant;
14868 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14869 if (C->getZExtValue() <= 0xff)
14870 weight = CW_Constant;
14875 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14876 weight = CW_Constant;
14880 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14881 if ((C->getSExtValue() >= -0x80000000LL) &&
14882 (C->getSExtValue() <= 0x7fffffffLL))
14883 weight = CW_Constant;
14887 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14888 if (C->getZExtValue() <= 0xffffffff)
14889 weight = CW_Constant;
14896 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14897 /// with another that has more specific requirements based on the type of the
14898 /// corresponding operand.
14899 const char *X86TargetLowering::
14900 LowerXConstraint(EVT ConstraintVT) const {
14901 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14902 // 'f' like normal targets.
14903 if (ConstraintVT.isFloatingPoint()) {
14904 if (Subtarget->hasXMMInt())
14906 if (Subtarget->hasXMM())
14910 return TargetLowering::LowerXConstraint(ConstraintVT);
14913 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14914 /// vector. If it is invalid, don't add anything to Ops.
14915 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14916 std::string &Constraint,
14917 std::vector<SDValue>&Ops,
14918 SelectionDAG &DAG) const {
14919 SDValue Result(0, 0);
14921 // Only support length 1 constraints for now.
14922 if (Constraint.length() > 1) return;
14924 char ConstraintLetter = Constraint[0];
14925 switch (ConstraintLetter) {
14928 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14929 if (C->getZExtValue() <= 31) {
14930 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14936 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14937 if (C->getZExtValue() <= 63) {
14938 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14945 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14946 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14952 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14953 if (C->getZExtValue() <= 255) {
14954 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14960 // 32-bit signed value
14961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14962 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14963 C->getSExtValue())) {
14964 // Widen to 64 bits here to get it sign extended.
14965 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14968 // FIXME gcc accepts some relocatable values here too, but only in certain
14969 // memory models; it's complicated.
14974 // 32-bit unsigned value
14975 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14976 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14977 C->getZExtValue())) {
14978 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14982 // FIXME gcc accepts some relocatable values here too, but only in certain
14983 // memory models; it's complicated.
14987 // Literal immediates are always ok.
14988 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14989 // Widen to 64 bits here to get it sign extended.
14990 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14994 // In any sort of PIC mode addresses need to be computed at runtime by
14995 // adding in a register or some sort of table lookup. These can't
14996 // be used as immediates.
14997 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15000 // If we are in non-pic codegen mode, we allow the address of a global (with
15001 // an optional displacement) to be used with 'i'.
15002 GlobalAddressSDNode *GA = 0;
15003 int64_t Offset = 0;
15005 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15007 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15008 Offset += GA->getOffset();
15010 } else if (Op.getOpcode() == ISD::ADD) {
15011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15012 Offset += C->getZExtValue();
15013 Op = Op.getOperand(0);
15016 } else if (Op.getOpcode() == ISD::SUB) {
15017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15018 Offset += -C->getZExtValue();
15019 Op = Op.getOperand(0);
15024 // Otherwise, this isn't something we can handle, reject it.
15028 const GlobalValue *GV = GA->getGlobal();
15029 // If we require an extra load to get this address, as in PIC mode, we
15030 // can't accept it.
15031 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15032 getTargetMachine())))
15035 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15036 GA->getValueType(0), Offset);
15041 if (Result.getNode()) {
15042 Ops.push_back(Result);
15045 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15048 std::pair<unsigned, const TargetRegisterClass*>
15049 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15051 // First, see if this is a constraint that directly corresponds to an LLVM
15053 if (Constraint.size() == 1) {
15054 // GCC Constraint Letters
15055 switch (Constraint[0]) {
15057 // TODO: Slight differences here in allocation order and leaving
15058 // RIP in the class. Do they matter any more here than they do
15059 // in the normal allocation?
15060 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15061 if (Subtarget->is64Bit()) {
15062 if (VT == MVT::i32 || VT == MVT::f32)
15063 return std::make_pair(0U, X86::GR32RegisterClass);
15064 else if (VT == MVT::i16)
15065 return std::make_pair(0U, X86::GR16RegisterClass);
15066 else if (VT == MVT::i8 || VT == MVT::i1)
15067 return std::make_pair(0U, X86::GR8RegisterClass);
15068 else if (VT == MVT::i64 || VT == MVT::f64)
15069 return std::make_pair(0U, X86::GR64RegisterClass);
15072 // 32-bit fallthrough
15073 case 'Q': // Q_REGS
15074 if (VT == MVT::i32 || VT == MVT::f32)
15075 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15076 else if (VT == MVT::i16)
15077 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15078 else if (VT == MVT::i8 || VT == MVT::i1)
15079 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15080 else if (VT == MVT::i64)
15081 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15083 case 'r': // GENERAL_REGS
15084 case 'l': // INDEX_REGS
15085 if (VT == MVT::i8 || VT == MVT::i1)
15086 return std::make_pair(0U, X86::GR8RegisterClass);
15087 if (VT == MVT::i16)
15088 return std::make_pair(0U, X86::GR16RegisterClass);
15089 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15090 return std::make_pair(0U, X86::GR32RegisterClass);
15091 return std::make_pair(0U, X86::GR64RegisterClass);
15092 case 'R': // LEGACY_REGS
15093 if (VT == MVT::i8 || VT == MVT::i1)
15094 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15095 if (VT == MVT::i16)
15096 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15097 if (VT == MVT::i32 || !Subtarget->is64Bit())
15098 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15099 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15100 case 'f': // FP Stack registers.
15101 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15102 // value to the correct fpstack register class.
15103 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15104 return std::make_pair(0U, X86::RFP32RegisterClass);
15105 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15106 return std::make_pair(0U, X86::RFP64RegisterClass);
15107 return std::make_pair(0U, X86::RFP80RegisterClass);
15108 case 'y': // MMX_REGS if MMX allowed.
15109 if (!Subtarget->hasMMX()) break;
15110 return std::make_pair(0U, X86::VR64RegisterClass);
15111 case 'Y': // SSE_REGS if SSE2 allowed
15112 if (!Subtarget->hasXMMInt()) break;
15114 case 'x': // SSE_REGS if SSE1 allowed
15115 if (!Subtarget->hasXMM()) break;
15117 switch (VT.getSimpleVT().SimpleTy) {
15119 // Scalar SSE types.
15122 return std::make_pair(0U, X86::FR32RegisterClass);
15125 return std::make_pair(0U, X86::FR64RegisterClass);
15133 return std::make_pair(0U, X86::VR128RegisterClass);
15139 // Use the default implementation in TargetLowering to convert the register
15140 // constraint into a member of a register class.
15141 std::pair<unsigned, const TargetRegisterClass*> Res;
15142 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15144 // Not found as a standard register?
15145 if (Res.second == 0) {
15146 // Map st(0) -> st(7) -> ST0
15147 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15148 tolower(Constraint[1]) == 's' &&
15149 tolower(Constraint[2]) == 't' &&
15150 Constraint[3] == '(' &&
15151 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15152 Constraint[5] == ')' &&
15153 Constraint[6] == '}') {
15155 Res.first = X86::ST0+Constraint[4]-'0';
15156 Res.second = X86::RFP80RegisterClass;
15160 // GCC allows "st(0)" to be called just plain "st".
15161 if (StringRef("{st}").equals_lower(Constraint)) {
15162 Res.first = X86::ST0;
15163 Res.second = X86::RFP80RegisterClass;
15168 if (StringRef("{flags}").equals_lower(Constraint)) {
15169 Res.first = X86::EFLAGS;
15170 Res.second = X86::CCRRegisterClass;
15174 // 'A' means EAX + EDX.
15175 if (Constraint == "A") {
15176 Res.first = X86::EAX;
15177 Res.second = X86::GR32_ADRegisterClass;
15183 // Otherwise, check to see if this is a register class of the wrong value
15184 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15185 // turn into {ax},{dx}.
15186 if (Res.second->hasType(VT))
15187 return Res; // Correct type already, nothing to do.
15189 // All of the single-register GCC register classes map their values onto
15190 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15191 // really want an 8-bit or 32-bit register, map to the appropriate register
15192 // class and return the appropriate register.
15193 if (Res.second == X86::GR16RegisterClass) {
15194 if (VT == MVT::i8) {
15195 unsigned DestReg = 0;
15196 switch (Res.first) {
15198 case X86::AX: DestReg = X86::AL; break;
15199 case X86::DX: DestReg = X86::DL; break;
15200 case X86::CX: DestReg = X86::CL; break;
15201 case X86::BX: DestReg = X86::BL; break;
15204 Res.first = DestReg;
15205 Res.second = X86::GR8RegisterClass;
15207 } else if (VT == MVT::i32) {
15208 unsigned DestReg = 0;
15209 switch (Res.first) {
15211 case X86::AX: DestReg = X86::EAX; break;
15212 case X86::DX: DestReg = X86::EDX; break;
15213 case X86::CX: DestReg = X86::ECX; break;
15214 case X86::BX: DestReg = X86::EBX; break;
15215 case X86::SI: DestReg = X86::ESI; break;
15216 case X86::DI: DestReg = X86::EDI; break;
15217 case X86::BP: DestReg = X86::EBP; break;
15218 case X86::SP: DestReg = X86::ESP; break;
15221 Res.first = DestReg;
15222 Res.second = X86::GR32RegisterClass;
15224 } else if (VT == MVT::i64) {
15225 unsigned DestReg = 0;
15226 switch (Res.first) {
15228 case X86::AX: DestReg = X86::RAX; break;
15229 case X86::DX: DestReg = X86::RDX; break;
15230 case X86::CX: DestReg = X86::RCX; break;
15231 case X86::BX: DestReg = X86::RBX; break;
15232 case X86::SI: DestReg = X86::RSI; break;
15233 case X86::DI: DestReg = X86::RDI; break;
15234 case X86::BP: DestReg = X86::RBP; break;
15235 case X86::SP: DestReg = X86::RSP; break;
15238 Res.first = DestReg;
15239 Res.second = X86::GR64RegisterClass;
15242 } else if (Res.second == X86::FR32RegisterClass ||
15243 Res.second == X86::FR64RegisterClass ||
15244 Res.second == X86::VR128RegisterClass) {
15245 // Handle references to XMM physical registers that got mapped into the
15246 // wrong class. This can happen with constraints like {xmm0} where the
15247 // target independent register mapper will just pick the first match it can
15248 // find, ignoring the required type.
15249 if (VT == MVT::f32)
15250 Res.second = X86::FR32RegisterClass;
15251 else if (VT == MVT::f64)
15252 Res.second = X86::FR64RegisterClass;
15253 else if (X86::VR128RegisterClass->hasType(VT))
15254 Res.second = X86::VR128RegisterClass;