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 if (Subtarget->hasAVX2()) {
1040 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1041 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1042 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1043 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1045 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1046 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1047 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1048 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1050 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1051 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1052 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1054 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1055 // Don't lower v32i8 because there is no 128-bit byte mul
1057 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1058 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1059 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1060 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1062 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1063 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1064 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1065 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1067 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1068 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1069 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1070 // Don't lower v32i8 because there is no 128-bit byte mul
1073 // Custom lower several nodes for 256-bit types.
1074 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1075 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1076 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1079 // Extract subvector is special because the value type
1080 // (result) is 128-bit but the source is 256-bit wide.
1081 if (VT.is128BitVector())
1082 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1084 // Do not attempt to custom lower other non-256-bit vectors
1085 if (!VT.is256BitVector())
1088 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1089 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1092 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1093 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1096 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1097 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1098 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1101 // Do not attempt to promote non-256-bit vectors
1102 if (!VT.is256BitVector())
1105 setOperationAction(ISD::AND, SVT, Promote);
1106 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1107 setOperationAction(ISD::OR, SVT, Promote);
1108 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1109 setOperationAction(ISD::XOR, SVT, Promote);
1110 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1111 setOperationAction(ISD::LOAD, SVT, Promote);
1112 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1113 setOperationAction(ISD::SELECT, SVT, Promote);
1114 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1118 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1119 // of this type with custom code.
1120 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1121 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1122 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1125 // We want to custom lower some of our intrinsics.
1126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1129 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1130 // handle type legalization for these operations here.
1132 // FIXME: We really should do custom legalization for addition and
1133 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1134 // than generic legalization for 64-bit multiplication-with-overflow, though.
1135 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1136 // Add/Sub/Mul with overflow operations are custom lowered.
1138 setOperationAction(ISD::SADDO, VT, Custom);
1139 setOperationAction(ISD::UADDO, VT, Custom);
1140 setOperationAction(ISD::SSUBO, VT, Custom);
1141 setOperationAction(ISD::USUBO, VT, Custom);
1142 setOperationAction(ISD::SMULO, VT, Custom);
1143 setOperationAction(ISD::UMULO, VT, Custom);
1146 // There are no 8-bit 3-address imul/mul instructions
1147 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1148 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1150 if (!Subtarget->is64Bit()) {
1151 // These libcalls are not available in 32-bit.
1152 setLibcallName(RTLIB::SHL_I128, 0);
1153 setLibcallName(RTLIB::SRL_I128, 0);
1154 setLibcallName(RTLIB::SRA_I128, 0);
1157 // We have target-specific dag combine patterns for the following nodes:
1158 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1159 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1160 setTargetDAGCombine(ISD::BUILD_VECTOR);
1161 setTargetDAGCombine(ISD::VSELECT);
1162 setTargetDAGCombine(ISD::SELECT);
1163 setTargetDAGCombine(ISD::SHL);
1164 setTargetDAGCombine(ISD::SRA);
1165 setTargetDAGCombine(ISD::SRL);
1166 setTargetDAGCombine(ISD::OR);
1167 setTargetDAGCombine(ISD::AND);
1168 setTargetDAGCombine(ISD::ADD);
1169 setTargetDAGCombine(ISD::FADD);
1170 setTargetDAGCombine(ISD::FSUB);
1171 setTargetDAGCombine(ISD::SUB);
1172 setTargetDAGCombine(ISD::LOAD);
1173 setTargetDAGCombine(ISD::STORE);
1174 setTargetDAGCombine(ISD::ZERO_EXTEND);
1175 setTargetDAGCombine(ISD::SINT_TO_FP);
1176 if (Subtarget->is64Bit())
1177 setTargetDAGCombine(ISD::MUL);
1178 if (Subtarget->hasBMI())
1179 setTargetDAGCombine(ISD::XOR);
1181 computeRegisterProperties();
1183 // On Darwin, -Os means optimize for size without hurting performance,
1184 // do not reduce the limit.
1185 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1186 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1187 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1188 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1189 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1190 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1191 setPrefLoopAlignment(16);
1192 benefitFromCodePlacementOpt = true;
1194 setPrefFunctionAlignment(4);
1198 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1199 if (!VT.isVector()) return MVT::i8;
1200 return VT.changeVectorElementTypeToInteger();
1204 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1205 /// the desired ByVal argument alignment.
1206 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1209 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1210 if (VTy->getBitWidth() == 128)
1212 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1213 unsigned EltAlign = 0;
1214 getMaxByValAlign(ATy->getElementType(), EltAlign);
1215 if (EltAlign > MaxAlign)
1216 MaxAlign = EltAlign;
1217 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1218 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1219 unsigned EltAlign = 0;
1220 getMaxByValAlign(STy->getElementType(i), EltAlign);
1221 if (EltAlign > MaxAlign)
1222 MaxAlign = EltAlign;
1230 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1231 /// function arguments in the caller parameter area. For X86, aggregates
1232 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1233 /// are at 4-byte boundaries.
1234 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1235 if (Subtarget->is64Bit()) {
1236 // Max of 8 and alignment of type.
1237 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1244 if (Subtarget->hasXMM())
1245 getMaxByValAlign(Ty, Align);
1249 /// getOptimalMemOpType - Returns the target specific optimal type for load
1250 /// and store operations as a result of memset, memcpy, and memmove
1251 /// lowering. If DstAlign is zero that means it's safe to destination
1252 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1253 /// means there isn't a need to check it against alignment requirement,
1254 /// probably because the source does not need to be loaded. If
1255 /// 'IsZeroVal' is true, that means it's safe to return a
1256 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1257 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1258 /// constant so it does not need to be loaded.
1259 /// It returns EVT::Other if the type should be determined using generic
1260 /// target-independent logic.
1262 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1263 unsigned DstAlign, unsigned SrcAlign,
1266 MachineFunction &MF) const {
1267 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1268 // linux. This is because the stack realignment code can't handle certain
1269 // cases like PR2962. This should be removed when PR2962 is fixed.
1270 const Function *F = MF.getFunction();
1272 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1274 (Subtarget->isUnalignedMemAccessFast() ||
1275 ((DstAlign == 0 || DstAlign >= 16) &&
1276 (SrcAlign == 0 || SrcAlign >= 16))) &&
1277 Subtarget->getStackAlignment() >= 16) {
1278 if (Subtarget->hasAVX() &&
1279 Subtarget->getStackAlignment() >= 32)
1281 if (Subtarget->hasXMMInt())
1283 if (Subtarget->hasXMM())
1285 } else if (!MemcpyStrSrc && Size >= 8 &&
1286 !Subtarget->is64Bit() &&
1287 Subtarget->getStackAlignment() >= 8 &&
1288 Subtarget->hasXMMInt()) {
1289 // Do not use f64 to lower memcpy if source is string constant. It's
1290 // better to use i32 to avoid the loads.
1294 if (Subtarget->is64Bit() && Size >= 8)
1299 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1300 /// current function. The returned value is a member of the
1301 /// MachineJumpTableInfo::JTEntryKind enum.
1302 unsigned X86TargetLowering::getJumpTableEncoding() const {
1303 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1305 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1306 Subtarget->isPICStyleGOT())
1307 return MachineJumpTableInfo::EK_Custom32;
1309 // Otherwise, use the normal jump table encoding heuristics.
1310 return TargetLowering::getJumpTableEncoding();
1314 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1315 const MachineBasicBlock *MBB,
1316 unsigned uid,MCContext &Ctx) const{
1317 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1318 Subtarget->isPICStyleGOT());
1319 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1321 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1322 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1325 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1327 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1328 SelectionDAG &DAG) const {
1329 if (!Subtarget->is64Bit())
1330 // This doesn't have DebugLoc associated with it, but is not really the
1331 // same as a Register.
1332 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1336 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1337 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1339 const MCExpr *X86TargetLowering::
1340 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1341 MCContext &Ctx) const {
1342 // X86-64 uses RIP relative addressing based on the jump table label.
1343 if (Subtarget->isPICStyleRIPRel())
1344 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1346 // Otherwise, the reference is relative to the PIC base.
1347 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1350 // FIXME: Why this routine is here? Move to RegInfo!
1351 std::pair<const TargetRegisterClass*, uint8_t>
1352 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1353 const TargetRegisterClass *RRC = 0;
1355 switch (VT.getSimpleVT().SimpleTy) {
1357 return TargetLowering::findRepresentativeClass(VT);
1358 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1359 RRC = (Subtarget->is64Bit()
1360 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1363 RRC = X86::VR64RegisterClass;
1365 case MVT::f32: case MVT::f64:
1366 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1367 case MVT::v4f32: case MVT::v2f64:
1368 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1370 RRC = X86::VR128RegisterClass;
1373 return std::make_pair(RRC, Cost);
1376 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1377 unsigned &Offset) const {
1378 if (!Subtarget->isTargetLinux())
1381 if (Subtarget->is64Bit()) {
1382 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1384 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1397 //===----------------------------------------------------------------------===//
1398 // Return Value Calling Convention Implementation
1399 //===----------------------------------------------------------------------===//
1401 #include "X86GenCallingConv.inc"
1404 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1405 MachineFunction &MF, bool isVarArg,
1406 const SmallVectorImpl<ISD::OutputArg> &Outs,
1407 LLVMContext &Context) const {
1408 SmallVector<CCValAssign, 16> RVLocs;
1409 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1411 return CCInfo.CheckReturn(Outs, RetCC_X86);
1415 X86TargetLowering::LowerReturn(SDValue Chain,
1416 CallingConv::ID CallConv, bool isVarArg,
1417 const SmallVectorImpl<ISD::OutputArg> &Outs,
1418 const SmallVectorImpl<SDValue> &OutVals,
1419 DebugLoc dl, SelectionDAG &DAG) const {
1420 MachineFunction &MF = DAG.getMachineFunction();
1421 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1423 SmallVector<CCValAssign, 16> RVLocs;
1424 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1425 RVLocs, *DAG.getContext());
1426 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1428 // Add the regs to the liveout set for the function.
1429 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1430 for (unsigned i = 0; i != RVLocs.size(); ++i)
1431 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1432 MRI.addLiveOut(RVLocs[i].getLocReg());
1436 SmallVector<SDValue, 6> RetOps;
1437 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1438 // Operand #1 = Bytes To Pop
1439 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1442 // Copy the result values into the output registers.
1443 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1444 CCValAssign &VA = RVLocs[i];
1445 assert(VA.isRegLoc() && "Can only return in registers!");
1446 SDValue ValToCopy = OutVals[i];
1447 EVT ValVT = ValToCopy.getValueType();
1449 // If this is x86-64, and we disabled SSE, we can't return FP values,
1450 // or SSE or MMX vectors.
1451 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1452 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1453 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1454 report_fatal_error("SSE register return with SSE disabled");
1456 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1457 // llvm-gcc has never done it right and no one has noticed, so this
1458 // should be OK for now.
1459 if (ValVT == MVT::f64 &&
1460 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1461 report_fatal_error("SSE2 register return with SSE2 disabled");
1463 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1464 // the RET instruction and handled by the FP Stackifier.
1465 if (VA.getLocReg() == X86::ST0 ||
1466 VA.getLocReg() == X86::ST1) {
1467 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1468 // change the value to the FP stack register class.
1469 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1470 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1471 RetOps.push_back(ValToCopy);
1472 // Don't emit a copytoreg.
1476 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1477 // which is returned in RAX / RDX.
1478 if (Subtarget->is64Bit()) {
1479 if (ValVT == MVT::x86mmx) {
1480 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1481 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1482 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1484 // If we don't have SSE2 available, convert to v4f32 so the generated
1485 // register is legal.
1486 if (!Subtarget->hasXMMInt())
1487 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1492 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1493 Flag = Chain.getValue(1);
1496 // The x86-64 ABI for returning structs by value requires that we copy
1497 // the sret argument into %rax for the return. We saved the argument into
1498 // a virtual register in the entry block, so now we copy the value out
1500 if (Subtarget->is64Bit() &&
1501 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1502 MachineFunction &MF = DAG.getMachineFunction();
1503 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1504 unsigned Reg = FuncInfo->getSRetReturnReg();
1506 "SRetReturnReg should have been set in LowerFormalArguments().");
1507 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1509 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1510 Flag = Chain.getValue(1);
1512 // RAX now acts like a return value.
1513 MRI.addLiveOut(X86::RAX);
1516 RetOps[0] = Chain; // Update chain.
1518 // Add the flag if we have it.
1520 RetOps.push_back(Flag);
1522 return DAG.getNode(X86ISD::RET_FLAG, dl,
1523 MVT::Other, &RetOps[0], RetOps.size());
1526 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1527 if (N->getNumValues() != 1)
1529 if (!N->hasNUsesOfValue(1, 0))
1532 SDNode *Copy = *N->use_begin();
1533 if (Copy->getOpcode() != ISD::CopyToReg &&
1534 Copy->getOpcode() != ISD::FP_EXTEND)
1537 bool HasRet = false;
1538 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1540 if (UI->getOpcode() != X86ISD::RET_FLAG)
1549 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1550 ISD::NodeType ExtendKind) const {
1552 // TODO: Is this also valid on 32-bit?
1553 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1554 ReturnMVT = MVT::i8;
1556 ReturnMVT = MVT::i32;
1558 EVT MinVT = getRegisterType(Context, ReturnMVT);
1559 return VT.bitsLT(MinVT) ? MinVT : VT;
1562 /// LowerCallResult - Lower the result values of a call into the
1563 /// appropriate copies out of appropriate physical registers.
1566 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1567 CallingConv::ID CallConv, bool isVarArg,
1568 const SmallVectorImpl<ISD::InputArg> &Ins,
1569 DebugLoc dl, SelectionDAG &DAG,
1570 SmallVectorImpl<SDValue> &InVals) const {
1572 // Assign locations to each value returned by this call.
1573 SmallVector<CCValAssign, 16> RVLocs;
1574 bool Is64Bit = Subtarget->is64Bit();
1575 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1576 getTargetMachine(), RVLocs, *DAG.getContext());
1577 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1579 // Copy all of the result registers out of their specified physreg.
1580 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1581 CCValAssign &VA = RVLocs[i];
1582 EVT CopyVT = VA.getValVT();
1584 // If this is x86-64, and we disabled SSE, we can't return FP values
1585 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1586 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1587 report_fatal_error("SSE register return with SSE disabled");
1592 // If this is a call to a function that returns an fp value on the floating
1593 // point stack, we must guarantee the the value is popped from the stack, so
1594 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1595 // if the return value is not used. We use the FpPOP_RETVAL instruction
1597 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1598 // If we prefer to use the value in xmm registers, copy it out as f80 and
1599 // use a truncate to move it from fp stack reg to xmm reg.
1600 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1601 SDValue Ops[] = { Chain, InFlag };
1602 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1603 MVT::Other, MVT::Glue, Ops, 2), 1);
1604 Val = Chain.getValue(0);
1606 // Round the f80 to the right size, which also moves it to the appropriate
1608 if (CopyVT != VA.getValVT())
1609 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1610 // This truncation won't change the value.
1611 DAG.getIntPtrConstant(1));
1613 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1614 CopyVT, InFlag).getValue(1);
1615 Val = Chain.getValue(0);
1617 InFlag = Chain.getValue(2);
1618 InVals.push_back(Val);
1625 //===----------------------------------------------------------------------===//
1626 // C & StdCall & Fast Calling Convention implementation
1627 //===----------------------------------------------------------------------===//
1628 // StdCall calling convention seems to be standard for many Windows' API
1629 // routines and around. It differs from C calling convention just a little:
1630 // callee should clean up the stack, not caller. Symbols should be also
1631 // decorated in some fancy way :) It doesn't support any vector arguments.
1632 // For info on fast calling convention see Fast Calling Convention (tail call)
1633 // implementation LowerX86_32FastCCCallTo.
1635 /// CallIsStructReturn - Determines whether a call uses struct return
1637 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1641 return Outs[0].Flags.isSRet();
1644 /// ArgsAreStructReturn - Determines whether a function uses struct
1645 /// return semantics.
1647 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1651 return Ins[0].Flags.isSRet();
1654 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1655 /// by "Src" to address "Dst" with size and alignment information specified by
1656 /// the specific parameter attribute. The copy will be passed as a byval
1657 /// function parameter.
1659 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1660 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1662 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1664 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1665 /*isVolatile*/false, /*AlwaysInline=*/true,
1666 MachinePointerInfo(), MachinePointerInfo());
1669 /// IsTailCallConvention - Return true if the calling convention is one that
1670 /// supports tail call optimization.
1671 static bool IsTailCallConvention(CallingConv::ID CC) {
1672 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1675 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1676 if (!CI->isTailCall())
1680 CallingConv::ID CalleeCC = CS.getCallingConv();
1681 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1687 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1688 /// a tailcall target by changing its ABI.
1689 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1690 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1694 X86TargetLowering::LowerMemArgument(SDValue Chain,
1695 CallingConv::ID CallConv,
1696 const SmallVectorImpl<ISD::InputArg> &Ins,
1697 DebugLoc dl, SelectionDAG &DAG,
1698 const CCValAssign &VA,
1699 MachineFrameInfo *MFI,
1701 // Create the nodes corresponding to a load from this parameter slot.
1702 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1703 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1704 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1707 // If value is passed by pointer we have address passed instead of the value
1709 if (VA.getLocInfo() == CCValAssign::Indirect)
1710 ValVT = VA.getLocVT();
1712 ValVT = VA.getValVT();
1714 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1715 // changed with more analysis.
1716 // In case of tail call optimization mark all arguments mutable. Since they
1717 // could be overwritten by lowering of arguments in case of a tail call.
1718 if (Flags.isByVal()) {
1719 unsigned Bytes = Flags.getByValSize();
1720 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1721 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1722 return DAG.getFrameIndex(FI, getPointerTy());
1724 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1725 VA.getLocMemOffset(), isImmutable);
1726 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1727 return DAG.getLoad(ValVT, dl, Chain, FIN,
1728 MachinePointerInfo::getFixedStack(FI),
1729 false, false, false, 0);
1734 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1735 CallingConv::ID CallConv,
1737 const SmallVectorImpl<ISD::InputArg> &Ins,
1740 SmallVectorImpl<SDValue> &InVals)
1742 MachineFunction &MF = DAG.getMachineFunction();
1743 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1745 const Function* Fn = MF.getFunction();
1746 if (Fn->hasExternalLinkage() &&
1747 Subtarget->isTargetCygMing() &&
1748 Fn->getName() == "main")
1749 FuncInfo->setForceFramePointer(true);
1751 MachineFrameInfo *MFI = MF.getFrameInfo();
1752 bool Is64Bit = Subtarget->is64Bit();
1753 bool IsWin64 = Subtarget->isTargetWin64();
1755 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1756 "Var args not supported with calling convention fastcc or ghc");
1758 // Assign locations to all of the incoming arguments.
1759 SmallVector<CCValAssign, 16> ArgLocs;
1760 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1761 ArgLocs, *DAG.getContext());
1763 // Allocate shadow area for Win64
1765 CCInfo.AllocateStack(32, 8);
1768 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1770 unsigned LastVal = ~0U;
1772 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1773 CCValAssign &VA = ArgLocs[i];
1774 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1776 assert(VA.getValNo() != LastVal &&
1777 "Don't support value assigned to multiple locs yet");
1779 LastVal = VA.getValNo();
1781 if (VA.isRegLoc()) {
1782 EVT RegVT = VA.getLocVT();
1783 TargetRegisterClass *RC = NULL;
1784 if (RegVT == MVT::i32)
1785 RC = X86::GR32RegisterClass;
1786 else if (Is64Bit && RegVT == MVT::i64)
1787 RC = X86::GR64RegisterClass;
1788 else if (RegVT == MVT::f32)
1789 RC = X86::FR32RegisterClass;
1790 else if (RegVT == MVT::f64)
1791 RC = X86::FR64RegisterClass;
1792 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1793 RC = X86::VR256RegisterClass;
1794 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1795 RC = X86::VR128RegisterClass;
1796 else if (RegVT == MVT::x86mmx)
1797 RC = X86::VR64RegisterClass;
1799 llvm_unreachable("Unknown argument type!");
1801 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1802 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1804 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1805 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1807 if (VA.getLocInfo() == CCValAssign::SExt)
1808 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1809 DAG.getValueType(VA.getValVT()));
1810 else if (VA.getLocInfo() == CCValAssign::ZExt)
1811 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1812 DAG.getValueType(VA.getValVT()));
1813 else if (VA.getLocInfo() == CCValAssign::BCvt)
1814 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1816 if (VA.isExtInLoc()) {
1817 // Handle MMX values passed in XMM regs.
1818 if (RegVT.isVector()) {
1819 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1822 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1825 assert(VA.isMemLoc());
1826 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1829 // If value is passed via pointer - do a load.
1830 if (VA.getLocInfo() == CCValAssign::Indirect)
1831 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1832 MachinePointerInfo(), false, false, false, 0);
1834 InVals.push_back(ArgValue);
1837 // The x86-64 ABI for returning structs by value requires that we copy
1838 // the sret argument into %rax for the return. Save the argument into
1839 // a virtual register so that we can access it from the return points.
1840 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1841 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1842 unsigned Reg = FuncInfo->getSRetReturnReg();
1844 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1845 FuncInfo->setSRetReturnReg(Reg);
1847 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1848 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1851 unsigned StackSize = CCInfo.getNextStackOffset();
1852 // Align stack specially for tail calls.
1853 if (FuncIsMadeTailCallSafe(CallConv))
1854 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1856 // If the function takes variable number of arguments, make a frame index for
1857 // the start of the first vararg value... for expansion of llvm.va_start.
1859 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1860 CallConv != CallingConv::X86_ThisCall)) {
1861 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1864 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1866 // FIXME: We should really autogenerate these arrays
1867 static const unsigned GPR64ArgRegsWin64[] = {
1868 X86::RCX, X86::RDX, X86::R8, X86::R9
1870 static const unsigned GPR64ArgRegs64Bit[] = {
1871 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1873 static const unsigned XMMArgRegs64Bit[] = {
1874 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1875 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1877 const unsigned *GPR64ArgRegs;
1878 unsigned NumXMMRegs = 0;
1881 // The XMM registers which might contain var arg parameters are shadowed
1882 // in their paired GPR. So we only need to save the GPR to their home
1884 TotalNumIntRegs = 4;
1885 GPR64ArgRegs = GPR64ArgRegsWin64;
1887 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1888 GPR64ArgRegs = GPR64ArgRegs64Bit;
1890 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1892 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1895 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1896 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1897 "SSE register cannot be used when SSE is disabled!");
1898 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1899 "SSE register cannot be used when SSE is disabled!");
1900 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1901 // Kernel mode asks for SSE to be disabled, so don't push them
1903 TotalNumXMMRegs = 0;
1906 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1907 // Get to the caller-allocated home save location. Add 8 to account
1908 // for the return address.
1909 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1910 FuncInfo->setRegSaveFrameIndex(
1911 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1912 // Fixup to set vararg frame on shadow area (4 x i64).
1914 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1916 // For X86-64, if there are vararg parameters that are passed via
1917 // registers, then we must store them to their spots on the stack so they
1918 // may be loaded by deferencing the result of va_next.
1919 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1920 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1921 FuncInfo->setRegSaveFrameIndex(
1922 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1926 // Store the integer parameter registers.
1927 SmallVector<SDValue, 8> MemOps;
1928 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1930 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1931 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1932 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1933 DAG.getIntPtrConstant(Offset));
1934 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1935 X86::GR64RegisterClass);
1936 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1938 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1939 MachinePointerInfo::getFixedStack(
1940 FuncInfo->getRegSaveFrameIndex(), Offset),
1942 MemOps.push_back(Store);
1946 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1947 // Now store the XMM (fp + vector) parameter registers.
1948 SmallVector<SDValue, 11> SaveXMMOps;
1949 SaveXMMOps.push_back(Chain);
1951 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1952 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1953 SaveXMMOps.push_back(ALVal);
1955 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1956 FuncInfo->getRegSaveFrameIndex()));
1957 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1958 FuncInfo->getVarArgsFPOffset()));
1960 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1961 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1962 X86::VR128RegisterClass);
1963 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1964 SaveXMMOps.push_back(Val);
1966 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1968 &SaveXMMOps[0], SaveXMMOps.size()));
1971 if (!MemOps.empty())
1972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1973 &MemOps[0], MemOps.size());
1977 // Some CCs need callee pop.
1978 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1979 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1981 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1982 // If this is an sret function, the return should pop the hidden pointer.
1983 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1984 FuncInfo->setBytesToPopOnReturn(4);
1988 // RegSaveFrameIndex is X86-64 only.
1989 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1990 if (CallConv == CallingConv::X86_FastCall ||
1991 CallConv == CallingConv::X86_ThisCall)
1992 // fastcc functions can't have varargs.
1993 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1996 FuncInfo->setArgumentStackSize(StackSize);
2002 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2003 SDValue StackPtr, SDValue Arg,
2004 DebugLoc dl, SelectionDAG &DAG,
2005 const CCValAssign &VA,
2006 ISD::ArgFlagsTy Flags) const {
2007 unsigned LocMemOffset = VA.getLocMemOffset();
2008 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2009 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2010 if (Flags.isByVal())
2011 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2013 return DAG.getStore(Chain, dl, Arg, PtrOff,
2014 MachinePointerInfo::getStack(LocMemOffset),
2018 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2019 /// optimization is performed and it is required.
2021 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2022 SDValue &OutRetAddr, SDValue Chain,
2023 bool IsTailCall, bool Is64Bit,
2024 int FPDiff, DebugLoc dl) const {
2025 // Adjust the Return address stack slot.
2026 EVT VT = getPointerTy();
2027 OutRetAddr = getReturnAddressFrameIndex(DAG);
2029 // Load the "old" Return address.
2030 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2031 false, false, false, 0);
2032 return SDValue(OutRetAddr.getNode(), 1);
2035 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2036 /// optimization is performed and it is required (FPDiff!=0).
2038 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2039 SDValue Chain, SDValue RetAddrFrIdx,
2040 bool Is64Bit, int FPDiff, DebugLoc dl) {
2041 // Store the return address to the appropriate stack slot.
2042 if (!FPDiff) return Chain;
2043 // Calculate the new stack slot for the return address.
2044 int SlotSize = Is64Bit ? 8 : 4;
2045 int NewReturnAddrFI =
2046 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2047 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2048 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2049 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2050 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2056 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2057 CallingConv::ID CallConv, bool isVarArg,
2059 const SmallVectorImpl<ISD::OutputArg> &Outs,
2060 const SmallVectorImpl<SDValue> &OutVals,
2061 const SmallVectorImpl<ISD::InputArg> &Ins,
2062 DebugLoc dl, SelectionDAG &DAG,
2063 SmallVectorImpl<SDValue> &InVals) const {
2064 MachineFunction &MF = DAG.getMachineFunction();
2065 bool Is64Bit = Subtarget->is64Bit();
2066 bool IsWin64 = Subtarget->isTargetWin64();
2067 bool IsStructRet = CallIsStructReturn(Outs);
2068 bool IsSibcall = false;
2071 // Check if it's really possible to do a tail call.
2072 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2073 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2074 Outs, OutVals, Ins, DAG);
2076 // Sibcalls are automatically detected tailcalls which do not require
2078 if (!GuaranteedTailCallOpt && isTailCall)
2085 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2086 "Var args not supported with calling convention fastcc or ghc");
2088 // Analyze operands of the call, assigning locations to each operand.
2089 SmallVector<CCValAssign, 16> ArgLocs;
2090 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2091 ArgLocs, *DAG.getContext());
2093 // Allocate shadow area for Win64
2095 CCInfo.AllocateStack(32, 8);
2098 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2100 // Get a count of how many bytes are to be pushed on the stack.
2101 unsigned NumBytes = CCInfo.getNextStackOffset();
2103 // This is a sibcall. The memory operands are available in caller's
2104 // own caller's stack.
2106 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2107 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2110 if (isTailCall && !IsSibcall) {
2111 // Lower arguments at fp - stackoffset + fpdiff.
2112 unsigned NumBytesCallerPushed =
2113 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2114 FPDiff = NumBytesCallerPushed - NumBytes;
2116 // Set the delta of movement of the returnaddr stackslot.
2117 // But only set if delta is greater than previous delta.
2118 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2119 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2123 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2125 SDValue RetAddrFrIdx;
2126 // Load return address for tail calls.
2127 if (isTailCall && FPDiff)
2128 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2129 Is64Bit, FPDiff, dl);
2131 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2132 SmallVector<SDValue, 8> MemOpChains;
2135 // Walk the register/memloc assignments, inserting copies/loads. In the case
2136 // of tail call optimization arguments are handle later.
2137 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2138 CCValAssign &VA = ArgLocs[i];
2139 EVT RegVT = VA.getLocVT();
2140 SDValue Arg = OutVals[i];
2141 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2142 bool isByVal = Flags.isByVal();
2144 // Promote the value if needed.
2145 switch (VA.getLocInfo()) {
2146 default: llvm_unreachable("Unknown loc info!");
2147 case CCValAssign::Full: break;
2148 case CCValAssign::SExt:
2149 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2151 case CCValAssign::ZExt:
2152 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2154 case CCValAssign::AExt:
2155 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2156 // Special case: passing MMX values in XMM registers.
2157 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2158 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2159 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2161 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2163 case CCValAssign::BCvt:
2164 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2166 case CCValAssign::Indirect: {
2167 // Store the argument.
2168 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2169 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2170 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2171 MachinePointerInfo::getFixedStack(FI),
2178 if (VA.isRegLoc()) {
2179 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2180 if (isVarArg && IsWin64) {
2181 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2182 // shadow reg if callee is a varargs function.
2183 unsigned ShadowReg = 0;
2184 switch (VA.getLocReg()) {
2185 case X86::XMM0: ShadowReg = X86::RCX; break;
2186 case X86::XMM1: ShadowReg = X86::RDX; break;
2187 case X86::XMM2: ShadowReg = X86::R8; break;
2188 case X86::XMM3: ShadowReg = X86::R9; break;
2191 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2193 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2194 assert(VA.isMemLoc());
2195 if (StackPtr.getNode() == 0)
2196 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2197 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2198 dl, DAG, VA, Flags));
2202 if (!MemOpChains.empty())
2203 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2204 &MemOpChains[0], MemOpChains.size());
2206 // Build a sequence of copy-to-reg nodes chained together with token chain
2207 // and flag operands which copy the outgoing args into registers.
2209 // Tail call byval lowering might overwrite argument registers so in case of
2210 // tail call optimization the copies to registers are lowered later.
2212 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2213 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2214 RegsToPass[i].second, InFlag);
2215 InFlag = Chain.getValue(1);
2218 if (Subtarget->isPICStyleGOT()) {
2219 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2222 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2223 DAG.getNode(X86ISD::GlobalBaseReg,
2224 DebugLoc(), getPointerTy()),
2226 InFlag = Chain.getValue(1);
2228 // If we are tail calling and generating PIC/GOT style code load the
2229 // address of the callee into ECX. The value in ecx is used as target of
2230 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2231 // for tail calls on PIC/GOT architectures. Normally we would just put the
2232 // address of GOT into ebx and then call target@PLT. But for tail calls
2233 // ebx would be restored (since ebx is callee saved) before jumping to the
2236 // Note: The actual moving to ECX is done further down.
2237 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2238 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2239 !G->getGlobal()->hasProtectedVisibility())
2240 Callee = LowerGlobalAddress(Callee, DAG);
2241 else if (isa<ExternalSymbolSDNode>(Callee))
2242 Callee = LowerExternalSymbol(Callee, DAG);
2246 if (Is64Bit && isVarArg && !IsWin64) {
2247 // From AMD64 ABI document:
2248 // For calls that may call functions that use varargs or stdargs
2249 // (prototype-less calls or calls to functions containing ellipsis (...) in
2250 // the declaration) %al is used as hidden argument to specify the number
2251 // of SSE registers used. The contents of %al do not need to match exactly
2252 // the number of registers, but must be an ubound on the number of SSE
2253 // registers used and is in the range 0 - 8 inclusive.
2255 // Count the number of XMM registers allocated.
2256 static const unsigned XMMArgRegs[] = {
2257 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2258 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2260 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2261 assert((Subtarget->hasXMM() || !NumXMMRegs)
2262 && "SSE registers cannot be used when SSE is disabled");
2264 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2265 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2266 InFlag = Chain.getValue(1);
2270 // For tail calls lower the arguments to the 'real' stack slot.
2272 // Force all the incoming stack arguments to be loaded from the stack
2273 // before any new outgoing arguments are stored to the stack, because the
2274 // outgoing stack slots may alias the incoming argument stack slots, and
2275 // the alias isn't otherwise explicit. This is slightly more conservative
2276 // than necessary, because it means that each store effectively depends
2277 // on every argument instead of just those arguments it would clobber.
2278 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2280 SmallVector<SDValue, 8> MemOpChains2;
2283 // Do not flag preceding copytoreg stuff together with the following stuff.
2285 if (GuaranteedTailCallOpt) {
2286 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2287 CCValAssign &VA = ArgLocs[i];
2290 assert(VA.isMemLoc());
2291 SDValue Arg = OutVals[i];
2292 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2293 // Create frame index.
2294 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2295 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2296 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2297 FIN = DAG.getFrameIndex(FI, getPointerTy());
2299 if (Flags.isByVal()) {
2300 // Copy relative to framepointer.
2301 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2302 if (StackPtr.getNode() == 0)
2303 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2305 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2307 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2311 // Store relative to framepointer.
2312 MemOpChains2.push_back(
2313 DAG.getStore(ArgChain, dl, Arg, FIN,
2314 MachinePointerInfo::getFixedStack(FI),
2320 if (!MemOpChains2.empty())
2321 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2322 &MemOpChains2[0], MemOpChains2.size());
2324 // Copy arguments to their registers.
2325 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2326 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2327 RegsToPass[i].second, InFlag);
2328 InFlag = Chain.getValue(1);
2332 // Store the return address to the appropriate stack slot.
2333 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2337 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2338 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2339 // In the 64-bit large code model, we have to make all calls
2340 // through a register, since the call instruction's 32-bit
2341 // pc-relative offset may not be large enough to hold the whole
2343 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2344 // If the callee is a GlobalAddress node (quite common, every direct call
2345 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2348 // We should use extra load for direct calls to dllimported functions in
2350 const GlobalValue *GV = G->getGlobal();
2351 if (!GV->hasDLLImportLinkage()) {
2352 unsigned char OpFlags = 0;
2353 bool ExtraLoad = false;
2354 unsigned WrapperKind = ISD::DELETED_NODE;
2356 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2357 // external symbols most go through the PLT in PIC mode. If the symbol
2358 // has hidden or protected visibility, or if it is static or local, then
2359 // we don't need to use the PLT - we can directly call it.
2360 if (Subtarget->isTargetELF() &&
2361 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2362 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2363 OpFlags = X86II::MO_PLT;
2364 } else if (Subtarget->isPICStyleStubAny() &&
2365 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2366 (!Subtarget->getTargetTriple().isMacOSX() ||
2367 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2368 // PC-relative references to external symbols should go through $stub,
2369 // unless we're building with the leopard linker or later, which
2370 // automatically synthesizes these stubs.
2371 OpFlags = X86II::MO_DARWIN_STUB;
2372 } else if (Subtarget->isPICStyleRIPRel() &&
2373 isa<Function>(GV) &&
2374 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2375 // If the function is marked as non-lazy, generate an indirect call
2376 // which loads from the GOT directly. This avoids runtime overhead
2377 // at the cost of eager binding (and one extra byte of encoding).
2378 OpFlags = X86II::MO_GOTPCREL;
2379 WrapperKind = X86ISD::WrapperRIP;
2383 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2384 G->getOffset(), OpFlags);
2386 // Add a wrapper if needed.
2387 if (WrapperKind != ISD::DELETED_NODE)
2388 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2389 // Add extra indirection if needed.
2391 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2392 MachinePointerInfo::getGOT(),
2393 false, false, false, 0);
2395 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2396 unsigned char OpFlags = 0;
2398 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2399 // external symbols should go through the PLT.
2400 if (Subtarget->isTargetELF() &&
2401 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2402 OpFlags = X86II::MO_PLT;
2403 } else if (Subtarget->isPICStyleStubAny() &&
2404 (!Subtarget->getTargetTriple().isMacOSX() ||
2405 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2406 // PC-relative references to external symbols should go through $stub,
2407 // unless we're building with the leopard linker or later, which
2408 // automatically synthesizes these stubs.
2409 OpFlags = X86II::MO_DARWIN_STUB;
2412 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2416 // Returns a chain & a flag for retval copy to use.
2417 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2418 SmallVector<SDValue, 8> Ops;
2420 if (!IsSibcall && isTailCall) {
2421 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2422 DAG.getIntPtrConstant(0, true), InFlag);
2423 InFlag = Chain.getValue(1);
2426 Ops.push_back(Chain);
2427 Ops.push_back(Callee);
2430 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2432 // Add argument registers to the end of the list so that they are known live
2434 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2435 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2436 RegsToPass[i].second.getValueType()));
2438 // Add an implicit use GOT pointer in EBX.
2439 if (!isTailCall && Subtarget->isPICStyleGOT())
2440 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2442 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2443 if (Is64Bit && isVarArg && !IsWin64)
2444 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2446 if (InFlag.getNode())
2447 Ops.push_back(InFlag);
2451 //// If this is the first return lowered for this function, add the regs
2452 //// to the liveout set for the function.
2453 // This isn't right, although it's probably harmless on x86; liveouts
2454 // should be computed from returns not tail calls. Consider a void
2455 // function making a tail call to a function returning int.
2456 return DAG.getNode(X86ISD::TC_RETURN, dl,
2457 NodeTys, &Ops[0], Ops.size());
2460 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2461 InFlag = Chain.getValue(1);
2463 // Create the CALLSEQ_END node.
2464 unsigned NumBytesForCalleeToPush;
2465 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2466 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2467 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2468 // If this is a call to a struct-return function, the callee
2469 // pops the hidden struct pointer, so we have to push it back.
2470 // This is common for Darwin/X86, Linux & Mingw32 targets.
2471 NumBytesForCalleeToPush = 4;
2473 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2475 // Returns a flag for retval copy to use.
2477 Chain = DAG.getCALLSEQ_END(Chain,
2478 DAG.getIntPtrConstant(NumBytes, true),
2479 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2482 InFlag = Chain.getValue(1);
2485 // Handle result values, copying them out of physregs into vregs that we
2487 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2488 Ins, dl, DAG, InVals);
2492 //===----------------------------------------------------------------------===//
2493 // Fast Calling Convention (tail call) implementation
2494 //===----------------------------------------------------------------------===//
2496 // Like std call, callee cleans arguments, convention except that ECX is
2497 // reserved for storing the tail called function address. Only 2 registers are
2498 // free for argument passing (inreg). Tail call optimization is performed
2500 // * tailcallopt is enabled
2501 // * caller/callee are fastcc
2502 // On X86_64 architecture with GOT-style position independent code only local
2503 // (within module) calls are supported at the moment.
2504 // To keep the stack aligned according to platform abi the function
2505 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2506 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2507 // If a tail called function callee has more arguments than the caller the
2508 // caller needs to make sure that there is room to move the RETADDR to. This is
2509 // achieved by reserving an area the size of the argument delta right after the
2510 // original REtADDR, but before the saved framepointer or the spilled registers
2511 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2523 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2524 /// for a 16 byte align requirement.
2526 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2527 SelectionDAG& DAG) const {
2528 MachineFunction &MF = DAG.getMachineFunction();
2529 const TargetMachine &TM = MF.getTarget();
2530 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2531 unsigned StackAlignment = TFI.getStackAlignment();
2532 uint64_t AlignMask = StackAlignment - 1;
2533 int64_t Offset = StackSize;
2534 uint64_t SlotSize = TD->getPointerSize();
2535 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2536 // Number smaller than 12 so just add the difference.
2537 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2539 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2540 Offset = ((~AlignMask) & Offset) + StackAlignment +
2541 (StackAlignment-SlotSize);
2546 /// MatchingStackOffset - Return true if the given stack call argument is
2547 /// already available in the same position (relatively) of the caller's
2548 /// incoming argument stack.
2550 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2551 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2552 const X86InstrInfo *TII) {
2553 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2555 if (Arg.getOpcode() == ISD::CopyFromReg) {
2556 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2557 if (!TargetRegisterInfo::isVirtualRegister(VR))
2559 MachineInstr *Def = MRI->getVRegDef(VR);
2562 if (!Flags.isByVal()) {
2563 if (!TII->isLoadFromStackSlot(Def, FI))
2566 unsigned Opcode = Def->getOpcode();
2567 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2568 Def->getOperand(1).isFI()) {
2569 FI = Def->getOperand(1).getIndex();
2570 Bytes = Flags.getByValSize();
2574 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2575 if (Flags.isByVal())
2576 // ByVal argument is passed in as a pointer but it's now being
2577 // dereferenced. e.g.
2578 // define @foo(%struct.X* %A) {
2579 // tail call @bar(%struct.X* byval %A)
2582 SDValue Ptr = Ld->getBasePtr();
2583 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2586 FI = FINode->getIndex();
2587 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2588 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2589 FI = FINode->getIndex();
2590 Bytes = Flags.getByValSize();
2594 assert(FI != INT_MAX);
2595 if (!MFI->isFixedObjectIndex(FI))
2597 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2600 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2601 /// for tail call optimization. Targets which want to do tail call
2602 /// optimization should implement this function.
2604 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2605 CallingConv::ID CalleeCC,
2607 bool isCalleeStructRet,
2608 bool isCallerStructRet,
2609 const SmallVectorImpl<ISD::OutputArg> &Outs,
2610 const SmallVectorImpl<SDValue> &OutVals,
2611 const SmallVectorImpl<ISD::InputArg> &Ins,
2612 SelectionDAG& DAG) const {
2613 if (!IsTailCallConvention(CalleeCC) &&
2614 CalleeCC != CallingConv::C)
2617 // If -tailcallopt is specified, make fastcc functions tail-callable.
2618 const MachineFunction &MF = DAG.getMachineFunction();
2619 const Function *CallerF = DAG.getMachineFunction().getFunction();
2620 CallingConv::ID CallerCC = CallerF->getCallingConv();
2621 bool CCMatch = CallerCC == CalleeCC;
2623 if (GuaranteedTailCallOpt) {
2624 if (IsTailCallConvention(CalleeCC) && CCMatch)
2629 // Look for obvious safe cases to perform tail call optimization that do not
2630 // require ABI changes. This is what gcc calls sibcall.
2632 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2633 // emit a special epilogue.
2634 if (RegInfo->needsStackRealignment(MF))
2637 // Also avoid sibcall optimization if either caller or callee uses struct
2638 // return semantics.
2639 if (isCalleeStructRet || isCallerStructRet)
2642 // An stdcall caller is expected to clean up its arguments; the callee
2643 // isn't going to do that.
2644 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2647 // Do not sibcall optimize vararg calls unless all arguments are passed via
2649 if (isVarArg && !Outs.empty()) {
2651 // Optimizing for varargs on Win64 is unlikely to be safe without
2652 // additional testing.
2653 if (Subtarget->isTargetWin64())
2656 SmallVector<CCValAssign, 16> ArgLocs;
2657 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2658 getTargetMachine(), ArgLocs, *DAG.getContext());
2660 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2661 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2662 if (!ArgLocs[i].isRegLoc())
2666 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2667 // Therefore if it's not used by the call it is not safe to optimize this into
2669 bool Unused = false;
2670 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2677 SmallVector<CCValAssign, 16> RVLocs;
2678 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2679 getTargetMachine(), RVLocs, *DAG.getContext());
2680 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2681 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2682 CCValAssign &VA = RVLocs[i];
2683 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2688 // If the calling conventions do not match, then we'd better make sure the
2689 // results are returned in the same way as what the caller expects.
2691 SmallVector<CCValAssign, 16> RVLocs1;
2692 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2693 getTargetMachine(), RVLocs1, *DAG.getContext());
2694 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2696 SmallVector<CCValAssign, 16> RVLocs2;
2697 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2698 getTargetMachine(), RVLocs2, *DAG.getContext());
2699 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2701 if (RVLocs1.size() != RVLocs2.size())
2703 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2704 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2706 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2708 if (RVLocs1[i].isRegLoc()) {
2709 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2712 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2718 // If the callee takes no arguments then go on to check the results of the
2720 if (!Outs.empty()) {
2721 // Check if stack adjustment is needed. For now, do not do this if any
2722 // argument is passed on the stack.
2723 SmallVector<CCValAssign, 16> ArgLocs;
2724 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2725 getTargetMachine(), ArgLocs, *DAG.getContext());
2727 // Allocate shadow area for Win64
2728 if (Subtarget->isTargetWin64()) {
2729 CCInfo.AllocateStack(32, 8);
2732 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2733 if (CCInfo.getNextStackOffset()) {
2734 MachineFunction &MF = DAG.getMachineFunction();
2735 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2738 // Check if the arguments are already laid out in the right way as
2739 // the caller's fixed stack objects.
2740 MachineFrameInfo *MFI = MF.getFrameInfo();
2741 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2742 const X86InstrInfo *TII =
2743 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2744 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2745 CCValAssign &VA = ArgLocs[i];
2746 SDValue Arg = OutVals[i];
2747 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2748 if (VA.getLocInfo() == CCValAssign::Indirect)
2750 if (!VA.isRegLoc()) {
2751 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2758 // If the tailcall address may be in a register, then make sure it's
2759 // possible to register allocate for it. In 32-bit, the call address can
2760 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2761 // callee-saved registers are restored. These happen to be the same
2762 // registers used to pass 'inreg' arguments so watch out for those.
2763 if (!Subtarget->is64Bit() &&
2764 !isa<GlobalAddressSDNode>(Callee) &&
2765 !isa<ExternalSymbolSDNode>(Callee)) {
2766 unsigned NumInRegs = 0;
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768 CCValAssign &VA = ArgLocs[i];
2771 unsigned Reg = VA.getLocReg();
2774 case X86::EAX: case X86::EDX: case X86::ECX:
2775 if (++NumInRegs == 3)
2787 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2788 return X86::createFastISel(funcInfo);
2792 //===----------------------------------------------------------------------===//
2793 // Other Lowering Hooks
2794 //===----------------------------------------------------------------------===//
2796 static bool MayFoldLoad(SDValue Op) {
2797 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2800 static bool MayFoldIntoStore(SDValue Op) {
2801 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2804 static bool isTargetShuffle(unsigned Opcode) {
2806 default: return false;
2807 case X86ISD::PSHUFD:
2808 case X86ISD::PSHUFHW:
2809 case X86ISD::PSHUFLW:
2810 case X86ISD::SHUFPD:
2811 case X86ISD::PALIGN:
2812 case X86ISD::SHUFPS:
2813 case X86ISD::MOVLHPS:
2814 case X86ISD::MOVLHPD:
2815 case X86ISD::MOVHLPS:
2816 case X86ISD::MOVLPS:
2817 case X86ISD::MOVLPD:
2818 case X86ISD::MOVSHDUP:
2819 case X86ISD::MOVSLDUP:
2820 case X86ISD::MOVDDUP:
2823 case X86ISD::UNPCKLPS:
2824 case X86ISD::UNPCKLPD:
2825 case X86ISD::VUNPCKLPSY:
2826 case X86ISD::VUNPCKLPDY:
2827 case X86ISD::PUNPCKLWD:
2828 case X86ISD::PUNPCKLBW:
2829 case X86ISD::PUNPCKLDQ:
2830 case X86ISD::PUNPCKLQDQ:
2831 case X86ISD::UNPCKHPS:
2832 case X86ISD::UNPCKHPD:
2833 case X86ISD::VUNPCKHPSY:
2834 case X86ISD::VUNPCKHPDY:
2835 case X86ISD::PUNPCKHWD:
2836 case X86ISD::PUNPCKHBW:
2837 case X86ISD::PUNPCKHDQ:
2838 case X86ISD::PUNPCKHQDQ:
2839 case X86ISD::VPERMILPS:
2840 case X86ISD::VPERMILPSY:
2841 case X86ISD::VPERMILPD:
2842 case X86ISD::VPERMILPDY:
2843 case X86ISD::VPERM2F128:
2849 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2850 SDValue V1, SelectionDAG &DAG) {
2852 default: llvm_unreachable("Unknown x86 shuffle node");
2853 case X86ISD::MOVSHDUP:
2854 case X86ISD::MOVSLDUP:
2855 case X86ISD::MOVDDUP:
2856 return DAG.getNode(Opc, dl, VT, V1);
2862 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2863 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2865 default: llvm_unreachable("Unknown x86 shuffle node");
2866 case X86ISD::PSHUFD:
2867 case X86ISD::PSHUFHW:
2868 case X86ISD::PSHUFLW:
2869 case X86ISD::VPERMILPS:
2870 case X86ISD::VPERMILPSY:
2871 case X86ISD::VPERMILPD:
2872 case X86ISD::VPERMILPDY:
2873 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2879 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2880 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2882 default: llvm_unreachable("Unknown x86 shuffle node");
2883 case X86ISD::PALIGN:
2884 case X86ISD::SHUFPD:
2885 case X86ISD::SHUFPS:
2886 case X86ISD::VPERM2F128:
2887 return DAG.getNode(Opc, dl, VT, V1, V2,
2888 DAG.getConstant(TargetMask, MVT::i8));
2893 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2894 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2896 default: llvm_unreachable("Unknown x86 shuffle node");
2897 case X86ISD::MOVLHPS:
2898 case X86ISD::MOVLHPD:
2899 case X86ISD::MOVHLPS:
2900 case X86ISD::MOVLPS:
2901 case X86ISD::MOVLPD:
2904 case X86ISD::UNPCKLPS:
2905 case X86ISD::UNPCKLPD:
2906 case X86ISD::VUNPCKLPSY:
2907 case X86ISD::VUNPCKLPDY:
2908 case X86ISD::PUNPCKLWD:
2909 case X86ISD::PUNPCKLBW:
2910 case X86ISD::PUNPCKLDQ:
2911 case X86ISD::PUNPCKLQDQ:
2912 case X86ISD::UNPCKHPS:
2913 case X86ISD::UNPCKHPD:
2914 case X86ISD::VUNPCKHPSY:
2915 case X86ISD::VUNPCKHPDY:
2916 case X86ISD::PUNPCKHWD:
2917 case X86ISD::PUNPCKHBW:
2918 case X86ISD::PUNPCKHDQ:
2919 case X86ISD::PUNPCKHQDQ:
2920 return DAG.getNode(Opc, dl, VT, V1, V2);
2925 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2928 int ReturnAddrIndex = FuncInfo->getRAIndex();
2930 if (ReturnAddrIndex == 0) {
2931 // Set up a frame object for the return address.
2932 uint64_t SlotSize = TD->getPointerSize();
2933 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2935 FuncInfo->setRAIndex(ReturnAddrIndex);
2938 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2942 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2943 bool hasSymbolicDisplacement) {
2944 // Offset should fit into 32 bit immediate field.
2945 if (!isInt<32>(Offset))
2948 // If we don't have a symbolic displacement - we don't have any extra
2950 if (!hasSymbolicDisplacement)
2953 // FIXME: Some tweaks might be needed for medium code model.
2954 if (M != CodeModel::Small && M != CodeModel::Kernel)
2957 // For small code model we assume that latest object is 16MB before end of 31
2958 // bits boundary. We may also accept pretty large negative constants knowing
2959 // that all objects are in the positive half of address space.
2960 if (M == CodeModel::Small && Offset < 16*1024*1024)
2963 // For kernel code model we know that all object resist in the negative half
2964 // of 32bits address space. We may not accept negative offsets, since they may
2965 // be just off and we may accept pretty large positive ones.
2966 if (M == CodeModel::Kernel && Offset > 0)
2972 /// isCalleePop - Determines whether the callee is required to pop its
2973 /// own arguments. Callee pop is necessary to support tail calls.
2974 bool X86::isCalleePop(CallingConv::ID CallingConv,
2975 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2979 switch (CallingConv) {
2982 case CallingConv::X86_StdCall:
2984 case CallingConv::X86_FastCall:
2986 case CallingConv::X86_ThisCall:
2988 case CallingConv::Fast:
2990 case CallingConv::GHC:
2995 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2996 /// specific condition code, returning the condition code and the LHS/RHS of the
2997 /// comparison to make.
2998 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2999 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3001 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3002 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3003 // X > -1 -> X == 0, jump !sign.
3004 RHS = DAG.getConstant(0, RHS.getValueType());
3005 return X86::COND_NS;
3006 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3007 // X < 0 -> X == 0, jump on sign.
3009 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3011 RHS = DAG.getConstant(0, RHS.getValueType());
3012 return X86::COND_LE;
3016 switch (SetCCOpcode) {
3017 default: llvm_unreachable("Invalid integer condition!");
3018 case ISD::SETEQ: return X86::COND_E;
3019 case ISD::SETGT: return X86::COND_G;
3020 case ISD::SETGE: return X86::COND_GE;
3021 case ISD::SETLT: return X86::COND_L;
3022 case ISD::SETLE: return X86::COND_LE;
3023 case ISD::SETNE: return X86::COND_NE;
3024 case ISD::SETULT: return X86::COND_B;
3025 case ISD::SETUGT: return X86::COND_A;
3026 case ISD::SETULE: return X86::COND_BE;
3027 case ISD::SETUGE: return X86::COND_AE;
3031 // First determine if it is required or is profitable to flip the operands.
3033 // If LHS is a foldable load, but RHS is not, flip the condition.
3034 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3035 !ISD::isNON_EXTLoad(RHS.getNode())) {
3036 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3037 std::swap(LHS, RHS);
3040 switch (SetCCOpcode) {
3046 std::swap(LHS, RHS);
3050 // On a floating point condition, the flags are set as follows:
3052 // 0 | 0 | 0 | X > Y
3053 // 0 | 0 | 1 | X < Y
3054 // 1 | 0 | 0 | X == Y
3055 // 1 | 1 | 1 | unordered
3056 switch (SetCCOpcode) {
3057 default: llvm_unreachable("Condcode should be pre-legalized away");
3059 case ISD::SETEQ: return X86::COND_E;
3060 case ISD::SETOLT: // flipped
3062 case ISD::SETGT: return X86::COND_A;
3063 case ISD::SETOLE: // flipped
3065 case ISD::SETGE: return X86::COND_AE;
3066 case ISD::SETUGT: // flipped
3068 case ISD::SETLT: return X86::COND_B;
3069 case ISD::SETUGE: // flipped
3071 case ISD::SETLE: return X86::COND_BE;
3073 case ISD::SETNE: return X86::COND_NE;
3074 case ISD::SETUO: return X86::COND_P;
3075 case ISD::SETO: return X86::COND_NP;
3077 case ISD::SETUNE: return X86::COND_INVALID;
3081 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3082 /// code. Current x86 isa includes the following FP cmov instructions:
3083 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3084 static bool hasFPCMov(unsigned X86CC) {
3100 /// isFPImmLegal - Returns true if the target can instruction select the
3101 /// specified FP immediate natively. If false, the legalizer will
3102 /// materialize the FP immediate as a load from a constant pool.
3103 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3104 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3105 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3111 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3112 /// the specified range (L, H].
3113 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3114 return (Val < 0) || (Val >= Low && Val < Hi);
3117 /// isUndefOrInRange - Return true if every element in Mask, begining
3118 /// from position Pos and ending in Pos+Size, falls within the specified
3119 /// range (L, L+Pos]. or is undef.
3120 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3121 int Pos, int Size, int Low, int Hi) {
3122 for (int i = Pos, e = Pos+Size; i != e; ++i)
3123 if (!isUndefOrInRange(Mask[i], Low, Hi))
3128 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3129 /// specified value.
3130 static bool isUndefOrEqual(int Val, int CmpVal) {
3131 if (Val < 0 || Val == CmpVal)
3136 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3137 /// from position Pos and ending in Pos+Size, falls within the specified
3138 /// sequential range (L, L+Pos]. or is undef.
3139 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3140 int Pos, int Size, int Low) {
3141 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3142 if (!isUndefOrEqual(Mask[i], Low))
3147 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3148 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3149 /// the second operand.
3150 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3151 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3152 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3153 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3154 return (Mask[0] < 2 && Mask[1] < 2);
3158 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3159 SmallVector<int, 8> M;
3161 return ::isPSHUFDMask(M, N->getValueType(0));
3164 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3165 /// is suitable for input to PSHUFHW.
3166 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3167 if (VT != MVT::v8i16)
3170 // Lower quadword copied in order or undef.
3171 for (int i = 0; i != 4; ++i)
3172 if (Mask[i] >= 0 && Mask[i] != i)
3175 // Upper quadword shuffled.
3176 for (int i = 4; i != 8; ++i)
3177 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3183 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3184 SmallVector<int, 8> M;
3186 return ::isPSHUFHWMask(M, N->getValueType(0));
3189 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3190 /// is suitable for input to PSHUFLW.
3191 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3192 if (VT != MVT::v8i16)
3195 // Upper quadword copied in order.
3196 for (int i = 4; i != 8; ++i)
3197 if (Mask[i] >= 0 && Mask[i] != i)
3200 // Lower quadword shuffled.
3201 for (int i = 0; i != 4; ++i)
3208 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3209 SmallVector<int, 8> M;
3211 return ::isPSHUFLWMask(M, N->getValueType(0));
3214 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3215 /// is suitable for input to PALIGNR.
3216 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3217 bool hasSSSE3OrAVX) {
3218 int i, e = VT.getVectorNumElements();
3219 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3222 // Do not handle v2i64 / v2f64 shuffles with palignr.
3223 if (e < 4 || !hasSSSE3OrAVX)
3226 for (i = 0; i != e; ++i)
3230 // All undef, not a palignr.
3234 // Make sure we're shifting in the right direction.
3238 int s = Mask[i] - i;
3240 // Check the rest of the elements to see if they are consecutive.
3241 for (++i; i != e; ++i) {
3243 if (m >= 0 && m != s+i)
3249 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3250 /// specifies a shuffle of elements that is suitable for input to 256-bit
3252 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3253 const X86Subtarget *Subtarget) {
3254 int NumElems = VT.getVectorNumElements();
3256 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3262 // VSHUFPSY divides the resulting vector into 4 chunks.
3263 // The sources are also splitted into 4 chunks, and each destination
3264 // chunk must come from a different source chunk.
3266 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3267 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3269 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3270 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3272 int QuarterSize = NumElems/4;
3273 int HalfSize = QuarterSize*2;
3274 for (int i = 0; i < QuarterSize; ++i)
3275 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3277 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3278 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3281 // The mask of the second half must be the same as the first but with
3282 // the appropriate offsets. This works in the same way as VPERMILPS
3283 // works with masks.
3284 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3285 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3287 int FstHalfIdx = i-HalfSize;
3288 if (Mask[FstHalfIdx] < 0)
3290 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3293 for (int i = QuarterSize*3; i < NumElems; ++i) {
3294 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3296 int FstHalfIdx = i-HalfSize;
3297 if (Mask[FstHalfIdx] < 0)
3299 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3307 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3308 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3309 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3310 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3311 EVT VT = SVOp->getValueType(0);
3312 int NumElems = VT.getVectorNumElements();
3314 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3315 "Only supports v8i32 and v8f32 types");
3317 int HalfSize = NumElems/2;
3319 for (int i = 0; i != NumElems ; ++i) {
3320 if (SVOp->getMaskElt(i) < 0)
3322 // The mask of the first half must be equal to the second one.
3323 unsigned Shamt = (i%HalfSize)*2;
3324 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3325 Mask |= Elt << Shamt;
3331 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3332 /// specifies a shuffle of elements that is suitable for input to 256-bit
3333 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3334 /// version and the mask of the second half isn't binded with the first
3336 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3337 const X86Subtarget *Subtarget) {
3338 int NumElems = VT.getVectorNumElements();
3340 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3346 // VSHUFPSY divides the resulting vector into 4 chunks.
3347 // The sources are also splitted into 4 chunks, and each destination
3348 // chunk must come from a different source chunk.
3350 // SRC1 => X3 X2 X1 X0
3351 // SRC2 => Y3 Y2 Y1 Y0
3353 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3355 int QuarterSize = NumElems/4;
3356 int HalfSize = QuarterSize*2;
3357 for (int i = 0; i < QuarterSize; ++i)
3358 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3360 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3361 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3363 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3364 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3366 for (int i = QuarterSize*3; i < NumElems; ++i)
3367 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3373 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3374 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3375 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3376 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3377 EVT VT = SVOp->getValueType(0);
3378 int NumElems = VT.getVectorNumElements();
3380 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3381 "Only supports v4i64 and v4f64 types");
3383 int HalfSize = NumElems/2;
3385 for (int i = 0; i != NumElems ; ++i) {
3386 if (SVOp->getMaskElt(i) < 0)
3388 int Elt = SVOp->getMaskElt(i) % HalfSize;
3395 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3396 /// specifies a shuffle of elements that is suitable for input to 128-bit
3397 /// SHUFPS and SHUFPD.
3398 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3399 int NumElems = VT.getVectorNumElements();
3401 if (VT.getSizeInBits() != 128)
3404 if (NumElems != 2 && NumElems != 4)
3407 int Half = NumElems / 2;
3408 for (int i = 0; i < Half; ++i)
3409 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3411 for (int i = Half; i < NumElems; ++i)
3412 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3418 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3419 SmallVector<int, 8> M;
3421 return ::isSHUFPMask(M, N->getValueType(0));
3424 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3425 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3426 /// half elements to come from vector 1 (which would equal the dest.) and
3427 /// the upper half to come from vector 2.
3428 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3429 int NumElems = VT.getVectorNumElements();
3431 if (NumElems != 2 && NumElems != 4)
3434 int Half = NumElems / 2;
3435 for (int i = 0; i < Half; ++i)
3436 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3438 for (int i = Half; i < NumElems; ++i)
3439 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3444 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3445 SmallVector<int, 8> M;
3447 return isCommutedSHUFPMask(M, N->getValueType(0));
3450 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3451 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3452 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3453 EVT VT = N->getValueType(0);
3454 unsigned NumElems = VT.getVectorNumElements();
3456 if (VT.getSizeInBits() != 128)
3462 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3463 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3464 isUndefOrEqual(N->getMaskElt(1), 7) &&
3465 isUndefOrEqual(N->getMaskElt(2), 2) &&
3466 isUndefOrEqual(N->getMaskElt(3), 3);
3469 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3470 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3472 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3473 EVT VT = N->getValueType(0);
3474 unsigned NumElems = VT.getVectorNumElements();
3476 if (VT.getSizeInBits() != 128)
3482 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3483 isUndefOrEqual(N->getMaskElt(1), 3) &&
3484 isUndefOrEqual(N->getMaskElt(2), 2) &&
3485 isUndefOrEqual(N->getMaskElt(3), 3);
3488 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3490 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3491 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3493 if (NumElems != 2 && NumElems != 4)
3496 for (unsigned i = 0; i < NumElems/2; ++i)
3497 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3500 for (unsigned i = NumElems/2; i < NumElems; ++i)
3501 if (!isUndefOrEqual(N->getMaskElt(i), i))
3507 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3509 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3510 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3512 if ((NumElems != 2 && NumElems != 4)
3513 || N->getValueType(0).getSizeInBits() > 128)
3516 for (unsigned i = 0; i < NumElems/2; ++i)
3517 if (!isUndefOrEqual(N->getMaskElt(i), i))
3520 for (unsigned i = 0; i < NumElems/2; ++i)
3521 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3527 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3528 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3529 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3530 bool V2IsSplat = false) {
3531 int NumElts = VT.getVectorNumElements();
3533 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3534 "Unsupported vector type for unpckh");
3536 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3539 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3540 // independently on 128-bit lanes.
3541 unsigned NumLanes = VT.getSizeInBits()/128;
3542 unsigned NumLaneElts = NumElts/NumLanes;
3545 unsigned End = NumLaneElts;
3546 for (unsigned s = 0; s < NumLanes; ++s) {
3547 for (unsigned i = Start, j = s * NumLaneElts;
3551 int BitI1 = Mask[i+1];
3552 if (!isUndefOrEqual(BitI, j))
3555 if (!isUndefOrEqual(BitI1, NumElts))
3558 if (!isUndefOrEqual(BitI1, j + NumElts))
3562 // Process the next 128 bits.
3563 Start += NumLaneElts;
3570 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3571 SmallVector<int, 8> M;
3573 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3576 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3577 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3578 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3579 bool V2IsSplat = false) {
3580 int NumElts = VT.getVectorNumElements();
3582 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3583 "Unsupported vector type for unpckh");
3585 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3588 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3589 // independently on 128-bit lanes.
3590 unsigned NumLanes = VT.getSizeInBits()/128;
3591 unsigned NumLaneElts = NumElts/NumLanes;
3594 unsigned End = NumLaneElts;
3595 for (unsigned l = 0; l != NumLanes; ++l) {
3596 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3597 i != End; i += 2, ++j) {
3599 int BitI1 = Mask[i+1];
3600 if (!isUndefOrEqual(BitI, j))
3603 if (isUndefOrEqual(BitI1, NumElts))
3606 if (!isUndefOrEqual(BitI1, j+NumElts))
3610 // Process the next 128 bits.
3611 Start += NumLaneElts;
3617 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3618 SmallVector<int, 8> M;
3620 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3623 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3624 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3626 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3627 int NumElems = VT.getVectorNumElements();
3628 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3631 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3632 // FIXME: Need a better way to get rid of this, there's no latency difference
3633 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3634 // the former later. We should also remove the "_undef" special mask.
3635 if (NumElems == 4 && VT.getSizeInBits() == 256)
3638 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3639 // independently on 128-bit lanes.
3640 unsigned NumLanes = VT.getSizeInBits() / 128;
3641 unsigned NumLaneElts = NumElems / NumLanes;
3643 for (unsigned s = 0; s < NumLanes; ++s) {
3644 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3645 i != NumLaneElts * (s + 1);
3648 int BitI1 = Mask[i+1];
3650 if (!isUndefOrEqual(BitI, j))
3652 if (!isUndefOrEqual(BitI1, j))
3660 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3661 SmallVector<int, 8> M;
3663 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3666 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3667 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3669 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3670 int NumElems = VT.getVectorNumElements();
3671 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3674 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3676 int BitI1 = Mask[i+1];
3677 if (!isUndefOrEqual(BitI, j))
3679 if (!isUndefOrEqual(BitI1, j))
3685 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3686 SmallVector<int, 8> M;
3688 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3691 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3692 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3693 /// MOVSD, and MOVD, i.e. setting the lowest element.
3694 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3695 if (VT.getVectorElementType().getSizeInBits() < 32)
3698 int NumElts = VT.getVectorNumElements();
3700 if (!isUndefOrEqual(Mask[0], NumElts))
3703 for (int i = 1; i < NumElts; ++i)
3704 if (!isUndefOrEqual(Mask[i], i))
3710 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3711 SmallVector<int, 8> M;
3713 return ::isMOVLMask(M, N->getValueType(0));
3716 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3717 /// as permutations between 128-bit chunks or halves. As an example: this
3719 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3720 /// The first half comes from the second half of V1 and the second half from the
3721 /// the second half of V2.
3722 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3723 const X86Subtarget *Subtarget) {
3724 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3727 // The shuffle result is divided into half A and half B. In total the two
3728 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3729 // B must come from C, D, E or F.
3730 int HalfSize = VT.getVectorNumElements()/2;
3731 bool MatchA = false, MatchB = false;
3733 // Check if A comes from one of C, D, E, F.
3734 for (int Half = 0; Half < 4; ++Half) {
3735 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3741 // Check if B comes from one of C, D, E, F.
3742 for (int Half = 0; Half < 4; ++Half) {
3743 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3749 return MatchA && MatchB;
3752 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3753 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3754 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3755 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3756 EVT VT = SVOp->getValueType(0);
3758 int HalfSize = VT.getVectorNumElements()/2;
3760 int FstHalf = 0, SndHalf = 0;
3761 for (int i = 0; i < HalfSize; ++i) {
3762 if (SVOp->getMaskElt(i) > 0) {
3763 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3767 for (int i = HalfSize; i < HalfSize*2; ++i) {
3768 if (SVOp->getMaskElt(i) > 0) {
3769 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3774 return (FstHalf | (SndHalf << 4));
3777 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3778 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3779 /// Note that VPERMIL mask matching is different depending whether theunderlying
3780 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3781 /// to the same elements of the low, but to the higher half of the source.
3782 /// In VPERMILPD the two lanes could be shuffled independently of each other
3783 /// with the same restriction that lanes can't be crossed.
3784 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3785 const X86Subtarget *Subtarget) {
3786 int NumElts = VT.getVectorNumElements();
3787 int NumLanes = VT.getSizeInBits()/128;
3789 if (!Subtarget->hasAVX())
3792 // Only match 256-bit with 64-bit types
3793 if (VT.getSizeInBits() != 256 || NumElts != 4)
3796 // The mask on the high lane is independent of the low. Both can match
3797 // any element in inside its own lane, but can't cross.
3798 int LaneSize = NumElts/NumLanes;
3799 for (int l = 0; l < NumLanes; ++l)
3800 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3801 int LaneStart = l*LaneSize;
3802 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3809 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3810 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3811 /// Note that VPERMIL mask matching is different depending whether theunderlying
3812 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3813 /// to the same elements of the low, but to the higher half of the source.
3814 /// In VPERMILPD the two lanes could be shuffled independently of each other
3815 /// with the same restriction that lanes can't be crossed.
3816 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3817 const X86Subtarget *Subtarget) {
3818 unsigned NumElts = VT.getVectorNumElements();
3819 unsigned NumLanes = VT.getSizeInBits()/128;
3821 if (!Subtarget->hasAVX())
3824 // Only match 256-bit with 32-bit types
3825 if (VT.getSizeInBits() != 256 || NumElts != 8)
3828 // The mask on the high lane should be the same as the low. Actually,
3829 // they can differ if any of the corresponding index in a lane is undef
3830 // and the other stays in range.
3831 int LaneSize = NumElts/NumLanes;
3832 for (int i = 0; i < LaneSize; ++i) {
3833 int HighElt = i+LaneSize;
3834 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3835 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3837 if (!HighValid || !LowValid)
3839 if (Mask[i] < 0 || Mask[HighElt] < 0)
3841 if (Mask[HighElt]-Mask[i] != LaneSize)
3848 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3849 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3850 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3851 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3852 EVT VT = SVOp->getValueType(0);
3854 int NumElts = VT.getVectorNumElements();
3855 int NumLanes = VT.getSizeInBits()/128;
3856 int LaneSize = NumElts/NumLanes;
3858 // Although the mask is equal for both lanes do it twice to get the cases
3859 // where a mask will match because the same mask element is undef on the
3860 // first half but valid on the second. This would get pathological cases
3861 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3863 for (int l = 0; l < NumLanes; ++l) {
3864 for (int i = 0; i < LaneSize; ++i) {
3865 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3868 if (MaskElt >= LaneSize)
3869 MaskElt -= LaneSize;
3870 Mask |= MaskElt << (i*2);
3877 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3878 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3879 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3880 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3881 EVT VT = SVOp->getValueType(0);
3883 int NumElts = VT.getVectorNumElements();
3884 int NumLanes = VT.getSizeInBits()/128;
3887 int LaneSize = NumElts/NumLanes;
3888 for (int l = 0; l < NumLanes; ++l)
3889 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3890 int MaskElt = SVOp->getMaskElt(i);
3893 Mask |= (MaskElt-l*LaneSize) << i;
3899 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3900 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3901 /// element of vector 2 and the other elements to come from vector 1 in order.
3902 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3903 bool V2IsSplat = false, bool V2IsUndef = false) {
3904 int NumOps = VT.getVectorNumElements();
3905 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3908 if (!isUndefOrEqual(Mask[0], 0))
3911 for (int i = 1; i < NumOps; ++i)
3912 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3913 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3914 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3920 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3921 bool V2IsUndef = false) {
3922 SmallVector<int, 8> M;
3924 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3927 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3928 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3929 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3930 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3931 const X86Subtarget *Subtarget) {
3932 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3935 // The second vector must be undef
3936 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3939 EVT VT = N->getValueType(0);
3940 unsigned NumElems = VT.getVectorNumElements();
3942 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3943 (VT.getSizeInBits() == 256 && NumElems != 8))
3946 // "i+1" is the value the indexed mask element must have
3947 for (unsigned i = 0; i < NumElems; i += 2)
3948 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3949 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3955 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3956 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3957 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3958 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3959 const X86Subtarget *Subtarget) {
3960 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3963 // The second vector must be undef
3964 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3967 EVT VT = N->getValueType(0);
3968 unsigned NumElems = VT.getVectorNumElements();
3970 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3971 (VT.getSizeInBits() == 256 && NumElems != 8))
3974 // "i" is the value the indexed mask element must have
3975 for (unsigned i = 0; i < NumElems; i += 2)
3976 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3977 !isUndefOrEqual(N->getMaskElt(i+1), i))
3983 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3984 /// specifies a shuffle of elements that is suitable for input to 256-bit
3985 /// version of MOVDDUP.
3986 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3987 const X86Subtarget *Subtarget) {
3988 EVT VT = N->getValueType(0);
3989 int NumElts = VT.getVectorNumElements();
3990 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3992 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3993 !V2IsUndef || NumElts != 4)
3996 for (int i = 0; i != NumElts/2; ++i)
3997 if (!isUndefOrEqual(N->getMaskElt(i), 0))
3999 for (int i = NumElts/2; i != NumElts; ++i)
4000 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4005 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4006 /// specifies a shuffle of elements that is suitable for input to 128-bit
4007 /// version of MOVDDUP.
4008 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4009 EVT VT = N->getValueType(0);
4011 if (VT.getSizeInBits() != 128)
4014 int e = VT.getVectorNumElements() / 2;
4015 for (int i = 0; i < e; ++i)
4016 if (!isUndefOrEqual(N->getMaskElt(i), i))
4018 for (int i = 0; i < e; ++i)
4019 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4024 /// isVEXTRACTF128Index - Return true if the specified
4025 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4026 /// suitable for input to VEXTRACTF128.
4027 bool X86::isVEXTRACTF128Index(SDNode *N) {
4028 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4031 // The index should be aligned on a 128-bit boundary.
4033 cast<ConstantSDNode>(N->getOperand(1).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 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4044 /// operand specifies a subvector insert that is suitable for input to
4046 bool X86::isVINSERTF128Index(SDNode *N) {
4047 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4050 // The index should be aligned on a 128-bit boundary.
4052 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4054 unsigned VL = N->getValueType(0).getVectorNumElements();
4055 unsigned VBits = N->getValueType(0).getSizeInBits();
4056 unsigned ElSize = VBits / VL;
4057 bool Result = (Index * ElSize) % 128 == 0;
4062 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4063 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4064 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4066 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4068 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4070 for (int i = 0; i < NumOperands; ++i) {
4071 int Val = SVOp->getMaskElt(NumOperands-i-1);
4072 if (Val < 0) Val = 0;
4073 if (Val >= NumOperands) Val -= NumOperands;
4075 if (i != NumOperands - 1)
4081 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4083 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4084 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4086 // 8 nodes, but we only care about the last 4.
4087 for (unsigned i = 7; i >= 4; --i) {
4088 int Val = SVOp->getMaskElt(i);
4097 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4098 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4099 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4102 // 8 nodes, but we only care about the first 4.
4103 for (int i = 3; i >= 0; --i) {
4104 int Val = SVOp->getMaskElt(i);
4113 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4115 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4116 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4117 EVT VVT = N->getValueType(0);
4118 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4122 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4123 Val = SVOp->getMaskElt(i);
4127 assert(Val - i > 0 && "PALIGNR imm should be positive");
4128 return (Val - i) * EltSize;
4131 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4132 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4134 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4135 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4136 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4139 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4141 EVT VecVT = N->getOperand(0).getValueType();
4142 EVT ElVT = VecVT.getVectorElementType();
4144 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4145 return Index / NumElemsPerChunk;
4148 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4149 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4151 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4152 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4153 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4156 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4158 EVT VecVT = N->getValueType(0);
4159 EVT ElVT = VecVT.getVectorElementType();
4161 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4162 return Index / NumElemsPerChunk;
4165 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4167 bool X86::isZeroNode(SDValue Elt) {
4168 return ((isa<ConstantSDNode>(Elt) &&
4169 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4170 (isa<ConstantFPSDNode>(Elt) &&
4171 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4174 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4175 /// their permute mask.
4176 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4177 SelectionDAG &DAG) {
4178 EVT VT = SVOp->getValueType(0);
4179 unsigned NumElems = VT.getVectorNumElements();
4180 SmallVector<int, 8> MaskVec;
4182 for (unsigned i = 0; i != NumElems; ++i) {
4183 int idx = SVOp->getMaskElt(i);
4185 MaskVec.push_back(idx);
4186 else if (idx < (int)NumElems)
4187 MaskVec.push_back(idx + NumElems);
4189 MaskVec.push_back(idx - NumElems);
4191 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4192 SVOp->getOperand(0), &MaskVec[0]);
4195 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4196 /// the two vector operands have swapped position.
4197 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4198 unsigned NumElems = VT.getVectorNumElements();
4199 for (unsigned i = 0; i != NumElems; ++i) {
4203 else if (idx < (int)NumElems)
4204 Mask[i] = idx + NumElems;
4206 Mask[i] = idx - NumElems;
4210 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4211 /// match movhlps. The lower half elements should come from upper half of
4212 /// V1 (and in order), and the upper half elements should come from the upper
4213 /// half of V2 (and in order).
4214 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4215 EVT VT = Op->getValueType(0);
4216 if (VT.getSizeInBits() != 128)
4218 if (VT.getVectorNumElements() != 4)
4220 for (unsigned i = 0, e = 2; i != e; ++i)
4221 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4223 for (unsigned i = 2; i != 4; ++i)
4224 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4229 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4230 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4232 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4233 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4235 N = N->getOperand(0).getNode();
4236 if (!ISD::isNON_EXTLoad(N))
4239 *LD = cast<LoadSDNode>(N);
4243 // Test whether the given value is a vector value which will be legalized
4245 static bool WillBeConstantPoolLoad(SDNode *N) {
4246 if (N->getOpcode() != ISD::BUILD_VECTOR)
4249 // Check for any non-constant elements.
4250 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4251 switch (N->getOperand(i).getNode()->getOpcode()) {
4253 case ISD::ConstantFP:
4260 // Vectors of all-zeros and all-ones are materialized with special
4261 // instructions rather than being loaded.
4262 return !ISD::isBuildVectorAllZeros(N) &&
4263 !ISD::isBuildVectorAllOnes(N);
4266 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4267 /// match movlp{s|d}. The lower half elements should come from lower half of
4268 /// V1 (and in order), and the upper half elements should come from the upper
4269 /// half of V2 (and in order). And since V1 will become the source of the
4270 /// MOVLP, it must be either a vector load or a scalar load to vector.
4271 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4272 ShuffleVectorSDNode *Op) {
4273 EVT VT = Op->getValueType(0);
4274 if (VT.getSizeInBits() != 128)
4277 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4279 // Is V2 is a vector load, don't do this transformation. We will try to use
4280 // load folding shufps op.
4281 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4284 unsigned NumElems = VT.getVectorNumElements();
4286 if (NumElems != 2 && NumElems != 4)
4288 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4289 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4291 for (unsigned i = NumElems/2; i != NumElems; ++i)
4292 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4297 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4299 static bool isSplatVector(SDNode *N) {
4300 if (N->getOpcode() != ISD::BUILD_VECTOR)
4303 SDValue SplatValue = N->getOperand(0);
4304 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4305 if (N->getOperand(i) != SplatValue)
4310 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4311 /// to an zero vector.
4312 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4313 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4314 SDValue V1 = N->getOperand(0);
4315 SDValue V2 = N->getOperand(1);
4316 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4317 for (unsigned i = 0; i != NumElems; ++i) {
4318 int Idx = N->getMaskElt(i);
4319 if (Idx >= (int)NumElems) {
4320 unsigned Opc = V2.getOpcode();
4321 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4323 if (Opc != ISD::BUILD_VECTOR ||
4324 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4326 } else if (Idx >= 0) {
4327 unsigned Opc = V1.getOpcode();
4328 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4330 if (Opc != ISD::BUILD_VECTOR ||
4331 !X86::isZeroNode(V1.getOperand(Idx)))
4338 /// getZeroVector - Returns a vector of specified type with all zero elements.
4340 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4342 assert(VT.isVector() && "Expected a vector type");
4344 // Always build SSE zero vectors as <4 x i32> bitcasted
4345 // to their dest type. This ensures they get CSE'd.
4347 if (VT.getSizeInBits() == 128) { // SSE
4348 if (HasXMMInt) { // SSE2
4349 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4350 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4352 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4353 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4355 } else if (VT.getSizeInBits() == 256) { // AVX
4356 // 256-bit logic and arithmetic instructions in AVX are
4357 // all floating-point, no support for integer ops. Default
4358 // to emitting fp zeroed vectors then.
4359 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4360 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4361 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4363 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4366 /// getOnesVector - Returns a vector of specified type with all bits set.
4367 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4368 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4369 /// original type, ensuring they get CSE'd.
4370 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4371 assert(VT.isVector() && "Expected a vector type");
4372 assert((VT.is128BitVector() || VT.is256BitVector())
4373 && "Expected a 128-bit or 256-bit vector type");
4375 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4376 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4377 Cst, Cst, Cst, Cst);
4379 if (VT.is256BitVector()) {
4380 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4381 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4382 Vec = Insert128BitVector(InsV, Vec,
4383 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4386 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4389 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4390 /// that point to V2 points to its first element.
4391 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4392 EVT VT = SVOp->getValueType(0);
4393 unsigned NumElems = VT.getVectorNumElements();
4395 bool Changed = false;
4396 SmallVector<int, 8> MaskVec;
4397 SVOp->getMask(MaskVec);
4399 for (unsigned i = 0; i != NumElems; ++i) {
4400 if (MaskVec[i] > (int)NumElems) {
4401 MaskVec[i] = NumElems;
4406 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4407 SVOp->getOperand(1), &MaskVec[0]);
4408 return SDValue(SVOp, 0);
4411 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4412 /// operation of specified width.
4413 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4415 unsigned NumElems = VT.getVectorNumElements();
4416 SmallVector<int, 8> Mask;
4417 Mask.push_back(NumElems);
4418 for (unsigned i = 1; i != NumElems; ++i)
4420 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4423 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4424 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4426 unsigned NumElems = VT.getVectorNumElements();
4427 SmallVector<int, 8> Mask;
4428 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4430 Mask.push_back(i + NumElems);
4432 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4435 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4436 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4438 unsigned NumElems = VT.getVectorNumElements();
4439 unsigned Half = NumElems/2;
4440 SmallVector<int, 8> Mask;
4441 for (unsigned i = 0; i != Half; ++i) {
4442 Mask.push_back(i + Half);
4443 Mask.push_back(i + NumElems + Half);
4445 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4448 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4449 // a generic shuffle instruction because the target has no such instructions.
4450 // Generate shuffles which repeat i16 and i8 several times until they can be
4451 // represented by v4f32 and then be manipulated by target suported shuffles.
4452 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4453 EVT VT = V.getValueType();
4454 int NumElems = VT.getVectorNumElements();
4455 DebugLoc dl = V.getDebugLoc();
4457 while (NumElems > 4) {
4458 if (EltNo < NumElems/2) {
4459 V = getUnpackl(DAG, dl, VT, V, V);
4461 V = getUnpackh(DAG, dl, VT, V, V);
4462 EltNo -= NumElems/2;
4469 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4470 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4471 EVT VT = V.getValueType();
4472 DebugLoc dl = V.getDebugLoc();
4473 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4474 && "Vector size not supported");
4476 if (VT.getSizeInBits() == 128) {
4477 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4478 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4479 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4482 // To use VPERMILPS to splat scalars, the second half of indicies must
4483 // refer to the higher part, which is a duplication of the lower one,
4484 // because VPERMILPS can only handle in-lane permutations.
4485 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4486 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4488 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4489 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4493 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4496 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4497 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4498 EVT SrcVT = SV->getValueType(0);
4499 SDValue V1 = SV->getOperand(0);
4500 DebugLoc dl = SV->getDebugLoc();
4502 int EltNo = SV->getSplatIndex();
4503 int NumElems = SrcVT.getVectorNumElements();
4504 unsigned Size = SrcVT.getSizeInBits();
4506 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4507 "Unknown how to promote splat for type");
4509 // Extract the 128-bit part containing the splat element and update
4510 // the splat element index when it refers to the higher register.
4512 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4513 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4515 EltNo -= NumElems/2;
4518 // All i16 and i8 vector types can't be used directly by a generic shuffle
4519 // instruction because the target has no such instruction. Generate shuffles
4520 // which repeat i16 and i8 several times until they fit in i32, and then can
4521 // be manipulated by target suported shuffles.
4522 EVT EltVT = SrcVT.getVectorElementType();
4523 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4524 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4526 // Recreate the 256-bit vector and place the same 128-bit vector
4527 // into the low and high part. This is necessary because we want
4528 // to use VPERM* to shuffle the vectors
4530 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4531 DAG.getConstant(0, MVT::i32), DAG, dl);
4532 V1 = Insert128BitVector(InsV, V1,
4533 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4536 return getLegalSplat(DAG, V1, EltNo);
4539 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4540 /// vector of zero or undef vector. This produces a shuffle where the low
4541 /// element of V2 is swizzled into the zero/undef vector, landing at element
4542 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4543 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4544 bool isZero, bool HasXMMInt,
4545 SelectionDAG &DAG) {
4546 EVT VT = V2.getValueType();
4548 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4549 unsigned NumElems = VT.getVectorNumElements();
4550 SmallVector<int, 16> MaskVec;
4551 for (unsigned i = 0; i != NumElems; ++i)
4552 // If this is the insertion idx, put the low elt of V2 here.
4553 MaskVec.push_back(i == Idx ? NumElems : i);
4554 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4557 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4558 /// element of the result of the vector shuffle.
4559 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4562 return SDValue(); // Limit search depth.
4564 SDValue V = SDValue(N, 0);
4565 EVT VT = V.getValueType();
4566 unsigned Opcode = V.getOpcode();
4568 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4569 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4570 Index = SV->getMaskElt(Index);
4573 return DAG.getUNDEF(VT.getVectorElementType());
4575 int NumElems = VT.getVectorNumElements();
4576 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4577 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4580 // Recurse into target specific vector shuffles to find scalars.
4581 if (isTargetShuffle(Opcode)) {
4582 int NumElems = VT.getVectorNumElements();
4583 SmallVector<unsigned, 16> ShuffleMask;
4587 case X86ISD::SHUFPS:
4588 case X86ISD::SHUFPD:
4589 ImmN = N->getOperand(N->getNumOperands()-1);
4590 DecodeSHUFPSMask(NumElems,
4591 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4594 case X86ISD::PUNPCKHBW:
4595 case X86ISD::PUNPCKHWD:
4596 case X86ISD::PUNPCKHDQ:
4597 case X86ISD::PUNPCKHQDQ:
4598 DecodePUNPCKHMask(NumElems, ShuffleMask);
4600 case X86ISD::UNPCKHPS:
4601 case X86ISD::UNPCKHPD:
4602 case X86ISD::VUNPCKHPSY:
4603 case X86ISD::VUNPCKHPDY:
4604 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4606 case X86ISD::PUNPCKLBW:
4607 case X86ISD::PUNPCKLWD:
4608 case X86ISD::PUNPCKLDQ:
4609 case X86ISD::PUNPCKLQDQ:
4610 DecodePUNPCKLMask(VT, ShuffleMask);
4612 case X86ISD::UNPCKLPS:
4613 case X86ISD::UNPCKLPD:
4614 case X86ISD::VUNPCKLPSY:
4615 case X86ISD::VUNPCKLPDY:
4616 DecodeUNPCKLPMask(VT, ShuffleMask);
4618 case X86ISD::MOVHLPS:
4619 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4621 case X86ISD::MOVLHPS:
4622 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4624 case X86ISD::PSHUFD:
4625 ImmN = N->getOperand(N->getNumOperands()-1);
4626 DecodePSHUFMask(NumElems,
4627 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4630 case X86ISD::PSHUFHW:
4631 ImmN = N->getOperand(N->getNumOperands()-1);
4632 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4635 case X86ISD::PSHUFLW:
4636 ImmN = N->getOperand(N->getNumOperands()-1);
4637 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4641 case X86ISD::MOVSD: {
4642 // The index 0 always comes from the first element of the second source,
4643 // this is why MOVSS and MOVSD are used in the first place. The other
4644 // elements come from the other positions of the first source vector.
4645 unsigned OpNum = (Index == 0) ? 1 : 0;
4646 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4649 case X86ISD::VPERMILPS:
4650 ImmN = N->getOperand(N->getNumOperands()-1);
4651 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4654 case X86ISD::VPERMILPSY:
4655 ImmN = N->getOperand(N->getNumOperands()-1);
4656 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4659 case X86ISD::VPERMILPD:
4660 ImmN = N->getOperand(N->getNumOperands()-1);
4661 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4664 case X86ISD::VPERMILPDY:
4665 ImmN = N->getOperand(N->getNumOperands()-1);
4666 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4669 case X86ISD::VPERM2F128:
4670 ImmN = N->getOperand(N->getNumOperands()-1);
4671 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4674 case X86ISD::MOVDDUP:
4675 case X86ISD::MOVLHPD:
4676 case X86ISD::MOVLPD:
4677 case X86ISD::MOVLPS:
4678 case X86ISD::MOVSHDUP:
4679 case X86ISD::MOVSLDUP:
4680 case X86ISD::PALIGN:
4681 return SDValue(); // Not yet implemented.
4683 assert(0 && "unknown target shuffle node");
4687 Index = ShuffleMask[Index];
4689 return DAG.getUNDEF(VT.getVectorElementType());
4691 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4692 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4696 // Actual nodes that may contain scalar elements
4697 if (Opcode == ISD::BITCAST) {
4698 V = V.getOperand(0);
4699 EVT SrcVT = V.getValueType();
4700 unsigned NumElems = VT.getVectorNumElements();
4702 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4706 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4707 return (Index == 0) ? V.getOperand(0)
4708 : DAG.getUNDEF(VT.getVectorElementType());
4710 if (V.getOpcode() == ISD::BUILD_VECTOR)
4711 return V.getOperand(Index);
4716 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4717 /// shuffle operation which come from a consecutively from a zero. The
4718 /// search can start in two different directions, from left or right.
4720 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4721 bool ZerosFromLeft, SelectionDAG &DAG) {
4724 while (i < NumElems) {
4725 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4726 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4727 if (!(Elt.getNode() &&
4728 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4736 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4737 /// MaskE correspond consecutively to elements from one of the vector operands,
4738 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4740 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4741 int OpIdx, int NumElems, unsigned &OpNum) {
4742 bool SeenV1 = false;
4743 bool SeenV2 = false;
4745 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4746 int Idx = SVOp->getMaskElt(i);
4747 // Ignore undef indicies
4756 // Only accept consecutive elements from the same vector
4757 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4761 OpNum = SeenV1 ? 0 : 1;
4765 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4766 /// logical left shift of a vector.
4767 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4768 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4769 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4770 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4771 false /* check zeros from right */, DAG);
4777 // Considering the elements in the mask that are not consecutive zeros,
4778 // check if they consecutively come from only one of the source vectors.
4780 // V1 = {X, A, B, C} 0
4782 // vector_shuffle V1, V2 <1, 2, 3, X>
4784 if (!isShuffleMaskConsecutive(SVOp,
4785 0, // Mask Start Index
4786 NumElems-NumZeros-1, // Mask End Index
4787 NumZeros, // Where to start looking in the src vector
4788 NumElems, // Number of elements in vector
4789 OpSrc)) // Which source operand ?
4794 ShVal = SVOp->getOperand(OpSrc);
4798 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4799 /// logical left shift of a vector.
4800 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4801 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4802 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4803 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4804 true /* check zeros from left */, DAG);
4810 // Considering the elements in the mask that are not consecutive zeros,
4811 // check if they consecutively come from only one of the source vectors.
4813 // 0 { A, B, X, X } = V2
4815 // vector_shuffle V1, V2 <X, X, 4, 5>
4817 if (!isShuffleMaskConsecutive(SVOp,
4818 NumZeros, // Mask Start Index
4819 NumElems-1, // Mask End Index
4820 0, // Where to start looking in the src vector
4821 NumElems, // Number of elements in vector
4822 OpSrc)) // Which source operand ?
4827 ShVal = SVOp->getOperand(OpSrc);
4831 /// isVectorShift - Returns true if the shuffle can be implemented as a
4832 /// logical left or right shift of a vector.
4833 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4834 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4835 // Although the logic below support any bitwidth size, there are no
4836 // shift instructions which handle more than 128-bit vectors.
4837 if (SVOp->getValueType(0).getSizeInBits() > 128)
4840 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4841 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4847 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4849 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4850 unsigned NumNonZero, unsigned NumZero,
4852 const TargetLowering &TLI) {
4856 DebugLoc dl = Op.getDebugLoc();
4859 for (unsigned i = 0; i < 16; ++i) {
4860 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4861 if (ThisIsNonZero && First) {
4863 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4865 V = DAG.getUNDEF(MVT::v8i16);
4870 SDValue ThisElt(0, 0), LastElt(0, 0);
4871 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4872 if (LastIsNonZero) {
4873 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4874 MVT::i16, Op.getOperand(i-1));
4876 if (ThisIsNonZero) {
4877 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4878 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4879 ThisElt, DAG.getConstant(8, MVT::i8));
4881 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4885 if (ThisElt.getNode())
4886 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4887 DAG.getIntPtrConstant(i/2));
4891 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4894 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4896 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4897 unsigned NumNonZero, unsigned NumZero,
4899 const TargetLowering &TLI) {
4903 DebugLoc dl = Op.getDebugLoc();
4906 for (unsigned i = 0; i < 8; ++i) {
4907 bool isNonZero = (NonZeros & (1 << i)) != 0;
4911 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4913 V = DAG.getUNDEF(MVT::v8i16);
4916 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4917 MVT::v8i16, V, Op.getOperand(i),
4918 DAG.getIntPtrConstant(i));
4925 /// getVShift - Return a vector logical shift node.
4927 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4928 unsigned NumBits, SelectionDAG &DAG,
4929 const TargetLowering &TLI, DebugLoc dl) {
4930 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4931 EVT ShVT = MVT::v2i64;
4932 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4933 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4934 return DAG.getNode(ISD::BITCAST, dl, VT,
4935 DAG.getNode(Opc, dl, ShVT, SrcOp,
4936 DAG.getConstant(NumBits,
4937 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4941 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4942 SelectionDAG &DAG) const {
4944 // Check if the scalar load can be widened into a vector load. And if
4945 // the address is "base + cst" see if the cst can be "absorbed" into
4946 // the shuffle mask.
4947 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4948 SDValue Ptr = LD->getBasePtr();
4949 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4951 EVT PVT = LD->getValueType(0);
4952 if (PVT != MVT::i32 && PVT != MVT::f32)
4957 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4958 FI = FINode->getIndex();
4960 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4961 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4962 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4963 Offset = Ptr.getConstantOperandVal(1);
4964 Ptr = Ptr.getOperand(0);
4969 // FIXME: 256-bit vector instructions don't require a strict alignment,
4970 // improve this code to support it better.
4971 unsigned RequiredAlign = VT.getSizeInBits()/8;
4972 SDValue Chain = LD->getChain();
4973 // Make sure the stack object alignment is at least 16 or 32.
4974 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4975 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4976 if (MFI->isFixedObjectIndex(FI)) {
4977 // Can't change the alignment. FIXME: It's possible to compute
4978 // the exact stack offset and reference FI + adjust offset instead.
4979 // If someone *really* cares about this. That's the way to implement it.
4982 MFI->setObjectAlignment(FI, RequiredAlign);
4986 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4987 // Ptr + (Offset & ~15).
4990 if ((Offset % RequiredAlign) & 3)
4992 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4994 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4995 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4997 int EltNo = (Offset - StartOffset) >> 2;
4998 int NumElems = VT.getVectorNumElements();
5000 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5001 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5002 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5003 LD->getPointerInfo().getWithOffset(StartOffset),
5004 false, false, false, 0);
5006 // Canonicalize it to a v4i32 or v8i32 shuffle.
5007 SmallVector<int, 8> Mask;
5008 for (int i = 0; i < NumElems; ++i)
5009 Mask.push_back(EltNo);
5011 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5012 return DAG.getNode(ISD::BITCAST, dl, NVT,
5013 DAG.getVectorShuffle(CanonVT, dl, V1,
5014 DAG.getUNDEF(CanonVT),&Mask[0]));
5020 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5021 /// vector of type 'VT', see if the elements can be replaced by a single large
5022 /// load which has the same value as a build_vector whose operands are 'elts'.
5024 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5026 /// FIXME: we'd also like to handle the case where the last elements are zero
5027 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5028 /// There's even a handy isZeroNode for that purpose.
5029 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5030 DebugLoc &DL, SelectionDAG &DAG) {
5031 EVT EltVT = VT.getVectorElementType();
5032 unsigned NumElems = Elts.size();
5034 LoadSDNode *LDBase = NULL;
5035 unsigned LastLoadedElt = -1U;
5037 // For each element in the initializer, see if we've found a load or an undef.
5038 // If we don't find an initial load element, or later load elements are
5039 // non-consecutive, bail out.
5040 for (unsigned i = 0; i < NumElems; ++i) {
5041 SDValue Elt = Elts[i];
5043 if (!Elt.getNode() ||
5044 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5047 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5049 LDBase = cast<LoadSDNode>(Elt.getNode());
5053 if (Elt.getOpcode() == ISD::UNDEF)
5056 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5057 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5062 // If we have found an entire vector of loads and undefs, then return a large
5063 // load of the entire vector width starting at the base pointer. If we found
5064 // consecutive loads for the low half, generate a vzext_load node.
5065 if (LastLoadedElt == NumElems - 1) {
5066 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5067 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5068 LDBase->getPointerInfo(),
5069 LDBase->isVolatile(), LDBase->isNonTemporal(),
5070 LDBase->isInvariant(), 0);
5071 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5072 LDBase->getPointerInfo(),
5073 LDBase->isVolatile(), LDBase->isNonTemporal(),
5074 LDBase->isInvariant(), LDBase->getAlignment());
5075 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5076 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5077 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5078 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5080 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5081 LDBase->getPointerInfo(),
5082 LDBase->getAlignment(),
5083 false/*isVolatile*/, true/*ReadMem*/,
5085 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5091 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5092 DebugLoc dl = Op.getDebugLoc();
5094 EVT VT = Op.getValueType();
5095 EVT ExtVT = VT.getVectorElementType();
5096 unsigned NumElems = Op.getNumOperands();
5098 // Vectors containing all zeros can be matched by pxor and xorps later
5099 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5100 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5101 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5102 if (Op.getValueType() == MVT::v4i32 ||
5103 Op.getValueType() == MVT::v8i32)
5106 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5109 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5110 // vectors or broken into v4i32 operations on 256-bit vectors.
5111 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5112 if (Op.getValueType() == MVT::v4i32)
5115 return getOnesVector(Op.getValueType(), DAG, dl);
5118 unsigned EVTBits = ExtVT.getSizeInBits();
5120 unsigned NumZero = 0;
5121 unsigned NumNonZero = 0;
5122 unsigned NonZeros = 0;
5123 bool IsAllConstants = true;
5124 SmallSet<SDValue, 8> Values;
5125 for (unsigned i = 0; i < NumElems; ++i) {
5126 SDValue Elt = Op.getOperand(i);
5127 if (Elt.getOpcode() == ISD::UNDEF)
5130 if (Elt.getOpcode() != ISD::Constant &&
5131 Elt.getOpcode() != ISD::ConstantFP)
5132 IsAllConstants = false;
5133 if (X86::isZeroNode(Elt))
5136 NonZeros |= (1 << i);
5141 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5142 if (NumNonZero == 0)
5143 return DAG.getUNDEF(VT);
5145 // Special case for single non-zero, non-undef, element.
5146 if (NumNonZero == 1) {
5147 unsigned Idx = CountTrailingZeros_32(NonZeros);
5148 SDValue Item = Op.getOperand(Idx);
5150 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5151 // the value are obviously zero, truncate the value to i32 and do the
5152 // insertion that way. Only do this if the value is non-constant or if the
5153 // value is a constant being inserted into element 0. It is cheaper to do
5154 // a constant pool load than it is to do a movd + shuffle.
5155 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5156 (!IsAllConstants || Idx == 0)) {
5157 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5159 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5160 EVT VecVT = MVT::v4i32;
5161 unsigned VecElts = 4;
5163 // Truncate the value (which may itself be a constant) to i32, and
5164 // convert it to a vector with movd (S2V+shuffle to zero extend).
5165 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5166 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5167 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5168 Subtarget->hasXMMInt(), DAG);
5170 // Now we have our 32-bit value zero extended in the low element of
5171 // a vector. If Idx != 0, swizzle it into place.
5173 SmallVector<int, 4> Mask;
5174 Mask.push_back(Idx);
5175 for (unsigned i = 1; i != VecElts; ++i)
5177 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5178 DAG.getUNDEF(Item.getValueType()),
5181 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5185 // If we have a constant or non-constant insertion into the low element of
5186 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5187 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5188 // depending on what the source datatype is.
5191 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5192 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5193 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5194 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5195 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5196 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5198 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5199 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5200 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5201 EVT MiddleVT = MVT::v4i32;
5202 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5203 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5204 Subtarget->hasXMMInt(), DAG);
5205 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5209 // Is it a vector logical left shift?
5210 if (NumElems == 2 && Idx == 1 &&
5211 X86::isZeroNode(Op.getOperand(0)) &&
5212 !X86::isZeroNode(Op.getOperand(1))) {
5213 unsigned NumBits = VT.getSizeInBits();
5214 return getVShift(true, VT,
5215 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5216 VT, Op.getOperand(1)),
5217 NumBits/2, DAG, *this, dl);
5220 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5223 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5224 // is a non-constant being inserted into an element other than the low one,
5225 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5226 // movd/movss) to move this into the low element, then shuffle it into
5228 if (EVTBits == 32) {
5229 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5231 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5232 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5233 Subtarget->hasXMMInt(), DAG);
5234 SmallVector<int, 8> MaskVec;
5235 for (unsigned i = 0; i < NumElems; i++)
5236 MaskVec.push_back(i == Idx ? 0 : 1);
5237 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5241 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5242 if (Values.size() == 1) {
5243 if (EVTBits == 32) {
5244 // Instead of a shuffle like this:
5245 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5246 // Check if it's possible to issue this instead.
5247 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5248 unsigned Idx = CountTrailingZeros_32(NonZeros);
5249 SDValue Item = Op.getOperand(Idx);
5250 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5251 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5256 // A vector full of immediates; various special cases are already
5257 // handled, so this is best done with a single constant-pool load.
5261 // For AVX-length vectors, build the individual 128-bit pieces and use
5262 // shuffles to put them in place.
5263 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5264 SmallVector<SDValue, 32> V;
5265 for (unsigned i = 0; i < NumElems; ++i)
5266 V.push_back(Op.getOperand(i));
5268 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5270 // Build both the lower and upper subvector.
5271 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5272 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5275 // Recreate the wider vector with the lower and upper part.
5276 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5277 DAG.getConstant(0, MVT::i32), DAG, dl);
5278 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5282 // Let legalizer expand 2-wide build_vectors.
5283 if (EVTBits == 64) {
5284 if (NumNonZero == 1) {
5285 // One half is zero or undef.
5286 unsigned Idx = CountTrailingZeros_32(NonZeros);
5287 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5288 Op.getOperand(Idx));
5289 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5290 Subtarget->hasXMMInt(), DAG);
5295 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5296 if (EVTBits == 8 && NumElems == 16) {
5297 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5299 if (V.getNode()) return V;
5302 if (EVTBits == 16 && NumElems == 8) {
5303 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5305 if (V.getNode()) return V;
5308 // If element VT is == 32 bits, turn it into a number of shuffles.
5309 SmallVector<SDValue, 8> V;
5311 if (NumElems == 4 && NumZero > 0) {
5312 for (unsigned i = 0; i < 4; ++i) {
5313 bool isZero = !(NonZeros & (1 << i));
5315 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5317 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5320 for (unsigned i = 0; i < 2; ++i) {
5321 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5324 V[i] = V[i*2]; // Must be a zero vector.
5327 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5330 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5333 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5338 SmallVector<int, 8> MaskVec;
5339 bool Reverse = (NonZeros & 0x3) == 2;
5340 for (unsigned i = 0; i < 2; ++i)
5341 MaskVec.push_back(Reverse ? 1-i : i);
5342 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5343 for (unsigned i = 0; i < 2; ++i)
5344 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5345 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5348 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5349 // Check for a build vector of consecutive loads.
5350 for (unsigned i = 0; i < NumElems; ++i)
5351 V[i] = Op.getOperand(i);
5353 // Check for elements which are consecutive loads.
5354 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5358 // For SSE 4.1, use insertps to put the high elements into the low element.
5359 if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5361 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5362 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5364 Result = DAG.getUNDEF(VT);
5366 for (unsigned i = 1; i < NumElems; ++i) {
5367 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5368 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5369 Op.getOperand(i), DAG.getIntPtrConstant(i));
5374 // Otherwise, expand into a number of unpckl*, start by extending each of
5375 // our (non-undef) elements to the full vector width with the element in the
5376 // bottom slot of the vector (which generates no code for SSE).
5377 for (unsigned i = 0; i < NumElems; ++i) {
5378 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5379 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5381 V[i] = DAG.getUNDEF(VT);
5384 // Next, we iteratively mix elements, e.g. for v4f32:
5385 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5386 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5387 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5388 unsigned EltStride = NumElems >> 1;
5389 while (EltStride != 0) {
5390 for (unsigned i = 0; i < EltStride; ++i) {
5391 // If V[i+EltStride] is undef and this is the first round of mixing,
5392 // then it is safe to just drop this shuffle: V[i] is already in the
5393 // right place, the one element (since it's the first round) being
5394 // inserted as undef can be dropped. This isn't safe for successive
5395 // rounds because they will permute elements within both vectors.
5396 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5397 EltStride == NumElems/2)
5400 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5409 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5410 // them in a MMX register. This is better than doing a stack convert.
5411 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5412 DebugLoc dl = Op.getDebugLoc();
5413 EVT ResVT = Op.getValueType();
5415 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5416 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5418 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5419 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5420 InVec = Op.getOperand(1);
5421 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5422 unsigned NumElts = ResVT.getVectorNumElements();
5423 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5424 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5425 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5427 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5428 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5429 Mask[0] = 0; Mask[1] = 2;
5430 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5432 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5435 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5436 // to create 256-bit vectors from two other 128-bit ones.
5437 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5438 DebugLoc dl = Op.getDebugLoc();
5439 EVT ResVT = Op.getValueType();
5441 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5443 SDValue V1 = Op.getOperand(0);
5444 SDValue V2 = Op.getOperand(1);
5445 unsigned NumElems = ResVT.getVectorNumElements();
5447 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5448 DAG.getConstant(0, MVT::i32), DAG, dl);
5449 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5454 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5455 EVT ResVT = Op.getValueType();
5457 assert(Op.getNumOperands() == 2);
5458 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5459 "Unsupported CONCAT_VECTORS for value type");
5461 // We support concatenate two MMX registers and place them in a MMX register.
5462 // This is better than doing a stack convert.
5463 if (ResVT.is128BitVector())
5464 return LowerMMXCONCAT_VECTORS(Op, DAG);
5466 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5467 // from two other 128-bit ones.
5468 return LowerAVXCONCAT_VECTORS(Op, DAG);
5471 // v8i16 shuffles - Prefer shuffles in the following order:
5472 // 1. [all] pshuflw, pshufhw, optional move
5473 // 2. [ssse3] 1 x pshufb
5474 // 3. [ssse3] 2 x pshufb + 1 x por
5475 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5477 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5478 SelectionDAG &DAG) const {
5479 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5480 SDValue V1 = SVOp->getOperand(0);
5481 SDValue V2 = SVOp->getOperand(1);
5482 DebugLoc dl = SVOp->getDebugLoc();
5483 SmallVector<int, 8> MaskVals;
5485 // Determine if more than 1 of the words in each of the low and high quadwords
5486 // of the result come from the same quadword of one of the two inputs. Undef
5487 // mask values count as coming from any quadword, for better codegen.
5488 unsigned LoQuad[] = { 0, 0, 0, 0 };
5489 unsigned HiQuad[] = { 0, 0, 0, 0 };
5490 BitVector InputQuads(4);
5491 for (unsigned i = 0; i < 8; ++i) {
5492 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5493 int EltIdx = SVOp->getMaskElt(i);
5494 MaskVals.push_back(EltIdx);
5503 InputQuads.set(EltIdx / 4);
5506 int BestLoQuad = -1;
5507 unsigned MaxQuad = 1;
5508 for (unsigned i = 0; i < 4; ++i) {
5509 if (LoQuad[i] > MaxQuad) {
5511 MaxQuad = LoQuad[i];
5515 int BestHiQuad = -1;
5517 for (unsigned i = 0; i < 4; ++i) {
5518 if (HiQuad[i] > MaxQuad) {
5520 MaxQuad = HiQuad[i];
5524 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5525 // of the two input vectors, shuffle them into one input vector so only a
5526 // single pshufb instruction is necessary. If There are more than 2 input
5527 // quads, disable the next transformation since it does not help SSSE3.
5528 bool V1Used = InputQuads[0] || InputQuads[1];
5529 bool V2Used = InputQuads[2] || InputQuads[3];
5530 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5531 if (InputQuads.count() == 2 && V1Used && V2Used) {
5532 BestLoQuad = InputQuads.find_first();
5533 BestHiQuad = InputQuads.find_next(BestLoQuad);
5535 if (InputQuads.count() > 2) {
5541 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5542 // the shuffle mask. If a quad is scored as -1, that means that it contains
5543 // words from all 4 input quadwords.
5545 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5546 SmallVector<int, 8> MaskV;
5547 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5548 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5549 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5550 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5551 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5552 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5554 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5555 // source words for the shuffle, to aid later transformations.
5556 bool AllWordsInNewV = true;
5557 bool InOrder[2] = { true, true };
5558 for (unsigned i = 0; i != 8; ++i) {
5559 int idx = MaskVals[i];
5561 InOrder[i/4] = false;
5562 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5564 AllWordsInNewV = false;
5568 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5569 if (AllWordsInNewV) {
5570 for (int i = 0; i != 8; ++i) {
5571 int idx = MaskVals[i];
5574 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5575 if ((idx != i) && idx < 4)
5577 if ((idx != i) && idx > 3)
5586 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5587 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5588 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5589 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5590 unsigned TargetMask = 0;
5591 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5592 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5593 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5594 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5595 V1 = NewV.getOperand(0);
5596 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5600 // If we have SSSE3, and all words of the result are from 1 input vector,
5601 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5602 // is present, fall back to case 4.
5603 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5604 SmallVector<SDValue,16> pshufbMask;
5606 // If we have elements from both input vectors, set the high bit of the
5607 // shuffle mask element to zero out elements that come from V2 in the V1
5608 // mask, and elements that come from V1 in the V2 mask, so that the two
5609 // results can be OR'd together.
5610 bool TwoInputs = V1Used && V2Used;
5611 for (unsigned i = 0; i != 8; ++i) {
5612 int EltIdx = MaskVals[i] * 2;
5613 if (TwoInputs && (EltIdx >= 16)) {
5614 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5615 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5618 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5619 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5621 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5622 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5623 DAG.getNode(ISD::BUILD_VECTOR, dl,
5624 MVT::v16i8, &pshufbMask[0], 16));
5626 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5628 // Calculate the shuffle mask for the second input, shuffle it, and
5629 // OR it with the first shuffled input.
5631 for (unsigned i = 0; i != 8; ++i) {
5632 int EltIdx = MaskVals[i] * 2;
5634 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5635 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5638 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5639 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5641 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5642 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5643 DAG.getNode(ISD::BUILD_VECTOR, dl,
5644 MVT::v16i8, &pshufbMask[0], 16));
5645 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5646 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5649 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5650 // and update MaskVals with new element order.
5651 BitVector InOrder(8);
5652 if (BestLoQuad >= 0) {
5653 SmallVector<int, 8> MaskV;
5654 for (int i = 0; i != 4; ++i) {
5655 int idx = MaskVals[i];
5657 MaskV.push_back(-1);
5659 } else if ((idx / 4) == BestLoQuad) {
5660 MaskV.push_back(idx & 3);
5663 MaskV.push_back(-1);
5666 for (unsigned i = 4; i != 8; ++i)
5668 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5671 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5672 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5673 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5675 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5679 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5680 // and update MaskVals with the new element order.
5681 if (BestHiQuad >= 0) {
5682 SmallVector<int, 8> MaskV;
5683 for (unsigned i = 0; i != 4; ++i)
5685 for (unsigned i = 4; i != 8; ++i) {
5686 int idx = MaskVals[i];
5688 MaskV.push_back(-1);
5690 } else if ((idx / 4) == BestHiQuad) {
5691 MaskV.push_back((idx & 3) + 4);
5694 MaskV.push_back(-1);
5697 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5700 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5701 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5702 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5704 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5708 // In case BestHi & BestLo were both -1, which means each quadword has a word
5709 // from each of the four input quadwords, calculate the InOrder bitvector now
5710 // before falling through to the insert/extract cleanup.
5711 if (BestLoQuad == -1 && BestHiQuad == -1) {
5713 for (int i = 0; i != 8; ++i)
5714 if (MaskVals[i] < 0 || MaskVals[i] == i)
5718 // The other elements are put in the right place using pextrw and pinsrw.
5719 for (unsigned i = 0; i != 8; ++i) {
5722 int EltIdx = MaskVals[i];
5725 SDValue ExtOp = (EltIdx < 8)
5726 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5727 DAG.getIntPtrConstant(EltIdx))
5728 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5729 DAG.getIntPtrConstant(EltIdx - 8));
5730 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5731 DAG.getIntPtrConstant(i));
5736 // v16i8 shuffles - Prefer shuffles in the following order:
5737 // 1. [ssse3] 1 x pshufb
5738 // 2. [ssse3] 2 x pshufb + 1 x por
5739 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5741 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5743 const X86TargetLowering &TLI) {
5744 SDValue V1 = SVOp->getOperand(0);
5745 SDValue V2 = SVOp->getOperand(1);
5746 DebugLoc dl = SVOp->getDebugLoc();
5747 SmallVector<int, 16> MaskVals;
5748 SVOp->getMask(MaskVals);
5750 // If we have SSSE3, case 1 is generated when all result bytes come from
5751 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5752 // present, fall back to case 3.
5753 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5756 for (unsigned i = 0; i < 16; ++i) {
5757 int EltIdx = MaskVals[i];
5766 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5767 if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5768 SmallVector<SDValue,16> pshufbMask;
5770 // If all result elements are from one input vector, then only translate
5771 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5773 // Otherwise, we have elements from both input vectors, and must zero out
5774 // elements that come from V2 in the first mask, and V1 in the second mask
5775 // so that we can OR them together.
5776 bool TwoInputs = !(V1Only || V2Only);
5777 for (unsigned i = 0; i != 16; ++i) {
5778 int EltIdx = MaskVals[i];
5779 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5780 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5783 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5785 // If all the elements are from V2, assign it to V1 and return after
5786 // building the first pshufb.
5789 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5790 DAG.getNode(ISD::BUILD_VECTOR, dl,
5791 MVT::v16i8, &pshufbMask[0], 16));
5795 // Calculate the shuffle mask for the second input, shuffle it, and
5796 // OR it with the first shuffled input.
5798 for (unsigned i = 0; i != 16; ++i) {
5799 int EltIdx = MaskVals[i];
5801 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5804 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5806 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5807 DAG.getNode(ISD::BUILD_VECTOR, dl,
5808 MVT::v16i8, &pshufbMask[0], 16));
5809 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5812 // No SSSE3 - Calculate in place words and then fix all out of place words
5813 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5814 // the 16 different words that comprise the two doublequadword input vectors.
5815 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5816 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5817 SDValue NewV = V2Only ? V2 : V1;
5818 for (int i = 0; i != 8; ++i) {
5819 int Elt0 = MaskVals[i*2];
5820 int Elt1 = MaskVals[i*2+1];
5822 // This word of the result is all undef, skip it.
5823 if (Elt0 < 0 && Elt1 < 0)
5826 // This word of the result is already in the correct place, skip it.
5827 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5829 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5832 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5833 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5836 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5837 // using a single extract together, load it and store it.
5838 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5839 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5840 DAG.getIntPtrConstant(Elt1 / 2));
5841 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5842 DAG.getIntPtrConstant(i));
5846 // If Elt1 is defined, extract it from the appropriate source. If the
5847 // source byte is not also odd, shift the extracted word left 8 bits
5848 // otherwise clear the bottom 8 bits if we need to do an or.
5850 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5851 DAG.getIntPtrConstant(Elt1 / 2));
5852 if ((Elt1 & 1) == 0)
5853 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5855 TLI.getShiftAmountTy(InsElt.getValueType())));
5857 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5858 DAG.getConstant(0xFF00, MVT::i16));
5860 // If Elt0 is defined, extract it from the appropriate source. If the
5861 // source byte is not also even, shift the extracted word right 8 bits. If
5862 // Elt1 was also defined, OR the extracted values together before
5863 // inserting them in the result.
5865 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5866 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5867 if ((Elt0 & 1) != 0)
5868 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5870 TLI.getShiftAmountTy(InsElt0.getValueType())));
5872 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5873 DAG.getConstant(0x00FF, MVT::i16));
5874 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5877 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5878 DAG.getIntPtrConstant(i));
5880 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5883 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5884 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5885 /// done when every pair / quad of shuffle mask elements point to elements in
5886 /// the right sequence. e.g.
5887 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5889 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5890 SelectionDAG &DAG, DebugLoc dl) {
5891 EVT VT = SVOp->getValueType(0);
5892 SDValue V1 = SVOp->getOperand(0);
5893 SDValue V2 = SVOp->getOperand(1);
5894 unsigned NumElems = VT.getVectorNumElements();
5895 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5897 switch (VT.getSimpleVT().SimpleTy) {
5898 default: assert(false && "Unexpected!");
5899 case MVT::v4f32: NewVT = MVT::v2f64; break;
5900 case MVT::v4i32: NewVT = MVT::v2i64; break;
5901 case MVT::v8i16: NewVT = MVT::v4i32; break;
5902 case MVT::v16i8: NewVT = MVT::v4i32; break;
5905 int Scale = NumElems / NewWidth;
5906 SmallVector<int, 8> MaskVec;
5907 for (unsigned i = 0; i < NumElems; i += Scale) {
5909 for (int j = 0; j < Scale; ++j) {
5910 int EltIdx = SVOp->getMaskElt(i+j);
5914 StartIdx = EltIdx - (EltIdx % Scale);
5915 if (EltIdx != StartIdx + j)
5919 MaskVec.push_back(-1);
5921 MaskVec.push_back(StartIdx / Scale);
5924 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5925 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5926 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5929 /// getVZextMovL - Return a zero-extending vector move low node.
5931 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5932 SDValue SrcOp, SelectionDAG &DAG,
5933 const X86Subtarget *Subtarget, DebugLoc dl) {
5934 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5935 LoadSDNode *LD = NULL;
5936 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5937 LD = dyn_cast<LoadSDNode>(SrcOp);
5939 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5941 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5942 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5943 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5944 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5945 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5947 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5948 return DAG.getNode(ISD::BITCAST, dl, VT,
5949 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5950 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5958 return DAG.getNode(ISD::BITCAST, dl, VT,
5959 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5960 DAG.getNode(ISD::BITCAST, dl,
5964 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5965 /// shuffle node referes to only one lane in the sources.
5966 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5967 EVT VT = SVOp->getValueType(0);
5968 int NumElems = VT.getVectorNumElements();
5969 int HalfSize = NumElems/2;
5970 SmallVector<int, 16> M;
5972 bool MatchA = false, MatchB = false;
5974 for (int l = 0; l < NumElems*2; l += HalfSize) {
5975 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5981 for (int l = 0; l < NumElems*2; l += HalfSize) {
5982 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5988 return MatchA && MatchB;
5991 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5992 /// which could not be matched by any known target speficic shuffle
5994 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5995 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5996 // If each half of a vector shuffle node referes to only one lane in the
5997 // source vectors, extract each used 128-bit lane and shuffle them using
5998 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5999 // the work to the legalizer.
6000 DebugLoc dl = SVOp->getDebugLoc();
6001 EVT VT = SVOp->getValueType(0);
6002 int NumElems = VT.getVectorNumElements();
6003 int HalfSize = NumElems/2;
6005 // Extract the reference for each half
6006 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6007 int FstVecOpNum = 0, SndVecOpNum = 0;
6008 for (int i = 0; i < HalfSize; ++i) {
6009 int Elt = SVOp->getMaskElt(i);
6010 if (SVOp->getMaskElt(i) < 0)
6012 FstVecOpNum = Elt/NumElems;
6013 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6016 for (int i = HalfSize; i < NumElems; ++i) {
6017 int Elt = SVOp->getMaskElt(i);
6018 if (SVOp->getMaskElt(i) < 0)
6020 SndVecOpNum = Elt/NumElems;
6021 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6025 // Extract the subvectors
6026 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6027 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6028 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6029 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6031 // Generate 128-bit shuffles
6032 SmallVector<int, 16> MaskV1, MaskV2;
6033 for (int i = 0; i < HalfSize; ++i) {
6034 int Elt = SVOp->getMaskElt(i);
6035 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6037 for (int i = HalfSize; i < NumElems; ++i) {
6038 int Elt = SVOp->getMaskElt(i);
6039 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6042 EVT NVT = V1.getValueType();
6043 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6044 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6046 // Concatenate the result back
6047 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6048 DAG.getConstant(0, MVT::i32), DAG, dl);
6049 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6056 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6057 /// 4 elements, and match them with several different shuffle types.
6059 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6060 SDValue V1 = SVOp->getOperand(0);
6061 SDValue V2 = SVOp->getOperand(1);
6062 DebugLoc dl = SVOp->getDebugLoc();
6063 EVT VT = SVOp->getValueType(0);
6065 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6067 SmallVector<std::pair<int, int>, 8> Locs;
6069 SmallVector<int, 8> Mask1(4U, -1);
6070 SmallVector<int, 8> PermMask;
6071 SVOp->getMask(PermMask);
6075 for (unsigned i = 0; i != 4; ++i) {
6076 int Idx = PermMask[i];
6078 Locs[i] = std::make_pair(-1, -1);
6080 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6082 Locs[i] = std::make_pair(0, NumLo);
6086 Locs[i] = std::make_pair(1, NumHi);
6088 Mask1[2+NumHi] = Idx;
6094 if (NumLo <= 2 && NumHi <= 2) {
6095 // If no more than two elements come from either vector. This can be
6096 // implemented with two shuffles. First shuffle gather the elements.
6097 // The second shuffle, which takes the first shuffle as both of its
6098 // vector operands, put the elements into the right order.
6099 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6101 SmallVector<int, 8> Mask2(4U, -1);
6103 for (unsigned i = 0; i != 4; ++i) {
6104 if (Locs[i].first == -1)
6107 unsigned Idx = (i < 2) ? 0 : 4;
6108 Idx += Locs[i].first * 2 + Locs[i].second;
6113 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6114 } else if (NumLo == 3 || NumHi == 3) {
6115 // Otherwise, we must have three elements from one vector, call it X, and
6116 // one element from the other, call it Y. First, use a shufps to build an
6117 // intermediate vector with the one element from Y and the element from X
6118 // that will be in the same half in the final destination (the indexes don't
6119 // matter). Then, use a shufps to build the final vector, taking the half
6120 // containing the element from Y from the intermediate, and the other half
6123 // Normalize it so the 3 elements come from V1.
6124 CommuteVectorShuffleMask(PermMask, VT);
6128 // Find the element from V2.
6130 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6131 int Val = PermMask[HiIndex];
6138 Mask1[0] = PermMask[HiIndex];
6140 Mask1[2] = PermMask[HiIndex^1];
6142 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6145 Mask1[0] = PermMask[0];
6146 Mask1[1] = PermMask[1];
6147 Mask1[2] = HiIndex & 1 ? 6 : 4;
6148 Mask1[3] = HiIndex & 1 ? 4 : 6;
6149 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6151 Mask1[0] = HiIndex & 1 ? 2 : 0;
6152 Mask1[1] = HiIndex & 1 ? 0 : 2;
6153 Mask1[2] = PermMask[2];
6154 Mask1[3] = PermMask[3];
6159 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6163 // Break it into (shuffle shuffle_hi, shuffle_lo).
6166 SmallVector<int,8> LoMask(4U, -1);
6167 SmallVector<int,8> HiMask(4U, -1);
6169 SmallVector<int,8> *MaskPtr = &LoMask;
6170 unsigned MaskIdx = 0;
6173 for (unsigned i = 0; i != 4; ++i) {
6180 int Idx = PermMask[i];
6182 Locs[i] = std::make_pair(-1, -1);
6183 } else if (Idx < 4) {
6184 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6185 (*MaskPtr)[LoIdx] = Idx;
6188 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6189 (*MaskPtr)[HiIdx] = Idx;
6194 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6195 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6196 SmallVector<int, 8> MaskOps;
6197 for (unsigned i = 0; i != 4; ++i) {
6198 if (Locs[i].first == -1) {
6199 MaskOps.push_back(-1);
6201 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6202 MaskOps.push_back(Idx);
6205 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6208 static bool MayFoldVectorLoad(SDValue V) {
6209 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6210 V = V.getOperand(0);
6211 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6212 V = V.getOperand(0);
6213 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6214 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6215 // BUILD_VECTOR (load), undef
6216 V = V.getOperand(0);
6222 // FIXME: the version above should always be used. Since there's
6223 // a bug where several vector shuffles can't be folded because the
6224 // DAG is not updated during lowering and a node claims to have two
6225 // uses while it only has one, use this version, and let isel match
6226 // another instruction if the load really happens to have more than
6227 // one use. Remove this version after this bug get fixed.
6228 // rdar://8434668, PR8156
6229 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6230 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6231 V = V.getOperand(0);
6232 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6233 V = V.getOperand(0);
6234 if (ISD::isNormalLoad(V.getNode()))
6239 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6240 /// a vector extract, and if both can be later optimized into a single load.
6241 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6242 /// here because otherwise a target specific shuffle node is going to be
6243 /// emitted for this shuffle, and the optimization not done.
6244 /// FIXME: This is probably not the best approach, but fix the problem
6245 /// until the right path is decided.
6247 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6248 const TargetLowering &TLI) {
6249 EVT VT = V.getValueType();
6250 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6252 // Be sure that the vector shuffle is present in a pattern like this:
6253 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6257 SDNode *N = *V.getNode()->use_begin();
6258 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6261 SDValue EltNo = N->getOperand(1);
6262 if (!isa<ConstantSDNode>(EltNo))
6265 // If the bit convert changed the number of elements, it is unsafe
6266 // to examine the mask.
6267 bool HasShuffleIntoBitcast = false;
6268 if (V.getOpcode() == ISD::BITCAST) {
6269 EVT SrcVT = V.getOperand(0).getValueType();
6270 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6272 V = V.getOperand(0);
6273 HasShuffleIntoBitcast = true;
6276 // Select the input vector, guarding against out of range extract vector.
6277 unsigned NumElems = VT.getVectorNumElements();
6278 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6279 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6280 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6282 // Skip one more bit_convert if necessary
6283 if (V.getOpcode() == ISD::BITCAST)
6284 V = V.getOperand(0);
6286 if (ISD::isNormalLoad(V.getNode())) {
6287 // Is the original load suitable?
6288 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6290 // FIXME: avoid the multi-use bug that is preventing lots of
6291 // of foldings to be detected, this is still wrong of course, but
6292 // give the temporary desired behavior, and if it happens that
6293 // the load has real more uses, during isel it will not fold, and
6294 // will generate poor code.
6295 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6298 if (!HasShuffleIntoBitcast)
6301 // If there's a bitcast before the shuffle, check if the load type and
6302 // alignment is valid.
6303 unsigned Align = LN0->getAlignment();
6305 TLI.getTargetData()->getABITypeAlignment(
6306 VT.getTypeForEVT(*DAG.getContext()));
6308 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6316 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6317 EVT VT = Op.getValueType();
6319 // Canonizalize to v2f64.
6320 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6321 return DAG.getNode(ISD::BITCAST, dl, VT,
6322 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6327 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6329 SDValue V1 = Op.getOperand(0);
6330 SDValue V2 = Op.getOperand(1);
6331 EVT VT = Op.getValueType();
6333 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6335 if (HasXMMInt && VT == MVT::v2f64)
6336 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6338 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6339 return DAG.getNode(ISD::BITCAST, dl, VT,
6340 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6341 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6342 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6346 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6347 SDValue V1 = Op.getOperand(0);
6348 SDValue V2 = Op.getOperand(1);
6349 EVT VT = Op.getValueType();
6351 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6352 "unsupported shuffle type");
6354 if (V2.getOpcode() == ISD::UNDEF)
6358 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6361 static inline unsigned getSHUFPOpcode(EVT VT) {
6362 switch(VT.getSimpleVT().SimpleTy) {
6363 case MVT::v8i32: // Use fp unit for int unpack.
6365 case MVT::v4i32: // Use fp unit for int unpack.
6366 case MVT::v4f32: return X86ISD::SHUFPS;
6367 case MVT::v4i64: // Use fp unit for int unpack.
6369 case MVT::v2i64: // Use fp unit for int unpack.
6370 case MVT::v2f64: return X86ISD::SHUFPD;
6372 llvm_unreachable("Unknown type for shufp*");
6378 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6379 SDValue V1 = Op.getOperand(0);
6380 SDValue V2 = Op.getOperand(1);
6381 EVT VT = Op.getValueType();
6382 unsigned NumElems = VT.getVectorNumElements();
6384 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6385 // operand of these instructions is only memory, so check if there's a
6386 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6388 bool CanFoldLoad = false;
6390 // Trivial case, when V2 comes from a load.
6391 if (MayFoldVectorLoad(V2))
6394 // When V1 is a load, it can be folded later into a store in isel, example:
6395 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6397 // (MOVLPSmr addr:$src1, VR128:$src2)
6398 // So, recognize this potential and also use MOVLPS or MOVLPD
6399 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6402 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6404 if (HasXMMInt && NumElems == 2)
6405 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6408 // If we don't care about the second element, procede to use movss.
6409 if (SVOp->getMaskElt(1) != -1)
6410 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6413 // movl and movlp will both match v2i64, but v2i64 is never matched by
6414 // movl earlier because we make it strict to avoid messing with the movlp load
6415 // folding logic (see the code above getMOVLP call). Match it here then,
6416 // this is horrible, but will stay like this until we move all shuffle
6417 // matching to x86 specific nodes. Note that for the 1st condition all
6418 // types are matched with movsd.
6420 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6421 // as to remove this logic from here, as much as possible
6422 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6423 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6424 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6427 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6429 // Invert the operand order and use SHUFPS to match it.
6430 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6431 X86::getShuffleSHUFImmediate(SVOp), DAG);
6434 static inline unsigned getUNPCKLOpcode(EVT VT) {
6435 switch(VT.getSimpleVT().SimpleTy) {
6436 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6437 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6438 case MVT::v4f32: return X86ISD::UNPCKLPS;
6439 case MVT::v2f64: return X86ISD::UNPCKLPD;
6440 case MVT::v8i32: // Use fp unit for int unpack.
6441 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6442 case MVT::v4i64: // Use fp unit for int unpack.
6443 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6444 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6445 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6447 llvm_unreachable("Unknown type for unpckl");
6452 static inline unsigned getUNPCKHOpcode(EVT VT) {
6453 switch(VT.getSimpleVT().SimpleTy) {
6454 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6455 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6456 case MVT::v4f32: return X86ISD::UNPCKHPS;
6457 case MVT::v2f64: return X86ISD::UNPCKHPD;
6458 case MVT::v8i32: // Use fp unit for int unpack.
6459 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6460 case MVT::v4i64: // Use fp unit for int unpack.
6461 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6462 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6463 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6465 llvm_unreachable("Unknown type for unpckh");
6470 static inline unsigned getVPERMILOpcode(EVT VT) {
6471 switch(VT.getSimpleVT().SimpleTy) {
6473 case MVT::v4f32: return X86ISD::VPERMILPS;
6475 case MVT::v2f64: return X86ISD::VPERMILPD;
6477 case MVT::v8f32: return X86ISD::VPERMILPSY;
6479 case MVT::v4f64: return X86ISD::VPERMILPDY;
6481 llvm_unreachable("Unknown type for vpermil");
6486 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6487 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6488 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6489 static bool isVectorBroadcast(SDValue &Op) {
6490 EVT VT = Op.getValueType();
6491 bool Is256 = VT.getSizeInBits() == 256;
6493 assert((VT.getSizeInBits() == 128 || Is256) &&
6494 "Unsupported type for vbroadcast node");
6497 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6498 V = V.getOperand(0);
6500 if (Is256 && !(V.hasOneUse() &&
6501 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6502 V.getOperand(0).getOpcode() == ISD::UNDEF))
6506 V = V.getOperand(1);
6511 // Check the source scalar_to_vector type. 256-bit broadcasts are
6512 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6513 // for 32-bit scalars.
6514 if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6517 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6518 if (ScalarSize != 32 && ScalarSize != 64)
6520 if (!Is256 && ScalarSize == 64)
6523 V = V.getOperand(0);
6524 if (!MayFoldLoad(V))
6527 // Return the load node
6533 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6534 const TargetLowering &TLI,
6535 const X86Subtarget *Subtarget) {
6536 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6537 EVT VT = Op.getValueType();
6538 DebugLoc dl = Op.getDebugLoc();
6539 SDValue V1 = Op.getOperand(0);
6540 SDValue V2 = Op.getOperand(1);
6542 if (isZeroShuffle(SVOp))
6543 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6545 // Handle splat operations
6546 if (SVOp->isSplat()) {
6547 unsigned NumElem = VT.getVectorNumElements();
6548 int Size = VT.getSizeInBits();
6549 // Special case, this is the only place now where it's allowed to return
6550 // a vector_shuffle operation without using a target specific node, because
6551 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6552 // this be moved to DAGCombine instead?
6553 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6556 // Use vbroadcast whenever the splat comes from a foldable load
6557 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6558 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6560 // Handle splats by matching through known shuffle masks
6561 if ((Size == 128 && NumElem <= 4) ||
6562 (Size == 256 && NumElem < 8))
6565 // All remaning splats are promoted to target supported vector shuffles.
6566 return PromoteSplat(SVOp, DAG);
6569 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6571 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6572 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6573 if (NewOp.getNode())
6574 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6575 } else if ((VT == MVT::v4i32 ||
6576 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6577 // FIXME: Figure out a cleaner way to do this.
6578 // Try to make use of movq to zero out the top part.
6579 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6580 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6581 if (NewOp.getNode()) {
6582 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6583 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6584 DAG, Subtarget, dl);
6586 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6587 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6588 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6589 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6590 DAG, Subtarget, dl);
6597 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6598 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6599 SDValue V1 = Op.getOperand(0);
6600 SDValue V2 = Op.getOperand(1);
6601 EVT VT = Op.getValueType();
6602 DebugLoc dl = Op.getDebugLoc();
6603 unsigned NumElems = VT.getVectorNumElements();
6604 bool isMMX = VT.getSizeInBits() == 64;
6605 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6606 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6607 bool V1IsSplat = false;
6608 bool V2IsSplat = false;
6609 bool HasXMMInt = Subtarget->hasXMMInt();
6610 MachineFunction &MF = DAG.getMachineFunction();
6611 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6613 // Shuffle operations on MMX not supported.
6617 // Vector shuffle lowering takes 3 steps:
6619 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6620 // narrowing and commutation of operands should be handled.
6621 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6623 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6624 // so the shuffle can be broken into other shuffles and the legalizer can
6625 // try the lowering again.
6627 // The general ideia is that no vector_shuffle operation should be left to
6628 // be matched during isel, all of them must be converted to a target specific
6631 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6632 // narrowing and commutation of operands should be handled. The actual code
6633 // doesn't include all of those, work in progress...
6634 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6635 if (NewOp.getNode())
6638 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6639 // unpckh_undef). Only use pshufd if speed is more important than size.
6640 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6641 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6642 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6643 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6645 if (X86::isMOVDDUPMask(SVOp) &&
6646 (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6647 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6648 return getMOVDDup(Op, dl, V1, DAG);
6650 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6651 return getMOVHighToLow(Op, dl, DAG);
6653 // Use to match splats
6654 if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6655 (VT == MVT::v2f64 || VT == MVT::v2i64))
6656 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6658 if (X86::isPSHUFDMask(SVOp)) {
6659 // The actual implementation will match the mask in the if above and then
6660 // during isel it can match several different instructions, not only pshufd
6661 // as its name says, sad but true, emulate the behavior for now...
6662 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6663 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6665 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6667 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6668 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6670 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6674 // Check if this can be converted into a logical shift.
6675 bool isLeft = false;
6678 bool isShift = getSubtarget()->hasXMMInt() &&
6679 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6680 if (isShift && ShVal.hasOneUse()) {
6681 // If the shifted value has multiple uses, it may be cheaper to use
6682 // v_set0 + movlhps or movhlps, etc.
6683 EVT EltVT = VT.getVectorElementType();
6684 ShAmt *= EltVT.getSizeInBits();
6685 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6688 if (X86::isMOVLMask(SVOp)) {
6691 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6692 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6693 if (!X86::isMOVLPMask(SVOp)) {
6694 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6695 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6697 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6698 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6702 // FIXME: fold these into legal mask.
6703 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6704 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6706 if (X86::isMOVHLPSMask(SVOp))
6707 return getMOVHighToLow(Op, dl, DAG);
6709 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6710 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6712 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6713 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6715 if (X86::isMOVLPMask(SVOp))
6716 return getMOVLP(Op, dl, DAG, HasXMMInt);
6718 if (ShouldXformToMOVHLPS(SVOp) ||
6719 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6720 return CommuteVectorShuffle(SVOp, DAG);
6723 // No better options. Use a vshl / vsrl.
6724 EVT EltVT = VT.getVectorElementType();
6725 ShAmt *= EltVT.getSizeInBits();
6726 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6729 bool Commuted = false;
6730 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6731 // 1,1,1,1 -> v8i16 though.
6732 V1IsSplat = isSplatVector(V1.getNode());
6733 V2IsSplat = isSplatVector(V2.getNode());
6735 // Canonicalize the splat or undef, if present, to be on the RHS.
6736 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6737 Op = CommuteVectorShuffle(SVOp, DAG);
6738 SVOp = cast<ShuffleVectorSDNode>(Op);
6739 V1 = SVOp->getOperand(0);
6740 V2 = SVOp->getOperand(1);
6741 std::swap(V1IsSplat, V2IsSplat);
6742 std::swap(V1IsUndef, V2IsUndef);
6746 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6747 // Shuffling low element of v1 into undef, just return v1.
6750 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6751 // the instruction selector will not match, so get a canonical MOVL with
6752 // swapped operands to undo the commute.
6753 return getMOVL(DAG, dl, VT, V2, V1);
6756 if (X86::isUNPCKLMask(SVOp))
6757 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6759 if (X86::isUNPCKHMask(SVOp))
6760 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6763 // Normalize mask so all entries that point to V2 points to its first
6764 // element then try to match unpck{h|l} again. If match, return a
6765 // new vector_shuffle with the corrected mask.
6766 SDValue NewMask = NormalizeMask(SVOp, DAG);
6767 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6768 if (NSVOp != SVOp) {
6769 if (X86::isUNPCKLMask(NSVOp, true)) {
6771 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6778 // Commute is back and try unpck* again.
6779 // FIXME: this seems wrong.
6780 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6781 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6783 if (X86::isUNPCKLMask(NewSVOp))
6784 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6786 if (X86::isUNPCKHMask(NewSVOp))
6787 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6790 // Normalize the node to match x86 shuffle ops if needed
6791 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6792 return CommuteVectorShuffle(SVOp, DAG);
6794 // The checks below are all present in isShuffleMaskLegal, but they are
6795 // inlined here right now to enable us to directly emit target specific
6796 // nodes, and remove one by one until they don't return Op anymore.
6797 SmallVector<int, 16> M;
6800 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6801 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6802 X86::getShufflePALIGNRImmediate(SVOp),
6805 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6806 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6807 if (VT == MVT::v2f64)
6808 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6809 if (VT == MVT::v2i64)
6810 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6813 if (isPSHUFHWMask(M, VT))
6814 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6815 X86::getShufflePSHUFHWImmediate(SVOp),
6818 if (isPSHUFLWMask(M, VT))
6819 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6820 X86::getShufflePSHUFLWImmediate(SVOp),
6823 if (isSHUFPMask(M, VT))
6824 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6825 X86::getShuffleSHUFImmediate(SVOp), DAG);
6827 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6828 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6829 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6830 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6832 //===--------------------------------------------------------------------===//
6833 // Generate target specific nodes for 128 or 256-bit shuffles only
6834 // supported in the AVX instruction set.
6837 // Handle VMOVDDUPY permutations
6838 if (isMOVDDUPYMask(SVOp, Subtarget))
6839 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6841 // Handle VPERMILPS* permutations
6842 if (isVPERMILPSMask(M, VT, Subtarget))
6843 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6844 getShuffleVPERMILPSImmediate(SVOp), DAG);
6846 // Handle VPERMILPD* permutations
6847 if (isVPERMILPDMask(M, VT, Subtarget))
6848 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6849 getShuffleVPERMILPDImmediate(SVOp), DAG);
6851 // Handle VPERM2F128 permutations
6852 if (isVPERM2F128Mask(M, VT, Subtarget))
6853 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6854 getShuffleVPERM2F128Immediate(SVOp), DAG);
6856 // Handle VSHUFPSY permutations
6857 if (isVSHUFPSYMask(M, VT, Subtarget))
6858 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6859 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6861 // Handle VSHUFPDY permutations
6862 if (isVSHUFPDYMask(M, VT, Subtarget))
6863 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6864 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6866 //===--------------------------------------------------------------------===//
6867 // Since no target specific shuffle was selected for this generic one,
6868 // lower it into other known shuffles. FIXME: this isn't true yet, but
6869 // this is the plan.
6872 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6873 if (VT == MVT::v8i16) {
6874 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6875 if (NewOp.getNode())
6879 if (VT == MVT::v16i8) {
6880 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6881 if (NewOp.getNode())
6885 // Handle all 128-bit wide vectors with 4 elements, and match them with
6886 // several different shuffle types.
6887 if (NumElems == 4 && VT.getSizeInBits() == 128)
6888 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6890 // Handle general 256-bit shuffles
6891 if (VT.is256BitVector())
6892 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6898 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6899 SelectionDAG &DAG) const {
6900 EVT VT = Op.getValueType();
6901 DebugLoc dl = Op.getDebugLoc();
6903 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6906 if (VT.getSizeInBits() == 8) {
6907 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6908 Op.getOperand(0), Op.getOperand(1));
6909 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6910 DAG.getValueType(VT));
6911 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6912 } else if (VT.getSizeInBits() == 16) {
6913 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6914 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6916 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6917 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6918 DAG.getNode(ISD::BITCAST, dl,
6922 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6923 Op.getOperand(0), Op.getOperand(1));
6924 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6925 DAG.getValueType(VT));
6926 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6927 } else if (VT == MVT::f32) {
6928 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6929 // the result back to FR32 register. It's only worth matching if the
6930 // result has a single use which is a store or a bitcast to i32. And in
6931 // the case of a store, it's not worth it if the index is a constant 0,
6932 // because a MOVSSmr can be used instead, which is smaller and faster.
6933 if (!Op.hasOneUse())
6935 SDNode *User = *Op.getNode()->use_begin();
6936 if ((User->getOpcode() != ISD::STORE ||
6937 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6938 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6939 (User->getOpcode() != ISD::BITCAST ||
6940 User->getValueType(0) != MVT::i32))
6942 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6943 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6946 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6947 } else if (VT == MVT::i32) {
6948 // ExtractPS works with constant index.
6949 if (isa<ConstantSDNode>(Op.getOperand(1)))
6957 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6958 SelectionDAG &DAG) const {
6959 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6962 SDValue Vec = Op.getOperand(0);
6963 EVT VecVT = Vec.getValueType();
6965 // If this is a 256-bit vector result, first extract the 128-bit vector and
6966 // then extract the element from the 128-bit vector.
6967 if (VecVT.getSizeInBits() == 256) {
6968 DebugLoc dl = Op.getNode()->getDebugLoc();
6969 unsigned NumElems = VecVT.getVectorNumElements();
6970 SDValue Idx = Op.getOperand(1);
6971 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6973 // Get the 128-bit vector.
6974 bool Upper = IdxVal >= NumElems/2;
6975 Vec = Extract128BitVector(Vec,
6976 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6978 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6979 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6982 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6984 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6985 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6990 EVT VT = Op.getValueType();
6991 DebugLoc dl = Op.getDebugLoc();
6992 // TODO: handle v16i8.
6993 if (VT.getSizeInBits() == 16) {
6994 SDValue Vec = Op.getOperand(0);
6995 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6997 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6998 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6999 DAG.getNode(ISD::BITCAST, dl,
7002 // Transform it so it match pextrw which produces a 32-bit result.
7003 EVT EltVT = MVT::i32;
7004 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7005 Op.getOperand(0), Op.getOperand(1));
7006 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7007 DAG.getValueType(VT));
7008 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7009 } else if (VT.getSizeInBits() == 32) {
7010 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7014 // SHUFPS the element to the lowest double word, then movss.
7015 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7016 EVT VVT = Op.getOperand(0).getValueType();
7017 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7018 DAG.getUNDEF(VVT), Mask);
7019 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7020 DAG.getIntPtrConstant(0));
7021 } else if (VT.getSizeInBits() == 64) {
7022 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7023 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7024 // to match extract_elt for f64.
7025 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7029 // UNPCKHPD the element to the lowest double word, then movsd.
7030 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7031 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7032 int Mask[2] = { 1, -1 };
7033 EVT VVT = Op.getOperand(0).getValueType();
7034 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7035 DAG.getUNDEF(VVT), Mask);
7036 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7037 DAG.getIntPtrConstant(0));
7044 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7045 SelectionDAG &DAG) const {
7046 EVT VT = Op.getValueType();
7047 EVT EltVT = VT.getVectorElementType();
7048 DebugLoc dl = Op.getDebugLoc();
7050 SDValue N0 = Op.getOperand(0);
7051 SDValue N1 = Op.getOperand(1);
7052 SDValue N2 = Op.getOperand(2);
7054 if (VT.getSizeInBits() == 256)
7057 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7058 isa<ConstantSDNode>(N2)) {
7060 if (VT == MVT::v8i16)
7061 Opc = X86ISD::PINSRW;
7062 else if (VT == MVT::v16i8)
7063 Opc = X86ISD::PINSRB;
7065 Opc = X86ISD::PINSRB;
7067 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7069 if (N1.getValueType() != MVT::i32)
7070 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7071 if (N2.getValueType() != MVT::i32)
7072 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7073 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7074 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7075 // Bits [7:6] of the constant are the source select. This will always be
7076 // zero here. The DAG Combiner may combine an extract_elt index into these
7077 // bits. For example (insert (extract, 3), 2) could be matched by putting
7078 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7079 // Bits [5:4] of the constant are the destination select. This is the
7080 // value of the incoming immediate.
7081 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7082 // combine either bitwise AND or insert of float 0.0 to set these bits.
7083 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7084 // Create this as a scalar to vector..
7085 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7086 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7087 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7088 // PINSR* works with constant index.
7095 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7096 EVT VT = Op.getValueType();
7097 EVT EltVT = VT.getVectorElementType();
7099 DebugLoc dl = Op.getDebugLoc();
7100 SDValue N0 = Op.getOperand(0);
7101 SDValue N1 = Op.getOperand(1);
7102 SDValue N2 = Op.getOperand(2);
7104 // If this is a 256-bit vector result, first extract the 128-bit vector,
7105 // insert the element into the extracted half and then place it back.
7106 if (VT.getSizeInBits() == 256) {
7107 if (!isa<ConstantSDNode>(N2))
7110 // Get the desired 128-bit vector half.
7111 unsigned NumElems = VT.getVectorNumElements();
7112 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7113 bool Upper = IdxVal >= NumElems/2;
7114 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7115 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7117 // Insert the element into the desired half.
7118 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7119 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7121 // Insert the changed part back to the 256-bit vector
7122 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7125 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7126 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7128 if (EltVT == MVT::i8)
7131 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7132 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7133 // as its second argument.
7134 if (N1.getValueType() != MVT::i32)
7135 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7136 if (N2.getValueType() != MVT::i32)
7137 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7138 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7144 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7145 LLVMContext *Context = DAG.getContext();
7146 DebugLoc dl = Op.getDebugLoc();
7147 EVT OpVT = Op.getValueType();
7149 // If this is a 256-bit vector result, first insert into a 128-bit
7150 // vector and then insert into the 256-bit vector.
7151 if (OpVT.getSizeInBits() > 128) {
7152 // Insert into a 128-bit vector.
7153 EVT VT128 = EVT::getVectorVT(*Context,
7154 OpVT.getVectorElementType(),
7155 OpVT.getVectorNumElements() / 2);
7157 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7159 // Insert the 128-bit vector.
7160 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7161 DAG.getConstant(0, MVT::i32),
7165 if (Op.getValueType() == MVT::v1i64 &&
7166 Op.getOperand(0).getValueType() == MVT::i64)
7167 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7169 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7170 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7171 "Expected an SSE type!");
7172 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7173 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7176 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7177 // a simple subregister reference or explicit instructions to grab
7178 // upper bits of a vector.
7180 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7181 if (Subtarget->hasAVX()) {
7182 DebugLoc dl = Op.getNode()->getDebugLoc();
7183 SDValue Vec = Op.getNode()->getOperand(0);
7184 SDValue Idx = Op.getNode()->getOperand(1);
7186 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7187 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7188 return Extract128BitVector(Vec, Idx, DAG, dl);
7194 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7195 // simple superregister reference or explicit instructions to insert
7196 // the upper bits of a vector.
7198 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7199 if (Subtarget->hasAVX()) {
7200 DebugLoc dl = Op.getNode()->getDebugLoc();
7201 SDValue Vec = Op.getNode()->getOperand(0);
7202 SDValue SubVec = Op.getNode()->getOperand(1);
7203 SDValue Idx = Op.getNode()->getOperand(2);
7205 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7206 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7207 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7213 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7214 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7215 // one of the above mentioned nodes. It has to be wrapped because otherwise
7216 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7217 // be used to form addressing mode. These wrapped nodes will be selected
7220 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7221 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7225 unsigned char OpFlag = 0;
7226 unsigned WrapperKind = X86ISD::Wrapper;
7227 CodeModel::Model M = getTargetMachine().getCodeModel();
7229 if (Subtarget->isPICStyleRIPRel() &&
7230 (M == CodeModel::Small || M == CodeModel::Kernel))
7231 WrapperKind = X86ISD::WrapperRIP;
7232 else if (Subtarget->isPICStyleGOT())
7233 OpFlag = X86II::MO_GOTOFF;
7234 else if (Subtarget->isPICStyleStubPIC())
7235 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7237 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7239 CP->getOffset(), OpFlag);
7240 DebugLoc DL = CP->getDebugLoc();
7241 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7242 // With PIC, the address is actually $g + Offset.
7244 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7245 DAG.getNode(X86ISD::GlobalBaseReg,
7246 DebugLoc(), getPointerTy()),
7253 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7254 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7256 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7258 unsigned char OpFlag = 0;
7259 unsigned WrapperKind = X86ISD::Wrapper;
7260 CodeModel::Model M = getTargetMachine().getCodeModel();
7262 if (Subtarget->isPICStyleRIPRel() &&
7263 (M == CodeModel::Small || M == CodeModel::Kernel))
7264 WrapperKind = X86ISD::WrapperRIP;
7265 else if (Subtarget->isPICStyleGOT())
7266 OpFlag = X86II::MO_GOTOFF;
7267 else if (Subtarget->isPICStyleStubPIC())
7268 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7270 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7272 DebugLoc DL = JT->getDebugLoc();
7273 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7275 // With PIC, the address is actually $g + Offset.
7277 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7278 DAG.getNode(X86ISD::GlobalBaseReg,
7279 DebugLoc(), getPointerTy()),
7286 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7287 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7289 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7291 unsigned char OpFlag = 0;
7292 unsigned WrapperKind = X86ISD::Wrapper;
7293 CodeModel::Model M = getTargetMachine().getCodeModel();
7295 if (Subtarget->isPICStyleRIPRel() &&
7296 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7297 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7298 OpFlag = X86II::MO_GOTPCREL;
7299 WrapperKind = X86ISD::WrapperRIP;
7300 } else if (Subtarget->isPICStyleGOT()) {
7301 OpFlag = X86II::MO_GOT;
7302 } else if (Subtarget->isPICStyleStubPIC()) {
7303 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7304 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7305 OpFlag = X86II::MO_DARWIN_NONLAZY;
7308 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7310 DebugLoc DL = Op.getDebugLoc();
7311 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7314 // With PIC, the address is actually $g + Offset.
7315 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7316 !Subtarget->is64Bit()) {
7317 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7318 DAG.getNode(X86ISD::GlobalBaseReg,
7319 DebugLoc(), getPointerTy()),
7323 // For symbols that require a load from a stub to get the address, emit the
7325 if (isGlobalStubReference(OpFlag))
7326 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7327 MachinePointerInfo::getGOT(), false, false, false, 0);
7333 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7334 // Create the TargetBlockAddressAddress node.
7335 unsigned char OpFlags =
7336 Subtarget->ClassifyBlockAddressReference();
7337 CodeModel::Model M = getTargetMachine().getCodeModel();
7338 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7339 DebugLoc dl = Op.getDebugLoc();
7340 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7341 /*isTarget=*/true, OpFlags);
7343 if (Subtarget->isPICStyleRIPRel() &&
7344 (M == CodeModel::Small || M == CodeModel::Kernel))
7345 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7347 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7349 // With PIC, the address is actually $g + Offset.
7350 if (isGlobalRelativeToPICBase(OpFlags)) {
7351 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7352 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7360 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7362 SelectionDAG &DAG) const {
7363 // Create the TargetGlobalAddress node, folding in the constant
7364 // offset if it is legal.
7365 unsigned char OpFlags =
7366 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7367 CodeModel::Model M = getTargetMachine().getCodeModel();
7369 if (OpFlags == X86II::MO_NO_FLAG &&
7370 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7371 // A direct static reference to a global.
7372 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7375 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7378 if (Subtarget->isPICStyleRIPRel() &&
7379 (M == CodeModel::Small || M == CodeModel::Kernel))
7380 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7382 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7384 // With PIC, the address is actually $g + Offset.
7385 if (isGlobalRelativeToPICBase(OpFlags)) {
7386 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7387 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7391 // For globals that require a load from a stub to get the address, emit the
7393 if (isGlobalStubReference(OpFlags))
7394 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7395 MachinePointerInfo::getGOT(), false, false, false, 0);
7397 // If there was a non-zero offset that we didn't fold, create an explicit
7400 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7401 DAG.getConstant(Offset, getPointerTy()));
7407 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7408 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7409 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7410 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7414 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7415 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7416 unsigned char OperandFlags) {
7417 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7418 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7419 DebugLoc dl = GA->getDebugLoc();
7420 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7421 GA->getValueType(0),
7425 SDValue Ops[] = { Chain, TGA, *InFlag };
7426 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7428 SDValue Ops[] = { Chain, TGA };
7429 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7432 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7433 MFI->setAdjustsStack(true);
7435 SDValue Flag = Chain.getValue(1);
7436 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7439 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7441 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7444 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7445 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7446 DAG.getNode(X86ISD::GlobalBaseReg,
7447 DebugLoc(), PtrVT), InFlag);
7448 InFlag = Chain.getValue(1);
7450 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7453 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7455 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7457 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7458 X86::RAX, X86II::MO_TLSGD);
7461 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7462 // "local exec" model.
7463 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7464 const EVT PtrVT, TLSModel::Model model,
7466 DebugLoc dl = GA->getDebugLoc();
7468 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7469 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7470 is64Bit ? 257 : 256));
7472 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7473 DAG.getIntPtrConstant(0),
7474 MachinePointerInfo(Ptr),
7475 false, false, false, 0);
7477 unsigned char OperandFlags = 0;
7478 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7480 unsigned WrapperKind = X86ISD::Wrapper;
7481 if (model == TLSModel::LocalExec) {
7482 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7483 } else if (is64Bit) {
7484 assert(model == TLSModel::InitialExec);
7485 OperandFlags = X86II::MO_GOTTPOFF;
7486 WrapperKind = X86ISD::WrapperRIP;
7488 assert(model == TLSModel::InitialExec);
7489 OperandFlags = X86II::MO_INDNTPOFF;
7492 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7494 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7495 GA->getValueType(0),
7496 GA->getOffset(), OperandFlags);
7497 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7499 if (model == TLSModel::InitialExec)
7500 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7501 MachinePointerInfo::getGOT(), false, false, false, 0);
7503 // The address of the thread local variable is the add of the thread
7504 // pointer with the offset of the variable.
7505 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7509 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7511 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7512 const GlobalValue *GV = GA->getGlobal();
7514 if (Subtarget->isTargetELF()) {
7515 // TODO: implement the "local dynamic" model
7516 // TODO: implement the "initial exec"model for pic executables
7518 // If GV is an alias then use the aliasee for determining
7519 // thread-localness.
7520 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7521 GV = GA->resolveAliasedGlobal(false);
7523 TLSModel::Model model
7524 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7527 case TLSModel::GeneralDynamic:
7528 case TLSModel::LocalDynamic: // not implemented
7529 if (Subtarget->is64Bit())
7530 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7531 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7533 case TLSModel::InitialExec:
7534 case TLSModel::LocalExec:
7535 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7536 Subtarget->is64Bit());
7538 } else if (Subtarget->isTargetDarwin()) {
7539 // Darwin only has one model of TLS. Lower to that.
7540 unsigned char OpFlag = 0;
7541 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7542 X86ISD::WrapperRIP : X86ISD::Wrapper;
7544 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7546 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7547 !Subtarget->is64Bit();
7549 OpFlag = X86II::MO_TLVP_PIC_BASE;
7551 OpFlag = X86II::MO_TLVP;
7552 DebugLoc DL = Op.getDebugLoc();
7553 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7554 GA->getValueType(0),
7555 GA->getOffset(), OpFlag);
7556 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7558 // With PIC32, the address is actually $g + Offset.
7560 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7561 DAG.getNode(X86ISD::GlobalBaseReg,
7562 DebugLoc(), getPointerTy()),
7565 // Lowering the machine isd will make sure everything is in the right
7567 SDValue Chain = DAG.getEntryNode();
7568 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7569 SDValue Args[] = { Chain, Offset };
7570 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7572 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7573 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7574 MFI->setAdjustsStack(true);
7576 // And our return value (tls address) is in the standard call return value
7578 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7579 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7584 "TLS not implemented for this target.");
7586 llvm_unreachable("Unreachable");
7591 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7592 /// take a 2 x i32 value to shift plus a shift amount.
7593 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7594 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7595 EVT VT = Op.getValueType();
7596 unsigned VTBits = VT.getSizeInBits();
7597 DebugLoc dl = Op.getDebugLoc();
7598 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7599 SDValue ShOpLo = Op.getOperand(0);
7600 SDValue ShOpHi = Op.getOperand(1);
7601 SDValue ShAmt = Op.getOperand(2);
7602 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7603 DAG.getConstant(VTBits - 1, MVT::i8))
7604 : DAG.getConstant(0, VT);
7607 if (Op.getOpcode() == ISD::SHL_PARTS) {
7608 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7609 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7611 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7612 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7615 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7616 DAG.getConstant(VTBits, MVT::i8));
7617 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7618 AndNode, DAG.getConstant(0, MVT::i8));
7621 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7622 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7623 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7625 if (Op.getOpcode() == ISD::SHL_PARTS) {
7626 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7627 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7629 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7630 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7633 SDValue Ops[2] = { Lo, Hi };
7634 return DAG.getMergeValues(Ops, 2, dl);
7637 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7638 SelectionDAG &DAG) const {
7639 EVT SrcVT = Op.getOperand(0).getValueType();
7641 if (SrcVT.isVector())
7644 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7645 "Unknown SINT_TO_FP to lower!");
7647 // These are really Legal; return the operand so the caller accepts it as
7649 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7651 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7652 Subtarget->is64Bit()) {
7656 DebugLoc dl = Op.getDebugLoc();
7657 unsigned Size = SrcVT.getSizeInBits()/8;
7658 MachineFunction &MF = DAG.getMachineFunction();
7659 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7660 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7661 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7663 MachinePointerInfo::getFixedStack(SSFI),
7665 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7668 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7670 SelectionDAG &DAG) const {
7672 DebugLoc DL = Op.getDebugLoc();
7674 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7676 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7678 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7680 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7682 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7683 MachineMemOperand *MMO;
7685 int SSFI = FI->getIndex();
7687 DAG.getMachineFunction()
7688 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7689 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7691 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7692 StackSlot = StackSlot.getOperand(1);
7694 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7695 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7697 Tys, Ops, array_lengthof(Ops),
7701 Chain = Result.getValue(1);
7702 SDValue InFlag = Result.getValue(2);
7704 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7705 // shouldn't be necessary except that RFP cannot be live across
7706 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7707 MachineFunction &MF = DAG.getMachineFunction();
7708 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7709 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7710 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7711 Tys = DAG.getVTList(MVT::Other);
7713 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7715 MachineMemOperand *MMO =
7716 DAG.getMachineFunction()
7717 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7718 MachineMemOperand::MOStore, SSFISize, SSFISize);
7720 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7721 Ops, array_lengthof(Ops),
7722 Op.getValueType(), MMO);
7723 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7724 MachinePointerInfo::getFixedStack(SSFI),
7725 false, false, false, 0);
7731 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7732 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7733 SelectionDAG &DAG) const {
7734 // This algorithm is not obvious. Here it is in C code, more or less:
7736 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7737 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7738 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7740 // Copy ints to xmm registers.
7741 __m128i xh = _mm_cvtsi32_si128( hi );
7742 __m128i xl = _mm_cvtsi32_si128( lo );
7744 // Combine into low half of a single xmm register.
7745 __m128i x = _mm_unpacklo_epi32( xh, xl );
7749 // Merge in appropriate exponents to give the integer bits the right
7751 x = _mm_unpacklo_epi32( x, exp );
7753 // Subtract away the biases to deal with the IEEE-754 double precision
7755 d = _mm_sub_pd( (__m128d) x, bias );
7757 // All conversions up to here are exact. The correctly rounded result is
7758 // calculated using the current rounding mode using the following
7760 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7761 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7762 // store doesn't really need to be here (except
7763 // maybe to zero the other double)
7768 DebugLoc dl = Op.getDebugLoc();
7769 LLVMContext *Context = DAG.getContext();
7771 // Build some magic constants.
7772 std::vector<Constant*> CV0;
7773 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7774 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7775 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7776 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7777 Constant *C0 = ConstantVector::get(CV0);
7778 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7780 std::vector<Constant*> CV1;
7782 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7784 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7785 Constant *C1 = ConstantVector::get(CV1);
7786 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7788 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7789 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7791 DAG.getIntPtrConstant(1)));
7792 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7793 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7795 DAG.getIntPtrConstant(0)));
7796 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7797 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7798 MachinePointerInfo::getConstantPool(),
7799 false, false, false, 16);
7800 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7801 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7802 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7803 MachinePointerInfo::getConstantPool(),
7804 false, false, false, 16);
7805 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7807 // Add the halves; easiest way is to swap them into another reg first.
7808 int ShufMask[2] = { 1, -1 };
7809 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7810 DAG.getUNDEF(MVT::v2f64), ShufMask);
7811 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7812 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7813 DAG.getIntPtrConstant(0));
7816 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7817 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7818 SelectionDAG &DAG) const {
7819 DebugLoc dl = Op.getDebugLoc();
7820 // FP constant to bias correct the final result.
7821 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7824 // Load the 32-bit value into an XMM register.
7825 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7828 // Zero out the upper parts of the register.
7829 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7832 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7833 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7834 DAG.getIntPtrConstant(0));
7836 // Or the load with the bias.
7837 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7838 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7839 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7841 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7842 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7843 MVT::v2f64, Bias)));
7844 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7845 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7846 DAG.getIntPtrConstant(0));
7848 // Subtract the bias.
7849 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7851 // Handle final rounding.
7852 EVT DestVT = Op.getValueType();
7854 if (DestVT.bitsLT(MVT::f64)) {
7855 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7856 DAG.getIntPtrConstant(0));
7857 } else if (DestVT.bitsGT(MVT::f64)) {
7858 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7861 // Handle final rounding.
7865 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7866 SelectionDAG &DAG) const {
7867 SDValue N0 = Op.getOperand(0);
7868 DebugLoc dl = Op.getDebugLoc();
7870 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7871 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7872 // the optimization here.
7873 if (DAG.SignBitIsZero(N0))
7874 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7876 EVT SrcVT = N0.getValueType();
7877 EVT DstVT = Op.getValueType();
7878 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7879 return LowerUINT_TO_FP_i64(Op, DAG);
7880 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7881 return LowerUINT_TO_FP_i32(Op, DAG);
7883 // Make a 64-bit buffer, and use it to build an FILD.
7884 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7885 if (SrcVT == MVT::i32) {
7886 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7887 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7888 getPointerTy(), StackSlot, WordOff);
7889 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7890 StackSlot, MachinePointerInfo(),
7892 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7893 OffsetSlot, MachinePointerInfo(),
7895 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7899 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7900 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7901 StackSlot, MachinePointerInfo(),
7903 // For i64 source, we need to add the appropriate power of 2 if the input
7904 // was negative. This is the same as the optimization in
7905 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7906 // we must be careful to do the computation in x87 extended precision, not
7907 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7908 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7909 MachineMemOperand *MMO =
7910 DAG.getMachineFunction()
7911 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7912 MachineMemOperand::MOLoad, 8, 8);
7914 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7915 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7916 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7919 APInt FF(32, 0x5F800000ULL);
7921 // Check whether the sign bit is set.
7922 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7923 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7926 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7927 SDValue FudgePtr = DAG.getConstantPool(
7928 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7931 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7932 SDValue Zero = DAG.getIntPtrConstant(0);
7933 SDValue Four = DAG.getIntPtrConstant(4);
7934 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7936 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7938 // Load the value out, extending it from f32 to f80.
7939 // FIXME: Avoid the extend by constructing the right constant pool?
7940 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7941 FudgePtr, MachinePointerInfo::getConstantPool(),
7942 MVT::f32, false, false, 4);
7943 // Extend everything to 80 bits to force it to be done on x87.
7944 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7945 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7948 std::pair<SDValue,SDValue> X86TargetLowering::
7949 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7950 DebugLoc DL = Op.getDebugLoc();
7952 EVT DstTy = Op.getValueType();
7955 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7959 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7960 DstTy.getSimpleVT() >= MVT::i16 &&
7961 "Unknown FP_TO_SINT to lower!");
7963 // These are really Legal.
7964 if (DstTy == MVT::i32 &&
7965 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7966 return std::make_pair(SDValue(), SDValue());
7967 if (Subtarget->is64Bit() &&
7968 DstTy == MVT::i64 &&
7969 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7970 return std::make_pair(SDValue(), SDValue());
7972 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7974 MachineFunction &MF = DAG.getMachineFunction();
7975 unsigned MemSize = DstTy.getSizeInBits()/8;
7976 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7977 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7982 switch (DstTy.getSimpleVT().SimpleTy) {
7983 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7984 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7985 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7986 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7989 SDValue Chain = DAG.getEntryNode();
7990 SDValue Value = Op.getOperand(0);
7991 EVT TheVT = Op.getOperand(0).getValueType();
7992 if (isScalarFPTypeInSSEReg(TheVT)) {
7993 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7994 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7995 MachinePointerInfo::getFixedStack(SSFI),
7997 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7999 Chain, StackSlot, DAG.getValueType(TheVT)
8002 MachineMemOperand *MMO =
8003 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8004 MachineMemOperand::MOLoad, MemSize, MemSize);
8005 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8007 Chain = Value.getValue(1);
8008 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8009 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8012 MachineMemOperand *MMO =
8013 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8014 MachineMemOperand::MOStore, MemSize, MemSize);
8016 // Build the FP_TO_INT*_IN_MEM
8017 SDValue Ops[] = { Chain, Value, StackSlot };
8018 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8019 Ops, 3, DstTy, MMO);
8021 return std::make_pair(FIST, StackSlot);
8024 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8025 SelectionDAG &DAG) const {
8026 if (Op.getValueType().isVector())
8029 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8030 SDValue FIST = Vals.first, StackSlot = Vals.second;
8031 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8032 if (FIST.getNode() == 0) return Op;
8035 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8036 FIST, StackSlot, MachinePointerInfo(),
8037 false, false, false, 0);
8040 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8041 SelectionDAG &DAG) const {
8042 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8043 SDValue FIST = Vals.first, StackSlot = Vals.second;
8044 assert(FIST.getNode() && "Unexpected failure");
8047 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8048 FIST, StackSlot, MachinePointerInfo(),
8049 false, false, false, 0);
8052 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8053 SelectionDAG &DAG) const {
8054 LLVMContext *Context = DAG.getContext();
8055 DebugLoc dl = Op.getDebugLoc();
8056 EVT VT = Op.getValueType();
8059 EltVT = VT.getVectorElementType();
8060 std::vector<Constant*> CV;
8061 if (EltVT == MVT::f64) {
8062 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8066 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8072 Constant *C = ConstantVector::get(CV);
8073 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8074 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8075 MachinePointerInfo::getConstantPool(),
8076 false, false, false, 16);
8077 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8080 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8081 LLVMContext *Context = DAG.getContext();
8082 DebugLoc dl = Op.getDebugLoc();
8083 EVT VT = Op.getValueType();
8086 EltVT = VT.getVectorElementType();
8087 std::vector<Constant*> CV;
8088 if (EltVT == MVT::f64) {
8089 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8093 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8099 Constant *C = ConstantVector::get(CV);
8100 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8101 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8102 MachinePointerInfo::getConstantPool(),
8103 false, false, false, 16);
8104 if (VT.isVector()) {
8105 return DAG.getNode(ISD::BITCAST, dl, VT,
8106 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8107 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8109 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8111 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8115 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8116 LLVMContext *Context = DAG.getContext();
8117 SDValue Op0 = Op.getOperand(0);
8118 SDValue Op1 = Op.getOperand(1);
8119 DebugLoc dl = Op.getDebugLoc();
8120 EVT VT = Op.getValueType();
8121 EVT SrcVT = Op1.getValueType();
8123 // If second operand is smaller, extend it first.
8124 if (SrcVT.bitsLT(VT)) {
8125 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8128 // And if it is bigger, shrink it first.
8129 if (SrcVT.bitsGT(VT)) {
8130 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8134 // At this point the operands and the result should have the same
8135 // type, and that won't be f80 since that is not custom lowered.
8137 // First get the sign bit of second operand.
8138 std::vector<Constant*> CV;
8139 if (SrcVT == MVT::f64) {
8140 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8141 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8143 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8144 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8145 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8146 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8148 Constant *C = ConstantVector::get(CV);
8149 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8150 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8151 MachinePointerInfo::getConstantPool(),
8152 false, false, false, 16);
8153 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8155 // Shift sign bit right or left if the two operands have different types.
8156 if (SrcVT.bitsGT(VT)) {
8157 // Op0 is MVT::f32, Op1 is MVT::f64.
8158 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8159 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8160 DAG.getConstant(32, MVT::i32));
8161 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8162 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8163 DAG.getIntPtrConstant(0));
8166 // Clear first operand sign bit.
8168 if (VT == MVT::f64) {
8169 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8170 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8172 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8173 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8174 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8175 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8177 C = ConstantVector::get(CV);
8178 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8179 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8180 MachinePointerInfo::getConstantPool(),
8181 false, false, false, 16);
8182 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8184 // Or the value with the sign bit.
8185 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8188 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8189 SDValue N0 = Op.getOperand(0);
8190 DebugLoc dl = Op.getDebugLoc();
8191 EVT VT = Op.getValueType();
8193 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8194 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8195 DAG.getConstant(1, VT));
8196 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8199 /// Emit nodes that will be selected as "test Op0,Op0", or something
8201 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8202 SelectionDAG &DAG) const {
8203 DebugLoc dl = Op.getDebugLoc();
8205 // CF and OF aren't always set the way we want. Determine which
8206 // of these we need.
8207 bool NeedCF = false;
8208 bool NeedOF = false;
8211 case X86::COND_A: case X86::COND_AE:
8212 case X86::COND_B: case X86::COND_BE:
8215 case X86::COND_G: case X86::COND_GE:
8216 case X86::COND_L: case X86::COND_LE:
8217 case X86::COND_O: case X86::COND_NO:
8222 // See if we can use the EFLAGS value from the operand instead of
8223 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8224 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8225 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8226 // Emit a CMP with 0, which is the TEST pattern.
8227 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8228 DAG.getConstant(0, Op.getValueType()));
8230 unsigned Opcode = 0;
8231 unsigned NumOperands = 0;
8232 switch (Op.getNode()->getOpcode()) {
8234 // Due to an isel shortcoming, be conservative if this add is likely to be
8235 // selected as part of a load-modify-store instruction. When the root node
8236 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8237 // uses of other nodes in the match, such as the ADD in this case. This
8238 // leads to the ADD being left around and reselected, with the result being
8239 // two adds in the output. Alas, even if none our users are stores, that
8240 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8241 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8242 // climbing the DAG back to the root, and it doesn't seem to be worth the
8244 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8245 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8246 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8249 if (ConstantSDNode *C =
8250 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8251 // An add of one will be selected as an INC.
8252 if (C->getAPIntValue() == 1) {
8253 Opcode = X86ISD::INC;
8258 // An add of negative one (subtract of one) will be selected as a DEC.
8259 if (C->getAPIntValue().isAllOnesValue()) {
8260 Opcode = X86ISD::DEC;
8266 // Otherwise use a regular EFLAGS-setting add.
8267 Opcode = X86ISD::ADD;
8271 // If the primary and result isn't used, don't bother using X86ISD::AND,
8272 // because a TEST instruction will be better.
8273 bool NonFlagUse = false;
8274 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8275 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8277 unsigned UOpNo = UI.getOperandNo();
8278 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8279 // Look pass truncate.
8280 UOpNo = User->use_begin().getOperandNo();
8281 User = *User->use_begin();
8284 if (User->getOpcode() != ISD::BRCOND &&
8285 User->getOpcode() != ISD::SETCC &&
8286 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8299 // Due to the ISEL shortcoming noted above, be conservative if this op is
8300 // likely to be selected as part of a load-modify-store instruction.
8301 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8302 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8303 if (UI->getOpcode() == ISD::STORE)
8306 // Otherwise use a regular EFLAGS-setting instruction.
8307 switch (Op.getNode()->getOpcode()) {
8308 default: llvm_unreachable("unexpected operator!");
8309 case ISD::SUB: Opcode = X86ISD::SUB; break;
8310 case ISD::OR: Opcode = X86ISD::OR; break;
8311 case ISD::XOR: Opcode = X86ISD::XOR; break;
8312 case ISD::AND: Opcode = X86ISD::AND; break;
8324 return SDValue(Op.getNode(), 1);
8331 // Emit a CMP with 0, which is the TEST pattern.
8332 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8333 DAG.getConstant(0, Op.getValueType()));
8335 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8336 SmallVector<SDValue, 4> Ops;
8337 for (unsigned i = 0; i != NumOperands; ++i)
8338 Ops.push_back(Op.getOperand(i));
8340 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8341 DAG.ReplaceAllUsesWith(Op, New);
8342 return SDValue(New.getNode(), 1);
8345 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8347 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8348 SelectionDAG &DAG) const {
8349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8350 if (C->getAPIntValue() == 0)
8351 return EmitTest(Op0, X86CC, DAG);
8353 DebugLoc dl = Op0.getDebugLoc();
8354 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8357 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8358 /// if it's possible.
8359 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8360 DebugLoc dl, SelectionDAG &DAG) const {
8361 SDValue Op0 = And.getOperand(0);
8362 SDValue Op1 = And.getOperand(1);
8363 if (Op0.getOpcode() == ISD::TRUNCATE)
8364 Op0 = Op0.getOperand(0);
8365 if (Op1.getOpcode() == ISD::TRUNCATE)
8366 Op1 = Op1.getOperand(0);
8369 if (Op1.getOpcode() == ISD::SHL)
8370 std::swap(Op0, Op1);
8371 if (Op0.getOpcode() == ISD::SHL) {
8372 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8373 if (And00C->getZExtValue() == 1) {
8374 // If we looked past a truncate, check that it's only truncating away
8376 unsigned BitWidth = Op0.getValueSizeInBits();
8377 unsigned AndBitWidth = And.getValueSizeInBits();
8378 if (BitWidth > AndBitWidth) {
8379 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8380 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8381 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8385 RHS = Op0.getOperand(1);
8387 } else if (Op1.getOpcode() == ISD::Constant) {
8388 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8389 SDValue AndLHS = Op0;
8390 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8391 LHS = AndLHS.getOperand(0);
8392 RHS = AndLHS.getOperand(1);
8396 if (LHS.getNode()) {
8397 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8398 // instruction. Since the shift amount is in-range-or-undefined, we know
8399 // that doing a bittest on the i32 value is ok. We extend to i32 because
8400 // the encoding for the i16 version is larger than the i32 version.
8401 // Also promote i16 to i32 for performance / code size reason.
8402 if (LHS.getValueType() == MVT::i8 ||
8403 LHS.getValueType() == MVT::i16)
8404 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8406 // If the operand types disagree, extend the shift amount to match. Since
8407 // BT ignores high bits (like shifts) we can use anyextend.
8408 if (LHS.getValueType() != RHS.getValueType())
8409 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8411 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8412 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8413 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8414 DAG.getConstant(Cond, MVT::i8), BT);
8420 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8422 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8424 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8425 SDValue Op0 = Op.getOperand(0);
8426 SDValue Op1 = Op.getOperand(1);
8427 DebugLoc dl = Op.getDebugLoc();
8428 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8430 // Optimize to BT if possible.
8431 // Lower (X & (1 << N)) == 0 to BT(X, N).
8432 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8433 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8434 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8435 Op1.getOpcode() == ISD::Constant &&
8436 cast<ConstantSDNode>(Op1)->isNullValue() &&
8437 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8438 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8439 if (NewSetCC.getNode())
8443 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8445 if (Op1.getOpcode() == ISD::Constant &&
8446 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8447 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8448 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8450 // If the input is a setcc, then reuse the input setcc or use a new one with
8451 // the inverted condition.
8452 if (Op0.getOpcode() == X86ISD::SETCC) {
8453 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8454 bool Invert = (CC == ISD::SETNE) ^
8455 cast<ConstantSDNode>(Op1)->isNullValue();
8456 if (!Invert) return Op0;
8458 CCode = X86::GetOppositeBranchCondition(CCode);
8459 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8460 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8464 bool isFP = Op1.getValueType().isFloatingPoint();
8465 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8466 if (X86CC == X86::COND_INVALID)
8469 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8470 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8471 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8474 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8475 // ones, and then concatenate the result back.
8476 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8477 EVT VT = Op.getValueType();
8479 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8480 "Unsupported value type for operation");
8482 int NumElems = VT.getVectorNumElements();
8483 DebugLoc dl = Op.getDebugLoc();
8484 SDValue CC = Op.getOperand(2);
8485 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8486 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8488 // Extract the LHS vectors
8489 SDValue LHS = Op.getOperand(0);
8490 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8491 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8493 // Extract the RHS vectors
8494 SDValue RHS = Op.getOperand(1);
8495 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8496 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8498 // Issue the operation on the smaller types and concatenate the result back
8499 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8500 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8501 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8502 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8503 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8507 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8509 SDValue Op0 = Op.getOperand(0);
8510 SDValue Op1 = Op.getOperand(1);
8511 SDValue CC = Op.getOperand(2);
8512 EVT VT = Op.getValueType();
8513 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8514 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8515 DebugLoc dl = Op.getDebugLoc();
8519 EVT EltVT = Op0.getValueType().getVectorElementType();
8520 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8522 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8525 // SSE Condition code mapping:
8534 switch (SetCCOpcode) {
8537 case ISD::SETEQ: SSECC = 0; break;
8539 case ISD::SETGT: Swap = true; // Fallthrough
8541 case ISD::SETOLT: SSECC = 1; break;
8543 case ISD::SETGE: Swap = true; // Fallthrough
8545 case ISD::SETOLE: SSECC = 2; break;
8546 case ISD::SETUO: SSECC = 3; break;
8548 case ISD::SETNE: SSECC = 4; break;
8549 case ISD::SETULE: Swap = true;
8550 case ISD::SETUGE: SSECC = 5; break;
8551 case ISD::SETULT: Swap = true;
8552 case ISD::SETUGT: SSECC = 6; break;
8553 case ISD::SETO: SSECC = 7; break;
8556 std::swap(Op0, Op1);
8558 // In the two special cases we can't handle, emit two comparisons.
8560 if (SetCCOpcode == ISD::SETUEQ) {
8562 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8563 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8564 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8565 } else if (SetCCOpcode == ISD::SETONE) {
8567 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8568 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8569 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8571 llvm_unreachable("Illegal FP comparison");
8573 // Handle all other FP comparisons here.
8574 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8577 // Break 256-bit integer vector compare into smaller ones.
8578 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8579 return Lower256IntVSETCC(Op, DAG);
8581 // We are handling one of the integer comparisons here. Since SSE only has
8582 // GT and EQ comparisons for integer, swapping operands and multiple
8583 // operations may be required for some comparisons.
8584 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8585 bool Swap = false, Invert = false, FlipSigns = false;
8587 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8589 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8590 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8591 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8592 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8595 switch (SetCCOpcode) {
8597 case ISD::SETNE: Invert = true;
8598 case ISD::SETEQ: Opc = EQOpc; break;
8599 case ISD::SETLT: Swap = true;
8600 case ISD::SETGT: Opc = GTOpc; break;
8601 case ISD::SETGE: Swap = true;
8602 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8603 case ISD::SETULT: Swap = true;
8604 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8605 case ISD::SETUGE: Swap = true;
8606 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8609 std::swap(Op0, Op1);
8611 // Check that the operation in question is available (most are plain SSE2,
8612 // but PCMPGTQ and PCMPEQQ have different requirements).
8613 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8615 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8618 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8619 // bits of the inputs before performing those operations.
8621 EVT EltVT = VT.getVectorElementType();
8622 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8624 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8625 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8627 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8628 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8631 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8633 // If the logical-not of the result is required, perform that now.
8635 Result = DAG.getNOT(dl, Result, VT);
8640 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8641 static bool isX86LogicalCmp(SDValue Op) {
8642 unsigned Opc = Op.getNode()->getOpcode();
8643 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8645 if (Op.getResNo() == 1 &&
8646 (Opc == X86ISD::ADD ||
8647 Opc == X86ISD::SUB ||
8648 Opc == X86ISD::ADC ||
8649 Opc == X86ISD::SBB ||
8650 Opc == X86ISD::SMUL ||
8651 Opc == X86ISD::UMUL ||
8652 Opc == X86ISD::INC ||
8653 Opc == X86ISD::DEC ||
8654 Opc == X86ISD::OR ||
8655 Opc == X86ISD::XOR ||
8656 Opc == X86ISD::AND))
8659 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8665 static bool isZero(SDValue V) {
8666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8667 return C && C->isNullValue();
8670 static bool isAllOnes(SDValue V) {
8671 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8672 return C && C->isAllOnesValue();
8675 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8676 bool addTest = true;
8677 SDValue Cond = Op.getOperand(0);
8678 SDValue Op1 = Op.getOperand(1);
8679 SDValue Op2 = Op.getOperand(2);
8680 DebugLoc DL = Op.getDebugLoc();
8683 if (Cond.getOpcode() == ISD::SETCC) {
8684 SDValue NewCond = LowerSETCC(Cond, DAG);
8685 if (NewCond.getNode())
8689 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8690 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8691 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8692 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8693 if (Cond.getOpcode() == X86ISD::SETCC &&
8694 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8695 isZero(Cond.getOperand(1).getOperand(1))) {
8696 SDValue Cmp = Cond.getOperand(1);
8698 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8700 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8701 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8702 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8704 SDValue CmpOp0 = Cmp.getOperand(0);
8705 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8706 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8708 SDValue Res = // Res = 0 or -1.
8709 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8710 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8712 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8713 Res = DAG.getNOT(DL, Res, Res.getValueType());
8715 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8716 if (N2C == 0 || !N2C->isNullValue())
8717 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8722 // Look past (and (setcc_carry (cmp ...)), 1).
8723 if (Cond.getOpcode() == ISD::AND &&
8724 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8726 if (C && C->getAPIntValue() == 1)
8727 Cond = Cond.getOperand(0);
8730 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8731 // setting operand in place of the X86ISD::SETCC.
8732 unsigned CondOpcode = Cond.getOpcode();
8733 if (CondOpcode == X86ISD::SETCC ||
8734 CondOpcode == X86ISD::SETCC_CARRY) {
8735 CC = Cond.getOperand(0);
8737 SDValue Cmp = Cond.getOperand(1);
8738 unsigned Opc = Cmp.getOpcode();
8739 EVT VT = Op.getValueType();
8741 bool IllegalFPCMov = false;
8742 if (VT.isFloatingPoint() && !VT.isVector() &&
8743 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8744 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8746 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8747 Opc == X86ISD::BT) { // FIXME
8751 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8752 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8753 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8754 Cond.getOperand(0).getValueType() != MVT::i8)) {
8755 SDValue LHS = Cond.getOperand(0);
8756 SDValue RHS = Cond.getOperand(1);
8760 switch (CondOpcode) {
8761 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8762 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8763 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8764 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8765 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8766 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8767 default: llvm_unreachable("unexpected overflowing operator");
8769 if (CondOpcode == ISD::UMULO)
8770 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8773 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8775 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8777 if (CondOpcode == ISD::UMULO)
8778 Cond = X86Op.getValue(2);
8780 Cond = X86Op.getValue(1);
8782 CC = DAG.getConstant(X86Cond, MVT::i8);
8787 // Look pass the truncate.
8788 if (Cond.getOpcode() == ISD::TRUNCATE)
8789 Cond = Cond.getOperand(0);
8791 // We know the result of AND is compared against zero. Try to match
8793 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8794 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8795 if (NewSetCC.getNode()) {
8796 CC = NewSetCC.getOperand(0);
8797 Cond = NewSetCC.getOperand(1);
8804 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8805 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8808 // a < b ? -1 : 0 -> RES = ~setcc_carry
8809 // a < b ? 0 : -1 -> RES = setcc_carry
8810 // a >= b ? -1 : 0 -> RES = setcc_carry
8811 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8812 if (Cond.getOpcode() == X86ISD::CMP) {
8813 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8815 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8816 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8817 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8818 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8819 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8820 return DAG.getNOT(DL, Res, Res.getValueType());
8825 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8826 // condition is true.
8827 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8828 SDValue Ops[] = { Op2, Op1, CC, Cond };
8829 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8832 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8833 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8834 // from the AND / OR.
8835 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8836 Opc = Op.getOpcode();
8837 if (Opc != ISD::OR && Opc != ISD::AND)
8839 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8840 Op.getOperand(0).hasOneUse() &&
8841 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8842 Op.getOperand(1).hasOneUse());
8845 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8846 // 1 and that the SETCC node has a single use.
8847 static bool isXor1OfSetCC(SDValue Op) {
8848 if (Op.getOpcode() != ISD::XOR)
8850 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8851 if (N1C && N1C->getAPIntValue() == 1) {
8852 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8853 Op.getOperand(0).hasOneUse();
8858 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8859 bool addTest = true;
8860 SDValue Chain = Op.getOperand(0);
8861 SDValue Cond = Op.getOperand(1);
8862 SDValue Dest = Op.getOperand(2);
8863 DebugLoc dl = Op.getDebugLoc();
8865 bool Inverted = false;
8867 if (Cond.getOpcode() == ISD::SETCC) {
8868 // Check for setcc([su]{add,sub,mul}o == 0).
8869 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8870 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8871 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8872 Cond.getOperand(0).getResNo() == 1 &&
8873 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8874 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8875 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8876 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8877 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8878 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8880 Cond = Cond.getOperand(0);
8882 SDValue NewCond = LowerSETCC(Cond, DAG);
8883 if (NewCond.getNode())
8888 // FIXME: LowerXALUO doesn't handle these!!
8889 else if (Cond.getOpcode() == X86ISD::ADD ||
8890 Cond.getOpcode() == X86ISD::SUB ||
8891 Cond.getOpcode() == X86ISD::SMUL ||
8892 Cond.getOpcode() == X86ISD::UMUL)
8893 Cond = LowerXALUO(Cond, DAG);
8896 // Look pass (and (setcc_carry (cmp ...)), 1).
8897 if (Cond.getOpcode() == ISD::AND &&
8898 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8899 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8900 if (C && C->getAPIntValue() == 1)
8901 Cond = Cond.getOperand(0);
8904 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8905 // setting operand in place of the X86ISD::SETCC.
8906 unsigned CondOpcode = Cond.getOpcode();
8907 if (CondOpcode == X86ISD::SETCC ||
8908 CondOpcode == X86ISD::SETCC_CARRY) {
8909 CC = Cond.getOperand(0);
8911 SDValue Cmp = Cond.getOperand(1);
8912 unsigned Opc = Cmp.getOpcode();
8913 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8914 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8918 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8922 // These can only come from an arithmetic instruction with overflow,
8923 // e.g. SADDO, UADDO.
8924 Cond = Cond.getNode()->getOperand(1);
8930 CondOpcode = Cond.getOpcode();
8931 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8932 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8933 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8934 Cond.getOperand(0).getValueType() != MVT::i8)) {
8935 SDValue LHS = Cond.getOperand(0);
8936 SDValue RHS = Cond.getOperand(1);
8940 switch (CondOpcode) {
8941 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8942 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8943 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8944 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8945 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8946 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8947 default: llvm_unreachable("unexpected overflowing operator");
8950 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8951 if (CondOpcode == ISD::UMULO)
8952 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8955 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8957 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8959 if (CondOpcode == ISD::UMULO)
8960 Cond = X86Op.getValue(2);
8962 Cond = X86Op.getValue(1);
8964 CC = DAG.getConstant(X86Cond, MVT::i8);
8968 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8969 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8970 if (CondOpc == ISD::OR) {
8971 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8972 // two branches instead of an explicit OR instruction with a
8974 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8975 isX86LogicalCmp(Cmp)) {
8976 CC = Cond.getOperand(0).getOperand(0);
8977 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8978 Chain, Dest, CC, Cmp);
8979 CC = Cond.getOperand(1).getOperand(0);
8983 } else { // ISD::AND
8984 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8985 // two branches instead of an explicit AND instruction with a
8986 // separate test. However, we only do this if this block doesn't
8987 // have a fall-through edge, because this requires an explicit
8988 // jmp when the condition is false.
8989 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8990 isX86LogicalCmp(Cmp) &&
8991 Op.getNode()->hasOneUse()) {
8992 X86::CondCode CCode =
8993 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8994 CCode = X86::GetOppositeBranchCondition(CCode);
8995 CC = DAG.getConstant(CCode, MVT::i8);
8996 SDNode *User = *Op.getNode()->use_begin();
8997 // Look for an unconditional branch following this conditional branch.
8998 // We need this because we need to reverse the successors in order
8999 // to implement FCMP_OEQ.
9000 if (User->getOpcode() == ISD::BR) {
9001 SDValue FalseBB = User->getOperand(1);
9003 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9004 assert(NewBR == User);
9008 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9009 Chain, Dest, CC, Cmp);
9010 X86::CondCode CCode =
9011 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9012 CCode = X86::GetOppositeBranchCondition(CCode);
9013 CC = DAG.getConstant(CCode, MVT::i8);
9019 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9020 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9021 // It should be transformed during dag combiner except when the condition
9022 // is set by a arithmetics with overflow node.
9023 X86::CondCode CCode =
9024 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9025 CCode = X86::GetOppositeBranchCondition(CCode);
9026 CC = DAG.getConstant(CCode, MVT::i8);
9027 Cond = Cond.getOperand(0).getOperand(1);
9029 } else if (Cond.getOpcode() == ISD::SETCC &&
9030 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9031 // For FCMP_OEQ, we can emit
9032 // two branches instead of an explicit AND instruction with a
9033 // separate test. However, we only do this if this block doesn't
9034 // have a fall-through edge, because this requires an explicit
9035 // jmp when the condition is false.
9036 if (Op.getNode()->hasOneUse()) {
9037 SDNode *User = *Op.getNode()->use_begin();
9038 // Look for an unconditional branch following this conditional branch.
9039 // We need this because we need to reverse the successors in order
9040 // to implement FCMP_OEQ.
9041 if (User->getOpcode() == ISD::BR) {
9042 SDValue FalseBB = User->getOperand(1);
9044 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9045 assert(NewBR == User);
9049 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9050 Cond.getOperand(0), Cond.getOperand(1));
9051 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9052 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9053 Chain, Dest, CC, Cmp);
9054 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9059 } else if (Cond.getOpcode() == ISD::SETCC &&
9060 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9061 // For FCMP_UNE, we can emit
9062 // two branches instead of an explicit AND instruction with a
9063 // separate test. However, we only do this if this block doesn't
9064 // have a fall-through edge, because this requires an explicit
9065 // jmp when the condition is false.
9066 if (Op.getNode()->hasOneUse()) {
9067 SDNode *User = *Op.getNode()->use_begin();
9068 // Look for an unconditional branch following this conditional branch.
9069 // We need this because we need to reverse the successors in order
9070 // to implement FCMP_UNE.
9071 if (User->getOpcode() == ISD::BR) {
9072 SDValue FalseBB = User->getOperand(1);
9074 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9075 assert(NewBR == User);
9078 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9079 Cond.getOperand(0), Cond.getOperand(1));
9080 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9081 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9082 Chain, Dest, CC, Cmp);
9083 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9093 // Look pass the truncate.
9094 if (Cond.getOpcode() == ISD::TRUNCATE)
9095 Cond = Cond.getOperand(0);
9097 // We know the result of AND is compared against zero. Try to match
9099 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9100 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9101 if (NewSetCC.getNode()) {
9102 CC = NewSetCC.getOperand(0);
9103 Cond = NewSetCC.getOperand(1);
9110 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9111 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9113 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9114 Chain, Dest, CC, Cond);
9118 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9119 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9120 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9121 // that the guard pages used by the OS virtual memory manager are allocated in
9122 // correct sequence.
9124 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9125 SelectionDAG &DAG) const {
9126 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9127 EnableSegmentedStacks) &&
9128 "This should be used only on Windows targets or when segmented stacks "
9130 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9131 DebugLoc dl = Op.getDebugLoc();
9134 SDValue Chain = Op.getOperand(0);
9135 SDValue Size = Op.getOperand(1);
9136 // FIXME: Ensure alignment here
9138 bool Is64Bit = Subtarget->is64Bit();
9139 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9141 if (EnableSegmentedStacks) {
9142 MachineFunction &MF = DAG.getMachineFunction();
9143 MachineRegisterInfo &MRI = MF.getRegInfo();
9146 // The 64 bit implementation of segmented stacks needs to clobber both r10
9147 // r11. This makes it impossible to use it along with nested parameters.
9148 const Function *F = MF.getFunction();
9150 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9152 if (I->hasNestAttr())
9153 report_fatal_error("Cannot use segmented stacks with functions that "
9154 "have nested arguments.");
9157 const TargetRegisterClass *AddrRegClass =
9158 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9159 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9160 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9161 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9162 DAG.getRegister(Vreg, SPTy));
9163 SDValue Ops1[2] = { Value, Chain };
9164 return DAG.getMergeValues(Ops1, 2, dl);
9167 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9169 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9170 Flag = Chain.getValue(1);
9171 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9173 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9174 Flag = Chain.getValue(1);
9176 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9178 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9179 return DAG.getMergeValues(Ops1, 2, dl);
9183 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9184 MachineFunction &MF = DAG.getMachineFunction();
9185 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9187 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9188 DebugLoc DL = Op.getDebugLoc();
9190 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9191 // vastart just stores the address of the VarArgsFrameIndex slot into the
9192 // memory location argument.
9193 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9195 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9196 MachinePointerInfo(SV), false, false, 0);
9200 // gp_offset (0 - 6 * 8)
9201 // fp_offset (48 - 48 + 8 * 16)
9202 // overflow_arg_area (point to parameters coming in memory).
9204 SmallVector<SDValue, 8> MemOps;
9205 SDValue FIN = Op.getOperand(1);
9207 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9208 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9210 FIN, MachinePointerInfo(SV), false, false, 0);
9211 MemOps.push_back(Store);
9214 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9215 FIN, DAG.getIntPtrConstant(4));
9216 Store = DAG.getStore(Op.getOperand(0), DL,
9217 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9219 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9220 MemOps.push_back(Store);
9222 // Store ptr to overflow_arg_area
9223 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9224 FIN, DAG.getIntPtrConstant(4));
9225 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9227 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9228 MachinePointerInfo(SV, 8),
9230 MemOps.push_back(Store);
9232 // Store ptr to reg_save_area.
9233 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9234 FIN, DAG.getIntPtrConstant(8));
9235 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9237 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9238 MachinePointerInfo(SV, 16), false, false, 0);
9239 MemOps.push_back(Store);
9240 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9241 &MemOps[0], MemOps.size());
9244 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9245 assert(Subtarget->is64Bit() &&
9246 "LowerVAARG only handles 64-bit va_arg!");
9247 assert((Subtarget->isTargetLinux() ||
9248 Subtarget->isTargetDarwin()) &&
9249 "Unhandled target in LowerVAARG");
9250 assert(Op.getNode()->getNumOperands() == 4);
9251 SDValue Chain = Op.getOperand(0);
9252 SDValue SrcPtr = Op.getOperand(1);
9253 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9254 unsigned Align = Op.getConstantOperandVal(3);
9255 DebugLoc dl = Op.getDebugLoc();
9257 EVT ArgVT = Op.getNode()->getValueType(0);
9258 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9259 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9262 // Decide which area this value should be read from.
9263 // TODO: Implement the AMD64 ABI in its entirety. This simple
9264 // selection mechanism works only for the basic types.
9265 if (ArgVT == MVT::f80) {
9266 llvm_unreachable("va_arg for f80 not yet implemented");
9267 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9268 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9269 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9270 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9272 llvm_unreachable("Unhandled argument type in LowerVAARG");
9276 // Sanity Check: Make sure using fp_offset makes sense.
9277 assert(!UseSoftFloat &&
9278 !(DAG.getMachineFunction()
9279 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9280 Subtarget->hasXMM());
9283 // Insert VAARG_64 node into the DAG
9284 // VAARG_64 returns two values: Variable Argument Address, Chain
9285 SmallVector<SDValue, 11> InstOps;
9286 InstOps.push_back(Chain);
9287 InstOps.push_back(SrcPtr);
9288 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9289 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9290 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9291 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9292 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9293 VTs, &InstOps[0], InstOps.size(),
9295 MachinePointerInfo(SV),
9300 Chain = VAARG.getValue(1);
9302 // Load the next argument and return it
9303 return DAG.getLoad(ArgVT, dl,
9306 MachinePointerInfo(),
9307 false, false, false, 0);
9310 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9311 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9312 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9313 SDValue Chain = Op.getOperand(0);
9314 SDValue DstPtr = Op.getOperand(1);
9315 SDValue SrcPtr = Op.getOperand(2);
9316 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9317 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9318 DebugLoc DL = Op.getDebugLoc();
9320 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9321 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9323 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9327 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9328 DebugLoc dl = Op.getDebugLoc();
9329 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9331 default: return SDValue(); // Don't custom lower most intrinsics.
9332 // Comparison intrinsics.
9333 case Intrinsic::x86_sse_comieq_ss:
9334 case Intrinsic::x86_sse_comilt_ss:
9335 case Intrinsic::x86_sse_comile_ss:
9336 case Intrinsic::x86_sse_comigt_ss:
9337 case Intrinsic::x86_sse_comige_ss:
9338 case Intrinsic::x86_sse_comineq_ss:
9339 case Intrinsic::x86_sse_ucomieq_ss:
9340 case Intrinsic::x86_sse_ucomilt_ss:
9341 case Intrinsic::x86_sse_ucomile_ss:
9342 case Intrinsic::x86_sse_ucomigt_ss:
9343 case Intrinsic::x86_sse_ucomige_ss:
9344 case Intrinsic::x86_sse_ucomineq_ss:
9345 case Intrinsic::x86_sse2_comieq_sd:
9346 case Intrinsic::x86_sse2_comilt_sd:
9347 case Intrinsic::x86_sse2_comile_sd:
9348 case Intrinsic::x86_sse2_comigt_sd:
9349 case Intrinsic::x86_sse2_comige_sd:
9350 case Intrinsic::x86_sse2_comineq_sd:
9351 case Intrinsic::x86_sse2_ucomieq_sd:
9352 case Intrinsic::x86_sse2_ucomilt_sd:
9353 case Intrinsic::x86_sse2_ucomile_sd:
9354 case Intrinsic::x86_sse2_ucomigt_sd:
9355 case Intrinsic::x86_sse2_ucomige_sd:
9356 case Intrinsic::x86_sse2_ucomineq_sd: {
9358 ISD::CondCode CC = ISD::SETCC_INVALID;
9361 case Intrinsic::x86_sse_comieq_ss:
9362 case Intrinsic::x86_sse2_comieq_sd:
9366 case Intrinsic::x86_sse_comilt_ss:
9367 case Intrinsic::x86_sse2_comilt_sd:
9371 case Intrinsic::x86_sse_comile_ss:
9372 case Intrinsic::x86_sse2_comile_sd:
9376 case Intrinsic::x86_sse_comigt_ss:
9377 case Intrinsic::x86_sse2_comigt_sd:
9381 case Intrinsic::x86_sse_comige_ss:
9382 case Intrinsic::x86_sse2_comige_sd:
9386 case Intrinsic::x86_sse_comineq_ss:
9387 case Intrinsic::x86_sse2_comineq_sd:
9391 case Intrinsic::x86_sse_ucomieq_ss:
9392 case Intrinsic::x86_sse2_ucomieq_sd:
9393 Opc = X86ISD::UCOMI;
9396 case Intrinsic::x86_sse_ucomilt_ss:
9397 case Intrinsic::x86_sse2_ucomilt_sd:
9398 Opc = X86ISD::UCOMI;
9401 case Intrinsic::x86_sse_ucomile_ss:
9402 case Intrinsic::x86_sse2_ucomile_sd:
9403 Opc = X86ISD::UCOMI;
9406 case Intrinsic::x86_sse_ucomigt_ss:
9407 case Intrinsic::x86_sse2_ucomigt_sd:
9408 Opc = X86ISD::UCOMI;
9411 case Intrinsic::x86_sse_ucomige_ss:
9412 case Intrinsic::x86_sse2_ucomige_sd:
9413 Opc = X86ISD::UCOMI;
9416 case Intrinsic::x86_sse_ucomineq_ss:
9417 case Intrinsic::x86_sse2_ucomineq_sd:
9418 Opc = X86ISD::UCOMI;
9423 SDValue LHS = Op.getOperand(1);
9424 SDValue RHS = Op.getOperand(2);
9425 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9426 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9427 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9428 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9429 DAG.getConstant(X86CC, MVT::i8), Cond);
9430 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9432 // Arithmetic intrinsics.
9433 case Intrinsic::x86_sse3_hadd_ps:
9434 case Intrinsic::x86_sse3_hadd_pd:
9435 case Intrinsic::x86_avx_hadd_ps_256:
9436 case Intrinsic::x86_avx_hadd_pd_256:
9437 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9438 Op.getOperand(1), Op.getOperand(2));
9439 case Intrinsic::x86_sse3_hsub_ps:
9440 case Intrinsic::x86_sse3_hsub_pd:
9441 case Intrinsic::x86_avx_hsub_ps_256:
9442 case Intrinsic::x86_avx_hsub_pd_256:
9443 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9444 Op.getOperand(1), Op.getOperand(2));
9445 // ptest and testp intrinsics. The intrinsic these come from are designed to
9446 // return an integer value, not just an instruction so lower it to the ptest
9447 // or testp pattern and a setcc for the result.
9448 case Intrinsic::x86_sse41_ptestz:
9449 case Intrinsic::x86_sse41_ptestc:
9450 case Intrinsic::x86_sse41_ptestnzc:
9451 case Intrinsic::x86_avx_ptestz_256:
9452 case Intrinsic::x86_avx_ptestc_256:
9453 case Intrinsic::x86_avx_ptestnzc_256:
9454 case Intrinsic::x86_avx_vtestz_ps:
9455 case Intrinsic::x86_avx_vtestc_ps:
9456 case Intrinsic::x86_avx_vtestnzc_ps:
9457 case Intrinsic::x86_avx_vtestz_pd:
9458 case Intrinsic::x86_avx_vtestc_pd:
9459 case Intrinsic::x86_avx_vtestnzc_pd:
9460 case Intrinsic::x86_avx_vtestz_ps_256:
9461 case Intrinsic::x86_avx_vtestc_ps_256:
9462 case Intrinsic::x86_avx_vtestnzc_ps_256:
9463 case Intrinsic::x86_avx_vtestz_pd_256:
9464 case Intrinsic::x86_avx_vtestc_pd_256:
9465 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9466 bool IsTestPacked = false;
9469 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9470 case Intrinsic::x86_avx_vtestz_ps:
9471 case Intrinsic::x86_avx_vtestz_pd:
9472 case Intrinsic::x86_avx_vtestz_ps_256:
9473 case Intrinsic::x86_avx_vtestz_pd_256:
9474 IsTestPacked = true; // Fallthrough
9475 case Intrinsic::x86_sse41_ptestz:
9476 case Intrinsic::x86_avx_ptestz_256:
9478 X86CC = X86::COND_E;
9480 case Intrinsic::x86_avx_vtestc_ps:
9481 case Intrinsic::x86_avx_vtestc_pd:
9482 case Intrinsic::x86_avx_vtestc_ps_256:
9483 case Intrinsic::x86_avx_vtestc_pd_256:
9484 IsTestPacked = true; // Fallthrough
9485 case Intrinsic::x86_sse41_ptestc:
9486 case Intrinsic::x86_avx_ptestc_256:
9488 X86CC = X86::COND_B;
9490 case Intrinsic::x86_avx_vtestnzc_ps:
9491 case Intrinsic::x86_avx_vtestnzc_pd:
9492 case Intrinsic::x86_avx_vtestnzc_ps_256:
9493 case Intrinsic::x86_avx_vtestnzc_pd_256:
9494 IsTestPacked = true; // Fallthrough
9495 case Intrinsic::x86_sse41_ptestnzc:
9496 case Intrinsic::x86_avx_ptestnzc_256:
9498 X86CC = X86::COND_A;
9502 SDValue LHS = Op.getOperand(1);
9503 SDValue RHS = Op.getOperand(2);
9504 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9505 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9506 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9507 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9508 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9511 // Fix vector shift instructions where the last operand is a non-immediate
9513 case Intrinsic::x86_sse2_pslli_w:
9514 case Intrinsic::x86_sse2_pslli_d:
9515 case Intrinsic::x86_sse2_pslli_q:
9516 case Intrinsic::x86_sse2_psrli_w:
9517 case Intrinsic::x86_sse2_psrli_d:
9518 case Intrinsic::x86_sse2_psrli_q:
9519 case Intrinsic::x86_sse2_psrai_w:
9520 case Intrinsic::x86_sse2_psrai_d:
9521 case Intrinsic::x86_mmx_pslli_w:
9522 case Intrinsic::x86_mmx_pslli_d:
9523 case Intrinsic::x86_mmx_pslli_q:
9524 case Intrinsic::x86_mmx_psrli_w:
9525 case Intrinsic::x86_mmx_psrli_d:
9526 case Intrinsic::x86_mmx_psrli_q:
9527 case Intrinsic::x86_mmx_psrai_w:
9528 case Intrinsic::x86_mmx_psrai_d: {
9529 SDValue ShAmt = Op.getOperand(2);
9530 if (isa<ConstantSDNode>(ShAmt))
9533 unsigned NewIntNo = 0;
9534 EVT ShAmtVT = MVT::v4i32;
9536 case Intrinsic::x86_sse2_pslli_w:
9537 NewIntNo = Intrinsic::x86_sse2_psll_w;
9539 case Intrinsic::x86_sse2_pslli_d:
9540 NewIntNo = Intrinsic::x86_sse2_psll_d;
9542 case Intrinsic::x86_sse2_pslli_q:
9543 NewIntNo = Intrinsic::x86_sse2_psll_q;
9545 case Intrinsic::x86_sse2_psrli_w:
9546 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9548 case Intrinsic::x86_sse2_psrli_d:
9549 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9551 case Intrinsic::x86_sse2_psrli_q:
9552 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9554 case Intrinsic::x86_sse2_psrai_w:
9555 NewIntNo = Intrinsic::x86_sse2_psra_w;
9557 case Intrinsic::x86_sse2_psrai_d:
9558 NewIntNo = Intrinsic::x86_sse2_psra_d;
9561 ShAmtVT = MVT::v2i32;
9563 case Intrinsic::x86_mmx_pslli_w:
9564 NewIntNo = Intrinsic::x86_mmx_psll_w;
9566 case Intrinsic::x86_mmx_pslli_d:
9567 NewIntNo = Intrinsic::x86_mmx_psll_d;
9569 case Intrinsic::x86_mmx_pslli_q:
9570 NewIntNo = Intrinsic::x86_mmx_psll_q;
9572 case Intrinsic::x86_mmx_psrli_w:
9573 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9575 case Intrinsic::x86_mmx_psrli_d:
9576 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9578 case Intrinsic::x86_mmx_psrli_q:
9579 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9581 case Intrinsic::x86_mmx_psrai_w:
9582 NewIntNo = Intrinsic::x86_mmx_psra_w;
9584 case Intrinsic::x86_mmx_psrai_d:
9585 NewIntNo = Intrinsic::x86_mmx_psra_d;
9587 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9593 // The vector shift intrinsics with scalars uses 32b shift amounts but
9594 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9598 ShOps[1] = DAG.getConstant(0, MVT::i32);
9599 if (ShAmtVT == MVT::v4i32) {
9600 ShOps[2] = DAG.getUNDEF(MVT::i32);
9601 ShOps[3] = DAG.getUNDEF(MVT::i32);
9602 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9604 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9605 // FIXME this must be lowered to get rid of the invalid type.
9608 EVT VT = Op.getValueType();
9609 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9610 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9611 DAG.getConstant(NewIntNo, MVT::i32),
9612 Op.getOperand(1), ShAmt);
9617 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9618 SelectionDAG &DAG) const {
9619 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9620 MFI->setReturnAddressIsTaken(true);
9622 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9623 DebugLoc dl = Op.getDebugLoc();
9626 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9628 DAG.getConstant(TD->getPointerSize(),
9629 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9630 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9631 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9633 MachinePointerInfo(), false, false, false, 0);
9636 // Just load the return address.
9637 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9638 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9639 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9642 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9643 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9644 MFI->setFrameAddressIsTaken(true);
9646 EVT VT = Op.getValueType();
9647 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9648 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9649 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9650 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9652 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9653 MachinePointerInfo(),
9654 false, false, false, 0);
9658 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9659 SelectionDAG &DAG) const {
9660 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9663 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9664 MachineFunction &MF = DAG.getMachineFunction();
9665 SDValue Chain = Op.getOperand(0);
9666 SDValue Offset = Op.getOperand(1);
9667 SDValue Handler = Op.getOperand(2);
9668 DebugLoc dl = Op.getDebugLoc();
9670 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9671 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9673 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9675 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9676 DAG.getIntPtrConstant(TD->getPointerSize()));
9677 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9678 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9680 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9681 MF.getRegInfo().addLiveOut(StoreAddrReg);
9683 return DAG.getNode(X86ISD::EH_RETURN, dl,
9685 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9688 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9689 SelectionDAG &DAG) const {
9690 return Op.getOperand(0);
9693 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9694 SelectionDAG &DAG) const {
9695 SDValue Root = Op.getOperand(0);
9696 SDValue Trmp = Op.getOperand(1); // trampoline
9697 SDValue FPtr = Op.getOperand(2); // nested function
9698 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9699 DebugLoc dl = Op.getDebugLoc();
9701 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9703 if (Subtarget->is64Bit()) {
9704 SDValue OutChains[6];
9706 // Large code-model.
9707 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9708 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9710 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9711 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9713 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9715 // Load the pointer to the nested function into R11.
9716 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9717 SDValue Addr = Trmp;
9718 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9719 Addr, MachinePointerInfo(TrmpAddr),
9722 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9723 DAG.getConstant(2, MVT::i64));
9724 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9725 MachinePointerInfo(TrmpAddr, 2),
9728 // Load the 'nest' parameter value into R10.
9729 // R10 is specified in X86CallingConv.td
9730 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9731 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9732 DAG.getConstant(10, MVT::i64));
9733 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9734 Addr, MachinePointerInfo(TrmpAddr, 10),
9737 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9738 DAG.getConstant(12, MVT::i64));
9739 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9740 MachinePointerInfo(TrmpAddr, 12),
9743 // Jump to the nested function.
9744 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9746 DAG.getConstant(20, MVT::i64));
9747 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9748 Addr, MachinePointerInfo(TrmpAddr, 20),
9751 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9752 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9753 DAG.getConstant(22, MVT::i64));
9754 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9755 MachinePointerInfo(TrmpAddr, 22),
9758 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9760 const Function *Func =
9761 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9762 CallingConv::ID CC = Func->getCallingConv();
9767 llvm_unreachable("Unsupported calling convention");
9768 case CallingConv::C:
9769 case CallingConv::X86_StdCall: {
9770 // Pass 'nest' parameter in ECX.
9771 // Must be kept in sync with X86CallingConv.td
9774 // Check that ECX wasn't needed by an 'inreg' parameter.
9775 FunctionType *FTy = Func->getFunctionType();
9776 const AttrListPtr &Attrs = Func->getAttributes();
9778 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9779 unsigned InRegCount = 0;
9782 for (FunctionType::param_iterator I = FTy->param_begin(),
9783 E = FTy->param_end(); I != E; ++I, ++Idx)
9784 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9785 // FIXME: should only count parameters that are lowered to integers.
9786 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9788 if (InRegCount > 2) {
9789 report_fatal_error("Nest register in use - reduce number of inreg"
9795 case CallingConv::X86_FastCall:
9796 case CallingConv::X86_ThisCall:
9797 case CallingConv::Fast:
9798 // Pass 'nest' parameter in EAX.
9799 // Must be kept in sync with X86CallingConv.td
9804 SDValue OutChains[4];
9807 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9808 DAG.getConstant(10, MVT::i32));
9809 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9811 // This is storing the opcode for MOV32ri.
9812 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9813 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9814 OutChains[0] = DAG.getStore(Root, dl,
9815 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9816 Trmp, MachinePointerInfo(TrmpAddr),
9819 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9820 DAG.getConstant(1, MVT::i32));
9821 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9822 MachinePointerInfo(TrmpAddr, 1),
9825 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9826 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9827 DAG.getConstant(5, MVT::i32));
9828 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9829 MachinePointerInfo(TrmpAddr, 5),
9832 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9833 DAG.getConstant(6, MVT::i32));
9834 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9835 MachinePointerInfo(TrmpAddr, 6),
9838 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9842 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9843 SelectionDAG &DAG) const {
9845 The rounding mode is in bits 11:10 of FPSR, and has the following
9852 FLT_ROUNDS, on the other hand, expects the following:
9859 To perform the conversion, we do:
9860 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9863 MachineFunction &MF = DAG.getMachineFunction();
9864 const TargetMachine &TM = MF.getTarget();
9865 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9866 unsigned StackAlignment = TFI.getStackAlignment();
9867 EVT VT = Op.getValueType();
9868 DebugLoc DL = Op.getDebugLoc();
9870 // Save FP Control Word to stack slot
9871 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9872 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9875 MachineMemOperand *MMO =
9876 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9877 MachineMemOperand::MOStore, 2, 2);
9879 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9880 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9881 DAG.getVTList(MVT::Other),
9882 Ops, 2, MVT::i16, MMO);
9884 // Load FP Control Word from stack slot
9885 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9886 MachinePointerInfo(), false, false, false, 0);
9888 // Transform as necessary
9890 DAG.getNode(ISD::SRL, DL, MVT::i16,
9891 DAG.getNode(ISD::AND, DL, MVT::i16,
9892 CWD, DAG.getConstant(0x800, MVT::i16)),
9893 DAG.getConstant(11, MVT::i8));
9895 DAG.getNode(ISD::SRL, DL, MVT::i16,
9896 DAG.getNode(ISD::AND, DL, MVT::i16,
9897 CWD, DAG.getConstant(0x400, MVT::i16)),
9898 DAG.getConstant(9, MVT::i8));
9901 DAG.getNode(ISD::AND, DL, MVT::i16,
9902 DAG.getNode(ISD::ADD, DL, MVT::i16,
9903 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9904 DAG.getConstant(1, MVT::i16)),
9905 DAG.getConstant(3, MVT::i16));
9908 return DAG.getNode((VT.getSizeInBits() < 16 ?
9909 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9912 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9913 EVT VT = Op.getValueType();
9915 unsigned NumBits = VT.getSizeInBits();
9916 DebugLoc dl = Op.getDebugLoc();
9918 Op = Op.getOperand(0);
9919 if (VT == MVT::i8) {
9920 // Zero extend to i32 since there is not an i8 bsr.
9922 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9925 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9926 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9927 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9929 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9932 DAG.getConstant(NumBits+NumBits-1, OpVT),
9933 DAG.getConstant(X86::COND_E, MVT::i8),
9936 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9938 // Finally xor with NumBits-1.
9939 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9942 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9946 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9947 EVT VT = Op.getValueType();
9949 unsigned NumBits = VT.getSizeInBits();
9950 DebugLoc dl = Op.getDebugLoc();
9952 Op = Op.getOperand(0);
9953 if (VT == MVT::i8) {
9955 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9958 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9959 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9960 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9962 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9965 DAG.getConstant(NumBits, OpVT),
9966 DAG.getConstant(X86::COND_E, MVT::i8),
9969 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9972 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9976 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9977 // ones, and then concatenate the result back.
9978 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9979 EVT VT = Op.getValueType();
9981 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9982 "Unsupported value type for operation");
9984 int NumElems = VT.getVectorNumElements();
9985 DebugLoc dl = Op.getDebugLoc();
9986 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9987 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9989 // Extract the LHS vectors
9990 SDValue LHS = Op.getOperand(0);
9991 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9992 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9994 // Extract the RHS vectors
9995 SDValue RHS = Op.getOperand(1);
9996 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9997 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9999 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10000 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10002 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10003 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10004 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10007 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10008 assert(Op.getValueType().getSizeInBits() == 256 &&
10009 Op.getValueType().isInteger() &&
10010 "Only handle AVX 256-bit vector integer operation");
10011 return Lower256IntArith(Op, DAG);
10014 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10015 assert(Op.getValueType().getSizeInBits() == 256 &&
10016 Op.getValueType().isInteger() &&
10017 "Only handle AVX 256-bit vector integer operation");
10018 return Lower256IntArith(Op, DAG);
10021 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10022 EVT VT = Op.getValueType();
10024 // Decompose 256-bit ops into smaller 128-bit ops.
10025 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10026 return Lower256IntArith(Op, DAG);
10028 DebugLoc dl = Op.getDebugLoc();
10030 SDValue A = Op.getOperand(0);
10031 SDValue B = Op.getOperand(1);
10033 if (VT == MVT::v4i64) {
10034 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10036 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10037 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10038 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10039 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10040 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10042 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10043 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10044 // return AloBlo + AloBhi + AhiBlo;
10046 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10047 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10048 A, DAG.getConstant(32, MVT::i32));
10049 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10050 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10051 B, DAG.getConstant(32, MVT::i32));
10052 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10053 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10055 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10056 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10058 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10059 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10061 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10062 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10063 AloBhi, DAG.getConstant(32, MVT::i32));
10064 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10066 AhiBlo, DAG.getConstant(32, MVT::i32));
10067 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10068 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10072 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10074 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10075 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10076 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10077 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10078 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10080 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10081 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10082 // return AloBlo + AloBhi + AhiBlo;
10084 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10085 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10086 A, DAG.getConstant(32, MVT::i32));
10087 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10088 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10089 B, DAG.getConstant(32, MVT::i32));
10090 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10091 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10093 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10094 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10096 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10097 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10099 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10100 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10101 AloBhi, DAG.getConstant(32, MVT::i32));
10102 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10103 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10104 AhiBlo, DAG.getConstant(32, MVT::i32));
10105 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10106 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10110 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10112 EVT VT = Op.getValueType();
10113 DebugLoc dl = Op.getDebugLoc();
10114 SDValue R = Op.getOperand(0);
10115 SDValue Amt = Op.getOperand(1);
10116 LLVMContext *Context = DAG.getContext();
10118 if (!Subtarget->hasXMMInt())
10121 // Decompose 256-bit shifts into smaller 128-bit shifts.
10122 if (VT.getSizeInBits() == 256) {
10123 int NumElems = VT.getVectorNumElements();
10124 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10125 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10127 // Extract the two vectors
10128 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10129 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10132 // Recreate the shift amount vectors
10133 SDValue Amt1, Amt2;
10134 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10135 // Constant shift amount
10136 SmallVector<SDValue, 4> Amt1Csts;
10137 SmallVector<SDValue, 4> Amt2Csts;
10138 for (int i = 0; i < NumElems/2; ++i)
10139 Amt1Csts.push_back(Amt->getOperand(i));
10140 for (int i = NumElems/2; i < NumElems; ++i)
10141 Amt2Csts.push_back(Amt->getOperand(i));
10143 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10144 &Amt1Csts[0], NumElems/2);
10145 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10146 &Amt2Csts[0], NumElems/2);
10148 // Variable shift amount
10149 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10150 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10154 // Issue new vector shifts for the smaller types
10155 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10156 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10158 // Concatenate the result back
10159 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10162 // Optimize shl/srl/sra with constant shift amount.
10163 if (isSplatVector(Amt.getNode())) {
10164 SDValue SclrAmt = Amt->getOperand(0);
10165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10166 uint64_t ShiftAmt = C->getZExtValue();
10168 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10169 // Make a large shift.
10171 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10172 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10173 R, DAG.getConstant(ShiftAmt, MVT::i32));
10174 // Zero out the rightmost bits.
10175 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10177 return DAG.getNode(ISD::AND, dl, VT, SHL,
10178 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10181 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10182 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10183 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10184 R, DAG.getConstant(ShiftAmt, MVT::i32));
10186 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10187 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10188 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10189 R, DAG.getConstant(ShiftAmt, MVT::i32));
10191 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10192 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10193 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10194 R, DAG.getConstant(ShiftAmt, MVT::i32));
10196 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10197 // Make a large shift.
10199 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10200 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10201 R, DAG.getConstant(ShiftAmt, MVT::i32));
10202 // Zero out the leftmost bits.
10203 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10205 return DAG.getNode(ISD::AND, dl, VT, SRL,
10206 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10209 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10210 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10211 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10212 R, DAG.getConstant(ShiftAmt, MVT::i32));
10214 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10215 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10216 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10217 R, DAG.getConstant(ShiftAmt, MVT::i32));
10219 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10220 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10221 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10222 R, DAG.getConstant(ShiftAmt, MVT::i32));
10224 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10225 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10226 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10227 R, DAG.getConstant(ShiftAmt, MVT::i32));
10229 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10230 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10231 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10232 R, DAG.getConstant(ShiftAmt, MVT::i32));
10234 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10235 if (ShiftAmt == 7) {
10236 // R s>> 7 === R s< 0
10237 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10238 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10241 // R s>> a === ((R u>> a) ^ m) - m
10242 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10243 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10245 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10246 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10247 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10253 // Lower SHL with variable shift amount.
10254 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10255 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10256 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10257 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10259 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10261 std::vector<Constant*> CV(4, CI);
10262 Constant *C = ConstantVector::get(CV);
10263 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10264 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10265 MachinePointerInfo::getConstantPool(),
10266 false, false, false, 16);
10268 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10269 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10270 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10271 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10273 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10275 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10276 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10277 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10279 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10280 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10282 std::vector<Constant*> CVM1(16, CM1);
10283 std::vector<Constant*> CVM2(16, CM2);
10284 Constant *C = ConstantVector::get(CVM1);
10285 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10286 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10287 MachinePointerInfo::getConstantPool(),
10288 false, false, false, 16);
10290 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10291 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10292 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10293 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10294 DAG.getConstant(4, MVT::i32));
10295 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10297 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10299 C = ConstantVector::get(CVM2);
10300 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10301 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10302 MachinePointerInfo::getConstantPool(),
10303 false, false, false, 16);
10305 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10306 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10307 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10308 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10309 DAG.getConstant(2, MVT::i32));
10310 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10312 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10314 // return pblendv(r, r+r, a);
10315 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10316 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10322 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10323 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10324 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10325 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10326 // has only one use.
10327 SDNode *N = Op.getNode();
10328 SDValue LHS = N->getOperand(0);
10329 SDValue RHS = N->getOperand(1);
10330 unsigned BaseOp = 0;
10332 DebugLoc DL = Op.getDebugLoc();
10333 switch (Op.getOpcode()) {
10334 default: llvm_unreachable("Unknown ovf instruction!");
10336 // A subtract of one will be selected as a INC. Note that INC doesn't
10337 // set CF, so we can't do this for UADDO.
10338 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10340 BaseOp = X86ISD::INC;
10341 Cond = X86::COND_O;
10344 BaseOp = X86ISD::ADD;
10345 Cond = X86::COND_O;
10348 BaseOp = X86ISD::ADD;
10349 Cond = X86::COND_B;
10352 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10353 // set CF, so we can't do this for USUBO.
10354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10356 BaseOp = X86ISD::DEC;
10357 Cond = X86::COND_O;
10360 BaseOp = X86ISD::SUB;
10361 Cond = X86::COND_O;
10364 BaseOp = X86ISD::SUB;
10365 Cond = X86::COND_B;
10368 BaseOp = X86ISD::SMUL;
10369 Cond = X86::COND_O;
10371 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10372 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10374 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10377 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10378 DAG.getConstant(X86::COND_O, MVT::i32),
10379 SDValue(Sum.getNode(), 2));
10381 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10385 // Also sets EFLAGS.
10386 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10387 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10390 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10391 DAG.getConstant(Cond, MVT::i32),
10392 SDValue(Sum.getNode(), 1));
10394 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10397 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10398 DebugLoc dl = Op.getDebugLoc();
10399 SDNode* Node = Op.getNode();
10400 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10401 EVT VT = Node->getValueType(0);
10402 if (Subtarget->hasXMMInt() && VT.isVector()) {
10403 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10404 ExtraVT.getScalarType().getSizeInBits();
10405 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10407 unsigned SHLIntrinsicsID = 0;
10408 unsigned SRAIntrinsicsID = 0;
10409 switch (VT.getSimpleVT().SimpleTy) {
10413 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10414 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10418 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10419 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10424 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10425 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10426 Node->getOperand(0), ShAmt);
10428 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10429 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10437 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10438 DebugLoc dl = Op.getDebugLoc();
10440 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10441 // There isn't any reason to disable it if the target processor supports it.
10442 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10443 SDValue Chain = Op.getOperand(0);
10444 SDValue Zero = DAG.getConstant(0, MVT::i32);
10446 DAG.getRegister(X86::ESP, MVT::i32), // Base
10447 DAG.getTargetConstant(1, MVT::i8), // Scale
10448 DAG.getRegister(0, MVT::i32), // Index
10449 DAG.getTargetConstant(0, MVT::i32), // Disp
10450 DAG.getRegister(0, MVT::i32), // Segment.
10455 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10456 array_lengthof(Ops));
10457 return SDValue(Res, 0);
10460 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10462 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10464 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10465 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10466 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10467 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10469 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10470 if (!Op1 && !Op2 && !Op3 && Op4)
10471 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10473 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10474 if (Op1 && !Op2 && !Op3 && !Op4)
10475 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10477 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10479 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10482 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10483 SelectionDAG &DAG) const {
10484 DebugLoc dl = Op.getDebugLoc();
10485 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10486 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10487 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10488 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10490 // The only fence that needs an instruction is a sequentially-consistent
10491 // cross-thread fence.
10492 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10493 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10494 // no-sse2). There isn't any reason to disable it if the target processor
10496 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10497 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10499 SDValue Chain = Op.getOperand(0);
10500 SDValue Zero = DAG.getConstant(0, MVT::i32);
10502 DAG.getRegister(X86::ESP, MVT::i32), // Base
10503 DAG.getTargetConstant(1, MVT::i8), // Scale
10504 DAG.getRegister(0, MVT::i32), // Index
10505 DAG.getTargetConstant(0, MVT::i32), // Disp
10506 DAG.getRegister(0, MVT::i32), // Segment.
10511 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10512 array_lengthof(Ops));
10513 return SDValue(Res, 0);
10516 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10517 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10521 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10522 EVT T = Op.getValueType();
10523 DebugLoc DL = Op.getDebugLoc();
10526 switch(T.getSimpleVT().SimpleTy) {
10528 assert(false && "Invalid value type!");
10529 case MVT::i8: Reg = X86::AL; size = 1; break;
10530 case MVT::i16: Reg = X86::AX; size = 2; break;
10531 case MVT::i32: Reg = X86::EAX; size = 4; break;
10533 assert(Subtarget->is64Bit() && "Node not type legal!");
10534 Reg = X86::RAX; size = 8;
10537 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10538 Op.getOperand(2), SDValue());
10539 SDValue Ops[] = { cpIn.getValue(0),
10542 DAG.getTargetConstant(size, MVT::i8),
10543 cpIn.getValue(1) };
10544 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10545 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10546 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10549 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10553 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10554 SelectionDAG &DAG) const {
10555 assert(Subtarget->is64Bit() && "Result not type legalized?");
10556 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10557 SDValue TheChain = Op.getOperand(0);
10558 DebugLoc dl = Op.getDebugLoc();
10559 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10560 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10561 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10563 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10564 DAG.getConstant(32, MVT::i8));
10566 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10569 return DAG.getMergeValues(Ops, 2, dl);
10572 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10573 SelectionDAG &DAG) const {
10574 EVT SrcVT = Op.getOperand(0).getValueType();
10575 EVT DstVT = Op.getValueType();
10576 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10577 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10578 assert((DstVT == MVT::i64 ||
10579 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10580 "Unexpected custom BITCAST");
10581 // i64 <=> MMX conversions are Legal.
10582 if (SrcVT==MVT::i64 && DstVT.isVector())
10584 if (DstVT==MVT::i64 && SrcVT.isVector())
10586 // MMX <=> MMX conversions are Legal.
10587 if (SrcVT.isVector() && DstVT.isVector())
10589 // All other conversions need to be expanded.
10593 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10594 SDNode *Node = Op.getNode();
10595 DebugLoc dl = Node->getDebugLoc();
10596 EVT T = Node->getValueType(0);
10597 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10598 DAG.getConstant(0, T), Node->getOperand(2));
10599 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10600 cast<AtomicSDNode>(Node)->getMemoryVT(),
10601 Node->getOperand(0),
10602 Node->getOperand(1), negOp,
10603 cast<AtomicSDNode>(Node)->getSrcValue(),
10604 cast<AtomicSDNode>(Node)->getAlignment(),
10605 cast<AtomicSDNode>(Node)->getOrdering(),
10606 cast<AtomicSDNode>(Node)->getSynchScope());
10609 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10610 SDNode *Node = Op.getNode();
10611 DebugLoc dl = Node->getDebugLoc();
10612 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10614 // Convert seq_cst store -> xchg
10615 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10616 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10617 // (The only way to get a 16-byte store is cmpxchg16b)
10618 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10619 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10620 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10621 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10622 cast<AtomicSDNode>(Node)->getMemoryVT(),
10623 Node->getOperand(0),
10624 Node->getOperand(1), Node->getOperand(2),
10625 cast<AtomicSDNode>(Node)->getMemOperand(),
10626 cast<AtomicSDNode>(Node)->getOrdering(),
10627 cast<AtomicSDNode>(Node)->getSynchScope());
10628 return Swap.getValue(1);
10630 // Other atomic stores have a simple pattern.
10634 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10635 EVT VT = Op.getNode()->getValueType(0);
10637 // Let legalize expand this if it isn't a legal type yet.
10638 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10641 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10644 bool ExtraOp = false;
10645 switch (Op.getOpcode()) {
10646 default: assert(0 && "Invalid code");
10647 case ISD::ADDC: Opc = X86ISD::ADD; break;
10648 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10649 case ISD::SUBC: Opc = X86ISD::SUB; break;
10650 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10654 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10656 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10657 Op.getOperand(1), Op.getOperand(2));
10660 /// LowerOperation - Provide custom lowering hooks for some operations.
10662 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10663 switch (Op.getOpcode()) {
10664 default: llvm_unreachable("Should not custom lower this!");
10665 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10666 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10667 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10668 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10669 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10670 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10671 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10672 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10673 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10674 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10675 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10676 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10677 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10678 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10679 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10680 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10681 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10682 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10683 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10684 case ISD::SHL_PARTS:
10685 case ISD::SRA_PARTS:
10686 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10687 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10688 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10689 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10690 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10691 case ISD::FABS: return LowerFABS(Op, DAG);
10692 case ISD::FNEG: return LowerFNEG(Op, DAG);
10693 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10694 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10695 case ISD::SETCC: return LowerSETCC(Op, DAG);
10696 case ISD::SELECT: return LowerSELECT(Op, DAG);
10697 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10698 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10699 case ISD::VASTART: return LowerVASTART(Op, DAG);
10700 case ISD::VAARG: return LowerVAARG(Op, DAG);
10701 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10702 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10703 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10704 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10705 case ISD::FRAME_TO_ARGS_OFFSET:
10706 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10707 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10708 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10709 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10710 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10711 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10712 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10713 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10714 case ISD::MUL: return LowerMUL(Op, DAG);
10717 case ISD::SHL: return LowerShift(Op, DAG);
10723 case ISD::UMULO: return LowerXALUO(Op, DAG);
10724 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10725 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10729 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10730 case ISD::ADD: return LowerADD(Op, DAG);
10731 case ISD::SUB: return LowerSUB(Op, DAG);
10735 static void ReplaceATOMIC_LOAD(SDNode *Node,
10736 SmallVectorImpl<SDValue> &Results,
10737 SelectionDAG &DAG) {
10738 DebugLoc dl = Node->getDebugLoc();
10739 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10741 // Convert wide load -> cmpxchg8b/cmpxchg16b
10742 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10743 // (The only way to get a 16-byte load is cmpxchg16b)
10744 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10745 SDValue Zero = DAG.getConstant(0, VT);
10746 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10747 Node->getOperand(0),
10748 Node->getOperand(1), Zero, Zero,
10749 cast<AtomicSDNode>(Node)->getMemOperand(),
10750 cast<AtomicSDNode>(Node)->getOrdering(),
10751 cast<AtomicSDNode>(Node)->getSynchScope());
10752 Results.push_back(Swap.getValue(0));
10753 Results.push_back(Swap.getValue(1));
10756 void X86TargetLowering::
10757 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10758 SelectionDAG &DAG, unsigned NewOp) const {
10759 DebugLoc dl = Node->getDebugLoc();
10760 assert (Node->getValueType(0) == MVT::i64 &&
10761 "Only know how to expand i64 atomics");
10763 SDValue Chain = Node->getOperand(0);
10764 SDValue In1 = Node->getOperand(1);
10765 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10766 Node->getOperand(2), DAG.getIntPtrConstant(0));
10767 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10768 Node->getOperand(2), DAG.getIntPtrConstant(1));
10769 SDValue Ops[] = { Chain, In1, In2L, In2H };
10770 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10772 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10773 cast<MemSDNode>(Node)->getMemOperand());
10774 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10775 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10776 Results.push_back(Result.getValue(2));
10779 /// ReplaceNodeResults - Replace a node with an illegal result type
10780 /// with a new node built out of custom code.
10781 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10782 SmallVectorImpl<SDValue>&Results,
10783 SelectionDAG &DAG) const {
10784 DebugLoc dl = N->getDebugLoc();
10785 switch (N->getOpcode()) {
10787 assert(false && "Do not know how to custom type legalize this operation!");
10789 case ISD::SIGN_EXTEND_INREG:
10794 // We don't want to expand or promote these.
10796 case ISD::FP_TO_SINT: {
10797 std::pair<SDValue,SDValue> Vals =
10798 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10799 SDValue FIST = Vals.first, StackSlot = Vals.second;
10800 if (FIST.getNode() != 0) {
10801 EVT VT = N->getValueType(0);
10802 // Return a load from the stack slot.
10803 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10804 MachinePointerInfo(),
10805 false, false, false, 0));
10809 case ISD::READCYCLECOUNTER: {
10810 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10811 SDValue TheChain = N->getOperand(0);
10812 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10813 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10815 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10817 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10818 SDValue Ops[] = { eax, edx };
10819 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10820 Results.push_back(edx.getValue(1));
10823 case ISD::ATOMIC_CMP_SWAP: {
10824 EVT T = N->getValueType(0);
10825 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10826 bool Regs64bit = T == MVT::i128;
10827 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10828 SDValue cpInL, cpInH;
10829 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10830 DAG.getConstant(0, HalfT));
10831 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10832 DAG.getConstant(1, HalfT));
10833 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10834 Regs64bit ? X86::RAX : X86::EAX,
10836 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10837 Regs64bit ? X86::RDX : X86::EDX,
10838 cpInH, cpInL.getValue(1));
10839 SDValue swapInL, swapInH;
10840 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10841 DAG.getConstant(0, HalfT));
10842 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10843 DAG.getConstant(1, HalfT));
10844 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10845 Regs64bit ? X86::RBX : X86::EBX,
10846 swapInL, cpInH.getValue(1));
10847 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10848 Regs64bit ? X86::RCX : X86::ECX,
10849 swapInH, swapInL.getValue(1));
10850 SDValue Ops[] = { swapInH.getValue(0),
10852 swapInH.getValue(1) };
10853 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10854 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10855 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10856 X86ISD::LCMPXCHG8_DAG;
10857 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10859 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10860 Regs64bit ? X86::RAX : X86::EAX,
10861 HalfT, Result.getValue(1));
10862 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10863 Regs64bit ? X86::RDX : X86::EDX,
10864 HalfT, cpOutL.getValue(2));
10865 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10866 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10867 Results.push_back(cpOutH.getValue(1));
10870 case ISD::ATOMIC_LOAD_ADD:
10871 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10873 case ISD::ATOMIC_LOAD_AND:
10874 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10876 case ISD::ATOMIC_LOAD_NAND:
10877 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10879 case ISD::ATOMIC_LOAD_OR:
10880 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10882 case ISD::ATOMIC_LOAD_SUB:
10883 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10885 case ISD::ATOMIC_LOAD_XOR:
10886 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10888 case ISD::ATOMIC_SWAP:
10889 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10891 case ISD::ATOMIC_LOAD:
10892 ReplaceATOMIC_LOAD(N, Results, DAG);
10896 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10898 default: return NULL;
10899 case X86ISD::BSF: return "X86ISD::BSF";
10900 case X86ISD::BSR: return "X86ISD::BSR";
10901 case X86ISD::SHLD: return "X86ISD::SHLD";
10902 case X86ISD::SHRD: return "X86ISD::SHRD";
10903 case X86ISD::FAND: return "X86ISD::FAND";
10904 case X86ISD::FOR: return "X86ISD::FOR";
10905 case X86ISD::FXOR: return "X86ISD::FXOR";
10906 case X86ISD::FSRL: return "X86ISD::FSRL";
10907 case X86ISD::FILD: return "X86ISD::FILD";
10908 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10909 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10910 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10911 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10912 case X86ISD::FLD: return "X86ISD::FLD";
10913 case X86ISD::FST: return "X86ISD::FST";
10914 case X86ISD::CALL: return "X86ISD::CALL";
10915 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10916 case X86ISD::BT: return "X86ISD::BT";
10917 case X86ISD::CMP: return "X86ISD::CMP";
10918 case X86ISD::COMI: return "X86ISD::COMI";
10919 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10920 case X86ISD::SETCC: return "X86ISD::SETCC";
10921 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10922 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10923 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10924 case X86ISD::CMOV: return "X86ISD::CMOV";
10925 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10926 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10927 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10928 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10929 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10930 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10931 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10932 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10933 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10934 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10935 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10936 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10937 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10938 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10939 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10940 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10941 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10942 case X86ISD::FMAX: return "X86ISD::FMAX";
10943 case X86ISD::FMIN: return "X86ISD::FMIN";
10944 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10945 case X86ISD::FRCP: return "X86ISD::FRCP";
10946 case X86ISD::FHADD: return "X86ISD::FHADD";
10947 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10948 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10949 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10950 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10951 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10952 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10953 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10954 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10955 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10956 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10957 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10958 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10959 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10960 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10961 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10962 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10963 case X86ISD::VSHL: return "X86ISD::VSHL";
10964 case X86ISD::VSRL: return "X86ISD::VSRL";
10965 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10966 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10967 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10968 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10969 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10970 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10971 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10972 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10973 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10974 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10975 case X86ISD::ADD: return "X86ISD::ADD";
10976 case X86ISD::SUB: return "X86ISD::SUB";
10977 case X86ISD::ADC: return "X86ISD::ADC";
10978 case X86ISD::SBB: return "X86ISD::SBB";
10979 case X86ISD::SMUL: return "X86ISD::SMUL";
10980 case X86ISD::UMUL: return "X86ISD::UMUL";
10981 case X86ISD::INC: return "X86ISD::INC";
10982 case X86ISD::DEC: return "X86ISD::DEC";
10983 case X86ISD::OR: return "X86ISD::OR";
10984 case X86ISD::XOR: return "X86ISD::XOR";
10985 case X86ISD::AND: return "X86ISD::AND";
10986 case X86ISD::ANDN: return "X86ISD::ANDN";
10987 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10988 case X86ISD::PTEST: return "X86ISD::PTEST";
10989 case X86ISD::TESTP: return "X86ISD::TESTP";
10990 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10991 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10992 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10993 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10994 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10995 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10996 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10997 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10998 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10999 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11000 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11001 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
11002 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11003 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11004 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11005 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11006 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11007 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11008 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11009 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11010 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11011 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
11012 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
11013 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
11014 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
11015 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
11016 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
11017 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
11018 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
11019 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
11020 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
11021 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
11022 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
11023 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
11024 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11025 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
11026 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
11027 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
11028 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
11029 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
11030 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11031 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11032 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11033 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11034 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11038 // isLegalAddressingMode - Return true if the addressing mode represented
11039 // by AM is legal for this target, for a load/store of the specified type.
11040 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11042 // X86 supports extremely general addressing modes.
11043 CodeModel::Model M = getTargetMachine().getCodeModel();
11044 Reloc::Model R = getTargetMachine().getRelocationModel();
11046 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11047 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11052 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11054 // If a reference to this global requires an extra load, we can't fold it.
11055 if (isGlobalStubReference(GVFlags))
11058 // If BaseGV requires a register for the PIC base, we cannot also have a
11059 // BaseReg specified.
11060 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11063 // If lower 4G is not available, then we must use rip-relative addressing.
11064 if ((M != CodeModel::Small || R != Reloc::Static) &&
11065 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11069 switch (AM.Scale) {
11075 // These scales always work.
11080 // These scales are formed with basereg+scalereg. Only accept if there is
11085 default: // Other stuff never works.
11093 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11094 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11096 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11097 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11098 if (NumBits1 <= NumBits2)
11103 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11104 if (!VT1.isInteger() || !VT2.isInteger())
11106 unsigned NumBits1 = VT1.getSizeInBits();
11107 unsigned NumBits2 = VT2.getSizeInBits();
11108 if (NumBits1 <= NumBits2)
11113 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11114 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11115 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11118 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11119 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11120 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11123 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11124 // i16 instructions are longer (0x66 prefix) and potentially slower.
11125 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11128 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11129 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11130 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11131 /// are assumed to be legal.
11133 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11135 // Very little shuffling can be done for 64-bit vectors right now.
11136 if (VT.getSizeInBits() == 64)
11137 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11139 // FIXME: pshufb, blends, shifts.
11140 return (VT.getVectorNumElements() == 2 ||
11141 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11142 isMOVLMask(M, VT) ||
11143 isSHUFPMask(M, VT) ||
11144 isPSHUFDMask(M, VT) ||
11145 isPSHUFHWMask(M, VT) ||
11146 isPSHUFLWMask(M, VT) ||
11147 isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11148 isUNPCKLMask(M, VT) ||
11149 isUNPCKHMask(M, VT) ||
11150 isUNPCKL_v_undef_Mask(M, VT) ||
11151 isUNPCKH_v_undef_Mask(M, VT));
11155 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11157 unsigned NumElts = VT.getVectorNumElements();
11158 // FIXME: This collection of masks seems suspect.
11161 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11162 return (isMOVLMask(Mask, VT) ||
11163 isCommutedMOVLMask(Mask, VT, true) ||
11164 isSHUFPMask(Mask, VT) ||
11165 isCommutedSHUFPMask(Mask, VT));
11170 //===----------------------------------------------------------------------===//
11171 // X86 Scheduler Hooks
11172 //===----------------------------------------------------------------------===//
11174 // private utility function
11175 MachineBasicBlock *
11176 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11177 MachineBasicBlock *MBB,
11184 TargetRegisterClass *RC,
11185 bool invSrc) const {
11186 // For the atomic bitwise operator, we generate
11189 // ld t1 = [bitinstr.addr]
11190 // op t2 = t1, [bitinstr.val]
11192 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11194 // fallthrough -->nextMBB
11195 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11196 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11197 MachineFunction::iterator MBBIter = MBB;
11200 /// First build the CFG
11201 MachineFunction *F = MBB->getParent();
11202 MachineBasicBlock *thisMBB = MBB;
11203 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11204 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11205 F->insert(MBBIter, newMBB);
11206 F->insert(MBBIter, nextMBB);
11208 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11209 nextMBB->splice(nextMBB->begin(), thisMBB,
11210 llvm::next(MachineBasicBlock::iterator(bInstr)),
11212 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11214 // Update thisMBB to fall through to newMBB
11215 thisMBB->addSuccessor(newMBB);
11217 // newMBB jumps to itself and fall through to nextMBB
11218 newMBB->addSuccessor(nextMBB);
11219 newMBB->addSuccessor(newMBB);
11221 // Insert instructions into newMBB based on incoming instruction
11222 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11223 "unexpected number of operands");
11224 DebugLoc dl = bInstr->getDebugLoc();
11225 MachineOperand& destOper = bInstr->getOperand(0);
11226 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11227 int numArgs = bInstr->getNumOperands() - 1;
11228 for (int i=0; i < numArgs; ++i)
11229 argOpers[i] = &bInstr->getOperand(i+1);
11231 // x86 address has 4 operands: base, index, scale, and displacement
11232 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11233 int valArgIndx = lastAddrIndx + 1;
11235 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11236 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11237 for (int i=0; i <= lastAddrIndx; ++i)
11238 (*MIB).addOperand(*argOpers[i]);
11240 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11242 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11247 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11248 assert((argOpers[valArgIndx]->isReg() ||
11249 argOpers[valArgIndx]->isImm()) &&
11250 "invalid operand");
11251 if (argOpers[valArgIndx]->isReg())
11252 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11254 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11256 (*MIB).addOperand(*argOpers[valArgIndx]);
11258 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11261 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11262 for (int i=0; i <= lastAddrIndx; ++i)
11263 (*MIB).addOperand(*argOpers[i]);
11265 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11266 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11267 bInstr->memoperands_end());
11269 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11270 MIB.addReg(EAXreg);
11273 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11275 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11279 // private utility function: 64 bit atomics on 32 bit host.
11280 MachineBasicBlock *
11281 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11282 MachineBasicBlock *MBB,
11287 bool invSrc) const {
11288 // For the atomic bitwise operator, we generate
11289 // thisMBB (instructions are in pairs, except cmpxchg8b)
11290 // ld t1,t2 = [bitinstr.addr]
11292 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11293 // op t5, t6 <- out1, out2, [bitinstr.val]
11294 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11295 // mov ECX, EBX <- t5, t6
11296 // mov EAX, EDX <- t1, t2
11297 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11298 // mov t3, t4 <- EAX, EDX
11300 // result in out1, out2
11301 // fallthrough -->nextMBB
11303 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11304 const unsigned LoadOpc = X86::MOV32rm;
11305 const unsigned NotOpc = X86::NOT32r;
11306 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11307 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11308 MachineFunction::iterator MBBIter = MBB;
11311 /// First build the CFG
11312 MachineFunction *F = MBB->getParent();
11313 MachineBasicBlock *thisMBB = MBB;
11314 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11315 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11316 F->insert(MBBIter, newMBB);
11317 F->insert(MBBIter, nextMBB);
11319 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11320 nextMBB->splice(nextMBB->begin(), thisMBB,
11321 llvm::next(MachineBasicBlock::iterator(bInstr)),
11323 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11325 // Update thisMBB to fall through to newMBB
11326 thisMBB->addSuccessor(newMBB);
11328 // newMBB jumps to itself and fall through to nextMBB
11329 newMBB->addSuccessor(nextMBB);
11330 newMBB->addSuccessor(newMBB);
11332 DebugLoc dl = bInstr->getDebugLoc();
11333 // Insert instructions into newMBB based on incoming instruction
11334 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11335 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11336 "unexpected number of operands");
11337 MachineOperand& dest1Oper = bInstr->getOperand(0);
11338 MachineOperand& dest2Oper = bInstr->getOperand(1);
11339 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11340 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11341 argOpers[i] = &bInstr->getOperand(i+2);
11343 // We use some of the operands multiple times, so conservatively just
11344 // clear any kill flags that might be present.
11345 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11346 argOpers[i]->setIsKill(false);
11349 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11350 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11352 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11353 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11354 for (int i=0; i <= lastAddrIndx; ++i)
11355 (*MIB).addOperand(*argOpers[i]);
11356 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11357 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11358 // add 4 to displacement.
11359 for (int i=0; i <= lastAddrIndx-2; ++i)
11360 (*MIB).addOperand(*argOpers[i]);
11361 MachineOperand newOp3 = *(argOpers[3]);
11362 if (newOp3.isImm())
11363 newOp3.setImm(newOp3.getImm()+4);
11365 newOp3.setOffset(newOp3.getOffset()+4);
11366 (*MIB).addOperand(newOp3);
11367 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11369 // t3/4 are defined later, at the bottom of the loop
11370 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11371 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11372 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11373 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11374 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11375 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11377 // The subsequent operations should be using the destination registers of
11378 //the PHI instructions.
11380 t1 = F->getRegInfo().createVirtualRegister(RC);
11381 t2 = F->getRegInfo().createVirtualRegister(RC);
11382 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11383 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11385 t1 = dest1Oper.getReg();
11386 t2 = dest2Oper.getReg();
11389 int valArgIndx = lastAddrIndx + 1;
11390 assert((argOpers[valArgIndx]->isReg() ||
11391 argOpers[valArgIndx]->isImm()) &&
11392 "invalid operand");
11393 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11394 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11395 if (argOpers[valArgIndx]->isReg())
11396 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11398 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11399 if (regOpcL != X86::MOV32rr)
11401 (*MIB).addOperand(*argOpers[valArgIndx]);
11402 assert(argOpers[valArgIndx + 1]->isReg() ==
11403 argOpers[valArgIndx]->isReg());
11404 assert(argOpers[valArgIndx + 1]->isImm() ==
11405 argOpers[valArgIndx]->isImm());
11406 if (argOpers[valArgIndx + 1]->isReg())
11407 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11409 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11410 if (regOpcH != X86::MOV32rr)
11412 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11414 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11416 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11419 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11421 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11424 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11425 for (int i=0; i <= lastAddrIndx; ++i)
11426 (*MIB).addOperand(*argOpers[i]);
11428 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11429 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11430 bInstr->memoperands_end());
11432 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11433 MIB.addReg(X86::EAX);
11434 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11435 MIB.addReg(X86::EDX);
11438 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11440 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11444 // private utility function
11445 MachineBasicBlock *
11446 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11447 MachineBasicBlock *MBB,
11448 unsigned cmovOpc) const {
11449 // For the atomic min/max operator, we generate
11452 // ld t1 = [min/max.addr]
11453 // mov t2 = [min/max.val]
11455 // cmov[cond] t2 = t1
11457 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11459 // fallthrough -->nextMBB
11461 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11462 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11463 MachineFunction::iterator MBBIter = MBB;
11466 /// First build the CFG
11467 MachineFunction *F = MBB->getParent();
11468 MachineBasicBlock *thisMBB = MBB;
11469 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11470 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11471 F->insert(MBBIter, newMBB);
11472 F->insert(MBBIter, nextMBB);
11474 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11475 nextMBB->splice(nextMBB->begin(), thisMBB,
11476 llvm::next(MachineBasicBlock::iterator(mInstr)),
11478 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11480 // Update thisMBB to fall through to newMBB
11481 thisMBB->addSuccessor(newMBB);
11483 // newMBB jumps to newMBB and fall through to nextMBB
11484 newMBB->addSuccessor(nextMBB);
11485 newMBB->addSuccessor(newMBB);
11487 DebugLoc dl = mInstr->getDebugLoc();
11488 // Insert instructions into newMBB based on incoming instruction
11489 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11490 "unexpected number of operands");
11491 MachineOperand& destOper = mInstr->getOperand(0);
11492 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11493 int numArgs = mInstr->getNumOperands() - 1;
11494 for (int i=0; i < numArgs; ++i)
11495 argOpers[i] = &mInstr->getOperand(i+1);
11497 // x86 address has 4 operands: base, index, scale, and displacement
11498 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11499 int valArgIndx = lastAddrIndx + 1;
11501 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11502 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11503 for (int i=0; i <= lastAddrIndx; ++i)
11504 (*MIB).addOperand(*argOpers[i]);
11506 // We only support register and immediate values
11507 assert((argOpers[valArgIndx]->isReg() ||
11508 argOpers[valArgIndx]->isImm()) &&
11509 "invalid operand");
11511 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11512 if (argOpers[valArgIndx]->isReg())
11513 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11515 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11516 (*MIB).addOperand(*argOpers[valArgIndx]);
11518 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11521 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11526 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11527 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11531 // Cmp and exchange if none has modified the memory location
11532 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11533 for (int i=0; i <= lastAddrIndx; ++i)
11534 (*MIB).addOperand(*argOpers[i]);
11536 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11537 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11538 mInstr->memoperands_end());
11540 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11541 MIB.addReg(X86::EAX);
11544 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11546 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11550 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11551 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11552 // in the .td file.
11553 MachineBasicBlock *
11554 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11555 unsigned numArgs, bool memArg) const {
11556 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11557 "Target must have SSE4.2 or AVX features enabled");
11559 DebugLoc dl = MI->getDebugLoc();
11560 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11562 if (!Subtarget->hasAVX()) {
11564 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11566 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11569 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11571 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11574 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11575 for (unsigned i = 0; i < numArgs; ++i) {
11576 MachineOperand &Op = MI->getOperand(i+1);
11577 if (!(Op.isReg() && Op.isImplicit()))
11578 MIB.addOperand(Op);
11580 BuildMI(*BB, MI, dl,
11581 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11582 MI->getOperand(0).getReg())
11583 .addReg(X86::XMM0);
11585 MI->eraseFromParent();
11589 MachineBasicBlock *
11590 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11591 DebugLoc dl = MI->getDebugLoc();
11592 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11594 // Address into RAX/EAX, other two args into ECX, EDX.
11595 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11596 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11597 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11598 for (int i = 0; i < X86::AddrNumOperands; ++i)
11599 MIB.addOperand(MI->getOperand(i));
11601 unsigned ValOps = X86::AddrNumOperands;
11602 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11603 .addReg(MI->getOperand(ValOps).getReg());
11604 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11605 .addReg(MI->getOperand(ValOps+1).getReg());
11607 // The instruction doesn't actually take any operands though.
11608 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11610 MI->eraseFromParent(); // The pseudo is gone now.
11614 MachineBasicBlock *
11615 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11616 DebugLoc dl = MI->getDebugLoc();
11617 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11619 // First arg in ECX, the second in EAX.
11620 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11621 .addReg(MI->getOperand(0).getReg());
11622 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11623 .addReg(MI->getOperand(1).getReg());
11625 // The instruction doesn't actually take any operands though.
11626 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11628 MI->eraseFromParent(); // The pseudo is gone now.
11632 MachineBasicBlock *
11633 X86TargetLowering::EmitVAARG64WithCustomInserter(
11635 MachineBasicBlock *MBB) const {
11636 // Emit va_arg instruction on X86-64.
11638 // Operands to this pseudo-instruction:
11639 // 0 ) Output : destination address (reg)
11640 // 1-5) Input : va_list address (addr, i64mem)
11641 // 6 ) ArgSize : Size (in bytes) of vararg type
11642 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11643 // 8 ) Align : Alignment of type
11644 // 9 ) EFLAGS (implicit-def)
11646 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11647 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11649 unsigned DestReg = MI->getOperand(0).getReg();
11650 MachineOperand &Base = MI->getOperand(1);
11651 MachineOperand &Scale = MI->getOperand(2);
11652 MachineOperand &Index = MI->getOperand(3);
11653 MachineOperand &Disp = MI->getOperand(4);
11654 MachineOperand &Segment = MI->getOperand(5);
11655 unsigned ArgSize = MI->getOperand(6).getImm();
11656 unsigned ArgMode = MI->getOperand(7).getImm();
11657 unsigned Align = MI->getOperand(8).getImm();
11659 // Memory Reference
11660 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11661 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11662 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11664 // Machine Information
11665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11666 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11667 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11668 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11669 DebugLoc DL = MI->getDebugLoc();
11671 // struct va_list {
11674 // i64 overflow_area (address)
11675 // i64 reg_save_area (address)
11677 // sizeof(va_list) = 24
11678 // alignment(va_list) = 8
11680 unsigned TotalNumIntRegs = 6;
11681 unsigned TotalNumXMMRegs = 8;
11682 bool UseGPOffset = (ArgMode == 1);
11683 bool UseFPOffset = (ArgMode == 2);
11684 unsigned MaxOffset = TotalNumIntRegs * 8 +
11685 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11687 /* Align ArgSize to a multiple of 8 */
11688 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11689 bool NeedsAlign = (Align > 8);
11691 MachineBasicBlock *thisMBB = MBB;
11692 MachineBasicBlock *overflowMBB;
11693 MachineBasicBlock *offsetMBB;
11694 MachineBasicBlock *endMBB;
11696 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11697 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11698 unsigned OffsetReg = 0;
11700 if (!UseGPOffset && !UseFPOffset) {
11701 // If we only pull from the overflow region, we don't create a branch.
11702 // We don't need to alter control flow.
11703 OffsetDestReg = 0; // unused
11704 OverflowDestReg = DestReg;
11707 overflowMBB = thisMBB;
11710 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11711 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11712 // If not, pull from overflow_area. (branch to overflowMBB)
11717 // offsetMBB overflowMBB
11722 // Registers for the PHI in endMBB
11723 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11724 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11726 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11727 MachineFunction *MF = MBB->getParent();
11728 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11729 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11730 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11732 MachineFunction::iterator MBBIter = MBB;
11735 // Insert the new basic blocks
11736 MF->insert(MBBIter, offsetMBB);
11737 MF->insert(MBBIter, overflowMBB);
11738 MF->insert(MBBIter, endMBB);
11740 // Transfer the remainder of MBB and its successor edges to endMBB.
11741 endMBB->splice(endMBB->begin(), thisMBB,
11742 llvm::next(MachineBasicBlock::iterator(MI)),
11744 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11746 // Make offsetMBB and overflowMBB successors of thisMBB
11747 thisMBB->addSuccessor(offsetMBB);
11748 thisMBB->addSuccessor(overflowMBB);
11750 // endMBB is a successor of both offsetMBB and overflowMBB
11751 offsetMBB->addSuccessor(endMBB);
11752 overflowMBB->addSuccessor(endMBB);
11754 // Load the offset value into a register
11755 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11756 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11760 .addDisp(Disp, UseFPOffset ? 4 : 0)
11761 .addOperand(Segment)
11762 .setMemRefs(MMOBegin, MMOEnd);
11764 // Check if there is enough room left to pull this argument.
11765 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11767 .addImm(MaxOffset + 8 - ArgSizeA8);
11769 // Branch to "overflowMBB" if offset >= max
11770 // Fall through to "offsetMBB" otherwise
11771 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11772 .addMBB(overflowMBB);
11775 // In offsetMBB, emit code to use the reg_save_area.
11777 assert(OffsetReg != 0);
11779 // Read the reg_save_area address.
11780 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11781 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11786 .addOperand(Segment)
11787 .setMemRefs(MMOBegin, MMOEnd);
11789 // Zero-extend the offset
11790 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11791 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11794 .addImm(X86::sub_32bit);
11796 // Add the offset to the reg_save_area to get the final address.
11797 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11798 .addReg(OffsetReg64)
11799 .addReg(RegSaveReg);
11801 // Compute the offset for the next argument
11802 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11803 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11805 .addImm(UseFPOffset ? 16 : 8);
11807 // Store it back into the va_list.
11808 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11812 .addDisp(Disp, UseFPOffset ? 4 : 0)
11813 .addOperand(Segment)
11814 .addReg(NextOffsetReg)
11815 .setMemRefs(MMOBegin, MMOEnd);
11818 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11823 // Emit code to use overflow area
11826 // Load the overflow_area address into a register.
11827 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11828 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11833 .addOperand(Segment)
11834 .setMemRefs(MMOBegin, MMOEnd);
11836 // If we need to align it, do so. Otherwise, just copy the address
11837 // to OverflowDestReg.
11839 // Align the overflow address
11840 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11841 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11843 // aligned_addr = (addr + (align-1)) & ~(align-1)
11844 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11845 .addReg(OverflowAddrReg)
11848 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11850 .addImm(~(uint64_t)(Align-1));
11852 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11853 .addReg(OverflowAddrReg);
11856 // Compute the next overflow address after this argument.
11857 // (the overflow address should be kept 8-byte aligned)
11858 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11859 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11860 .addReg(OverflowDestReg)
11861 .addImm(ArgSizeA8);
11863 // Store the new overflow address.
11864 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11869 .addOperand(Segment)
11870 .addReg(NextAddrReg)
11871 .setMemRefs(MMOBegin, MMOEnd);
11873 // If we branched, emit the PHI to the front of endMBB.
11875 BuildMI(*endMBB, endMBB->begin(), DL,
11876 TII->get(X86::PHI), DestReg)
11877 .addReg(OffsetDestReg).addMBB(offsetMBB)
11878 .addReg(OverflowDestReg).addMBB(overflowMBB);
11881 // Erase the pseudo instruction
11882 MI->eraseFromParent();
11887 MachineBasicBlock *
11888 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11890 MachineBasicBlock *MBB) const {
11891 // Emit code to save XMM registers to the stack. The ABI says that the
11892 // number of registers to save is given in %al, so it's theoretically
11893 // possible to do an indirect jump trick to avoid saving all of them,
11894 // however this code takes a simpler approach and just executes all
11895 // of the stores if %al is non-zero. It's less code, and it's probably
11896 // easier on the hardware branch predictor, and stores aren't all that
11897 // expensive anyway.
11899 // Create the new basic blocks. One block contains all the XMM stores,
11900 // and one block is the final destination regardless of whether any
11901 // stores were performed.
11902 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11903 MachineFunction *F = MBB->getParent();
11904 MachineFunction::iterator MBBIter = MBB;
11906 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11907 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11908 F->insert(MBBIter, XMMSaveMBB);
11909 F->insert(MBBIter, EndMBB);
11911 // Transfer the remainder of MBB and its successor edges to EndMBB.
11912 EndMBB->splice(EndMBB->begin(), MBB,
11913 llvm::next(MachineBasicBlock::iterator(MI)),
11915 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11917 // The original block will now fall through to the XMM save block.
11918 MBB->addSuccessor(XMMSaveMBB);
11919 // The XMMSaveMBB will fall through to the end block.
11920 XMMSaveMBB->addSuccessor(EndMBB);
11922 // Now add the instructions.
11923 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11924 DebugLoc DL = MI->getDebugLoc();
11926 unsigned CountReg = MI->getOperand(0).getReg();
11927 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11928 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11930 if (!Subtarget->isTargetWin64()) {
11931 // If %al is 0, branch around the XMM save block.
11932 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11933 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11934 MBB->addSuccessor(EndMBB);
11937 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11938 // In the XMM save block, save all the XMM argument registers.
11939 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11940 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11941 MachineMemOperand *MMO =
11942 F->getMachineMemOperand(
11943 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11944 MachineMemOperand::MOStore,
11945 /*Size=*/16, /*Align=*/16);
11946 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11947 .addFrameIndex(RegSaveFrameIndex)
11948 .addImm(/*Scale=*/1)
11949 .addReg(/*IndexReg=*/0)
11950 .addImm(/*Disp=*/Offset)
11951 .addReg(/*Segment=*/0)
11952 .addReg(MI->getOperand(i).getReg())
11953 .addMemOperand(MMO);
11956 MI->eraseFromParent(); // The pseudo instruction is gone now.
11961 MachineBasicBlock *
11962 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11963 MachineBasicBlock *BB) const {
11964 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11965 DebugLoc DL = MI->getDebugLoc();
11967 // To "insert" a SELECT_CC instruction, we actually have to insert the
11968 // diamond control-flow pattern. The incoming instruction knows the
11969 // destination vreg to set, the condition code register to branch on, the
11970 // true/false values to select between, and a branch opcode to use.
11971 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11972 MachineFunction::iterator It = BB;
11978 // cmpTY ccX, r1, r2
11980 // fallthrough --> copy0MBB
11981 MachineBasicBlock *thisMBB = BB;
11982 MachineFunction *F = BB->getParent();
11983 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11984 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11985 F->insert(It, copy0MBB);
11986 F->insert(It, sinkMBB);
11988 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11989 // live into the sink and copy blocks.
11990 if (!MI->killsRegister(X86::EFLAGS)) {
11991 copy0MBB->addLiveIn(X86::EFLAGS);
11992 sinkMBB->addLiveIn(X86::EFLAGS);
11995 // Transfer the remainder of BB and its successor edges to sinkMBB.
11996 sinkMBB->splice(sinkMBB->begin(), BB,
11997 llvm::next(MachineBasicBlock::iterator(MI)),
11999 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12001 // Add the true and fallthrough blocks as its successors.
12002 BB->addSuccessor(copy0MBB);
12003 BB->addSuccessor(sinkMBB);
12005 // Create the conditional branch instruction.
12007 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12008 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12011 // %FalseValue = ...
12012 // # fallthrough to sinkMBB
12013 copy0MBB->addSuccessor(sinkMBB);
12016 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12018 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12019 TII->get(X86::PHI), MI->getOperand(0).getReg())
12020 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12021 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12023 MI->eraseFromParent(); // The pseudo instruction is gone now.
12027 MachineBasicBlock *
12028 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12029 bool Is64Bit) const {
12030 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12031 DebugLoc DL = MI->getDebugLoc();
12032 MachineFunction *MF = BB->getParent();
12033 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12035 assert(EnableSegmentedStacks);
12037 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12038 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12041 // ... [Till the alloca]
12042 // If stacklet is not large enough, jump to mallocMBB
12045 // Allocate by subtracting from RSP
12046 // Jump to continueMBB
12049 // Allocate by call to runtime
12053 // [rest of original BB]
12056 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12057 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12058 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12060 MachineRegisterInfo &MRI = MF->getRegInfo();
12061 const TargetRegisterClass *AddrRegClass =
12062 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12064 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12065 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12066 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12067 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12068 sizeVReg = MI->getOperand(1).getReg(),
12069 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12071 MachineFunction::iterator MBBIter = BB;
12074 MF->insert(MBBIter, bumpMBB);
12075 MF->insert(MBBIter, mallocMBB);
12076 MF->insert(MBBIter, continueMBB);
12078 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12079 (MachineBasicBlock::iterator(MI)), BB->end());
12080 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12082 // Add code to the main basic block to check if the stack limit has been hit,
12083 // and if so, jump to mallocMBB otherwise to bumpMBB.
12084 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12085 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12086 .addReg(tmpSPVReg).addReg(sizeVReg);
12087 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12088 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12089 .addReg(SPLimitVReg);
12090 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12092 // bumpMBB simply decreases the stack pointer, since we know the current
12093 // stacklet has enough space.
12094 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12095 .addReg(SPLimitVReg);
12096 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12097 .addReg(SPLimitVReg);
12098 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12100 // Calls into a routine in libgcc to allocate more space from the heap.
12102 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12104 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12105 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12107 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12109 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12110 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12111 .addExternalSymbol("__morestack_allocate_stack_space");
12115 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12118 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12119 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12120 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12122 // Set up the CFG correctly.
12123 BB->addSuccessor(bumpMBB);
12124 BB->addSuccessor(mallocMBB);
12125 mallocMBB->addSuccessor(continueMBB);
12126 bumpMBB->addSuccessor(continueMBB);
12128 // Take care of the PHI nodes.
12129 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12130 MI->getOperand(0).getReg())
12131 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12132 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12134 // Delete the original pseudo instruction.
12135 MI->eraseFromParent();
12138 return continueMBB;
12141 MachineBasicBlock *
12142 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12143 MachineBasicBlock *BB) const {
12144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12145 DebugLoc DL = MI->getDebugLoc();
12147 assert(!Subtarget->isTargetEnvMacho());
12149 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12150 // non-trivial part is impdef of ESP.
12152 if (Subtarget->isTargetWin64()) {
12153 if (Subtarget->isTargetCygMing()) {
12154 // ___chkstk(Mingw64):
12155 // Clobbers R10, R11, RAX and EFLAGS.
12157 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12158 .addExternalSymbol("___chkstk")
12159 .addReg(X86::RAX, RegState::Implicit)
12160 .addReg(X86::RSP, RegState::Implicit)
12161 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12162 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12163 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12165 // __chkstk(MSVCRT): does not update stack pointer.
12166 // Clobbers R10, R11 and EFLAGS.
12167 // FIXME: RAX(allocated size) might be reused and not killed.
12168 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12169 .addExternalSymbol("__chkstk")
12170 .addReg(X86::RAX, RegState::Implicit)
12171 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12172 // RAX has the offset to subtracted from RSP.
12173 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12178 const char *StackProbeSymbol =
12179 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12181 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12182 .addExternalSymbol(StackProbeSymbol)
12183 .addReg(X86::EAX, RegState::Implicit)
12184 .addReg(X86::ESP, RegState::Implicit)
12185 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12186 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12187 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12190 MI->eraseFromParent(); // The pseudo instruction is gone now.
12194 MachineBasicBlock *
12195 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12196 MachineBasicBlock *BB) const {
12197 // This is pretty easy. We're taking the value that we received from
12198 // our load from the relocation, sticking it in either RDI (x86-64)
12199 // or EAX and doing an indirect call. The return value will then
12200 // be in the normal return register.
12201 const X86InstrInfo *TII
12202 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12203 DebugLoc DL = MI->getDebugLoc();
12204 MachineFunction *F = BB->getParent();
12206 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12207 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12209 if (Subtarget->is64Bit()) {
12210 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12211 TII->get(X86::MOV64rm), X86::RDI)
12213 .addImm(0).addReg(0)
12214 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12215 MI->getOperand(3).getTargetFlags())
12217 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12218 addDirectMem(MIB, X86::RDI);
12219 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12220 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12221 TII->get(X86::MOV32rm), X86::EAX)
12223 .addImm(0).addReg(0)
12224 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12225 MI->getOperand(3).getTargetFlags())
12227 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12228 addDirectMem(MIB, X86::EAX);
12230 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12231 TII->get(X86::MOV32rm), X86::EAX)
12232 .addReg(TII->getGlobalBaseReg(F))
12233 .addImm(0).addReg(0)
12234 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12235 MI->getOperand(3).getTargetFlags())
12237 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12238 addDirectMem(MIB, X86::EAX);
12241 MI->eraseFromParent(); // The pseudo instruction is gone now.
12245 MachineBasicBlock *
12246 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12247 MachineBasicBlock *BB) const {
12248 switch (MI->getOpcode()) {
12249 default: assert(0 && "Unexpected instr type to insert");
12250 case X86::TAILJMPd64:
12251 case X86::TAILJMPr64:
12252 case X86::TAILJMPm64:
12253 assert(0 && "TAILJMP64 would not be touched here.");
12254 case X86::TCRETURNdi64:
12255 case X86::TCRETURNri64:
12256 case X86::TCRETURNmi64:
12257 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12258 // On AMD64, additional defs should be added before register allocation.
12259 if (!Subtarget->isTargetWin64()) {
12260 MI->addRegisterDefined(X86::RSI);
12261 MI->addRegisterDefined(X86::RDI);
12262 MI->addRegisterDefined(X86::XMM6);
12263 MI->addRegisterDefined(X86::XMM7);
12264 MI->addRegisterDefined(X86::XMM8);
12265 MI->addRegisterDefined(X86::XMM9);
12266 MI->addRegisterDefined(X86::XMM10);
12267 MI->addRegisterDefined(X86::XMM11);
12268 MI->addRegisterDefined(X86::XMM12);
12269 MI->addRegisterDefined(X86::XMM13);
12270 MI->addRegisterDefined(X86::XMM14);
12271 MI->addRegisterDefined(X86::XMM15);
12274 case X86::WIN_ALLOCA:
12275 return EmitLoweredWinAlloca(MI, BB);
12276 case X86::SEG_ALLOCA_32:
12277 return EmitLoweredSegAlloca(MI, BB, false);
12278 case X86::SEG_ALLOCA_64:
12279 return EmitLoweredSegAlloca(MI, BB, true);
12280 case X86::TLSCall_32:
12281 case X86::TLSCall_64:
12282 return EmitLoweredTLSCall(MI, BB);
12283 case X86::CMOV_GR8:
12284 case X86::CMOV_FR32:
12285 case X86::CMOV_FR64:
12286 case X86::CMOV_V4F32:
12287 case X86::CMOV_V2F64:
12288 case X86::CMOV_V2I64:
12289 case X86::CMOV_V8F32:
12290 case X86::CMOV_V4F64:
12291 case X86::CMOV_V4I64:
12292 case X86::CMOV_GR16:
12293 case X86::CMOV_GR32:
12294 case X86::CMOV_RFP32:
12295 case X86::CMOV_RFP64:
12296 case X86::CMOV_RFP80:
12297 return EmitLoweredSelect(MI, BB);
12299 case X86::FP32_TO_INT16_IN_MEM:
12300 case X86::FP32_TO_INT32_IN_MEM:
12301 case X86::FP32_TO_INT64_IN_MEM:
12302 case X86::FP64_TO_INT16_IN_MEM:
12303 case X86::FP64_TO_INT32_IN_MEM:
12304 case X86::FP64_TO_INT64_IN_MEM:
12305 case X86::FP80_TO_INT16_IN_MEM:
12306 case X86::FP80_TO_INT32_IN_MEM:
12307 case X86::FP80_TO_INT64_IN_MEM: {
12308 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12309 DebugLoc DL = MI->getDebugLoc();
12311 // Change the floating point control register to use "round towards zero"
12312 // mode when truncating to an integer value.
12313 MachineFunction *F = BB->getParent();
12314 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12315 addFrameReference(BuildMI(*BB, MI, DL,
12316 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12318 // Load the old value of the high byte of the control word...
12320 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12321 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12324 // Set the high part to be round to zero...
12325 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12328 // Reload the modified control word now...
12329 addFrameReference(BuildMI(*BB, MI, DL,
12330 TII->get(X86::FLDCW16m)), CWFrameIdx);
12332 // Restore the memory image of control word to original value
12333 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12336 // Get the X86 opcode to use.
12338 switch (MI->getOpcode()) {
12339 default: llvm_unreachable("illegal opcode!");
12340 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12341 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12342 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12343 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12344 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12345 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12346 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12347 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12348 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12352 MachineOperand &Op = MI->getOperand(0);
12354 AM.BaseType = X86AddressMode::RegBase;
12355 AM.Base.Reg = Op.getReg();
12357 AM.BaseType = X86AddressMode::FrameIndexBase;
12358 AM.Base.FrameIndex = Op.getIndex();
12360 Op = MI->getOperand(1);
12362 AM.Scale = Op.getImm();
12363 Op = MI->getOperand(2);
12365 AM.IndexReg = Op.getImm();
12366 Op = MI->getOperand(3);
12367 if (Op.isGlobal()) {
12368 AM.GV = Op.getGlobal();
12370 AM.Disp = Op.getImm();
12372 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12373 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12375 // Reload the original control word now.
12376 addFrameReference(BuildMI(*BB, MI, DL,
12377 TII->get(X86::FLDCW16m)), CWFrameIdx);
12379 MI->eraseFromParent(); // The pseudo instruction is gone now.
12382 // String/text processing lowering.
12383 case X86::PCMPISTRM128REG:
12384 case X86::VPCMPISTRM128REG:
12385 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12386 case X86::PCMPISTRM128MEM:
12387 case X86::VPCMPISTRM128MEM:
12388 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12389 case X86::PCMPESTRM128REG:
12390 case X86::VPCMPESTRM128REG:
12391 return EmitPCMP(MI, BB, 5, false /* in mem */);
12392 case X86::PCMPESTRM128MEM:
12393 case X86::VPCMPESTRM128MEM:
12394 return EmitPCMP(MI, BB, 5, true /* in mem */);
12396 // Thread synchronization.
12398 return EmitMonitor(MI, BB);
12400 return EmitMwait(MI, BB);
12402 // Atomic Lowering.
12403 case X86::ATOMAND32:
12404 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12405 X86::AND32ri, X86::MOV32rm,
12407 X86::NOT32r, X86::EAX,
12408 X86::GR32RegisterClass);
12409 case X86::ATOMOR32:
12410 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12411 X86::OR32ri, X86::MOV32rm,
12413 X86::NOT32r, X86::EAX,
12414 X86::GR32RegisterClass);
12415 case X86::ATOMXOR32:
12416 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12417 X86::XOR32ri, X86::MOV32rm,
12419 X86::NOT32r, X86::EAX,
12420 X86::GR32RegisterClass);
12421 case X86::ATOMNAND32:
12422 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12423 X86::AND32ri, X86::MOV32rm,
12425 X86::NOT32r, X86::EAX,
12426 X86::GR32RegisterClass, true);
12427 case X86::ATOMMIN32:
12428 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12429 case X86::ATOMMAX32:
12430 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12431 case X86::ATOMUMIN32:
12432 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12433 case X86::ATOMUMAX32:
12434 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12436 case X86::ATOMAND16:
12437 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12438 X86::AND16ri, X86::MOV16rm,
12440 X86::NOT16r, X86::AX,
12441 X86::GR16RegisterClass);
12442 case X86::ATOMOR16:
12443 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12444 X86::OR16ri, X86::MOV16rm,
12446 X86::NOT16r, X86::AX,
12447 X86::GR16RegisterClass);
12448 case X86::ATOMXOR16:
12449 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12450 X86::XOR16ri, X86::MOV16rm,
12452 X86::NOT16r, X86::AX,
12453 X86::GR16RegisterClass);
12454 case X86::ATOMNAND16:
12455 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12456 X86::AND16ri, X86::MOV16rm,
12458 X86::NOT16r, X86::AX,
12459 X86::GR16RegisterClass, true);
12460 case X86::ATOMMIN16:
12461 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12462 case X86::ATOMMAX16:
12463 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12464 case X86::ATOMUMIN16:
12465 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12466 case X86::ATOMUMAX16:
12467 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12469 case X86::ATOMAND8:
12470 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12471 X86::AND8ri, X86::MOV8rm,
12473 X86::NOT8r, X86::AL,
12474 X86::GR8RegisterClass);
12476 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12477 X86::OR8ri, X86::MOV8rm,
12479 X86::NOT8r, X86::AL,
12480 X86::GR8RegisterClass);
12481 case X86::ATOMXOR8:
12482 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12483 X86::XOR8ri, X86::MOV8rm,
12485 X86::NOT8r, X86::AL,
12486 X86::GR8RegisterClass);
12487 case X86::ATOMNAND8:
12488 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12489 X86::AND8ri, X86::MOV8rm,
12491 X86::NOT8r, X86::AL,
12492 X86::GR8RegisterClass, true);
12493 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12494 // This group is for 64-bit host.
12495 case X86::ATOMAND64:
12496 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12497 X86::AND64ri32, X86::MOV64rm,
12499 X86::NOT64r, X86::RAX,
12500 X86::GR64RegisterClass);
12501 case X86::ATOMOR64:
12502 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12503 X86::OR64ri32, X86::MOV64rm,
12505 X86::NOT64r, X86::RAX,
12506 X86::GR64RegisterClass);
12507 case X86::ATOMXOR64:
12508 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12509 X86::XOR64ri32, X86::MOV64rm,
12511 X86::NOT64r, X86::RAX,
12512 X86::GR64RegisterClass);
12513 case X86::ATOMNAND64:
12514 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12515 X86::AND64ri32, X86::MOV64rm,
12517 X86::NOT64r, X86::RAX,
12518 X86::GR64RegisterClass, true);
12519 case X86::ATOMMIN64:
12520 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12521 case X86::ATOMMAX64:
12522 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12523 case X86::ATOMUMIN64:
12524 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12525 case X86::ATOMUMAX64:
12526 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12528 // This group does 64-bit operations on a 32-bit host.
12529 case X86::ATOMAND6432:
12530 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12531 X86::AND32rr, X86::AND32rr,
12532 X86::AND32ri, X86::AND32ri,
12534 case X86::ATOMOR6432:
12535 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12536 X86::OR32rr, X86::OR32rr,
12537 X86::OR32ri, X86::OR32ri,
12539 case X86::ATOMXOR6432:
12540 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12541 X86::XOR32rr, X86::XOR32rr,
12542 X86::XOR32ri, X86::XOR32ri,
12544 case X86::ATOMNAND6432:
12545 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12546 X86::AND32rr, X86::AND32rr,
12547 X86::AND32ri, X86::AND32ri,
12549 case X86::ATOMADD6432:
12550 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12551 X86::ADD32rr, X86::ADC32rr,
12552 X86::ADD32ri, X86::ADC32ri,
12554 case X86::ATOMSUB6432:
12555 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12556 X86::SUB32rr, X86::SBB32rr,
12557 X86::SUB32ri, X86::SBB32ri,
12559 case X86::ATOMSWAP6432:
12560 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12561 X86::MOV32rr, X86::MOV32rr,
12562 X86::MOV32ri, X86::MOV32ri,
12564 case X86::VASTART_SAVE_XMM_REGS:
12565 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12567 case X86::VAARG_64:
12568 return EmitVAARG64WithCustomInserter(MI, BB);
12572 //===----------------------------------------------------------------------===//
12573 // X86 Optimization Hooks
12574 //===----------------------------------------------------------------------===//
12576 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12580 const SelectionDAG &DAG,
12581 unsigned Depth) const {
12582 unsigned Opc = Op.getOpcode();
12583 assert((Opc >= ISD::BUILTIN_OP_END ||
12584 Opc == ISD::INTRINSIC_WO_CHAIN ||
12585 Opc == ISD::INTRINSIC_W_CHAIN ||
12586 Opc == ISD::INTRINSIC_VOID) &&
12587 "Should use MaskedValueIsZero if you don't know whether Op"
12588 " is a target node!");
12590 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12604 // These nodes' second result is a boolean.
12605 if (Op.getResNo() == 0)
12608 case X86ISD::SETCC:
12609 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12610 Mask.getBitWidth() - 1);
12612 case ISD::INTRINSIC_WO_CHAIN: {
12613 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12614 unsigned NumLoBits = 0;
12617 case Intrinsic::x86_sse_movmsk_ps:
12618 case Intrinsic::x86_avx_movmsk_ps_256:
12619 case Intrinsic::x86_sse2_movmsk_pd:
12620 case Intrinsic::x86_avx_movmsk_pd_256:
12621 case Intrinsic::x86_mmx_pmovmskb:
12622 case Intrinsic::x86_sse2_pmovmskb_128: {
12623 // High bits of movmskp{s|d}, pmovmskb are known zero.
12625 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12626 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12627 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12628 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12629 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12630 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12632 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12633 Mask.getBitWidth() - NumLoBits);
12642 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12643 unsigned Depth) const {
12644 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12645 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12646 return Op.getValueType().getScalarType().getSizeInBits();
12652 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12653 /// node is a GlobalAddress + offset.
12654 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12655 const GlobalValue* &GA,
12656 int64_t &Offset) const {
12657 if (N->getOpcode() == X86ISD::Wrapper) {
12658 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12659 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12660 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12664 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12667 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12668 /// same as extracting the high 128-bit part of 256-bit vector and then
12669 /// inserting the result into the low part of a new 256-bit vector
12670 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12671 EVT VT = SVOp->getValueType(0);
12672 int NumElems = VT.getVectorNumElements();
12674 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12675 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12676 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12677 SVOp->getMaskElt(j) >= 0)
12683 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12684 /// same as extracting the low 128-bit part of 256-bit vector and then
12685 /// inserting the result into the high part of a new 256-bit vector
12686 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12687 EVT VT = SVOp->getValueType(0);
12688 int NumElems = VT.getVectorNumElements();
12690 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12691 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12692 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12693 SVOp->getMaskElt(j) >= 0)
12699 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12700 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12701 TargetLowering::DAGCombinerInfo &DCI) {
12702 DebugLoc dl = N->getDebugLoc();
12703 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12704 SDValue V1 = SVOp->getOperand(0);
12705 SDValue V2 = SVOp->getOperand(1);
12706 EVT VT = SVOp->getValueType(0);
12707 int NumElems = VT.getVectorNumElements();
12709 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12710 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12714 // V UNDEF BUILD_VECTOR UNDEF
12716 // CONCAT_VECTOR CONCAT_VECTOR
12719 // RESULT: V + zero extended
12721 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12722 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12723 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12726 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12729 // To match the shuffle mask, the first half of the mask should
12730 // be exactly the first vector, and all the rest a splat with the
12731 // first element of the second one.
12732 for (int i = 0; i < NumElems/2; ++i)
12733 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12734 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12737 // Emit a zeroed vector and insert the desired subvector on its
12739 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12740 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12741 DAG.getConstant(0, MVT::i32), DAG, dl);
12742 return DCI.CombineTo(N, InsV);
12745 //===--------------------------------------------------------------------===//
12746 // Combine some shuffles into subvector extracts and inserts:
12749 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12750 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12751 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12753 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12754 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12755 return DCI.CombineTo(N, InsV);
12758 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12759 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12760 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12761 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12762 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12763 return DCI.CombineTo(N, InsV);
12769 /// PerformShuffleCombine - Performs several different shuffle combines.
12770 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12771 TargetLowering::DAGCombinerInfo &DCI,
12772 const X86Subtarget *Subtarget) {
12773 DebugLoc dl = N->getDebugLoc();
12774 EVT VT = N->getValueType(0);
12776 // Don't create instructions with illegal types after legalize types has run.
12777 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12778 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12781 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12782 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12783 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12784 return PerformShuffleCombine256(N, DAG, DCI);
12786 // Only handle 128 wide vector from here on.
12787 if (VT.getSizeInBits() != 128)
12790 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12791 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12792 // consecutive, non-overlapping, and in the right order.
12793 SmallVector<SDValue, 16> Elts;
12794 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12795 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12797 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12800 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12801 /// generation and convert it from being a bunch of shuffles and extracts
12802 /// to a simple store and scalar loads to extract the elements.
12803 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12804 const TargetLowering &TLI) {
12805 SDValue InputVector = N->getOperand(0);
12807 // Only operate on vectors of 4 elements, where the alternative shuffling
12808 // gets to be more expensive.
12809 if (InputVector.getValueType() != MVT::v4i32)
12812 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12813 // single use which is a sign-extend or zero-extend, and all elements are
12815 SmallVector<SDNode *, 4> Uses;
12816 unsigned ExtractedElements = 0;
12817 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12818 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12819 if (UI.getUse().getResNo() != InputVector.getResNo())
12822 SDNode *Extract = *UI;
12823 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12826 if (Extract->getValueType(0) != MVT::i32)
12828 if (!Extract->hasOneUse())
12830 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12831 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12833 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12836 // Record which element was extracted.
12837 ExtractedElements |=
12838 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12840 Uses.push_back(Extract);
12843 // If not all the elements were used, this may not be worthwhile.
12844 if (ExtractedElements != 15)
12847 // Ok, we've now decided to do the transformation.
12848 DebugLoc dl = InputVector.getDebugLoc();
12850 // Store the value to a temporary stack slot.
12851 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12852 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12853 MachinePointerInfo(), false, false, 0);
12855 // Replace each use (extract) with a load of the appropriate element.
12856 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12857 UE = Uses.end(); UI != UE; ++UI) {
12858 SDNode *Extract = *UI;
12860 // cOMpute the element's address.
12861 SDValue Idx = Extract->getOperand(1);
12863 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12864 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12865 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12867 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12868 StackPtr, OffsetVal);
12870 // Load the scalar.
12871 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12872 ScalarAddr, MachinePointerInfo(),
12873 false, false, false, 0);
12875 // Replace the exact with the load.
12876 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12879 // The replacement was made in place; don't return anything.
12883 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12885 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12886 const X86Subtarget *Subtarget) {
12887 DebugLoc DL = N->getDebugLoc();
12888 SDValue Cond = N->getOperand(0);
12889 // Get the LHS/RHS of the select.
12890 SDValue LHS = N->getOperand(1);
12891 SDValue RHS = N->getOperand(2);
12892 EVT VT = LHS.getValueType();
12894 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12895 // instructions match the semantics of the common C idiom x<y?x:y but not
12896 // x<=y?x:y, because of how they handle negative zero (which can be
12897 // ignored in unsafe-math mode).
12898 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12899 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12900 (Subtarget->hasXMMInt() ||
12901 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12902 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12904 unsigned Opcode = 0;
12905 // Check for x CC y ? x : y.
12906 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12907 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12911 // Converting this to a min would handle NaNs incorrectly, and swapping
12912 // the operands would cause it to handle comparisons between positive
12913 // and negative zero incorrectly.
12914 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12915 if (!UnsafeFPMath &&
12916 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12918 std::swap(LHS, RHS);
12920 Opcode = X86ISD::FMIN;
12923 // Converting this to a min would handle comparisons between positive
12924 // and negative zero incorrectly.
12925 if (!UnsafeFPMath &&
12926 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12928 Opcode = X86ISD::FMIN;
12931 // Converting this to a min would handle both negative zeros and NaNs
12932 // incorrectly, but we can swap the operands to fix both.
12933 std::swap(LHS, RHS);
12937 Opcode = X86ISD::FMIN;
12941 // Converting this to a max would handle comparisons between positive
12942 // and negative zero incorrectly.
12943 if (!UnsafeFPMath &&
12944 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12946 Opcode = X86ISD::FMAX;
12949 // Converting this to a max would handle NaNs incorrectly, and swapping
12950 // the operands would cause it to handle comparisons between positive
12951 // and negative zero incorrectly.
12952 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12953 if (!UnsafeFPMath &&
12954 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12956 std::swap(LHS, RHS);
12958 Opcode = X86ISD::FMAX;
12961 // Converting this to a max would handle both negative zeros and NaNs
12962 // incorrectly, but we can swap the operands to fix both.
12963 std::swap(LHS, RHS);
12967 Opcode = X86ISD::FMAX;
12970 // Check for x CC y ? y : x -- a min/max with reversed arms.
12971 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12972 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12976 // Converting this to a min would handle comparisons between positive
12977 // and negative zero incorrectly, and swapping the operands would
12978 // cause it to handle NaNs incorrectly.
12979 if (!UnsafeFPMath &&
12980 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12981 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12983 std::swap(LHS, RHS);
12985 Opcode = X86ISD::FMIN;
12988 // Converting this to a min would handle NaNs incorrectly.
12989 if (!UnsafeFPMath &&
12990 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12992 Opcode = X86ISD::FMIN;
12995 // Converting this to a min would handle both negative zeros and NaNs
12996 // incorrectly, but we can swap the operands to fix both.
12997 std::swap(LHS, RHS);
13001 Opcode = X86ISD::FMIN;
13005 // Converting this to a max would handle NaNs incorrectly.
13006 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13008 Opcode = X86ISD::FMAX;
13011 // Converting this to a max would handle comparisons between positive
13012 // and negative zero incorrectly, and swapping the operands would
13013 // cause it to handle NaNs incorrectly.
13014 if (!UnsafeFPMath &&
13015 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13016 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13018 std::swap(LHS, RHS);
13020 Opcode = X86ISD::FMAX;
13023 // Converting this to a max would handle both negative zeros and NaNs
13024 // incorrectly, but we can swap the operands to fix both.
13025 std::swap(LHS, RHS);
13029 Opcode = X86ISD::FMAX;
13035 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13038 // If this is a select between two integer constants, try to do some
13040 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13041 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13042 // Don't do this for crazy integer types.
13043 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13044 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13045 // so that TrueC (the true value) is larger than FalseC.
13046 bool NeedsCondInvert = false;
13048 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13049 // Efficiently invertible.
13050 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13051 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13052 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13053 NeedsCondInvert = true;
13054 std::swap(TrueC, FalseC);
13057 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13058 if (FalseC->getAPIntValue() == 0 &&
13059 TrueC->getAPIntValue().isPowerOf2()) {
13060 if (NeedsCondInvert) // Invert the condition if needed.
13061 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13062 DAG.getConstant(1, Cond.getValueType()));
13064 // Zero extend the condition if needed.
13065 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13067 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13068 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13069 DAG.getConstant(ShAmt, MVT::i8));
13072 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13073 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13074 if (NeedsCondInvert) // Invert the condition if needed.
13075 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13076 DAG.getConstant(1, Cond.getValueType()));
13078 // Zero extend the condition if needed.
13079 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13080 FalseC->getValueType(0), Cond);
13081 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13082 SDValue(FalseC, 0));
13085 // Optimize cases that will turn into an LEA instruction. This requires
13086 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13087 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13088 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13089 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13091 bool isFastMultiplier = false;
13093 switch ((unsigned char)Diff) {
13095 case 1: // result = add base, cond
13096 case 2: // result = lea base( , cond*2)
13097 case 3: // result = lea base(cond, cond*2)
13098 case 4: // result = lea base( , cond*4)
13099 case 5: // result = lea base(cond, cond*4)
13100 case 8: // result = lea base( , cond*8)
13101 case 9: // result = lea base(cond, cond*8)
13102 isFastMultiplier = true;
13107 if (isFastMultiplier) {
13108 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13109 if (NeedsCondInvert) // Invert the condition if needed.
13110 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13111 DAG.getConstant(1, Cond.getValueType()));
13113 // Zero extend the condition if needed.
13114 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13116 // Scale the condition by the difference.
13118 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13119 DAG.getConstant(Diff, Cond.getValueType()));
13121 // Add the base if non-zero.
13122 if (FalseC->getAPIntValue() != 0)
13123 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13124 SDValue(FalseC, 0));
13134 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13135 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13136 TargetLowering::DAGCombinerInfo &DCI) {
13137 DebugLoc DL = N->getDebugLoc();
13139 // If the flag operand isn't dead, don't touch this CMOV.
13140 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13143 SDValue FalseOp = N->getOperand(0);
13144 SDValue TrueOp = N->getOperand(1);
13145 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13146 SDValue Cond = N->getOperand(3);
13147 if (CC == X86::COND_E || CC == X86::COND_NE) {
13148 switch (Cond.getOpcode()) {
13152 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13153 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13154 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13158 // If this is a select between two integer constants, try to do some
13159 // optimizations. Note that the operands are ordered the opposite of SELECT
13161 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13162 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13163 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13164 // larger than FalseC (the false value).
13165 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13166 CC = X86::GetOppositeBranchCondition(CC);
13167 std::swap(TrueC, FalseC);
13170 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13171 // This is efficient for any integer data type (including i8/i16) and
13173 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13174 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13175 DAG.getConstant(CC, MVT::i8), Cond);
13177 // Zero extend the condition if needed.
13178 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13180 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13181 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13182 DAG.getConstant(ShAmt, MVT::i8));
13183 if (N->getNumValues() == 2) // Dead flag value?
13184 return DCI.CombineTo(N, Cond, SDValue());
13188 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13189 // for any integer data type, including i8/i16.
13190 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13191 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13192 DAG.getConstant(CC, MVT::i8), Cond);
13194 // Zero extend the condition if needed.
13195 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13196 FalseC->getValueType(0), Cond);
13197 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13198 SDValue(FalseC, 0));
13200 if (N->getNumValues() == 2) // Dead flag value?
13201 return DCI.CombineTo(N, Cond, SDValue());
13205 // Optimize cases that will turn into an LEA instruction. This requires
13206 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13207 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13208 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13209 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13211 bool isFastMultiplier = false;
13213 switch ((unsigned char)Diff) {
13215 case 1: // result = add base, cond
13216 case 2: // result = lea base( , cond*2)
13217 case 3: // result = lea base(cond, cond*2)
13218 case 4: // result = lea base( , cond*4)
13219 case 5: // result = lea base(cond, cond*4)
13220 case 8: // result = lea base( , cond*8)
13221 case 9: // result = lea base(cond, cond*8)
13222 isFastMultiplier = true;
13227 if (isFastMultiplier) {
13228 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13229 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13230 DAG.getConstant(CC, MVT::i8), Cond);
13231 // Zero extend the condition if needed.
13232 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13234 // Scale the condition by the difference.
13236 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13237 DAG.getConstant(Diff, Cond.getValueType()));
13239 // Add the base if non-zero.
13240 if (FalseC->getAPIntValue() != 0)
13241 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13242 SDValue(FalseC, 0));
13243 if (N->getNumValues() == 2) // Dead flag value?
13244 return DCI.CombineTo(N, Cond, SDValue());
13254 /// PerformMulCombine - Optimize a single multiply with constant into two
13255 /// in order to implement it with two cheaper instructions, e.g.
13256 /// LEA + SHL, LEA + LEA.
13257 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13258 TargetLowering::DAGCombinerInfo &DCI) {
13259 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13262 EVT VT = N->getValueType(0);
13263 if (VT != MVT::i64)
13266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13269 uint64_t MulAmt = C->getZExtValue();
13270 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13273 uint64_t MulAmt1 = 0;
13274 uint64_t MulAmt2 = 0;
13275 if ((MulAmt % 9) == 0) {
13277 MulAmt2 = MulAmt / 9;
13278 } else if ((MulAmt % 5) == 0) {
13280 MulAmt2 = MulAmt / 5;
13281 } else if ((MulAmt % 3) == 0) {
13283 MulAmt2 = MulAmt / 3;
13286 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13287 DebugLoc DL = N->getDebugLoc();
13289 if (isPowerOf2_64(MulAmt2) &&
13290 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13291 // If second multiplifer is pow2, issue it first. We want the multiply by
13292 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13294 std::swap(MulAmt1, MulAmt2);
13297 if (isPowerOf2_64(MulAmt1))
13298 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13299 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13301 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13302 DAG.getConstant(MulAmt1, VT));
13304 if (isPowerOf2_64(MulAmt2))
13305 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13306 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13308 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13309 DAG.getConstant(MulAmt2, VT));
13311 // Do not add new nodes to DAG combiner worklist.
13312 DCI.CombineTo(N, NewMul, false);
13317 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13318 SDValue N0 = N->getOperand(0);
13319 SDValue N1 = N->getOperand(1);
13320 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13321 EVT VT = N0.getValueType();
13323 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13324 // since the result of setcc_c is all zero's or all ones.
13325 if (VT.isInteger() && !VT.isVector() &&
13326 N1C && N0.getOpcode() == ISD::AND &&
13327 N0.getOperand(1).getOpcode() == ISD::Constant) {
13328 SDValue N00 = N0.getOperand(0);
13329 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13330 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13331 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13332 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13333 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13334 APInt ShAmt = N1C->getAPIntValue();
13335 Mask = Mask.shl(ShAmt);
13337 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13338 N00, DAG.getConstant(Mask, VT));
13343 // Hardware support for vector shifts is sparse which makes us scalarize the
13344 // vector operations in many cases. Also, on sandybridge ADD is faster than
13346 // (shl V, 1) -> add V,V
13347 if (isSplatVector(N1.getNode())) {
13348 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13349 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13350 // We shift all of the values by one. In many cases we do not have
13351 // hardware support for this operation. This is better expressed as an ADD
13353 if (N1C && (1 == N1C->getZExtValue())) {
13354 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13361 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13363 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13364 const X86Subtarget *Subtarget) {
13365 EVT VT = N->getValueType(0);
13366 if (N->getOpcode() == ISD::SHL) {
13367 SDValue V = PerformSHLCombine(N, DAG);
13368 if (V.getNode()) return V;
13371 // On X86 with SSE2 support, we can transform this to a vector shift if
13372 // all elements are shifted by the same amount. We can't do this in legalize
13373 // because the a constant vector is typically transformed to a constant pool
13374 // so we have no knowledge of the shift amount.
13375 if (!Subtarget->hasXMMInt())
13378 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13381 SDValue ShAmtOp = N->getOperand(1);
13382 EVT EltVT = VT.getVectorElementType();
13383 DebugLoc DL = N->getDebugLoc();
13384 SDValue BaseShAmt = SDValue();
13385 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13386 unsigned NumElts = VT.getVectorNumElements();
13388 for (; i != NumElts; ++i) {
13389 SDValue Arg = ShAmtOp.getOperand(i);
13390 if (Arg.getOpcode() == ISD::UNDEF) continue;
13394 for (; i != NumElts; ++i) {
13395 SDValue Arg = ShAmtOp.getOperand(i);
13396 if (Arg.getOpcode() == ISD::UNDEF) continue;
13397 if (Arg != BaseShAmt) {
13401 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13402 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13403 SDValue InVec = ShAmtOp.getOperand(0);
13404 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13405 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13407 for (; i != NumElts; ++i) {
13408 SDValue Arg = InVec.getOperand(i);
13409 if (Arg.getOpcode() == ISD::UNDEF) continue;
13413 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13415 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13416 if (C->getZExtValue() == SplatIdx)
13417 BaseShAmt = InVec.getOperand(1);
13420 if (BaseShAmt.getNode() == 0)
13421 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13422 DAG.getIntPtrConstant(0));
13426 // The shift amount is an i32.
13427 if (EltVT.bitsGT(MVT::i32))
13428 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13429 else if (EltVT.bitsLT(MVT::i32))
13430 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13432 // The shift amount is identical so we can do a vector shift.
13433 SDValue ValOp = N->getOperand(0);
13434 switch (N->getOpcode()) {
13436 llvm_unreachable("Unknown shift opcode!");
13439 if (VT == MVT::v2i64)
13440 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13441 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13443 if (VT == MVT::v4i32)
13444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13445 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13447 if (VT == MVT::v8i16)
13448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13449 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13453 if (VT == MVT::v4i32)
13454 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13455 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13457 if (VT == MVT::v8i16)
13458 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13459 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13463 if (VT == MVT::v2i64)
13464 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13465 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13467 if (VT == MVT::v4i32)
13468 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13469 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13471 if (VT == MVT::v8i16)
13472 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13473 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13481 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13482 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13483 // and friends. Likewise for OR -> CMPNEQSS.
13484 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13485 TargetLowering::DAGCombinerInfo &DCI,
13486 const X86Subtarget *Subtarget) {
13489 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13490 // we're requiring SSE2 for both.
13491 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13492 SDValue N0 = N->getOperand(0);
13493 SDValue N1 = N->getOperand(1);
13494 SDValue CMP0 = N0->getOperand(1);
13495 SDValue CMP1 = N1->getOperand(1);
13496 DebugLoc DL = N->getDebugLoc();
13498 // The SETCCs should both refer to the same CMP.
13499 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13502 SDValue CMP00 = CMP0->getOperand(0);
13503 SDValue CMP01 = CMP0->getOperand(1);
13504 EVT VT = CMP00.getValueType();
13506 if (VT == MVT::f32 || VT == MVT::f64) {
13507 bool ExpectingFlags = false;
13508 // Check for any users that want flags:
13509 for (SDNode::use_iterator UI = N->use_begin(),
13511 !ExpectingFlags && UI != UE; ++UI)
13512 switch (UI->getOpcode()) {
13517 ExpectingFlags = true;
13519 case ISD::CopyToReg:
13520 case ISD::SIGN_EXTEND:
13521 case ISD::ZERO_EXTEND:
13522 case ISD::ANY_EXTEND:
13526 if (!ExpectingFlags) {
13527 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13528 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13530 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13531 X86::CondCode tmp = cc0;
13536 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13537 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13538 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13539 X86ISD::NodeType NTOperator = is64BitFP ?
13540 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13541 // FIXME: need symbolic constants for these magic numbers.
13542 // See X86ATTInstPrinter.cpp:printSSECC().
13543 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13544 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13545 DAG.getConstant(x86cc, MVT::i8));
13546 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13548 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13549 DAG.getConstant(1, MVT::i32));
13550 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13551 return OneBitOfTruth;
13559 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13560 /// so it can be folded inside ANDNP.
13561 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13562 EVT VT = N->getValueType(0);
13564 // Match direct AllOnes for 128 and 256-bit vectors
13565 if (ISD::isBuildVectorAllOnes(N))
13568 // Look through a bit convert.
13569 if (N->getOpcode() == ISD::BITCAST)
13570 N = N->getOperand(0).getNode();
13572 // Sometimes the operand may come from a insert_subvector building a 256-bit
13574 if (VT.getSizeInBits() == 256 &&
13575 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13576 SDValue V1 = N->getOperand(0);
13577 SDValue V2 = N->getOperand(1);
13579 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13580 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13581 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13582 ISD::isBuildVectorAllOnes(V2.getNode()))
13589 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13590 TargetLowering::DAGCombinerInfo &DCI,
13591 const X86Subtarget *Subtarget) {
13592 if (DCI.isBeforeLegalizeOps())
13595 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13599 EVT VT = N->getValueType(0);
13601 // Create ANDN, BLSI, and BLSR instructions
13602 // BLSI is X & (-X)
13603 // BLSR is X & (X-1)
13604 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13605 SDValue N0 = N->getOperand(0);
13606 SDValue N1 = N->getOperand(1);
13607 DebugLoc DL = N->getDebugLoc();
13609 // Check LHS for not
13610 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13611 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13612 // Check RHS for not
13613 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13614 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13616 // Check LHS for neg
13617 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13618 isZero(N0.getOperand(0)))
13619 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13621 // Check RHS for neg
13622 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13623 isZero(N1.getOperand(0)))
13624 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13626 // Check LHS for X-1
13627 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13628 isAllOnes(N0.getOperand(1)))
13629 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13631 // Check RHS for X-1
13632 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13633 isAllOnes(N1.getOperand(1)))
13634 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13639 // Want to form ANDNP nodes:
13640 // 1) In the hopes of then easily combining them with OR and AND nodes
13641 // to form PBLEND/PSIGN.
13642 // 2) To match ANDN packed intrinsics
13643 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13646 SDValue N0 = N->getOperand(0);
13647 SDValue N1 = N->getOperand(1);
13648 DebugLoc DL = N->getDebugLoc();
13650 // Check LHS for vnot
13651 if (N0.getOpcode() == ISD::XOR &&
13652 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13653 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13654 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13656 // Check RHS for vnot
13657 if (N1.getOpcode() == ISD::XOR &&
13658 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13659 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13660 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13665 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13666 TargetLowering::DAGCombinerInfo &DCI,
13667 const X86Subtarget *Subtarget) {
13668 if (DCI.isBeforeLegalizeOps())
13671 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13675 EVT VT = N->getValueType(0);
13676 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13679 SDValue N0 = N->getOperand(0);
13680 SDValue N1 = N->getOperand(1);
13682 // look for psign/blend
13683 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13684 if (VT == MVT::v2i64) {
13685 // Canonicalize pandn to RHS
13686 if (N0.getOpcode() == X86ISD::ANDNP)
13688 // or (and (m, x), (pandn m, y))
13689 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13690 SDValue Mask = N1.getOperand(0);
13691 SDValue X = N1.getOperand(1);
13693 if (N0.getOperand(0) == Mask)
13694 Y = N0.getOperand(1);
13695 if (N0.getOperand(1) == Mask)
13696 Y = N0.getOperand(0);
13698 // Check to see if the mask appeared in both the AND and ANDNP and
13702 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13703 if (Mask.getOpcode() != ISD::BITCAST ||
13704 X.getOpcode() != ISD::BITCAST ||
13705 Y.getOpcode() != ISD::BITCAST)
13708 // Look through mask bitcast.
13709 Mask = Mask.getOperand(0);
13710 EVT MaskVT = Mask.getValueType();
13712 // Validate that the Mask operand is a vector sra node. The sra node
13713 // will be an intrinsic.
13714 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13717 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13718 // there is no psrai.b
13719 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13720 case Intrinsic::x86_sse2_psrai_w:
13721 case Intrinsic::x86_sse2_psrai_d:
13723 default: return SDValue();
13726 // Check that the SRA is all signbits.
13727 SDValue SraC = Mask.getOperand(2);
13728 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13729 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13730 if ((SraAmt + 1) != EltBits)
13733 DebugLoc DL = N->getDebugLoc();
13735 // Now we know we at least have a plendvb with the mask val. See if
13736 // we can form a psignb/w/d.
13737 // psign = x.type == y.type == mask.type && y = sub(0, x);
13738 X = X.getOperand(0);
13739 Y = Y.getOperand(0);
13740 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13741 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13742 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13745 case 8: Opc = X86ISD::PSIGNB; break;
13746 case 16: Opc = X86ISD::PSIGNW; break;
13747 case 32: Opc = X86ISD::PSIGND; break;
13751 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13752 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13755 // PBLENDVB only available on SSE 4.1
13756 if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13759 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13760 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13761 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13762 Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13763 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13768 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13769 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13771 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13773 if (!N0.hasOneUse() || !N1.hasOneUse())
13776 SDValue ShAmt0 = N0.getOperand(1);
13777 if (ShAmt0.getValueType() != MVT::i8)
13779 SDValue ShAmt1 = N1.getOperand(1);
13780 if (ShAmt1.getValueType() != MVT::i8)
13782 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13783 ShAmt0 = ShAmt0.getOperand(0);
13784 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13785 ShAmt1 = ShAmt1.getOperand(0);
13787 DebugLoc DL = N->getDebugLoc();
13788 unsigned Opc = X86ISD::SHLD;
13789 SDValue Op0 = N0.getOperand(0);
13790 SDValue Op1 = N1.getOperand(0);
13791 if (ShAmt0.getOpcode() == ISD::SUB) {
13792 Opc = X86ISD::SHRD;
13793 std::swap(Op0, Op1);
13794 std::swap(ShAmt0, ShAmt1);
13797 unsigned Bits = VT.getSizeInBits();
13798 if (ShAmt1.getOpcode() == ISD::SUB) {
13799 SDValue Sum = ShAmt1.getOperand(0);
13800 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13801 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13802 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13803 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13804 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13805 return DAG.getNode(Opc, DL, VT,
13807 DAG.getNode(ISD::TRUNCATE, DL,
13810 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13811 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13813 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13814 return DAG.getNode(Opc, DL, VT,
13815 N0.getOperand(0), N1.getOperand(0),
13816 DAG.getNode(ISD::TRUNCATE, DL,
13823 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13824 TargetLowering::DAGCombinerInfo &DCI,
13825 const X86Subtarget *Subtarget) {
13826 if (DCI.isBeforeLegalizeOps())
13829 EVT VT = N->getValueType(0);
13831 if (VT != MVT::i32 && VT != MVT::i64)
13834 // Create BLSMSK instructions by finding X ^ (X-1)
13835 SDValue N0 = N->getOperand(0);
13836 SDValue N1 = N->getOperand(1);
13837 DebugLoc DL = N->getDebugLoc();
13839 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13840 isAllOnes(N0.getOperand(1)))
13841 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13843 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13844 isAllOnes(N1.getOperand(1)))
13845 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13850 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13851 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13852 const X86Subtarget *Subtarget) {
13853 LoadSDNode *Ld = cast<LoadSDNode>(N);
13854 EVT RegVT = Ld->getValueType(0);
13855 EVT MemVT = Ld->getMemoryVT();
13856 DebugLoc dl = Ld->getDebugLoc();
13857 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13859 ISD::LoadExtType Ext = Ld->getExtensionType();
13861 // If this is a vector EXT Load then attempt to optimize it using a
13862 // shuffle. We need SSE4 for the shuffles.
13863 // TODO: It is possible to support ZExt by zeroing the undef values
13864 // during the shuffle phase or after the shuffle.
13865 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13866 assert(MemVT != RegVT && "Cannot extend to the same type");
13867 assert(MemVT.isVector() && "Must load a vector from memory");
13869 unsigned NumElems = RegVT.getVectorNumElements();
13870 unsigned RegSz = RegVT.getSizeInBits();
13871 unsigned MemSz = MemVT.getSizeInBits();
13872 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13873 // All sizes must be a power of two
13874 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13876 // Attempt to load the original value using a single load op.
13877 // Find a scalar type which is equal to the loaded word size.
13878 MVT SclrLoadTy = MVT::i8;
13879 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13880 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13881 MVT Tp = (MVT::SimpleValueType)tp;
13882 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13888 // Proceed if a load word is found.
13889 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13891 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13892 RegSz/SclrLoadTy.getSizeInBits());
13894 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13895 RegSz/MemVT.getScalarType().getSizeInBits());
13896 // Can't shuffle using an illegal type.
13897 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13899 // Perform a single load.
13900 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13902 Ld->getPointerInfo(), Ld->isVolatile(),
13903 Ld->isNonTemporal(), Ld->isInvariant(),
13904 Ld->getAlignment());
13906 // Insert the word loaded into a vector.
13907 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13908 LoadUnitVecVT, ScalarLoad);
13910 // Bitcast the loaded value to a vector of the original element type, in
13911 // the size of the target vector type.
13912 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13913 unsigned SizeRatio = RegSz/MemSz;
13915 // Redistribute the loaded elements into the different locations.
13916 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13917 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13919 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13920 DAG.getUNDEF(SlicedVec.getValueType()),
13921 ShuffleVec.data());
13923 // Bitcast to the requested type.
13924 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13925 // Replace the original load with the new sequence
13926 // and return the new chain.
13927 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13928 return SDValue(ScalarLoad.getNode(), 1);
13934 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13935 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13936 const X86Subtarget *Subtarget) {
13937 StoreSDNode *St = cast<StoreSDNode>(N);
13938 EVT VT = St->getValue().getValueType();
13939 EVT StVT = St->getMemoryVT();
13940 DebugLoc dl = St->getDebugLoc();
13941 SDValue StoredVal = St->getOperand(1);
13942 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13944 // If we are saving a concatination of two XMM registers, perform two stores.
13945 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13946 // 128-bit ones. If in the future the cost becomes only one memory access the
13947 // first version would be better.
13948 if (VT.getSizeInBits() == 256 &&
13949 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13950 StoredVal.getNumOperands() == 2) {
13952 SDValue Value0 = StoredVal.getOperand(0);
13953 SDValue Value1 = StoredVal.getOperand(1);
13955 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13956 SDValue Ptr0 = St->getBasePtr();
13957 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13959 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13960 St->getPointerInfo(), St->isVolatile(),
13961 St->isNonTemporal(), St->getAlignment());
13962 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13963 St->getPointerInfo(), St->isVolatile(),
13964 St->isNonTemporal(), St->getAlignment());
13965 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13968 // Optimize trunc store (of multiple scalars) to shuffle and store.
13969 // First, pack all of the elements in one place. Next, store to memory
13970 // in fewer chunks.
13971 if (St->isTruncatingStore() && VT.isVector()) {
13972 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13973 unsigned NumElems = VT.getVectorNumElements();
13974 assert(StVT != VT && "Cannot truncate to the same type");
13975 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13976 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13978 // From, To sizes and ElemCount must be pow of two
13979 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13980 // We are going to use the original vector elt for storing.
13981 // Accumulated smaller vector elements must be a multiple of the store size.
13982 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13984 unsigned SizeRatio = FromSz / ToSz;
13986 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13988 // Create a type on which we perform the shuffle
13989 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13990 StVT.getScalarType(), NumElems*SizeRatio);
13992 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13994 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13995 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13996 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13998 // Can't shuffle using an illegal type
13999 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14001 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14002 DAG.getUNDEF(WideVec.getValueType()),
14003 ShuffleVec.data());
14004 // At this point all of the data is stored at the bottom of the
14005 // register. We now need to save it to mem.
14007 // Find the largest store unit
14008 MVT StoreType = MVT::i8;
14009 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14010 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14011 MVT Tp = (MVT::SimpleValueType)tp;
14012 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14016 // Bitcast the original vector into a vector of store-size units
14017 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14018 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14019 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14020 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14021 SmallVector<SDValue, 8> Chains;
14022 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14023 TLI.getPointerTy());
14024 SDValue Ptr = St->getBasePtr();
14026 // Perform one or more big stores into memory.
14027 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14028 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14029 StoreType, ShuffWide,
14030 DAG.getIntPtrConstant(i));
14031 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14032 St->getPointerInfo(), St->isVolatile(),
14033 St->isNonTemporal(), St->getAlignment());
14034 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14035 Chains.push_back(Ch);
14038 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14043 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14044 // the FP state in cases where an emms may be missing.
14045 // A preferable solution to the general problem is to figure out the right
14046 // places to insert EMMS. This qualifies as a quick hack.
14048 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14049 if (VT.getSizeInBits() != 64)
14052 const Function *F = DAG.getMachineFunction().getFunction();
14053 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14054 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14055 && Subtarget->hasXMMInt();
14056 if ((VT.isVector() ||
14057 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14058 isa<LoadSDNode>(St->getValue()) &&
14059 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14060 St->getChain().hasOneUse() && !St->isVolatile()) {
14061 SDNode* LdVal = St->getValue().getNode();
14062 LoadSDNode *Ld = 0;
14063 int TokenFactorIndex = -1;
14064 SmallVector<SDValue, 8> Ops;
14065 SDNode* ChainVal = St->getChain().getNode();
14066 // Must be a store of a load. We currently handle two cases: the load
14067 // is a direct child, and it's under an intervening TokenFactor. It is
14068 // possible to dig deeper under nested TokenFactors.
14069 if (ChainVal == LdVal)
14070 Ld = cast<LoadSDNode>(St->getChain());
14071 else if (St->getValue().hasOneUse() &&
14072 ChainVal->getOpcode() == ISD::TokenFactor) {
14073 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14074 if (ChainVal->getOperand(i).getNode() == LdVal) {
14075 TokenFactorIndex = i;
14076 Ld = cast<LoadSDNode>(St->getValue());
14078 Ops.push_back(ChainVal->getOperand(i));
14082 if (!Ld || !ISD::isNormalLoad(Ld))
14085 // If this is not the MMX case, i.e. we are just turning i64 load/store
14086 // into f64 load/store, avoid the transformation if there are multiple
14087 // uses of the loaded value.
14088 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14091 DebugLoc LdDL = Ld->getDebugLoc();
14092 DebugLoc StDL = N->getDebugLoc();
14093 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14094 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14096 if (Subtarget->is64Bit() || F64IsLegal) {
14097 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14098 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14099 Ld->getPointerInfo(), Ld->isVolatile(),
14100 Ld->isNonTemporal(), Ld->isInvariant(),
14101 Ld->getAlignment());
14102 SDValue NewChain = NewLd.getValue(1);
14103 if (TokenFactorIndex != -1) {
14104 Ops.push_back(NewChain);
14105 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14108 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14109 St->getPointerInfo(),
14110 St->isVolatile(), St->isNonTemporal(),
14111 St->getAlignment());
14114 // Otherwise, lower to two pairs of 32-bit loads / stores.
14115 SDValue LoAddr = Ld->getBasePtr();
14116 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14117 DAG.getConstant(4, MVT::i32));
14119 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14120 Ld->getPointerInfo(),
14121 Ld->isVolatile(), Ld->isNonTemporal(),
14122 Ld->isInvariant(), Ld->getAlignment());
14123 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14124 Ld->getPointerInfo().getWithOffset(4),
14125 Ld->isVolatile(), Ld->isNonTemporal(),
14127 MinAlign(Ld->getAlignment(), 4));
14129 SDValue NewChain = LoLd.getValue(1);
14130 if (TokenFactorIndex != -1) {
14131 Ops.push_back(LoLd);
14132 Ops.push_back(HiLd);
14133 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14137 LoAddr = St->getBasePtr();
14138 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14139 DAG.getConstant(4, MVT::i32));
14141 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14142 St->getPointerInfo(),
14143 St->isVolatile(), St->isNonTemporal(),
14144 St->getAlignment());
14145 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14146 St->getPointerInfo().getWithOffset(4),
14148 St->isNonTemporal(),
14149 MinAlign(St->getAlignment(), 4));
14150 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14155 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14156 /// and return the operands for the horizontal operation in LHS and RHS. A
14157 /// horizontal operation performs the binary operation on successive elements
14158 /// of its first operand, then on successive elements of its second operand,
14159 /// returning the resulting values in a vector. For example, if
14160 /// A = < float a0, float a1, float a2, float a3 >
14162 /// B = < float b0, float b1, float b2, float b3 >
14163 /// then the result of doing a horizontal operation on A and B is
14164 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14165 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14166 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14167 /// set to A, RHS to B, and the routine returns 'true'.
14168 /// Note that the binary operation should have the property that if one of the
14169 /// operands is UNDEF then the result is UNDEF.
14170 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14171 // Look for the following pattern: if
14172 // A = < float a0, float a1, float a2, float a3 >
14173 // B = < float b0, float b1, float b2, float b3 >
14175 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14176 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14177 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14178 // which is A horizontal-op B.
14180 // At least one of the operands should be a vector shuffle.
14181 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14182 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14185 EVT VT = LHS.getValueType();
14186 unsigned N = VT.getVectorNumElements();
14188 // View LHS in the form
14189 // LHS = VECTOR_SHUFFLE A, B, LMask
14190 // If LHS is not a shuffle then pretend it is the shuffle
14191 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14192 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14195 SmallVector<int, 8> LMask(N);
14196 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14197 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14198 A = LHS.getOperand(0);
14199 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14200 B = LHS.getOperand(1);
14201 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14203 if (LHS.getOpcode() != ISD::UNDEF)
14205 for (unsigned i = 0; i != N; ++i)
14209 // Likewise, view RHS in the form
14210 // RHS = VECTOR_SHUFFLE C, D, RMask
14212 SmallVector<int, 8> RMask(N);
14213 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14214 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14215 C = RHS.getOperand(0);
14216 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14217 D = RHS.getOperand(1);
14218 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14220 if (RHS.getOpcode() != ISD::UNDEF)
14222 for (unsigned i = 0; i != N; ++i)
14226 // Check that the shuffles are both shuffling the same vectors.
14227 if (!(A == C && B == D) && !(A == D && B == C))
14230 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14231 if (!A.getNode() && !B.getNode())
14234 // If A and B occur in reverse order in RHS, then "swap" them (which means
14235 // rewriting the mask).
14237 for (unsigned i = 0; i != N; ++i) {
14238 unsigned Idx = RMask[i];
14241 else if (Idx < 2*N)
14245 // At this point LHS and RHS are equivalent to
14246 // LHS = VECTOR_SHUFFLE A, B, LMask
14247 // RHS = VECTOR_SHUFFLE A, B, RMask
14248 // Check that the masks correspond to performing a horizontal operation.
14249 for (unsigned i = 0; i != N; ++i) {
14250 unsigned LIdx = LMask[i], RIdx = RMask[i];
14252 // Ignore any UNDEF components.
14253 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14254 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14257 // Check that successive elements are being operated on. If not, this is
14258 // not a horizontal operation.
14259 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14260 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14264 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14265 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14269 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14270 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14271 const X86Subtarget *Subtarget) {
14272 EVT VT = N->getValueType(0);
14273 SDValue LHS = N->getOperand(0);
14274 SDValue RHS = N->getOperand(1);
14276 // Try to synthesize horizontal adds from adds of shuffles.
14277 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14278 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14279 isHorizontalBinOp(LHS, RHS, true))
14280 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14284 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14285 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14286 const X86Subtarget *Subtarget) {
14287 EVT VT = N->getValueType(0);
14288 SDValue LHS = N->getOperand(0);
14289 SDValue RHS = N->getOperand(1);
14291 // Try to synthesize horizontal subs from subs of shuffles.
14292 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14293 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14294 isHorizontalBinOp(LHS, RHS, false))
14295 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14299 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14300 /// X86ISD::FXOR nodes.
14301 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14302 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14303 // F[X]OR(0.0, x) -> x
14304 // F[X]OR(x, 0.0) -> x
14305 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14306 if (C->getValueAPF().isPosZero())
14307 return N->getOperand(1);
14308 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14309 if (C->getValueAPF().isPosZero())
14310 return N->getOperand(0);
14314 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14315 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14316 // FAND(0.0, x) -> 0.0
14317 // FAND(x, 0.0) -> 0.0
14318 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14319 if (C->getValueAPF().isPosZero())
14320 return N->getOperand(0);
14321 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14322 if (C->getValueAPF().isPosZero())
14323 return N->getOperand(1);
14327 static SDValue PerformBTCombine(SDNode *N,
14329 TargetLowering::DAGCombinerInfo &DCI) {
14330 // BT ignores high bits in the bit index operand.
14331 SDValue Op1 = N->getOperand(1);
14332 if (Op1.hasOneUse()) {
14333 unsigned BitWidth = Op1.getValueSizeInBits();
14334 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14335 APInt KnownZero, KnownOne;
14336 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14337 !DCI.isBeforeLegalizeOps());
14338 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14339 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14340 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14341 DCI.CommitTargetLoweringOpt(TLO);
14346 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14347 SDValue Op = N->getOperand(0);
14348 if (Op.getOpcode() == ISD::BITCAST)
14349 Op = Op.getOperand(0);
14350 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14351 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14352 VT.getVectorElementType().getSizeInBits() ==
14353 OpVT.getVectorElementType().getSizeInBits()) {
14354 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14359 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14360 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14361 // (and (i32 x86isd::setcc_carry), 1)
14362 // This eliminates the zext. This transformation is necessary because
14363 // ISD::SETCC is always legalized to i8.
14364 DebugLoc dl = N->getDebugLoc();
14365 SDValue N0 = N->getOperand(0);
14366 EVT VT = N->getValueType(0);
14367 if (N0.getOpcode() == ISD::AND &&
14369 N0.getOperand(0).hasOneUse()) {
14370 SDValue N00 = N0.getOperand(0);
14371 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14373 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14374 if (!C || C->getZExtValue() != 1)
14376 return DAG.getNode(ISD::AND, dl, VT,
14377 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14378 N00.getOperand(0), N00.getOperand(1)),
14379 DAG.getConstant(1, VT));
14385 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14386 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14387 unsigned X86CC = N->getConstantOperandVal(0);
14388 SDValue EFLAG = N->getOperand(1);
14389 DebugLoc DL = N->getDebugLoc();
14391 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14392 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14394 if (X86CC == X86::COND_B)
14395 return DAG.getNode(ISD::AND, DL, MVT::i8,
14396 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14397 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14398 DAG.getConstant(1, MVT::i8));
14403 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14404 const X86TargetLowering *XTLI) {
14405 SDValue Op0 = N->getOperand(0);
14406 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14407 // a 32-bit target where SSE doesn't support i64->FP operations.
14408 if (Op0.getOpcode() == ISD::LOAD) {
14409 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14410 EVT VT = Ld->getValueType(0);
14411 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14412 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14413 !XTLI->getSubtarget()->is64Bit() &&
14414 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14415 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14416 Ld->getChain(), Op0, DAG);
14417 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14424 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14425 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14426 X86TargetLowering::DAGCombinerInfo &DCI) {
14427 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14428 // the result is either zero or one (depending on the input carry bit).
14429 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14430 if (X86::isZeroNode(N->getOperand(0)) &&
14431 X86::isZeroNode(N->getOperand(1)) &&
14432 // We don't have a good way to replace an EFLAGS use, so only do this when
14434 SDValue(N, 1).use_empty()) {
14435 DebugLoc DL = N->getDebugLoc();
14436 EVT VT = N->getValueType(0);
14437 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14438 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14439 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14440 DAG.getConstant(X86::COND_B,MVT::i8),
14442 DAG.getConstant(1, VT));
14443 return DCI.CombineTo(N, Res1, CarryOut);
14449 // fold (add Y, (sete X, 0)) -> adc 0, Y
14450 // (add Y, (setne X, 0)) -> sbb -1, Y
14451 // (sub (sete X, 0), Y) -> sbb 0, Y
14452 // (sub (setne X, 0), Y) -> adc -1, Y
14453 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14454 DebugLoc DL = N->getDebugLoc();
14456 // Look through ZExts.
14457 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14458 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14461 SDValue SetCC = Ext.getOperand(0);
14462 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14465 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14466 if (CC != X86::COND_E && CC != X86::COND_NE)
14469 SDValue Cmp = SetCC.getOperand(1);
14470 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14471 !X86::isZeroNode(Cmp.getOperand(1)) ||
14472 !Cmp.getOperand(0).getValueType().isInteger())
14475 SDValue CmpOp0 = Cmp.getOperand(0);
14476 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14477 DAG.getConstant(1, CmpOp0.getValueType()));
14479 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14480 if (CC == X86::COND_NE)
14481 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14482 DL, OtherVal.getValueType(), OtherVal,
14483 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14484 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14485 DL, OtherVal.getValueType(), OtherVal,
14486 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14489 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14490 SDValue Op0 = N->getOperand(0);
14491 SDValue Op1 = N->getOperand(1);
14493 // X86 can't encode an immediate LHS of a sub. See if we can push the
14494 // negation into a preceding instruction.
14495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14496 // If the RHS of the sub is a XOR with one use and a constant, invert the
14497 // immediate. Then add one to the LHS of the sub so we can turn
14498 // X-Y -> X+~Y+1, saving one register.
14499 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14500 isa<ConstantSDNode>(Op1.getOperand(1))) {
14501 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14502 EVT VT = Op0.getValueType();
14503 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14505 DAG.getConstant(~XorC, VT));
14506 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14507 DAG.getConstant(C->getAPIntValue()+1, VT));
14511 return OptimizeConditionalInDecrement(N, DAG);
14514 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14515 DAGCombinerInfo &DCI) const {
14516 SelectionDAG &DAG = DCI.DAG;
14517 switch (N->getOpcode()) {
14519 case ISD::EXTRACT_VECTOR_ELT:
14520 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14522 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14523 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14524 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
14525 case ISD::SUB: return PerformSubCombine(N, DAG);
14526 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14527 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14530 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14531 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14532 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14533 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14534 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14535 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14536 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14537 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14538 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14540 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14541 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14542 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14543 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14544 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14545 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14546 case X86ISD::SHUFPS: // Handle all target specific shuffles
14547 case X86ISD::SHUFPD:
14548 case X86ISD::PALIGN:
14549 case X86ISD::PUNPCKHBW:
14550 case X86ISD::PUNPCKHWD:
14551 case X86ISD::PUNPCKHDQ:
14552 case X86ISD::PUNPCKHQDQ:
14553 case X86ISD::UNPCKHPS:
14554 case X86ISD::UNPCKHPD:
14555 case X86ISD::VUNPCKHPSY:
14556 case X86ISD::VUNPCKHPDY:
14557 case X86ISD::PUNPCKLBW:
14558 case X86ISD::PUNPCKLWD:
14559 case X86ISD::PUNPCKLDQ:
14560 case X86ISD::PUNPCKLQDQ:
14561 case X86ISD::UNPCKLPS:
14562 case X86ISD::UNPCKLPD:
14563 case X86ISD::VUNPCKLPSY:
14564 case X86ISD::VUNPCKLPDY:
14565 case X86ISD::MOVHLPS:
14566 case X86ISD::MOVLHPS:
14567 case X86ISD::PSHUFD:
14568 case X86ISD::PSHUFHW:
14569 case X86ISD::PSHUFLW:
14570 case X86ISD::MOVSS:
14571 case X86ISD::MOVSD:
14572 case X86ISD::VPERMILPS:
14573 case X86ISD::VPERMILPSY:
14574 case X86ISD::VPERMILPD:
14575 case X86ISD::VPERMILPDY:
14576 case X86ISD::VPERM2F128:
14577 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14583 /// isTypeDesirableForOp - Return true if the target has native support for
14584 /// the specified value type and it is 'desirable' to use the type for the
14585 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14586 /// instruction encodings are longer and some i16 instructions are slow.
14587 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14588 if (!isTypeLegal(VT))
14590 if (VT != MVT::i16)
14597 case ISD::SIGN_EXTEND:
14598 case ISD::ZERO_EXTEND:
14599 case ISD::ANY_EXTEND:
14612 /// IsDesirableToPromoteOp - This method query the target whether it is
14613 /// beneficial for dag combiner to promote the specified node. If true, it
14614 /// should return the desired promotion type by reference.
14615 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14616 EVT VT = Op.getValueType();
14617 if (VT != MVT::i16)
14620 bool Promote = false;
14621 bool Commute = false;
14622 switch (Op.getOpcode()) {
14625 LoadSDNode *LD = cast<LoadSDNode>(Op);
14626 // If the non-extending load has a single use and it's not live out, then it
14627 // might be folded.
14628 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14629 Op.hasOneUse()*/) {
14630 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14631 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14632 // The only case where we'd want to promote LOAD (rather then it being
14633 // promoted as an operand is when it's only use is liveout.
14634 if (UI->getOpcode() != ISD::CopyToReg)
14641 case ISD::SIGN_EXTEND:
14642 case ISD::ZERO_EXTEND:
14643 case ISD::ANY_EXTEND:
14648 SDValue N0 = Op.getOperand(0);
14649 // Look out for (store (shl (load), x)).
14650 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14663 SDValue N0 = Op.getOperand(0);
14664 SDValue N1 = Op.getOperand(1);
14665 if (!Commute && MayFoldLoad(N1))
14667 // Avoid disabling potential load folding opportunities.
14668 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14670 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14680 //===----------------------------------------------------------------------===//
14681 // X86 Inline Assembly Support
14682 //===----------------------------------------------------------------------===//
14684 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14685 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14687 std::string AsmStr = IA->getAsmString();
14689 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14690 SmallVector<StringRef, 4> AsmPieces;
14691 SplitString(AsmStr, AsmPieces, ";\n");
14693 switch (AsmPieces.size()) {
14694 default: return false;
14696 AsmStr = AsmPieces[0];
14698 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14700 // FIXME: this should verify that we are targeting a 486 or better. If not,
14701 // we will turn this bswap into something that will be lowered to logical ops
14702 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14703 // so don't worry about this.
14705 if (AsmPieces.size() == 2 &&
14706 (AsmPieces[0] == "bswap" ||
14707 AsmPieces[0] == "bswapq" ||
14708 AsmPieces[0] == "bswapl") &&
14709 (AsmPieces[1] == "$0" ||
14710 AsmPieces[1] == "${0:q}")) {
14711 // No need to check constraints, nothing other than the equivalent of
14712 // "=r,0" would be valid here.
14713 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14714 if (!Ty || Ty->getBitWidth() % 16 != 0)
14716 return IntrinsicLowering::LowerToByteSwap(CI);
14718 // rorw $$8, ${0:w} --> llvm.bswap.i16
14719 if (CI->getType()->isIntegerTy(16) &&
14720 AsmPieces.size() == 3 &&
14721 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14722 AsmPieces[1] == "$$8," &&
14723 AsmPieces[2] == "${0:w}" &&
14724 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14726 const std::string &ConstraintsStr = IA->getConstraintString();
14727 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14728 std::sort(AsmPieces.begin(), AsmPieces.end());
14729 if (AsmPieces.size() == 4 &&
14730 AsmPieces[0] == "~{cc}" &&
14731 AsmPieces[1] == "~{dirflag}" &&
14732 AsmPieces[2] == "~{flags}" &&
14733 AsmPieces[3] == "~{fpsr}") {
14734 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14735 if (!Ty || Ty->getBitWidth() % 16 != 0)
14737 return IntrinsicLowering::LowerToByteSwap(CI);
14742 if (CI->getType()->isIntegerTy(32) &&
14743 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14744 SmallVector<StringRef, 4> Words;
14745 SplitString(AsmPieces[0], Words, " \t,");
14746 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14747 Words[2] == "${0:w}") {
14749 SplitString(AsmPieces[1], Words, " \t,");
14750 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14751 Words[2] == "$0") {
14753 SplitString(AsmPieces[2], Words, " \t,");
14754 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14755 Words[2] == "${0:w}") {
14757 const std::string &ConstraintsStr = IA->getConstraintString();
14758 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14759 std::sort(AsmPieces.begin(), AsmPieces.end());
14760 if (AsmPieces.size() == 4 &&
14761 AsmPieces[0] == "~{cc}" &&
14762 AsmPieces[1] == "~{dirflag}" &&
14763 AsmPieces[2] == "~{flags}" &&
14764 AsmPieces[3] == "~{fpsr}") {
14765 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14766 if (!Ty || Ty->getBitWidth() % 16 != 0)
14768 return IntrinsicLowering::LowerToByteSwap(CI);
14775 if (CI->getType()->isIntegerTy(64)) {
14776 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14777 if (Constraints.size() >= 2 &&
14778 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14779 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14780 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14781 SmallVector<StringRef, 4> Words;
14782 SplitString(AsmPieces[0], Words, " \t");
14783 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14785 SplitString(AsmPieces[1], Words, " \t");
14786 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14788 SplitString(AsmPieces[2], Words, " \t,");
14789 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14790 Words[2] == "%edx") {
14791 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14792 if (!Ty || Ty->getBitWidth() % 16 != 0)
14794 return IntrinsicLowering::LowerToByteSwap(CI);
14807 /// getConstraintType - Given a constraint letter, return the type of
14808 /// constraint it is for this target.
14809 X86TargetLowering::ConstraintType
14810 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14811 if (Constraint.size() == 1) {
14812 switch (Constraint[0]) {
14823 return C_RegisterClass;
14847 return TargetLowering::getConstraintType(Constraint);
14850 /// Examine constraint type and operand type and determine a weight value.
14851 /// This object must already have been set up with the operand type
14852 /// and the current alternative constraint selected.
14853 TargetLowering::ConstraintWeight
14854 X86TargetLowering::getSingleConstraintMatchWeight(
14855 AsmOperandInfo &info, const char *constraint) const {
14856 ConstraintWeight weight = CW_Invalid;
14857 Value *CallOperandVal = info.CallOperandVal;
14858 // If we don't have a value, we can't do a match,
14859 // but allow it at the lowest weight.
14860 if (CallOperandVal == NULL)
14862 Type *type = CallOperandVal->getType();
14863 // Look at the constraint type.
14864 switch (*constraint) {
14866 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14877 if (CallOperandVal->getType()->isIntegerTy())
14878 weight = CW_SpecificReg;
14883 if (type->isFloatingPointTy())
14884 weight = CW_SpecificReg;
14887 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14888 weight = CW_SpecificReg;
14892 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14893 weight = CW_Register;
14896 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14897 if (C->getZExtValue() <= 31)
14898 weight = CW_Constant;
14902 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14903 if (C->getZExtValue() <= 63)
14904 weight = CW_Constant;
14908 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14909 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14910 weight = CW_Constant;
14914 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14915 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14916 weight = CW_Constant;
14920 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14921 if (C->getZExtValue() <= 3)
14922 weight = CW_Constant;
14926 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14927 if (C->getZExtValue() <= 0xff)
14928 weight = CW_Constant;
14933 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14934 weight = CW_Constant;
14938 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14939 if ((C->getSExtValue() >= -0x80000000LL) &&
14940 (C->getSExtValue() <= 0x7fffffffLL))
14941 weight = CW_Constant;
14945 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14946 if (C->getZExtValue() <= 0xffffffff)
14947 weight = CW_Constant;
14954 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14955 /// with another that has more specific requirements based on the type of the
14956 /// corresponding operand.
14957 const char *X86TargetLowering::
14958 LowerXConstraint(EVT ConstraintVT) const {
14959 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14960 // 'f' like normal targets.
14961 if (ConstraintVT.isFloatingPoint()) {
14962 if (Subtarget->hasXMMInt())
14964 if (Subtarget->hasXMM())
14968 return TargetLowering::LowerXConstraint(ConstraintVT);
14971 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14972 /// vector. If it is invalid, don't add anything to Ops.
14973 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14974 std::string &Constraint,
14975 std::vector<SDValue>&Ops,
14976 SelectionDAG &DAG) const {
14977 SDValue Result(0, 0);
14979 // Only support length 1 constraints for now.
14980 if (Constraint.length() > 1) return;
14982 char ConstraintLetter = Constraint[0];
14983 switch (ConstraintLetter) {
14986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14987 if (C->getZExtValue() <= 31) {
14988 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14995 if (C->getZExtValue() <= 63) {
14996 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15003 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15004 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15011 if (C->getZExtValue() <= 255) {
15012 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15018 // 32-bit signed value
15019 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15020 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15021 C->getSExtValue())) {
15022 // Widen to 64 bits here to get it sign extended.
15023 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15026 // FIXME gcc accepts some relocatable values here too, but only in certain
15027 // memory models; it's complicated.
15032 // 32-bit unsigned value
15033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15034 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15035 C->getZExtValue())) {
15036 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15040 // FIXME gcc accepts some relocatable values here too, but only in certain
15041 // memory models; it's complicated.
15045 // Literal immediates are always ok.
15046 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15047 // Widen to 64 bits here to get it sign extended.
15048 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15052 // In any sort of PIC mode addresses need to be computed at runtime by
15053 // adding in a register or some sort of table lookup. These can't
15054 // be used as immediates.
15055 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15058 // If we are in non-pic codegen mode, we allow the address of a global (with
15059 // an optional displacement) to be used with 'i'.
15060 GlobalAddressSDNode *GA = 0;
15061 int64_t Offset = 0;
15063 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15065 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15066 Offset += GA->getOffset();
15068 } else if (Op.getOpcode() == ISD::ADD) {
15069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15070 Offset += C->getZExtValue();
15071 Op = Op.getOperand(0);
15074 } else if (Op.getOpcode() == ISD::SUB) {
15075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15076 Offset += -C->getZExtValue();
15077 Op = Op.getOperand(0);
15082 // Otherwise, this isn't something we can handle, reject it.
15086 const GlobalValue *GV = GA->getGlobal();
15087 // If we require an extra load to get this address, as in PIC mode, we
15088 // can't accept it.
15089 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15090 getTargetMachine())))
15093 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15094 GA->getValueType(0), Offset);
15099 if (Result.getNode()) {
15100 Ops.push_back(Result);
15103 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15106 std::pair<unsigned, const TargetRegisterClass*>
15107 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15109 // First, see if this is a constraint that directly corresponds to an LLVM
15111 if (Constraint.size() == 1) {
15112 // GCC Constraint Letters
15113 switch (Constraint[0]) {
15115 // TODO: Slight differences here in allocation order and leaving
15116 // RIP in the class. Do they matter any more here than they do
15117 // in the normal allocation?
15118 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15119 if (Subtarget->is64Bit()) {
15120 if (VT == MVT::i32 || VT == MVT::f32)
15121 return std::make_pair(0U, X86::GR32RegisterClass);
15122 else if (VT == MVT::i16)
15123 return std::make_pair(0U, X86::GR16RegisterClass);
15124 else if (VT == MVT::i8 || VT == MVT::i1)
15125 return std::make_pair(0U, X86::GR8RegisterClass);
15126 else if (VT == MVT::i64 || VT == MVT::f64)
15127 return std::make_pair(0U, X86::GR64RegisterClass);
15130 // 32-bit fallthrough
15131 case 'Q': // Q_REGS
15132 if (VT == MVT::i32 || VT == MVT::f32)
15133 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15134 else if (VT == MVT::i16)
15135 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15136 else if (VT == MVT::i8 || VT == MVT::i1)
15137 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15138 else if (VT == MVT::i64)
15139 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15141 case 'r': // GENERAL_REGS
15142 case 'l': // INDEX_REGS
15143 if (VT == MVT::i8 || VT == MVT::i1)
15144 return std::make_pair(0U, X86::GR8RegisterClass);
15145 if (VT == MVT::i16)
15146 return std::make_pair(0U, X86::GR16RegisterClass);
15147 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15148 return std::make_pair(0U, X86::GR32RegisterClass);
15149 return std::make_pair(0U, X86::GR64RegisterClass);
15150 case 'R': // LEGACY_REGS
15151 if (VT == MVT::i8 || VT == MVT::i1)
15152 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15153 if (VT == MVT::i16)
15154 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15155 if (VT == MVT::i32 || !Subtarget->is64Bit())
15156 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15157 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15158 case 'f': // FP Stack registers.
15159 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15160 // value to the correct fpstack register class.
15161 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15162 return std::make_pair(0U, X86::RFP32RegisterClass);
15163 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15164 return std::make_pair(0U, X86::RFP64RegisterClass);
15165 return std::make_pair(0U, X86::RFP80RegisterClass);
15166 case 'y': // MMX_REGS if MMX allowed.
15167 if (!Subtarget->hasMMX()) break;
15168 return std::make_pair(0U, X86::VR64RegisterClass);
15169 case 'Y': // SSE_REGS if SSE2 allowed
15170 if (!Subtarget->hasXMMInt()) break;
15172 case 'x': // SSE_REGS if SSE1 allowed
15173 if (!Subtarget->hasXMM()) break;
15175 switch (VT.getSimpleVT().SimpleTy) {
15177 // Scalar SSE types.
15180 return std::make_pair(0U, X86::FR32RegisterClass);
15183 return std::make_pair(0U, X86::FR64RegisterClass);
15191 return std::make_pair(0U, X86::VR128RegisterClass);
15197 // Use the default implementation in TargetLowering to convert the register
15198 // constraint into a member of a register class.
15199 std::pair<unsigned, const TargetRegisterClass*> Res;
15200 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15202 // Not found as a standard register?
15203 if (Res.second == 0) {
15204 // Map st(0) -> st(7) -> ST0
15205 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15206 tolower(Constraint[1]) == 's' &&
15207 tolower(Constraint[2]) == 't' &&
15208 Constraint[3] == '(' &&
15209 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15210 Constraint[5] == ')' &&
15211 Constraint[6] == '}') {
15213 Res.first = X86::ST0+Constraint[4]-'0';
15214 Res.second = X86::RFP80RegisterClass;
15218 // GCC allows "st(0)" to be called just plain "st".
15219 if (StringRef("{st}").equals_lower(Constraint)) {
15220 Res.first = X86::ST0;
15221 Res.second = X86::RFP80RegisterClass;
15226 if (StringRef("{flags}").equals_lower(Constraint)) {
15227 Res.first = X86::EFLAGS;
15228 Res.second = X86::CCRRegisterClass;
15232 // 'A' means EAX + EDX.
15233 if (Constraint == "A") {
15234 Res.first = X86::EAX;
15235 Res.second = X86::GR32_ADRegisterClass;
15241 // Otherwise, check to see if this is a register class of the wrong value
15242 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15243 // turn into {ax},{dx}.
15244 if (Res.second->hasType(VT))
15245 return Res; // Correct type already, nothing to do.
15247 // All of the single-register GCC register classes map their values onto
15248 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15249 // really want an 8-bit or 32-bit register, map to the appropriate register
15250 // class and return the appropriate register.
15251 if (Res.second == X86::GR16RegisterClass) {
15252 if (VT == MVT::i8) {
15253 unsigned DestReg = 0;
15254 switch (Res.first) {
15256 case X86::AX: DestReg = X86::AL; break;
15257 case X86::DX: DestReg = X86::DL; break;
15258 case X86::CX: DestReg = X86::CL; break;
15259 case X86::BX: DestReg = X86::BL; break;
15262 Res.first = DestReg;
15263 Res.second = X86::GR8RegisterClass;
15265 } else if (VT == MVT::i32) {
15266 unsigned DestReg = 0;
15267 switch (Res.first) {
15269 case X86::AX: DestReg = X86::EAX; break;
15270 case X86::DX: DestReg = X86::EDX; break;
15271 case X86::CX: DestReg = X86::ECX; break;
15272 case X86::BX: DestReg = X86::EBX; break;
15273 case X86::SI: DestReg = X86::ESI; break;
15274 case X86::DI: DestReg = X86::EDI; break;
15275 case X86::BP: DestReg = X86::EBP; break;
15276 case X86::SP: DestReg = X86::ESP; break;
15279 Res.first = DestReg;
15280 Res.second = X86::GR32RegisterClass;
15282 } else if (VT == MVT::i64) {
15283 unsigned DestReg = 0;
15284 switch (Res.first) {
15286 case X86::AX: DestReg = X86::RAX; break;
15287 case X86::DX: DestReg = X86::RDX; break;
15288 case X86::CX: DestReg = X86::RCX; break;
15289 case X86::BX: DestReg = X86::RBX; break;
15290 case X86::SI: DestReg = X86::RSI; break;
15291 case X86::DI: DestReg = X86::RDI; break;
15292 case X86::BP: DestReg = X86::RBP; break;
15293 case X86::SP: DestReg = X86::RSP; break;
15296 Res.first = DestReg;
15297 Res.second = X86::GR64RegisterClass;
15300 } else if (Res.second == X86::FR32RegisterClass ||
15301 Res.second == X86::FR64RegisterClass ||
15302 Res.second == X86::VR128RegisterClass) {
15303 // Handle references to XMM physical registers that got mapped into the
15304 // wrong class. This can happen with constraints like {xmm0} where the
15305 // target independent register mapper will just pick the first match it can
15306 // find, ignoring the required type.
15307 if (VT == MVT::f32)
15308 Res.second = X86::FR32RegisterClass;
15309 else if (VT == MVT::f64)
15310 Res.second = X86::FR64RegisterClass;
15311 else if (X86::VR128RegisterClass->hasType(VT))
15312 Res.second = X86::VR128RegisterClass;