1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VariadicFunction.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
56 using namespace dwarf;
58 STATISTIC(NumTailCalls, "Number of tail calls");
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static SDValue Insert128BitVector(SDValue Result,
70 static SDValue Extract128BitVector(SDValue Vec,
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference. Idx is an index in the 128 bits we
78 /// want. It need not be aligned to a 128-bit bounday. That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
84 EVT VT = Vec.getValueType();
85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86 EVT ElVT = VT.getVectorElementType();
87 int Factor = VT.getSizeInBits()/128;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
95 if (isa<ConstantSDNode>(Idx)) {
96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
99 // we can match to VEXTRACTF128.
100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
102 // This is the index of the first element of the 128-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
117 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference. Idx is an index in the 128 bits
120 /// we want. It need not be aligned to a 128-bit bounday. That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
127 if (isa<ConstantSDNode>(Idx)) {
128 EVT VT = Vec.getValueType();
129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131 EVT ElVT = VT.getVectorElementType();
132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133 EVT ResultVT = Result.getValueType();
135 // Insert the relevant 128 bits.
136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
138 // This is the index of the first element of the 128-bit chunk
140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154 bool is64Bit = Subtarget->is64Bit();
156 if (Subtarget->isTargetEnvMacho()) {
158 return new X8664_MachoTargetObjectFile();
159 return new TargetLoweringObjectFileMachO();
162 if (Subtarget->isTargetELF())
163 return new TargetLoweringObjectFileELF();
164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165 return new TargetLoweringObjectFileCOFF();
166 llvm_unreachable("unknown subtarget type");
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<X86Subtarget>();
172 X86ScalarSSEf64 = Subtarget->hasXMMInt();
173 X86ScalarSSEf32 = Subtarget->hasXMM();
174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
176 RegInfo = TM.getRegisterInfo();
177 TD = getTargetData();
179 // Set up the TargetLowering object.
180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
182 // X86 is weird, it always uses i8 for shift amounts and setcc results.
183 setBooleanContents(ZeroOrOneBooleanContent);
184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
187 // For 64-bit since we have so many registers use the ILP scheduler, for
188 // 32-bit code use the register pressure specific scheduling.
189 if (Subtarget->is64Bit())
190 setSchedulingPreference(Sched::ILP);
192 setSchedulingPreference(Sched::RegPressure);
193 setStackPointerRegisterToSaveRestore(X86StackPtr);
195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196 // Setup Windows compiler runtime calls.
197 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199 setLibcallName(RTLIB::SREM_I64, "_allrem");
200 setLibcallName(RTLIB::UREM_I64, "_aullrem");
201 setLibcallName(RTLIB::MUL_I64, "_allmul");
202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
213 if (Subtarget->isTargetDarwin()) {
214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215 setUseUnderscoreSetJmp(false);
216 setUseUnderscoreLongJmp(false);
217 } else if (Subtarget->isTargetMingw()) {
218 // MS runtime is weird: it exports _setjmp, but longjmp!
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(false);
222 setUseUnderscoreSetJmp(true);
223 setUseUnderscoreLongJmp(true);
226 // Set up the register classes.
227 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230 if (Subtarget->is64Bit())
231 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
235 // We don't accept any truncstore of integer registers.
236 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
243 // SETOEQ and SETUNE require checking two conditions.
244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
260 } else if (!TM.Options.UseSoftFloat) {
261 // We have an algorithm for SSE2->double, and we turn this into a
262 // 64-bit FILD followed by conditional FADD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
264 // We have an algorithm for SSE2, and we turn this into a 64-bit
265 // FILD for other targets.
266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 if (!TM.Options.UseSoftFloat) {
275 // SSE has no i16 to fp conversion, only i32
276 if (X86ScalarSSEf32) {
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 // f32 and f64 cases are Legal, f80 case is not
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
290 // are Legal, f80 is custom lowered.
291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
308 // Handle FP_TO_UINT by promoting the destination to a larger signed
310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
317 } else if (!TM.Options.UseSoftFloat) {
318 // Since AVX is a superset of SSE3, only check for SSE here.
319 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320 // Expand FP_TO_UINT into a select.
321 // FIXME: We would like to use a Custom expander here eventually to do
322 // the optimal thing for SSE vs. the default expansion in the legalizer.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
325 // With SSE3 we can use fisttpll to convert to a signed i64; without
326 // SSE, we're stuck with a fistpll.
327 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
330 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331 if (!X86ScalarSSEf64) {
332 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
333 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
336 // Without SSE, i64->f64 goes through memory.
337 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
341 // Scalar integer divide and remainder are lowered to use operations that
342 // produce two results, to match the available instructions. This exposes
343 // the two-result form to trivial CSE, which is able to combine x/y and x%y
344 // into a single instruction.
346 // Scalar integer multiply-high is also lowered to use two-result
347 // operations, to match the available instructions. However, plain multiply
348 // (low) operations are left as Legal, as there are single-result
349 // instructions for this in x86. Using the two-result multiply instructions
350 // when both high and low results are needed must be arranged by dagcombine.
351 for (unsigned i = 0, e = 4; i != e; ++i) {
353 setOperationAction(ISD::MULHS, VT, Expand);
354 setOperationAction(ISD::MULHU, VT, Expand);
355 setOperationAction(ISD::SDIV, VT, Expand);
356 setOperationAction(ISD::UDIV, VT, Expand);
357 setOperationAction(ISD::SREM, VT, Expand);
358 setOperationAction(ISD::UREM, VT, Expand);
360 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361 setOperationAction(ISD::ADDC, VT, Custom);
362 setOperationAction(ISD::ADDE, VT, Custom);
363 setOperationAction(ISD::SUBC, VT, Custom);
364 setOperationAction(ISD::SUBE, VT, Custom);
367 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
368 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
369 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
370 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
376 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f32 , Expand);
378 setOperationAction(ISD::FREM , MVT::f64 , Expand);
379 setOperationAction(ISD::FREM , MVT::f80 , Expand);
380 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
382 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Expand);
383 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i16 , Expand);
384 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i64 , Expand);
386 if (Subtarget->hasBMI()) {
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
389 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
390 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
391 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
392 if (Subtarget->is64Bit())
393 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
396 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i8 , Expand);
397 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i16 , Expand);
398 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
399 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i64 , Expand);
400 if (Subtarget->hasLZCNT()) {
401 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
403 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
404 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
405 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
406 if (Subtarget->is64Bit())
407 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
410 if (Subtarget->hasPOPCNT()) {
411 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
413 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
414 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
415 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
416 if (Subtarget->is64Bit())
417 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
420 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
421 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
423 // These should be promoted to a larger select which is supported.
424 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
425 // X86 wants to expand cmov itself.
426 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
427 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
428 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
429 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
430 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
431 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
432 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
433 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
434 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
435 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
436 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
437 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
438 if (Subtarget->is64Bit()) {
439 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
440 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
442 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
445 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
446 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
447 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
448 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
449 if (Subtarget->is64Bit())
450 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
451 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
452 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
455 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
456 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
457 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
458 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
460 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
461 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
462 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
463 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
464 if (Subtarget->is64Bit()) {
465 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
466 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
467 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
470 if (Subtarget->hasXMM())
471 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
473 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
474 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
476 // On X86 and X86-64, atomic operations are lowered to locked instructions.
477 // Locked instructions, in turn, have implicit fence semantics (all memory
478 // operations are flushed before issuing the locked instruction, and they
479 // are not buffered), so we can fold away the common pattern of
480 // fence-atomic-fence.
481 setShouldFoldAtomicFences(true);
483 // Expand certain atomics
484 for (unsigned i = 0, e = 4; i != e; ++i) {
486 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
488 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
491 if (!Subtarget->is64Bit()) {
492 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
493 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
494 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
495 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
496 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
497 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
498 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
499 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
502 if (Subtarget->hasCmpxchg16b()) {
503 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
506 // FIXME - use subtarget debug flags
507 if (!Subtarget->isTargetDarwin() &&
508 !Subtarget->isTargetELF() &&
509 !Subtarget->isTargetCygMing()) {
510 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
513 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
514 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
515 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
516 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
517 if (Subtarget->is64Bit()) {
518 setExceptionPointerRegister(X86::RAX);
519 setExceptionSelectorRegister(X86::RDX);
521 setExceptionPointerRegister(X86::EAX);
522 setExceptionSelectorRegister(X86::EDX);
524 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
525 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
527 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
528 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
530 setOperationAction(ISD::TRAP, MVT::Other, Legal);
532 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
533 setOperationAction(ISD::VASTART , MVT::Other, Custom);
534 setOperationAction(ISD::VAEND , MVT::Other, Expand);
535 if (Subtarget->is64Bit()) {
536 setOperationAction(ISD::VAARG , MVT::Other, Custom);
537 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
539 setOperationAction(ISD::VAARG , MVT::Other, Expand);
540 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
543 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
544 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
546 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
547 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
548 MVT::i64 : MVT::i32, Custom);
549 else if (TM.Options.EnableSegmentedStacks)
550 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
551 MVT::i64 : MVT::i32, Custom);
553 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
554 MVT::i64 : MVT::i32, Expand);
556 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
557 // f32 and f64 use SSE.
558 // Set up the FP register classes.
559 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
560 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
562 // Use ANDPD to simulate FABS.
563 setOperationAction(ISD::FABS , MVT::f64, Custom);
564 setOperationAction(ISD::FABS , MVT::f32, Custom);
566 // Use XORP to simulate FNEG.
567 setOperationAction(ISD::FNEG , MVT::f64, Custom);
568 setOperationAction(ISD::FNEG , MVT::f32, Custom);
570 // Use ANDPD and ORPD to simulate FCOPYSIGN.
571 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
572 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
574 // Lower this to FGETSIGNx86 plus an AND.
575 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
576 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
578 // We don't support sin/cos/fmod
579 setOperationAction(ISD::FSIN , MVT::f64, Expand);
580 setOperationAction(ISD::FCOS , MVT::f64, Expand);
581 setOperationAction(ISD::FSIN , MVT::f32, Expand);
582 setOperationAction(ISD::FCOS , MVT::f32, Expand);
584 // Expand FP immediates into loads from the stack, except for the special
586 addLegalFPImmediate(APFloat(+0.0)); // xorpd
587 addLegalFPImmediate(APFloat(+0.0f)); // xorps
588 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
589 // Use SSE for f32, x87 for f64.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
592 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
594 // Use ANDPS to simulate FABS.
595 setOperationAction(ISD::FABS , MVT::f32, Custom);
597 // Use XORP to simulate FNEG.
598 setOperationAction(ISD::FNEG , MVT::f32, Custom);
600 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
602 // Use ANDPS and ORPS to simulate FCOPYSIGN.
603 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
606 // We don't support sin/cos/fmod
607 setOperationAction(ISD::FSIN , MVT::f32, Expand);
608 setOperationAction(ISD::FCOS , MVT::f32, Expand);
610 // Special cases we handle for FP constants.
611 addLegalFPImmediate(APFloat(+0.0f)); // xorps
612 addLegalFPImmediate(APFloat(+0.0)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 if (!TM.Options.UnsafeFPMath) {
618 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
619 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
621 } else if (!TM.Options.UseSoftFloat) {
622 // f32 and f64 in x87.
623 // Set up the FP register classes.
624 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
625 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
627 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
628 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
630 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
632 if (!TM.Options.UnsafeFPMath) {
633 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
634 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
636 addLegalFPImmediate(APFloat(+0.0)); // FLD0
637 addLegalFPImmediate(APFloat(+1.0)); // FLD1
638 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
639 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
640 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
641 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
642 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
643 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
646 // We don't support FMA.
647 setOperationAction(ISD::FMA, MVT::f64, Expand);
648 setOperationAction(ISD::FMA, MVT::f32, Expand);
650 // Long double always uses X87.
651 if (!TM.Options.UseSoftFloat) {
652 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
653 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
654 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
656 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
657 addLegalFPImmediate(TmpFlt); // FLD0
659 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
662 APFloat TmpFlt2(+1.0);
663 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
665 addLegalFPImmediate(TmpFlt2); // FLD1
666 TmpFlt2.changeSign();
667 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
670 if (!TM.Options.UnsafeFPMath) {
671 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
672 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
675 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
676 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
677 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
678 setOperationAction(ISD::FRINT, MVT::f80, Expand);
679 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
680 setOperationAction(ISD::FMA, MVT::f80, Expand);
683 // Always use a library call for pow.
684 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
685 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
686 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
688 setOperationAction(ISD::FLOG, MVT::f80, Expand);
689 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
690 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
691 setOperationAction(ISD::FEXP, MVT::f80, Expand);
692 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
694 // First set operation action for all vector types to either promote
695 // (for widening) or expand (for scalarization). Then we will selectively
696 // turn on ones that can be effectively codegen'd.
697 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
698 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
699 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
714 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
716 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
717 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
751 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
756 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
757 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
758 setTruncStoreAction((MVT::SimpleValueType)VT,
759 (MVT::SimpleValueType)InnerVT, Expand);
760 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
761 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
762 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
765 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
766 // with -msoft-float, disable use of MMX as well.
767 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
768 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
769 // No operations on x86mmx supported, everything uses intrinsics.
772 // MMX-sized vectors (other than x86mmx) are expected to be expanded
773 // into smaller operations.
774 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
775 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
776 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
777 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
778 setOperationAction(ISD::AND, MVT::v8i8, Expand);
779 setOperationAction(ISD::AND, MVT::v4i16, Expand);
780 setOperationAction(ISD::AND, MVT::v2i32, Expand);
781 setOperationAction(ISD::AND, MVT::v1i64, Expand);
782 setOperationAction(ISD::OR, MVT::v8i8, Expand);
783 setOperationAction(ISD::OR, MVT::v4i16, Expand);
784 setOperationAction(ISD::OR, MVT::v2i32, Expand);
785 setOperationAction(ISD::OR, MVT::v1i64, Expand);
786 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
787 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
788 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
789 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
790 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
791 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
792 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
793 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
794 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
795 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
796 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
797 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
798 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
799 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
800 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
801 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
802 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
804 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
805 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
807 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
808 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
809 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
810 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
811 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
812 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
813 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
814 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
815 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
817 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
818 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
821 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
822 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
824 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
825 // registers cannot be used even for integer operations.
826 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
827 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
828 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
829 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
831 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
832 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
833 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
834 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
835 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
836 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
837 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
838 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
839 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
840 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
841 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
842 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
843 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
844 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
845 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
846 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
848 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
849 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
850 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
851 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
853 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
854 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
855 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
856 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
857 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
859 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
860 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
861 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
862 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
863 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
865 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
866 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
867 EVT VT = (MVT::SimpleValueType)i;
868 // Do not attempt to custom lower non-power-of-2 vectors
869 if (!isPowerOf2_32(VT.getVectorNumElements()))
871 // Do not attempt to custom lower non-128-bit vectors
872 if (!VT.is128BitVector())
874 setOperationAction(ISD::BUILD_VECTOR,
875 VT.getSimpleVT().SimpleTy, Custom);
876 setOperationAction(ISD::VECTOR_SHUFFLE,
877 VT.getSimpleVT().SimpleTy, Custom);
878 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
879 VT.getSimpleVT().SimpleTy, Custom);
882 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
884 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889 if (Subtarget->is64Bit()) {
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
896 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
899 // Do not attempt to promote non-128-bit vectors
900 if (!VT.is128BitVector())
903 setOperationAction(ISD::AND, SVT, Promote);
904 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
905 setOperationAction(ISD::OR, SVT, Promote);
906 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
907 setOperationAction(ISD::XOR, SVT, Promote);
908 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
909 setOperationAction(ISD::LOAD, SVT, Promote);
910 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
911 setOperationAction(ISD::SELECT, SVT, Promote);
912 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
915 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
917 // Custom lower v2i64 and v2f64 selects.
918 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
919 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
920 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
921 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
923 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
924 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
927 if (Subtarget->hasSSE41orAVX()) {
928 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
929 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
930 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
931 setOperationAction(ISD::FRINT, MVT::f32, Legal);
932 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
933 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
934 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
935 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
936 setOperationAction(ISD::FRINT, MVT::f64, Legal);
937 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
939 // FIXME: Do we need to handle scalar-to-vector here?
940 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
942 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
943 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
944 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
945 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
946 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
948 // i8 and i16 vectors are custom , because the source register and source
949 // source memory operand types are not the same width. f32 vectors are
950 // custom since the immediate controlling the insert encodes additional
952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
953 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
954 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
955 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
958 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
959 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
962 // FIXME: these should be Legal but thats only for the case where
963 // the index is constant. For now custom expand to deal with that
964 if (Subtarget->is64Bit()) {
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
966 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
970 if (Subtarget->hasXMMInt()) {
971 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
972 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
974 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
975 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
977 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
978 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
980 if (Subtarget->hasAVX2()) {
981 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
982 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
984 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
985 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
987 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
989 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
990 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
992 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
993 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
995 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
999 if (Subtarget->hasSSE42orAVX())
1000 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1002 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1003 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
1004 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1005 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
1006 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
1007 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
1008 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
1010 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1011 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1012 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1014 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1015 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1016 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1017 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1018 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1019 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1021 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1022 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1023 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1024 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1025 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1026 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1028 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1029 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1030 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1032 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1033 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1034 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1035 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1036 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1037 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1039 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1040 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1042 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1043 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1045 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1046 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1048 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1049 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1050 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1051 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1053 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1054 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1055 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1057 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1058 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1059 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1060 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1062 if (Subtarget->hasAVX2()) {
1063 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1064 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1065 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1066 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1068 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1069 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1071 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1073 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1074 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1075 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1076 // Don't lower v32i8 because there is no 128-bit byte mul
1078 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1080 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1081 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1083 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1084 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1086 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1088 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1089 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1090 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1091 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1093 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1094 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1095 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1098 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1099 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1100 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1101 // Don't lower v32i8 because there is no 128-bit byte mul
1103 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1104 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1106 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1107 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1109 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1112 // Custom lower several nodes for 256-bit types.
1113 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1114 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1115 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1118 // Extract subvector is special because the value type
1119 // (result) is 128-bit but the source is 256-bit wide.
1120 if (VT.is128BitVector())
1121 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1123 // Do not attempt to custom lower other non-256-bit vectors
1124 if (!VT.is256BitVector())
1127 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1128 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1129 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1130 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1131 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1132 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1135 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1136 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1137 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1140 // Do not attempt to promote non-256-bit vectors
1141 if (!VT.is256BitVector())
1144 setOperationAction(ISD::AND, SVT, Promote);
1145 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1146 setOperationAction(ISD::OR, SVT, Promote);
1147 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1148 setOperationAction(ISD::XOR, SVT, Promote);
1149 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1150 setOperationAction(ISD::LOAD, SVT, Promote);
1151 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1152 setOperationAction(ISD::SELECT, SVT, Promote);
1153 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1157 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1158 // of this type with custom code.
1159 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1160 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1161 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1164 // We want to custom lower some of our intrinsics.
1165 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1168 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1169 // handle type legalization for these operations here.
1171 // FIXME: We really should do custom legalization for addition and
1172 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1173 // than generic legalization for 64-bit multiplication-with-overflow, though.
1174 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1175 // Add/Sub/Mul with overflow operations are custom lowered.
1177 setOperationAction(ISD::SADDO, VT, Custom);
1178 setOperationAction(ISD::UADDO, VT, Custom);
1179 setOperationAction(ISD::SSUBO, VT, Custom);
1180 setOperationAction(ISD::USUBO, VT, Custom);
1181 setOperationAction(ISD::SMULO, VT, Custom);
1182 setOperationAction(ISD::UMULO, VT, Custom);
1185 // There are no 8-bit 3-address imul/mul instructions
1186 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1187 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1189 if (!Subtarget->is64Bit()) {
1190 // These libcalls are not available in 32-bit.
1191 setLibcallName(RTLIB::SHL_I128, 0);
1192 setLibcallName(RTLIB::SRL_I128, 0);
1193 setLibcallName(RTLIB::SRA_I128, 0);
1196 // We have target-specific dag combine patterns for the following nodes:
1197 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1198 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1199 setTargetDAGCombine(ISD::BUILD_VECTOR);
1200 setTargetDAGCombine(ISD::VSELECT);
1201 setTargetDAGCombine(ISD::SELECT);
1202 setTargetDAGCombine(ISD::SHL);
1203 setTargetDAGCombine(ISD::SRA);
1204 setTargetDAGCombine(ISD::SRL);
1205 setTargetDAGCombine(ISD::OR);
1206 setTargetDAGCombine(ISD::AND);
1207 setTargetDAGCombine(ISD::ADD);
1208 setTargetDAGCombine(ISD::FADD);
1209 setTargetDAGCombine(ISD::FSUB);
1210 setTargetDAGCombine(ISD::SUB);
1211 setTargetDAGCombine(ISD::LOAD);
1212 setTargetDAGCombine(ISD::STORE);
1213 setTargetDAGCombine(ISD::ZERO_EXTEND);
1214 setTargetDAGCombine(ISD::SINT_TO_FP);
1215 if (Subtarget->is64Bit())
1216 setTargetDAGCombine(ISD::MUL);
1217 if (Subtarget->hasBMI())
1218 setTargetDAGCombine(ISD::XOR);
1220 computeRegisterProperties();
1222 // On Darwin, -Os means optimize for size without hurting performance,
1223 // do not reduce the limit.
1224 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1225 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1226 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1227 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1228 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1229 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1230 setPrefLoopAlignment(4); // 2^4 bytes.
1231 benefitFromCodePlacementOpt = true;
1233 setPrefFunctionAlignment(4); // 2^4 bytes.
1237 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1238 if (!VT.isVector()) return MVT::i8;
1239 return VT.changeVectorElementTypeToInteger();
1243 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1244 /// the desired ByVal argument alignment.
1245 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1248 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1249 if (VTy->getBitWidth() == 128)
1251 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1252 unsigned EltAlign = 0;
1253 getMaxByValAlign(ATy->getElementType(), EltAlign);
1254 if (EltAlign > MaxAlign)
1255 MaxAlign = EltAlign;
1256 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1257 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1258 unsigned EltAlign = 0;
1259 getMaxByValAlign(STy->getElementType(i), EltAlign);
1260 if (EltAlign > MaxAlign)
1261 MaxAlign = EltAlign;
1269 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1270 /// function arguments in the caller parameter area. For X86, aggregates
1271 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1272 /// are at 4-byte boundaries.
1273 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1274 if (Subtarget->is64Bit()) {
1275 // Max of 8 and alignment of type.
1276 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1283 if (Subtarget->hasXMM())
1284 getMaxByValAlign(Ty, Align);
1288 /// getOptimalMemOpType - Returns the target specific optimal type for load
1289 /// and store operations as a result of memset, memcpy, and memmove
1290 /// lowering. If DstAlign is zero that means it's safe to destination
1291 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1292 /// means there isn't a need to check it against alignment requirement,
1293 /// probably because the source does not need to be loaded. If
1294 /// 'IsZeroVal' is true, that means it's safe to return a
1295 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1296 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1297 /// constant so it does not need to be loaded.
1298 /// It returns EVT::Other if the type should be determined using generic
1299 /// target-independent logic.
1301 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1302 unsigned DstAlign, unsigned SrcAlign,
1305 MachineFunction &MF) const {
1306 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1307 // linux. This is because the stack realignment code can't handle certain
1308 // cases like PR2962. This should be removed when PR2962 is fixed.
1309 const Function *F = MF.getFunction();
1311 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1313 (Subtarget->isUnalignedMemAccessFast() ||
1314 ((DstAlign == 0 || DstAlign >= 16) &&
1315 (SrcAlign == 0 || SrcAlign >= 16))) &&
1316 Subtarget->getStackAlignment() >= 16) {
1317 if (Subtarget->hasAVX() &&
1318 Subtarget->getStackAlignment() >= 32)
1320 if (Subtarget->hasXMMInt())
1322 if (Subtarget->hasXMM())
1324 } else if (!MemcpyStrSrc && Size >= 8 &&
1325 !Subtarget->is64Bit() &&
1326 Subtarget->getStackAlignment() >= 8 &&
1327 Subtarget->hasXMMInt()) {
1328 // Do not use f64 to lower memcpy if source is string constant. It's
1329 // better to use i32 to avoid the loads.
1333 if (Subtarget->is64Bit() && Size >= 8)
1338 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1339 /// current function. The returned value is a member of the
1340 /// MachineJumpTableInfo::JTEntryKind enum.
1341 unsigned X86TargetLowering::getJumpTableEncoding() const {
1342 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1344 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1345 Subtarget->isPICStyleGOT())
1346 return MachineJumpTableInfo::EK_Custom32;
1348 // Otherwise, use the normal jump table encoding heuristics.
1349 return TargetLowering::getJumpTableEncoding();
1353 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1354 const MachineBasicBlock *MBB,
1355 unsigned uid,MCContext &Ctx) const{
1356 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1357 Subtarget->isPICStyleGOT());
1358 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1360 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1361 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1364 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1366 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1367 SelectionDAG &DAG) const {
1368 if (!Subtarget->is64Bit())
1369 // This doesn't have DebugLoc associated with it, but is not really the
1370 // same as a Register.
1371 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1375 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1376 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1378 const MCExpr *X86TargetLowering::
1379 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1380 MCContext &Ctx) const {
1381 // X86-64 uses RIP relative addressing based on the jump table label.
1382 if (Subtarget->isPICStyleRIPRel())
1383 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1385 // Otherwise, the reference is relative to the PIC base.
1386 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1389 // FIXME: Why this routine is here? Move to RegInfo!
1390 std::pair<const TargetRegisterClass*, uint8_t>
1391 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1392 const TargetRegisterClass *RRC = 0;
1394 switch (VT.getSimpleVT().SimpleTy) {
1396 return TargetLowering::findRepresentativeClass(VT);
1397 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1398 RRC = (Subtarget->is64Bit()
1399 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1402 RRC = X86::VR64RegisterClass;
1404 case MVT::f32: case MVT::f64:
1405 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1406 case MVT::v4f32: case MVT::v2f64:
1407 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1409 RRC = X86::VR128RegisterClass;
1412 return std::make_pair(RRC, Cost);
1415 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1416 unsigned &Offset) const {
1417 if (!Subtarget->isTargetLinux())
1420 if (Subtarget->is64Bit()) {
1421 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1423 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1436 //===----------------------------------------------------------------------===//
1437 // Return Value Calling Convention Implementation
1438 //===----------------------------------------------------------------------===//
1440 #include "X86GenCallingConv.inc"
1443 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1444 MachineFunction &MF, bool isVarArg,
1445 const SmallVectorImpl<ISD::OutputArg> &Outs,
1446 LLVMContext &Context) const {
1447 SmallVector<CCValAssign, 16> RVLocs;
1448 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1450 return CCInfo.CheckReturn(Outs, RetCC_X86);
1454 X86TargetLowering::LowerReturn(SDValue Chain,
1455 CallingConv::ID CallConv, bool isVarArg,
1456 const SmallVectorImpl<ISD::OutputArg> &Outs,
1457 const SmallVectorImpl<SDValue> &OutVals,
1458 DebugLoc dl, SelectionDAG &DAG) const {
1459 MachineFunction &MF = DAG.getMachineFunction();
1460 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1462 SmallVector<CCValAssign, 16> RVLocs;
1463 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1464 RVLocs, *DAG.getContext());
1465 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1467 // Add the regs to the liveout set for the function.
1468 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1469 for (unsigned i = 0; i != RVLocs.size(); ++i)
1470 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1471 MRI.addLiveOut(RVLocs[i].getLocReg());
1475 SmallVector<SDValue, 6> RetOps;
1476 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1477 // Operand #1 = Bytes To Pop
1478 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1481 // Copy the result values into the output registers.
1482 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1483 CCValAssign &VA = RVLocs[i];
1484 assert(VA.isRegLoc() && "Can only return in registers!");
1485 SDValue ValToCopy = OutVals[i];
1486 EVT ValVT = ValToCopy.getValueType();
1488 // If this is x86-64, and we disabled SSE, we can't return FP values,
1489 // or SSE or MMX vectors.
1490 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1491 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1492 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1493 report_fatal_error("SSE register return with SSE disabled");
1495 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1496 // llvm-gcc has never done it right and no one has noticed, so this
1497 // should be OK for now.
1498 if (ValVT == MVT::f64 &&
1499 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1500 report_fatal_error("SSE2 register return with SSE2 disabled");
1502 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1503 // the RET instruction and handled by the FP Stackifier.
1504 if (VA.getLocReg() == X86::ST0 ||
1505 VA.getLocReg() == X86::ST1) {
1506 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1507 // change the value to the FP stack register class.
1508 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1509 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1510 RetOps.push_back(ValToCopy);
1511 // Don't emit a copytoreg.
1515 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1516 // which is returned in RAX / RDX.
1517 if (Subtarget->is64Bit()) {
1518 if (ValVT == MVT::x86mmx) {
1519 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1520 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1521 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1523 // If we don't have SSE2 available, convert to v4f32 so the generated
1524 // register is legal.
1525 if (!Subtarget->hasXMMInt())
1526 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1531 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1532 Flag = Chain.getValue(1);
1535 // The x86-64 ABI for returning structs by value requires that we copy
1536 // the sret argument into %rax for the return. We saved the argument into
1537 // a virtual register in the entry block, so now we copy the value out
1539 if (Subtarget->is64Bit() &&
1540 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1541 MachineFunction &MF = DAG.getMachineFunction();
1542 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1543 unsigned Reg = FuncInfo->getSRetReturnReg();
1545 "SRetReturnReg should have been set in LowerFormalArguments().");
1546 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1548 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1549 Flag = Chain.getValue(1);
1551 // RAX now acts like a return value.
1552 MRI.addLiveOut(X86::RAX);
1555 RetOps[0] = Chain; // Update chain.
1557 // Add the flag if we have it.
1559 RetOps.push_back(Flag);
1561 return DAG.getNode(X86ISD::RET_FLAG, dl,
1562 MVT::Other, &RetOps[0], RetOps.size());
1565 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1566 if (N->getNumValues() != 1)
1568 if (!N->hasNUsesOfValue(1, 0))
1571 SDNode *Copy = *N->use_begin();
1572 if (Copy->getOpcode() != ISD::CopyToReg &&
1573 Copy->getOpcode() != ISD::FP_EXTEND)
1576 bool HasRet = false;
1577 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1579 if (UI->getOpcode() != X86ISD::RET_FLAG)
1588 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1589 ISD::NodeType ExtendKind) const {
1591 // TODO: Is this also valid on 32-bit?
1592 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1593 ReturnMVT = MVT::i8;
1595 ReturnMVT = MVT::i32;
1597 EVT MinVT = getRegisterType(Context, ReturnMVT);
1598 return VT.bitsLT(MinVT) ? MinVT : VT;
1601 /// LowerCallResult - Lower the result values of a call into the
1602 /// appropriate copies out of appropriate physical registers.
1605 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1606 CallingConv::ID CallConv, bool isVarArg,
1607 const SmallVectorImpl<ISD::InputArg> &Ins,
1608 DebugLoc dl, SelectionDAG &DAG,
1609 SmallVectorImpl<SDValue> &InVals) const {
1611 // Assign locations to each value returned by this call.
1612 SmallVector<CCValAssign, 16> RVLocs;
1613 bool Is64Bit = Subtarget->is64Bit();
1614 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1615 getTargetMachine(), RVLocs, *DAG.getContext());
1616 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1618 // Copy all of the result registers out of their specified physreg.
1619 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1620 CCValAssign &VA = RVLocs[i];
1621 EVT CopyVT = VA.getValVT();
1623 // If this is x86-64, and we disabled SSE, we can't return FP values
1624 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1625 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1626 report_fatal_error("SSE register return with SSE disabled");
1631 // If this is a call to a function that returns an fp value on the floating
1632 // point stack, we must guarantee the the value is popped from the stack, so
1633 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1634 // if the return value is not used. We use the FpPOP_RETVAL instruction
1636 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1637 // If we prefer to use the value in xmm registers, copy it out as f80 and
1638 // use a truncate to move it from fp stack reg to xmm reg.
1639 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1640 SDValue Ops[] = { Chain, InFlag };
1641 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1642 MVT::Other, MVT::Glue, Ops, 2), 1);
1643 Val = Chain.getValue(0);
1645 // Round the f80 to the right size, which also moves it to the appropriate
1647 if (CopyVT != VA.getValVT())
1648 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1649 // This truncation won't change the value.
1650 DAG.getIntPtrConstant(1));
1652 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1653 CopyVT, InFlag).getValue(1);
1654 Val = Chain.getValue(0);
1656 InFlag = Chain.getValue(2);
1657 InVals.push_back(Val);
1664 //===----------------------------------------------------------------------===//
1665 // C & StdCall & Fast Calling Convention implementation
1666 //===----------------------------------------------------------------------===//
1667 // StdCall calling convention seems to be standard for many Windows' API
1668 // routines and around. It differs from C calling convention just a little:
1669 // callee should clean up the stack, not caller. Symbols should be also
1670 // decorated in some fancy way :) It doesn't support any vector arguments.
1671 // For info on fast calling convention see Fast Calling Convention (tail call)
1672 // implementation LowerX86_32FastCCCallTo.
1674 /// CallIsStructReturn - Determines whether a call uses struct return
1676 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1680 return Outs[0].Flags.isSRet();
1683 /// ArgsAreStructReturn - Determines whether a function uses struct
1684 /// return semantics.
1686 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1690 return Ins[0].Flags.isSRet();
1693 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1694 /// by "Src" to address "Dst" with size and alignment information specified by
1695 /// the specific parameter attribute. The copy will be passed as a byval
1696 /// function parameter.
1698 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1699 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1701 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1703 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1704 /*isVolatile*/false, /*AlwaysInline=*/true,
1705 MachinePointerInfo(), MachinePointerInfo());
1708 /// IsTailCallConvention - Return true if the calling convention is one that
1709 /// supports tail call optimization.
1710 static bool IsTailCallConvention(CallingConv::ID CC) {
1711 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1714 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1715 if (!CI->isTailCall())
1719 CallingConv::ID CalleeCC = CS.getCallingConv();
1720 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1726 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1727 /// a tailcall target by changing its ABI.
1728 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1729 bool GuaranteedTailCallOpt) {
1730 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1734 X86TargetLowering::LowerMemArgument(SDValue Chain,
1735 CallingConv::ID CallConv,
1736 const SmallVectorImpl<ISD::InputArg> &Ins,
1737 DebugLoc dl, SelectionDAG &DAG,
1738 const CCValAssign &VA,
1739 MachineFrameInfo *MFI,
1741 // Create the nodes corresponding to a load from this parameter slot.
1742 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1743 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1744 getTargetMachine().Options.GuaranteedTailCallOpt);
1745 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1748 // If value is passed by pointer we have address passed instead of the value
1750 if (VA.getLocInfo() == CCValAssign::Indirect)
1751 ValVT = VA.getLocVT();
1753 ValVT = VA.getValVT();
1755 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1756 // changed with more analysis.
1757 // In case of tail call optimization mark all arguments mutable. Since they
1758 // could be overwritten by lowering of arguments in case of a tail call.
1759 if (Flags.isByVal()) {
1760 unsigned Bytes = Flags.getByValSize();
1761 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1762 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1763 return DAG.getFrameIndex(FI, getPointerTy());
1765 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1766 VA.getLocMemOffset(), isImmutable);
1767 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1768 return DAG.getLoad(ValVT, dl, Chain, FIN,
1769 MachinePointerInfo::getFixedStack(FI),
1770 false, false, false, 0);
1775 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1776 CallingConv::ID CallConv,
1778 const SmallVectorImpl<ISD::InputArg> &Ins,
1781 SmallVectorImpl<SDValue> &InVals)
1783 MachineFunction &MF = DAG.getMachineFunction();
1784 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1786 const Function* Fn = MF.getFunction();
1787 if (Fn->hasExternalLinkage() &&
1788 Subtarget->isTargetCygMing() &&
1789 Fn->getName() == "main")
1790 FuncInfo->setForceFramePointer(true);
1792 MachineFrameInfo *MFI = MF.getFrameInfo();
1793 bool Is64Bit = Subtarget->is64Bit();
1794 bool IsWin64 = Subtarget->isTargetWin64();
1796 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1797 "Var args not supported with calling convention fastcc or ghc");
1799 // Assign locations to all of the incoming arguments.
1800 SmallVector<CCValAssign, 16> ArgLocs;
1801 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1802 ArgLocs, *DAG.getContext());
1804 // Allocate shadow area for Win64
1806 CCInfo.AllocateStack(32, 8);
1809 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1811 unsigned LastVal = ~0U;
1813 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1814 CCValAssign &VA = ArgLocs[i];
1815 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1817 assert(VA.getValNo() != LastVal &&
1818 "Don't support value assigned to multiple locs yet");
1820 LastVal = VA.getValNo();
1822 if (VA.isRegLoc()) {
1823 EVT RegVT = VA.getLocVT();
1824 TargetRegisterClass *RC = NULL;
1825 if (RegVT == MVT::i32)
1826 RC = X86::GR32RegisterClass;
1827 else if (Is64Bit && RegVT == MVT::i64)
1828 RC = X86::GR64RegisterClass;
1829 else if (RegVT == MVT::f32)
1830 RC = X86::FR32RegisterClass;
1831 else if (RegVT == MVT::f64)
1832 RC = X86::FR64RegisterClass;
1833 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1834 RC = X86::VR256RegisterClass;
1835 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1836 RC = X86::VR128RegisterClass;
1837 else if (RegVT == MVT::x86mmx)
1838 RC = X86::VR64RegisterClass;
1840 llvm_unreachable("Unknown argument type!");
1842 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1843 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1845 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1846 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1848 if (VA.getLocInfo() == CCValAssign::SExt)
1849 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1850 DAG.getValueType(VA.getValVT()));
1851 else if (VA.getLocInfo() == CCValAssign::ZExt)
1852 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1853 DAG.getValueType(VA.getValVT()));
1854 else if (VA.getLocInfo() == CCValAssign::BCvt)
1855 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1857 if (VA.isExtInLoc()) {
1858 // Handle MMX values passed in XMM regs.
1859 if (RegVT.isVector()) {
1860 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1863 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1866 assert(VA.isMemLoc());
1867 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1870 // If value is passed via pointer - do a load.
1871 if (VA.getLocInfo() == CCValAssign::Indirect)
1872 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1873 MachinePointerInfo(), false, false, false, 0);
1875 InVals.push_back(ArgValue);
1878 // The x86-64 ABI for returning structs by value requires that we copy
1879 // the sret argument into %rax for the return. Save the argument into
1880 // a virtual register so that we can access it from the return points.
1881 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1882 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1883 unsigned Reg = FuncInfo->getSRetReturnReg();
1885 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1886 FuncInfo->setSRetReturnReg(Reg);
1888 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1892 unsigned StackSize = CCInfo.getNextStackOffset();
1893 // Align stack specially for tail calls.
1894 if (FuncIsMadeTailCallSafe(CallConv,
1895 MF.getTarget().Options.GuaranteedTailCallOpt))
1896 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1898 // If the function takes variable number of arguments, make a frame index for
1899 // the start of the first vararg value... for expansion of llvm.va_start.
1901 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1902 CallConv != CallingConv::X86_ThisCall)) {
1903 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1906 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1908 // FIXME: We should really autogenerate these arrays
1909 static const unsigned GPR64ArgRegsWin64[] = {
1910 X86::RCX, X86::RDX, X86::R8, X86::R9
1912 static const unsigned GPR64ArgRegs64Bit[] = {
1913 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1915 static const unsigned XMMArgRegs64Bit[] = {
1916 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1917 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1919 const unsigned *GPR64ArgRegs;
1920 unsigned NumXMMRegs = 0;
1923 // The XMM registers which might contain var arg parameters are shadowed
1924 // in their paired GPR. So we only need to save the GPR to their home
1926 TotalNumIntRegs = 4;
1927 GPR64ArgRegs = GPR64ArgRegsWin64;
1929 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1930 GPR64ArgRegs = GPR64ArgRegs64Bit;
1932 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1934 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1937 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1938 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1939 "SSE register cannot be used when SSE is disabled!");
1940 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1941 NoImplicitFloatOps) &&
1942 "SSE register cannot be used when SSE is disabled!");
1943 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1944 !Subtarget->hasXMM())
1945 // Kernel mode asks for SSE to be disabled, so don't push them
1947 TotalNumXMMRegs = 0;
1950 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1951 // Get to the caller-allocated home save location. Add 8 to account
1952 // for the return address.
1953 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1954 FuncInfo->setRegSaveFrameIndex(
1955 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1956 // Fixup to set vararg frame on shadow area (4 x i64).
1958 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1960 // For X86-64, if there are vararg parameters that are passed via
1961 // registers, then we must store them to their spots on the stack so they
1962 // may be loaded by deferencing the result of va_next.
1963 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1964 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1965 FuncInfo->setRegSaveFrameIndex(
1966 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1970 // Store the integer parameter registers.
1971 SmallVector<SDValue, 8> MemOps;
1972 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1974 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1975 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1976 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1977 DAG.getIntPtrConstant(Offset));
1978 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1979 X86::GR64RegisterClass);
1980 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1982 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1983 MachinePointerInfo::getFixedStack(
1984 FuncInfo->getRegSaveFrameIndex(), Offset),
1986 MemOps.push_back(Store);
1990 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1991 // Now store the XMM (fp + vector) parameter registers.
1992 SmallVector<SDValue, 11> SaveXMMOps;
1993 SaveXMMOps.push_back(Chain);
1995 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1996 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1997 SaveXMMOps.push_back(ALVal);
1999 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2000 FuncInfo->getRegSaveFrameIndex()));
2001 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2002 FuncInfo->getVarArgsFPOffset()));
2004 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2005 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2006 X86::VR128RegisterClass);
2007 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2008 SaveXMMOps.push_back(Val);
2010 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2012 &SaveXMMOps[0], SaveXMMOps.size()));
2015 if (!MemOps.empty())
2016 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2017 &MemOps[0], MemOps.size());
2021 // Some CCs need callee pop.
2022 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2023 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2024 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2026 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2027 // If this is an sret function, the return should pop the hidden pointer.
2028 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2029 FuncInfo->setBytesToPopOnReturn(4);
2033 // RegSaveFrameIndex is X86-64 only.
2034 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2035 if (CallConv == CallingConv::X86_FastCall ||
2036 CallConv == CallingConv::X86_ThisCall)
2037 // fastcc functions can't have varargs.
2038 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2041 FuncInfo->setArgumentStackSize(StackSize);
2047 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2048 SDValue StackPtr, SDValue Arg,
2049 DebugLoc dl, SelectionDAG &DAG,
2050 const CCValAssign &VA,
2051 ISD::ArgFlagsTy Flags) const {
2052 unsigned LocMemOffset = VA.getLocMemOffset();
2053 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2054 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2055 if (Flags.isByVal())
2056 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2058 return DAG.getStore(Chain, dl, Arg, PtrOff,
2059 MachinePointerInfo::getStack(LocMemOffset),
2063 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2064 /// optimization is performed and it is required.
2066 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2067 SDValue &OutRetAddr, SDValue Chain,
2068 bool IsTailCall, bool Is64Bit,
2069 int FPDiff, DebugLoc dl) const {
2070 // Adjust the Return address stack slot.
2071 EVT VT = getPointerTy();
2072 OutRetAddr = getReturnAddressFrameIndex(DAG);
2074 // Load the "old" Return address.
2075 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2076 false, false, false, 0);
2077 return SDValue(OutRetAddr.getNode(), 1);
2080 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2081 /// optimization is performed and it is required (FPDiff!=0).
2083 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2084 SDValue Chain, SDValue RetAddrFrIdx,
2085 bool Is64Bit, int FPDiff, DebugLoc dl) {
2086 // Store the return address to the appropriate stack slot.
2087 if (!FPDiff) return Chain;
2088 // Calculate the new stack slot for the return address.
2089 int SlotSize = Is64Bit ? 8 : 4;
2090 int NewReturnAddrFI =
2091 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2092 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2093 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2094 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2095 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2101 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2102 CallingConv::ID CallConv, bool isVarArg,
2104 const SmallVectorImpl<ISD::OutputArg> &Outs,
2105 const SmallVectorImpl<SDValue> &OutVals,
2106 const SmallVectorImpl<ISD::InputArg> &Ins,
2107 DebugLoc dl, SelectionDAG &DAG,
2108 SmallVectorImpl<SDValue> &InVals) const {
2109 MachineFunction &MF = DAG.getMachineFunction();
2110 bool Is64Bit = Subtarget->is64Bit();
2111 bool IsWin64 = Subtarget->isTargetWin64();
2112 bool IsStructRet = CallIsStructReturn(Outs);
2113 bool IsSibcall = false;
2116 // Check if it's really possible to do a tail call.
2117 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2118 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2119 Outs, OutVals, Ins, DAG);
2121 // Sibcalls are automatically detected tailcalls which do not require
2123 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2130 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2131 "Var args not supported with calling convention fastcc or ghc");
2133 // Analyze operands of the call, assigning locations to each operand.
2134 SmallVector<CCValAssign, 16> ArgLocs;
2135 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2136 ArgLocs, *DAG.getContext());
2138 // Allocate shadow area for Win64
2140 CCInfo.AllocateStack(32, 8);
2143 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2145 // Get a count of how many bytes are to be pushed on the stack.
2146 unsigned NumBytes = CCInfo.getNextStackOffset();
2148 // This is a sibcall. The memory operands are available in caller's
2149 // own caller's stack.
2151 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2152 IsTailCallConvention(CallConv))
2153 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2156 if (isTailCall && !IsSibcall) {
2157 // Lower arguments at fp - stackoffset + fpdiff.
2158 unsigned NumBytesCallerPushed =
2159 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2160 FPDiff = NumBytesCallerPushed - NumBytes;
2162 // Set the delta of movement of the returnaddr stackslot.
2163 // But only set if delta is greater than previous delta.
2164 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2165 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2169 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2171 SDValue RetAddrFrIdx;
2172 // Load return address for tail calls.
2173 if (isTailCall && FPDiff)
2174 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2175 Is64Bit, FPDiff, dl);
2177 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2178 SmallVector<SDValue, 8> MemOpChains;
2181 // Walk the register/memloc assignments, inserting copies/loads. In the case
2182 // of tail call optimization arguments are handle later.
2183 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2184 CCValAssign &VA = ArgLocs[i];
2185 EVT RegVT = VA.getLocVT();
2186 SDValue Arg = OutVals[i];
2187 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2188 bool isByVal = Flags.isByVal();
2190 // Promote the value if needed.
2191 switch (VA.getLocInfo()) {
2192 default: llvm_unreachable("Unknown loc info!");
2193 case CCValAssign::Full: break;
2194 case CCValAssign::SExt:
2195 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2197 case CCValAssign::ZExt:
2198 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2200 case CCValAssign::AExt:
2201 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2202 // Special case: passing MMX values in XMM registers.
2203 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2204 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2205 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2207 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2209 case CCValAssign::BCvt:
2210 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2212 case CCValAssign::Indirect: {
2213 // Store the argument.
2214 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2215 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2216 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2217 MachinePointerInfo::getFixedStack(FI),
2224 if (VA.isRegLoc()) {
2225 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2226 if (isVarArg && IsWin64) {
2227 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2228 // shadow reg if callee is a varargs function.
2229 unsigned ShadowReg = 0;
2230 switch (VA.getLocReg()) {
2231 case X86::XMM0: ShadowReg = X86::RCX; break;
2232 case X86::XMM1: ShadowReg = X86::RDX; break;
2233 case X86::XMM2: ShadowReg = X86::R8; break;
2234 case X86::XMM3: ShadowReg = X86::R9; break;
2237 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2239 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2240 assert(VA.isMemLoc());
2241 if (StackPtr.getNode() == 0)
2242 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2243 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2244 dl, DAG, VA, Flags));
2248 if (!MemOpChains.empty())
2249 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2250 &MemOpChains[0], MemOpChains.size());
2252 // Build a sequence of copy-to-reg nodes chained together with token chain
2253 // and flag operands which copy the outgoing args into registers.
2255 // Tail call byval lowering might overwrite argument registers so in case of
2256 // tail call optimization the copies to registers are lowered later.
2258 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2259 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2260 RegsToPass[i].second, InFlag);
2261 InFlag = Chain.getValue(1);
2264 if (Subtarget->isPICStyleGOT()) {
2265 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2268 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2269 DAG.getNode(X86ISD::GlobalBaseReg,
2270 DebugLoc(), getPointerTy()),
2272 InFlag = Chain.getValue(1);
2274 // If we are tail calling and generating PIC/GOT style code load the
2275 // address of the callee into ECX. The value in ecx is used as target of
2276 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2277 // for tail calls on PIC/GOT architectures. Normally we would just put the
2278 // address of GOT into ebx and then call target@PLT. But for tail calls
2279 // ebx would be restored (since ebx is callee saved) before jumping to the
2282 // Note: The actual moving to ECX is done further down.
2283 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2284 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2285 !G->getGlobal()->hasProtectedVisibility())
2286 Callee = LowerGlobalAddress(Callee, DAG);
2287 else if (isa<ExternalSymbolSDNode>(Callee))
2288 Callee = LowerExternalSymbol(Callee, DAG);
2292 if (Is64Bit && isVarArg && !IsWin64) {
2293 // From AMD64 ABI document:
2294 // For calls that may call functions that use varargs or stdargs
2295 // (prototype-less calls or calls to functions containing ellipsis (...) in
2296 // the declaration) %al is used as hidden argument to specify the number
2297 // of SSE registers used. The contents of %al do not need to match exactly
2298 // the number of registers, but must be an ubound on the number of SSE
2299 // registers used and is in the range 0 - 8 inclusive.
2301 // Count the number of XMM registers allocated.
2302 static const unsigned XMMArgRegs[] = {
2303 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2304 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2306 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2307 assert((Subtarget->hasXMM() || !NumXMMRegs)
2308 && "SSE registers cannot be used when SSE is disabled");
2310 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2311 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2312 InFlag = Chain.getValue(1);
2316 // For tail calls lower the arguments to the 'real' stack slot.
2318 // Force all the incoming stack arguments to be loaded from the stack
2319 // before any new outgoing arguments are stored to the stack, because the
2320 // outgoing stack slots may alias the incoming argument stack slots, and
2321 // the alias isn't otherwise explicit. This is slightly more conservative
2322 // than necessary, because it means that each store effectively depends
2323 // on every argument instead of just those arguments it would clobber.
2324 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2326 SmallVector<SDValue, 8> MemOpChains2;
2329 // Do not flag preceding copytoreg stuff together with the following stuff.
2331 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2332 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2333 CCValAssign &VA = ArgLocs[i];
2336 assert(VA.isMemLoc());
2337 SDValue Arg = OutVals[i];
2338 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2339 // Create frame index.
2340 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2341 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2342 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2343 FIN = DAG.getFrameIndex(FI, getPointerTy());
2345 if (Flags.isByVal()) {
2346 // Copy relative to framepointer.
2347 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2348 if (StackPtr.getNode() == 0)
2349 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2351 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2353 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2357 // Store relative to framepointer.
2358 MemOpChains2.push_back(
2359 DAG.getStore(ArgChain, dl, Arg, FIN,
2360 MachinePointerInfo::getFixedStack(FI),
2366 if (!MemOpChains2.empty())
2367 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2368 &MemOpChains2[0], MemOpChains2.size());
2370 // Copy arguments to their registers.
2371 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2372 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2373 RegsToPass[i].second, InFlag);
2374 InFlag = Chain.getValue(1);
2378 // Store the return address to the appropriate stack slot.
2379 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2383 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2384 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2385 // In the 64-bit large code model, we have to make all calls
2386 // through a register, since the call instruction's 32-bit
2387 // pc-relative offset may not be large enough to hold the whole
2389 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2390 // If the callee is a GlobalAddress node (quite common, every direct call
2391 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2394 // We should use extra load for direct calls to dllimported functions in
2396 const GlobalValue *GV = G->getGlobal();
2397 if (!GV->hasDLLImportLinkage()) {
2398 unsigned char OpFlags = 0;
2399 bool ExtraLoad = false;
2400 unsigned WrapperKind = ISD::DELETED_NODE;
2402 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2403 // external symbols most go through the PLT in PIC mode. If the symbol
2404 // has hidden or protected visibility, or if it is static or local, then
2405 // we don't need to use the PLT - we can directly call it.
2406 if (Subtarget->isTargetELF() &&
2407 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2408 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2409 OpFlags = X86II::MO_PLT;
2410 } else if (Subtarget->isPICStyleStubAny() &&
2411 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2412 (!Subtarget->getTargetTriple().isMacOSX() ||
2413 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2414 // PC-relative references to external symbols should go through $stub,
2415 // unless we're building with the leopard linker or later, which
2416 // automatically synthesizes these stubs.
2417 OpFlags = X86II::MO_DARWIN_STUB;
2418 } else if (Subtarget->isPICStyleRIPRel() &&
2419 isa<Function>(GV) &&
2420 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2421 // If the function is marked as non-lazy, generate an indirect call
2422 // which loads from the GOT directly. This avoids runtime overhead
2423 // at the cost of eager binding (and one extra byte of encoding).
2424 OpFlags = X86II::MO_GOTPCREL;
2425 WrapperKind = X86ISD::WrapperRIP;
2429 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2430 G->getOffset(), OpFlags);
2432 // Add a wrapper if needed.
2433 if (WrapperKind != ISD::DELETED_NODE)
2434 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2435 // Add extra indirection if needed.
2437 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2438 MachinePointerInfo::getGOT(),
2439 false, false, false, 0);
2441 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2442 unsigned char OpFlags = 0;
2444 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2445 // external symbols should go through the PLT.
2446 if (Subtarget->isTargetELF() &&
2447 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2448 OpFlags = X86II::MO_PLT;
2449 } else if (Subtarget->isPICStyleStubAny() &&
2450 (!Subtarget->getTargetTriple().isMacOSX() ||
2451 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2452 // PC-relative references to external symbols should go through $stub,
2453 // unless we're building with the leopard linker or later, which
2454 // automatically synthesizes these stubs.
2455 OpFlags = X86II::MO_DARWIN_STUB;
2458 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2462 // Returns a chain & a flag for retval copy to use.
2463 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2464 SmallVector<SDValue, 8> Ops;
2466 if (!IsSibcall && isTailCall) {
2467 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2468 DAG.getIntPtrConstant(0, true), InFlag);
2469 InFlag = Chain.getValue(1);
2472 Ops.push_back(Chain);
2473 Ops.push_back(Callee);
2476 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2478 // Add argument registers to the end of the list so that they are known live
2480 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2481 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2482 RegsToPass[i].second.getValueType()));
2484 // Add an implicit use GOT pointer in EBX.
2485 if (!isTailCall && Subtarget->isPICStyleGOT())
2486 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2488 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2489 if (Is64Bit && isVarArg && !IsWin64)
2490 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2492 if (InFlag.getNode())
2493 Ops.push_back(InFlag);
2497 //// If this is the first return lowered for this function, add the regs
2498 //// to the liveout set for the function.
2499 // This isn't right, although it's probably harmless on x86; liveouts
2500 // should be computed from returns not tail calls. Consider a void
2501 // function making a tail call to a function returning int.
2502 return DAG.getNode(X86ISD::TC_RETURN, dl,
2503 NodeTys, &Ops[0], Ops.size());
2506 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2507 InFlag = Chain.getValue(1);
2509 // Create the CALLSEQ_END node.
2510 unsigned NumBytesForCalleeToPush;
2511 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2512 getTargetMachine().Options.GuaranteedTailCallOpt))
2513 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2514 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2515 // If this is a call to a struct-return function, the callee
2516 // pops the hidden struct pointer, so we have to push it back.
2517 // This is common for Darwin/X86, Linux & Mingw32 targets.
2518 NumBytesForCalleeToPush = 4;
2520 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2522 // Returns a flag for retval copy to use.
2524 Chain = DAG.getCALLSEQ_END(Chain,
2525 DAG.getIntPtrConstant(NumBytes, true),
2526 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2529 InFlag = Chain.getValue(1);
2532 // Handle result values, copying them out of physregs into vregs that we
2534 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2535 Ins, dl, DAG, InVals);
2539 //===----------------------------------------------------------------------===//
2540 // Fast Calling Convention (tail call) implementation
2541 //===----------------------------------------------------------------------===//
2543 // Like std call, callee cleans arguments, convention except that ECX is
2544 // reserved for storing the tail called function address. Only 2 registers are
2545 // free for argument passing (inreg). Tail call optimization is performed
2547 // * tailcallopt is enabled
2548 // * caller/callee are fastcc
2549 // On X86_64 architecture with GOT-style position independent code only local
2550 // (within module) calls are supported at the moment.
2551 // To keep the stack aligned according to platform abi the function
2552 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2553 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2554 // If a tail called function callee has more arguments than the caller the
2555 // caller needs to make sure that there is room to move the RETADDR to. This is
2556 // achieved by reserving an area the size of the argument delta right after the
2557 // original REtADDR, but before the saved framepointer or the spilled registers
2558 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2570 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2571 /// for a 16 byte align requirement.
2573 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2574 SelectionDAG& DAG) const {
2575 MachineFunction &MF = DAG.getMachineFunction();
2576 const TargetMachine &TM = MF.getTarget();
2577 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2578 unsigned StackAlignment = TFI.getStackAlignment();
2579 uint64_t AlignMask = StackAlignment - 1;
2580 int64_t Offset = StackSize;
2581 uint64_t SlotSize = TD->getPointerSize();
2582 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2583 // Number smaller than 12 so just add the difference.
2584 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2586 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2587 Offset = ((~AlignMask) & Offset) + StackAlignment +
2588 (StackAlignment-SlotSize);
2593 /// MatchingStackOffset - Return true if the given stack call argument is
2594 /// already available in the same position (relatively) of the caller's
2595 /// incoming argument stack.
2597 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2598 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2599 const X86InstrInfo *TII) {
2600 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2602 if (Arg.getOpcode() == ISD::CopyFromReg) {
2603 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2604 if (!TargetRegisterInfo::isVirtualRegister(VR))
2606 MachineInstr *Def = MRI->getVRegDef(VR);
2609 if (!Flags.isByVal()) {
2610 if (!TII->isLoadFromStackSlot(Def, FI))
2613 unsigned Opcode = Def->getOpcode();
2614 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2615 Def->getOperand(1).isFI()) {
2616 FI = Def->getOperand(1).getIndex();
2617 Bytes = Flags.getByValSize();
2621 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2622 if (Flags.isByVal())
2623 // ByVal argument is passed in as a pointer but it's now being
2624 // dereferenced. e.g.
2625 // define @foo(%struct.X* %A) {
2626 // tail call @bar(%struct.X* byval %A)
2629 SDValue Ptr = Ld->getBasePtr();
2630 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2633 FI = FINode->getIndex();
2634 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2635 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2636 FI = FINode->getIndex();
2637 Bytes = Flags.getByValSize();
2641 assert(FI != INT_MAX);
2642 if (!MFI->isFixedObjectIndex(FI))
2644 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2647 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2648 /// for tail call optimization. Targets which want to do tail call
2649 /// optimization should implement this function.
2651 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2652 CallingConv::ID CalleeCC,
2654 bool isCalleeStructRet,
2655 bool isCallerStructRet,
2656 const SmallVectorImpl<ISD::OutputArg> &Outs,
2657 const SmallVectorImpl<SDValue> &OutVals,
2658 const SmallVectorImpl<ISD::InputArg> &Ins,
2659 SelectionDAG& DAG) const {
2660 if (!IsTailCallConvention(CalleeCC) &&
2661 CalleeCC != CallingConv::C)
2664 // If -tailcallopt is specified, make fastcc functions tail-callable.
2665 const MachineFunction &MF = DAG.getMachineFunction();
2666 const Function *CallerF = DAG.getMachineFunction().getFunction();
2667 CallingConv::ID CallerCC = CallerF->getCallingConv();
2668 bool CCMatch = CallerCC == CalleeCC;
2670 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2671 if (IsTailCallConvention(CalleeCC) && CCMatch)
2676 // Look for obvious safe cases to perform tail call optimization that do not
2677 // require ABI changes. This is what gcc calls sibcall.
2679 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2680 // emit a special epilogue.
2681 if (RegInfo->needsStackRealignment(MF))
2684 // Also avoid sibcall optimization if either caller or callee uses struct
2685 // return semantics.
2686 if (isCalleeStructRet || isCallerStructRet)
2689 // An stdcall caller is expected to clean up its arguments; the callee
2690 // isn't going to do that.
2691 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2694 // Do not sibcall optimize vararg calls unless all arguments are passed via
2696 if (isVarArg && !Outs.empty()) {
2698 // Optimizing for varargs on Win64 is unlikely to be safe without
2699 // additional testing.
2700 if (Subtarget->isTargetWin64())
2703 SmallVector<CCValAssign, 16> ArgLocs;
2704 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2705 getTargetMachine(), ArgLocs, *DAG.getContext());
2707 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2708 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2709 if (!ArgLocs[i].isRegLoc())
2713 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2714 // Therefore if it's not used by the call it is not safe to optimize this into
2716 bool Unused = false;
2717 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2724 SmallVector<CCValAssign, 16> RVLocs;
2725 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2726 getTargetMachine(), RVLocs, *DAG.getContext());
2727 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2728 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2729 CCValAssign &VA = RVLocs[i];
2730 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2735 // If the calling conventions do not match, then we'd better make sure the
2736 // results are returned in the same way as what the caller expects.
2738 SmallVector<CCValAssign, 16> RVLocs1;
2739 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2740 getTargetMachine(), RVLocs1, *DAG.getContext());
2741 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2743 SmallVector<CCValAssign, 16> RVLocs2;
2744 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2745 getTargetMachine(), RVLocs2, *DAG.getContext());
2746 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2748 if (RVLocs1.size() != RVLocs2.size())
2750 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2751 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2753 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2755 if (RVLocs1[i].isRegLoc()) {
2756 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2759 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2765 // If the callee takes no arguments then go on to check the results of the
2767 if (!Outs.empty()) {
2768 // Check if stack adjustment is needed. For now, do not do this if any
2769 // argument is passed on the stack.
2770 SmallVector<CCValAssign, 16> ArgLocs;
2771 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2772 getTargetMachine(), ArgLocs, *DAG.getContext());
2774 // Allocate shadow area for Win64
2775 if (Subtarget->isTargetWin64()) {
2776 CCInfo.AllocateStack(32, 8);
2779 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2780 if (CCInfo.getNextStackOffset()) {
2781 MachineFunction &MF = DAG.getMachineFunction();
2782 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2785 // Check if the arguments are already laid out in the right way as
2786 // the caller's fixed stack objects.
2787 MachineFrameInfo *MFI = MF.getFrameInfo();
2788 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2789 const X86InstrInfo *TII =
2790 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2791 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2792 CCValAssign &VA = ArgLocs[i];
2793 SDValue Arg = OutVals[i];
2794 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2795 if (VA.getLocInfo() == CCValAssign::Indirect)
2797 if (!VA.isRegLoc()) {
2798 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2805 // If the tailcall address may be in a register, then make sure it's
2806 // possible to register allocate for it. In 32-bit, the call address can
2807 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2808 // callee-saved registers are restored. These happen to be the same
2809 // registers used to pass 'inreg' arguments so watch out for those.
2810 if (!Subtarget->is64Bit() &&
2811 !isa<GlobalAddressSDNode>(Callee) &&
2812 !isa<ExternalSymbolSDNode>(Callee)) {
2813 unsigned NumInRegs = 0;
2814 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2815 CCValAssign &VA = ArgLocs[i];
2818 unsigned Reg = VA.getLocReg();
2821 case X86::EAX: case X86::EDX: case X86::ECX:
2822 if (++NumInRegs == 3)
2834 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2835 return X86::createFastISel(funcInfo);
2839 //===----------------------------------------------------------------------===//
2840 // Other Lowering Hooks
2841 //===----------------------------------------------------------------------===//
2843 static bool MayFoldLoad(SDValue Op) {
2844 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2847 static bool MayFoldIntoStore(SDValue Op) {
2848 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2851 static bool isTargetShuffle(unsigned Opcode) {
2853 default: return false;
2854 case X86ISD::PSHUFD:
2855 case X86ISD::PSHUFHW:
2856 case X86ISD::PSHUFLW:
2857 case X86ISD::SHUFPD:
2858 case X86ISD::PALIGN:
2859 case X86ISD::SHUFPS:
2860 case X86ISD::MOVLHPS:
2861 case X86ISD::MOVLHPD:
2862 case X86ISD::MOVHLPS:
2863 case X86ISD::MOVLPS:
2864 case X86ISD::MOVLPD:
2865 case X86ISD::MOVSHDUP:
2866 case X86ISD::MOVSLDUP:
2867 case X86ISD::MOVDDUP:
2870 case X86ISD::UNPCKL:
2871 case X86ISD::UNPCKH:
2872 case X86ISD::VPERMILP:
2873 case X86ISD::VPERM2X128:
2879 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2880 SDValue V1, SelectionDAG &DAG) {
2882 default: llvm_unreachable("Unknown x86 shuffle node");
2883 case X86ISD::MOVSHDUP:
2884 case X86ISD::MOVSLDUP:
2885 case X86ISD::MOVDDUP:
2886 return DAG.getNode(Opc, dl, VT, V1);
2892 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2893 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2895 default: llvm_unreachable("Unknown x86 shuffle node");
2896 case X86ISD::PSHUFD:
2897 case X86ISD::PSHUFHW:
2898 case X86ISD::PSHUFLW:
2899 case X86ISD::VPERMILP:
2900 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2906 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2907 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2909 default: llvm_unreachable("Unknown x86 shuffle node");
2910 case X86ISD::PALIGN:
2911 case X86ISD::SHUFPD:
2912 case X86ISD::SHUFPS:
2913 case X86ISD::VPERM2X128:
2914 return DAG.getNode(Opc, dl, VT, V1, V2,
2915 DAG.getConstant(TargetMask, MVT::i8));
2920 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2921 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2923 default: llvm_unreachable("Unknown x86 shuffle node");
2924 case X86ISD::MOVLHPS:
2925 case X86ISD::MOVLHPD:
2926 case X86ISD::MOVHLPS:
2927 case X86ISD::MOVLPS:
2928 case X86ISD::MOVLPD:
2931 case X86ISD::UNPCKL:
2932 case X86ISD::UNPCKH:
2933 return DAG.getNode(Opc, dl, VT, V1, V2);
2938 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2939 MachineFunction &MF = DAG.getMachineFunction();
2940 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2941 int ReturnAddrIndex = FuncInfo->getRAIndex();
2943 if (ReturnAddrIndex == 0) {
2944 // Set up a frame object for the return address.
2945 uint64_t SlotSize = TD->getPointerSize();
2946 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2948 FuncInfo->setRAIndex(ReturnAddrIndex);
2951 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2955 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2956 bool hasSymbolicDisplacement) {
2957 // Offset should fit into 32 bit immediate field.
2958 if (!isInt<32>(Offset))
2961 // If we don't have a symbolic displacement - we don't have any extra
2963 if (!hasSymbolicDisplacement)
2966 // FIXME: Some tweaks might be needed for medium code model.
2967 if (M != CodeModel::Small && M != CodeModel::Kernel)
2970 // For small code model we assume that latest object is 16MB before end of 31
2971 // bits boundary. We may also accept pretty large negative constants knowing
2972 // that all objects are in the positive half of address space.
2973 if (M == CodeModel::Small && Offset < 16*1024*1024)
2976 // For kernel code model we know that all object resist in the negative half
2977 // of 32bits address space. We may not accept negative offsets, since they may
2978 // be just off and we may accept pretty large positive ones.
2979 if (M == CodeModel::Kernel && Offset > 0)
2985 /// isCalleePop - Determines whether the callee is required to pop its
2986 /// own arguments. Callee pop is necessary to support tail calls.
2987 bool X86::isCalleePop(CallingConv::ID CallingConv,
2988 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2992 switch (CallingConv) {
2995 case CallingConv::X86_StdCall:
2997 case CallingConv::X86_FastCall:
2999 case CallingConv::X86_ThisCall:
3001 case CallingConv::Fast:
3003 case CallingConv::GHC:
3008 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3009 /// specific condition code, returning the condition code and the LHS/RHS of the
3010 /// comparison to make.
3011 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3012 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3014 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3015 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3016 // X > -1 -> X == 0, jump !sign.
3017 RHS = DAG.getConstant(0, RHS.getValueType());
3018 return X86::COND_NS;
3019 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3020 // X < 0 -> X == 0, jump on sign.
3022 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3024 RHS = DAG.getConstant(0, RHS.getValueType());
3025 return X86::COND_LE;
3029 switch (SetCCOpcode) {
3030 default: llvm_unreachable("Invalid integer condition!");
3031 case ISD::SETEQ: return X86::COND_E;
3032 case ISD::SETGT: return X86::COND_G;
3033 case ISD::SETGE: return X86::COND_GE;
3034 case ISD::SETLT: return X86::COND_L;
3035 case ISD::SETLE: return X86::COND_LE;
3036 case ISD::SETNE: return X86::COND_NE;
3037 case ISD::SETULT: return X86::COND_B;
3038 case ISD::SETUGT: return X86::COND_A;
3039 case ISD::SETULE: return X86::COND_BE;
3040 case ISD::SETUGE: return X86::COND_AE;
3044 // First determine if it is required or is profitable to flip the operands.
3046 // If LHS is a foldable load, but RHS is not, flip the condition.
3047 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3048 !ISD::isNON_EXTLoad(RHS.getNode())) {
3049 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3050 std::swap(LHS, RHS);
3053 switch (SetCCOpcode) {
3059 std::swap(LHS, RHS);
3063 // On a floating point condition, the flags are set as follows:
3065 // 0 | 0 | 0 | X > Y
3066 // 0 | 0 | 1 | X < Y
3067 // 1 | 0 | 0 | X == Y
3068 // 1 | 1 | 1 | unordered
3069 switch (SetCCOpcode) {
3070 default: llvm_unreachable("Condcode should be pre-legalized away");
3072 case ISD::SETEQ: return X86::COND_E;
3073 case ISD::SETOLT: // flipped
3075 case ISD::SETGT: return X86::COND_A;
3076 case ISD::SETOLE: // flipped
3078 case ISD::SETGE: return X86::COND_AE;
3079 case ISD::SETUGT: // flipped
3081 case ISD::SETLT: return X86::COND_B;
3082 case ISD::SETUGE: // flipped
3084 case ISD::SETLE: return X86::COND_BE;
3086 case ISD::SETNE: return X86::COND_NE;
3087 case ISD::SETUO: return X86::COND_P;
3088 case ISD::SETO: return X86::COND_NP;
3090 case ISD::SETUNE: return X86::COND_INVALID;
3094 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3095 /// code. Current x86 isa includes the following FP cmov instructions:
3096 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3097 static bool hasFPCMov(unsigned X86CC) {
3113 /// isFPImmLegal - Returns true if the target can instruction select the
3114 /// specified FP immediate natively. If false, the legalizer will
3115 /// materialize the FP immediate as a load from a constant pool.
3116 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3117 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3118 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3124 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3125 /// the specified range (L, H].
3126 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3127 return (Val < 0) || (Val >= Low && Val < Hi);
3130 /// isUndefOrInRange - Return true if every element in Mask, begining
3131 /// from position Pos and ending in Pos+Size, falls within the specified
3132 /// range (L, L+Pos]. or is undef.
3133 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3134 int Pos, int Size, int Low, int Hi) {
3135 for (int i = Pos, e = Pos+Size; i != e; ++i)
3136 if (!isUndefOrInRange(Mask[i], Low, Hi))
3141 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3142 /// specified value.
3143 static bool isUndefOrEqual(int Val, int CmpVal) {
3144 if (Val < 0 || Val == CmpVal)
3149 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3150 /// from position Pos and ending in Pos+Size, falls within the specified
3151 /// sequential range (L, L+Pos]. or is undef.
3152 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3153 int Pos, int Size, int Low) {
3154 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3155 if (!isUndefOrEqual(Mask[i], Low))
3160 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3161 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3162 /// the second operand.
3163 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3164 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3165 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3166 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3167 return (Mask[0] < 2 && Mask[1] < 2);
3171 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3172 SmallVector<int, 8> M;
3174 return ::isPSHUFDMask(M, N->getValueType(0));
3177 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3178 /// is suitable for input to PSHUFHW.
3179 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3180 if (VT != MVT::v8i16)
3183 // Lower quadword copied in order or undef.
3184 for (int i = 0; i != 4; ++i)
3185 if (Mask[i] >= 0 && Mask[i] != i)
3188 // Upper quadword shuffled.
3189 for (int i = 4; i != 8; ++i)
3190 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3196 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3197 SmallVector<int, 8> M;
3199 return ::isPSHUFHWMask(M, N->getValueType(0));
3202 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3203 /// is suitable for input to PSHUFLW.
3204 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3205 if (VT != MVT::v8i16)
3208 // Upper quadword copied in order.
3209 for (int i = 4; i != 8; ++i)
3210 if (Mask[i] >= 0 && Mask[i] != i)
3213 // Lower quadword shuffled.
3214 for (int i = 0; i != 4; ++i)
3221 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3222 SmallVector<int, 8> M;
3224 return ::isPSHUFLWMask(M, N->getValueType(0));
3227 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3228 /// is suitable for input to PALIGNR.
3229 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3230 bool hasSSSE3OrAVX) {
3231 int i, e = VT.getVectorNumElements();
3232 if (VT.getSizeInBits() != 128)
3235 // Do not handle v2i64 / v2f64 shuffles with palignr.
3236 if (e < 4 || !hasSSSE3OrAVX)
3239 for (i = 0; i != e; ++i)
3243 // All undef, not a palignr.
3247 // Make sure we're shifting in the right direction.
3251 int s = Mask[i] - i;
3253 // Check the rest of the elements to see if they are consecutive.
3254 for (++i; i != e; ++i) {
3256 if (m >= 0 && m != s+i)
3262 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3263 /// specifies a shuffle of elements that is suitable for input to 256-bit
3265 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3266 bool HasAVX, bool Commuted = false) {
3267 int NumElems = VT.getVectorNumElements();
3269 if (!HasAVX || VT.getSizeInBits() != 256)
3272 if (NumElems != 4 && NumElems != 8)
3275 // VSHUFPSY divides the resulting vector into 4 chunks.
3276 // The sources are also splitted into 4 chunks, and each destination
3277 // chunk must come from a different source chunk.
3279 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3280 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3282 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3283 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3285 // VSHUFPDY divides the resulting vector into 4 chunks.
3286 // The sources are also splitted into 4 chunks, and each destination
3287 // chunk must come from a different source chunk.
3289 // SRC1 => X3 X2 X1 X0
3290 // SRC2 => Y3 Y2 Y1 Y0
3292 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3294 unsigned QuarterSize = NumElems/4;
3295 unsigned HalfSize = QuarterSize*2;
3296 for (unsigned l = 0; l != 2; ++l) {
3297 unsigned LaneStart = l*HalfSize;
3298 for (unsigned s = 0; s != 2; ++s) {
3299 unsigned QuarterStart = s*QuarterSize;
3300 unsigned Src = (Commuted) ? (1-s) : s;
3301 unsigned SrcStart = Src*NumElems + LaneStart;
3302 for (unsigned i = 0; i != QuarterSize; ++i) {
3303 int Idx = Mask[i+QuarterStart+LaneStart];
3304 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3306 // For VSHUFPSY, the mask of the second half must be the same as the first
3307 // but with the appropriate offsets. This works in the same way as
3308 // VPERMILPS works with masks.
3309 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3311 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3320 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3321 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3322 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3323 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3324 EVT VT = SVOp->getValueType(0);
3325 int NumElems = VT.getVectorNumElements();
3327 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3328 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3330 int HalfSize = NumElems/2;
3331 unsigned Mul = (NumElems == 8) ? 2 : 1;
3333 for (int i = 0; i != NumElems; ++i) {
3334 int Elt = SVOp->getMaskElt(i);
3339 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3340 if (NumElems == 8) Shamt %= HalfSize;
3341 Mask |= Elt << (Shamt*Mul);
3347 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3348 /// the two vector operands have swapped position.
3349 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3350 unsigned NumElems) {
3351 for (unsigned i = 0; i != NumElems; ++i) {
3355 else if (idx < (int)NumElems)
3356 Mask[i] = idx + NumElems;
3358 Mask[i] = idx - NumElems;
3362 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3363 /// specifies a shuffle of elements that is suitable for input to 128-bit
3364 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3365 /// reverse of what x86 shuffles want.
3366 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3367 bool Commuted = false) {
3368 unsigned NumElems = VT.getVectorNumElements();
3370 if (VT.getSizeInBits() != 128)
3373 if (NumElems != 2 && NumElems != 4)
3376 unsigned Half = NumElems / 2;
3377 unsigned SrcStart = Commuted ? NumElems : 0;
3378 for (unsigned i = 0; i != Half; ++i)
3379 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3381 SrcStart = Commuted ? 0 : NumElems;
3382 for (unsigned i = Half; i != NumElems; ++i)
3383 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3389 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3390 SmallVector<int, 8> M;
3392 return ::isSHUFPMask(M, N->getValueType(0));
3395 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3396 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3397 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3398 EVT VT = N->getValueType(0);
3399 unsigned NumElems = VT.getVectorNumElements();
3401 if (VT.getSizeInBits() != 128)
3407 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3408 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3409 isUndefOrEqual(N->getMaskElt(1), 7) &&
3410 isUndefOrEqual(N->getMaskElt(2), 2) &&
3411 isUndefOrEqual(N->getMaskElt(3), 3);
3414 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3415 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3417 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3418 EVT VT = N->getValueType(0);
3419 unsigned NumElems = VT.getVectorNumElements();
3421 if (VT.getSizeInBits() != 128)
3427 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3428 isUndefOrEqual(N->getMaskElt(1), 3) &&
3429 isUndefOrEqual(N->getMaskElt(2), 2) &&
3430 isUndefOrEqual(N->getMaskElt(3), 3);
3433 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3434 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3435 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3436 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3438 if (NumElems != 2 && NumElems != 4)
3441 for (unsigned i = 0; i < NumElems/2; ++i)
3442 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3445 for (unsigned i = NumElems/2; i < NumElems; ++i)
3446 if (!isUndefOrEqual(N->getMaskElt(i), i))
3452 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3453 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3454 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3455 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3457 if ((NumElems != 2 && NumElems != 4)
3458 || N->getValueType(0).getSizeInBits() > 128)
3461 for (unsigned i = 0; i < NumElems/2; ++i)
3462 if (!isUndefOrEqual(N->getMaskElt(i), i))
3465 for (unsigned i = 0; i < NumElems/2; ++i)
3466 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3472 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3473 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3474 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3475 bool HasAVX2, bool V2IsSplat = false) {
3476 unsigned NumElts = VT.getVectorNumElements();
3478 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3479 "Unsupported vector type for unpckh");
3481 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3482 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3485 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3486 // independently on 128-bit lanes.
3487 unsigned NumLanes = VT.getSizeInBits()/128;
3488 unsigned NumLaneElts = NumElts/NumLanes;
3490 for (unsigned l = 0; l != NumLanes; ++l) {
3491 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3492 i != (l+1)*NumLaneElts;
3495 int BitI1 = Mask[i+1];
3496 if (!isUndefOrEqual(BitI, j))
3499 if (!isUndefOrEqual(BitI1, NumElts))
3502 if (!isUndefOrEqual(BitI1, j + NumElts))
3511 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3512 SmallVector<int, 8> M;
3514 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3517 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3518 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3519 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3520 bool HasAVX2, bool V2IsSplat = false) {
3521 unsigned NumElts = VT.getVectorNumElements();
3523 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3524 "Unsupported vector type for unpckh");
3526 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3527 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3530 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3531 // independently on 128-bit lanes.
3532 unsigned NumLanes = VT.getSizeInBits()/128;
3533 unsigned NumLaneElts = NumElts/NumLanes;
3535 for (unsigned l = 0; l != NumLanes; ++l) {
3536 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3537 i != (l+1)*NumLaneElts; i += 2, ++j) {
3539 int BitI1 = Mask[i+1];
3540 if (!isUndefOrEqual(BitI, j))
3543 if (isUndefOrEqual(BitI1, NumElts))
3546 if (!isUndefOrEqual(BitI1, j+NumElts))
3554 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3555 SmallVector<int, 8> M;
3557 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3560 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3561 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3563 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3565 unsigned NumElts = VT.getVectorNumElements();
3567 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3568 "Unsupported vector type for unpckh");
3570 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3571 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3574 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3575 // FIXME: Need a better way to get rid of this, there's no latency difference
3576 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3577 // the former later. We should also remove the "_undef" special mask.
3578 if (NumElts == 4 && VT.getSizeInBits() == 256)
3581 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3582 // independently on 128-bit lanes.
3583 unsigned NumLanes = VT.getSizeInBits()/128;
3584 unsigned NumLaneElts = NumElts/NumLanes;
3586 for (unsigned l = 0; l != NumLanes; ++l) {
3587 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3588 i != (l+1)*NumLaneElts;
3591 int BitI1 = Mask[i+1];
3593 if (!isUndefOrEqual(BitI, j))
3595 if (!isUndefOrEqual(BitI1, j))
3603 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3604 SmallVector<int, 8> M;
3606 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3609 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3610 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3612 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3614 unsigned NumElts = VT.getVectorNumElements();
3616 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3617 "Unsupported vector type for unpckh");
3619 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3620 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3623 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3624 // independently on 128-bit lanes.
3625 unsigned NumLanes = VT.getSizeInBits()/128;
3626 unsigned NumLaneElts = NumElts/NumLanes;
3628 for (unsigned l = 0; l != NumLanes; ++l) {
3629 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3630 i != (l+1)*NumLaneElts; i += 2, ++j) {
3632 int BitI1 = Mask[i+1];
3633 if (!isUndefOrEqual(BitI, j))
3635 if (!isUndefOrEqual(BitI1, j))
3642 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3643 SmallVector<int, 8> M;
3645 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3648 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3649 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3650 /// MOVSD, and MOVD, i.e. setting the lowest element.
3651 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3652 if (VT.getVectorElementType().getSizeInBits() < 32)
3655 int NumElts = VT.getVectorNumElements();
3657 if (!isUndefOrEqual(Mask[0], NumElts))
3660 for (int i = 1; i < NumElts; ++i)
3661 if (!isUndefOrEqual(Mask[i], i))
3667 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3668 SmallVector<int, 8> M;
3670 return ::isMOVLMask(M, N->getValueType(0));
3673 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3674 /// as permutations between 128-bit chunks or halves. As an example: this
3676 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3677 /// The first half comes from the second half of V1 and the second half from the
3678 /// the second half of V2.
3679 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3681 if (!HasAVX || VT.getSizeInBits() != 256)
3684 // The shuffle result is divided into half A and half B. In total the two
3685 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3686 // B must come from C, D, E or F.
3687 int HalfSize = VT.getVectorNumElements()/2;
3688 bool MatchA = false, MatchB = false;
3690 // Check if A comes from one of C, D, E, F.
3691 for (int Half = 0; Half < 4; ++Half) {
3692 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3698 // Check if B comes from one of C, D, E, F.
3699 for (int Half = 0; Half < 4; ++Half) {
3700 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3706 return MatchA && MatchB;
3709 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3710 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3711 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3712 EVT VT = SVOp->getValueType(0);
3714 int HalfSize = VT.getVectorNumElements()/2;
3716 int FstHalf = 0, SndHalf = 0;
3717 for (int i = 0; i < HalfSize; ++i) {
3718 if (SVOp->getMaskElt(i) > 0) {
3719 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3723 for (int i = HalfSize; i < HalfSize*2; ++i) {
3724 if (SVOp->getMaskElt(i) > 0) {
3725 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3730 return (FstHalf | (SndHalf << 4));
3733 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3734 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3735 /// Note that VPERMIL mask matching is different depending whether theunderlying
3736 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3737 /// to the same elements of the low, but to the higher half of the source.
3738 /// In VPERMILPD the two lanes could be shuffled independently of each other
3739 /// with the same restriction that lanes can't be crossed.
3740 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3742 int NumElts = VT.getVectorNumElements();
3743 int NumLanes = VT.getSizeInBits()/128;
3748 // Only match 256-bit with 32/64-bit types
3749 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3752 int LaneSize = NumElts/NumLanes;
3753 for (int l = 0; l != NumLanes; ++l) {
3754 int LaneStart = l*LaneSize;
3755 for (int i = 0; i != LaneSize; ++i) {
3756 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3758 if (NumElts == 4 || l == 0)
3760 // VPERMILPS handling
3763 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3771 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3772 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3773 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3774 EVT VT = SVOp->getValueType(0);
3776 int NumElts = VT.getVectorNumElements();
3777 int NumLanes = VT.getSizeInBits()/128;
3778 int LaneSize = NumElts/NumLanes;
3780 // Although the mask is equal for both lanes do it twice to get the cases
3781 // where a mask will match because the same mask element is undef on the
3782 // first half but valid on the second. This would get pathological cases
3783 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3784 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3786 for (int i = 0; i != NumElts; ++i) {
3787 int MaskElt = SVOp->getMaskElt(i);
3790 MaskElt %= LaneSize;
3792 // VPERMILPSY, the mask of the first half must be equal to the second one
3793 if (NumElts == 8) Shamt %= LaneSize;
3794 Mask |= MaskElt << (Shamt*Shift);
3800 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3801 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3802 /// element of vector 2 and the other elements to come from vector 1 in order.
3803 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3804 bool V2IsSplat = false, bool V2IsUndef = false) {
3805 int NumOps = VT.getVectorNumElements();
3806 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3809 if (!isUndefOrEqual(Mask[0], 0))
3812 for (int i = 1; i < NumOps; ++i)
3813 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3814 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3815 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3821 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3822 bool V2IsUndef = false) {
3823 SmallVector<int, 8> M;
3825 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3828 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3829 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3830 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3831 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3832 const X86Subtarget *Subtarget) {
3833 if (!Subtarget->hasSSE3orAVX())
3836 // The second vector must be undef
3837 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3840 EVT VT = N->getValueType(0);
3841 unsigned NumElems = VT.getVectorNumElements();
3843 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3844 (VT.getSizeInBits() == 256 && NumElems != 8))
3847 // "i+1" is the value the indexed mask element must have
3848 for (unsigned i = 0; i < NumElems; i += 2)
3849 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3850 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3856 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3857 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3858 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3859 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3860 const X86Subtarget *Subtarget) {
3861 if (!Subtarget->hasSSE3orAVX())
3864 // The second vector must be undef
3865 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3868 EVT VT = N->getValueType(0);
3869 unsigned NumElems = VT.getVectorNumElements();
3871 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3872 (VT.getSizeInBits() == 256 && NumElems != 8))
3875 // "i" is the value the indexed mask element must have
3876 for (unsigned i = 0; i < NumElems; i += 2)
3877 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3878 !isUndefOrEqual(N->getMaskElt(i+1), i))
3884 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to 256-bit
3886 /// version of MOVDDUP.
3887 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3889 int NumElts = VT.getVectorNumElements();
3891 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3894 for (int i = 0; i != NumElts/2; ++i)
3895 if (!isUndefOrEqual(Mask[i], 0))
3897 for (int i = NumElts/2; i != NumElts; ++i)
3898 if (!isUndefOrEqual(Mask[i], NumElts/2))
3903 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to 128-bit
3905 /// version of MOVDDUP.
3906 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3907 EVT VT = N->getValueType(0);
3909 if (VT.getSizeInBits() != 128)
3912 int e = VT.getVectorNumElements() / 2;
3913 for (int i = 0; i < e; ++i)
3914 if (!isUndefOrEqual(N->getMaskElt(i), i))
3916 for (int i = 0; i < e; ++i)
3917 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3922 /// isVEXTRACTF128Index - Return true if the specified
3923 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3924 /// suitable for input to VEXTRACTF128.
3925 bool X86::isVEXTRACTF128Index(SDNode *N) {
3926 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929 // The index should be aligned on a 128-bit boundary.
3931 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3933 unsigned VL = N->getValueType(0).getVectorNumElements();
3934 unsigned VBits = N->getValueType(0).getSizeInBits();
3935 unsigned ElSize = VBits / VL;
3936 bool Result = (Index * ElSize) % 128 == 0;
3941 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3942 /// operand specifies a subvector insert that is suitable for input to
3944 bool X86::isVINSERTF128Index(SDNode *N) {
3945 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948 // The index should be aligned on a 128-bit boundary.
3950 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3952 unsigned VL = N->getValueType(0).getVectorNumElements();
3953 unsigned VBits = N->getValueType(0).getSizeInBits();
3954 unsigned ElSize = VBits / VL;
3955 bool Result = (Index * ElSize) % 128 == 0;
3960 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3961 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3962 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3963 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3964 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3966 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3968 for (int i = 0; i < NumOperands; ++i) {
3969 int Val = SVOp->getMaskElt(NumOperands-i-1);
3970 if (Val < 0) Val = 0;
3971 if (Val >= NumOperands) Val -= NumOperands;
3973 if (i != NumOperands - 1)
3979 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3980 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3981 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3984 // 8 nodes, but we only care about the last 4.
3985 for (unsigned i = 7; i >= 4; --i) {
3986 int Val = SVOp->getMaskElt(i);
3995 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3996 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3997 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3998 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4000 // 8 nodes, but we only care about the first 4.
4001 for (int i = 3; i >= 0; --i) {
4002 int Val = SVOp->getMaskElt(i);
4011 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4012 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4013 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4014 EVT VT = SVOp->getValueType(0);
4015 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4019 for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4020 Val = SVOp->getMaskElt(i);
4024 assert(Val - i > 0 && "PALIGNR imm should be positive");
4025 return (Val - i) * EltSize;
4028 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4029 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4031 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4032 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4033 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4036 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4038 EVT VecVT = N->getOperand(0).getValueType();
4039 EVT ElVT = VecVT.getVectorElementType();
4041 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4042 return Index / NumElemsPerChunk;
4045 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4046 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4048 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4049 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4050 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4053 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4055 EVT VecVT = N->getValueType(0);
4056 EVT ElVT = VecVT.getVectorElementType();
4058 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4059 return Index / NumElemsPerChunk;
4062 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4064 bool X86::isZeroNode(SDValue Elt) {
4065 return ((isa<ConstantSDNode>(Elt) &&
4066 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4067 (isa<ConstantFPSDNode>(Elt) &&
4068 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4071 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4072 /// their permute mask.
4073 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4074 SelectionDAG &DAG) {
4075 EVT VT = SVOp->getValueType(0);
4076 unsigned NumElems = VT.getVectorNumElements();
4077 SmallVector<int, 8> MaskVec;
4079 for (unsigned i = 0; i != NumElems; ++i) {
4080 int idx = SVOp->getMaskElt(i);
4082 MaskVec.push_back(idx);
4083 else if (idx < (int)NumElems)
4084 MaskVec.push_back(idx + NumElems);
4086 MaskVec.push_back(idx - NumElems);
4088 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4089 SVOp->getOperand(0), &MaskVec[0]);
4092 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4093 /// match movhlps. The lower half elements should come from upper half of
4094 /// V1 (and in order), and the upper half elements should come from the upper
4095 /// half of V2 (and in order).
4096 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4097 EVT VT = Op->getValueType(0);
4098 if (VT.getSizeInBits() != 128)
4100 if (VT.getVectorNumElements() != 4)
4102 for (unsigned i = 0, e = 2; i != e; ++i)
4103 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4105 for (unsigned i = 2; i != 4; ++i)
4106 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4111 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4112 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4114 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4115 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4117 N = N->getOperand(0).getNode();
4118 if (!ISD::isNON_EXTLoad(N))
4121 *LD = cast<LoadSDNode>(N);
4125 // Test whether the given value is a vector value which will be legalized
4127 static bool WillBeConstantPoolLoad(SDNode *N) {
4128 if (N->getOpcode() != ISD::BUILD_VECTOR)
4131 // Check for any non-constant elements.
4132 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4133 switch (N->getOperand(i).getNode()->getOpcode()) {
4135 case ISD::ConstantFP:
4142 // Vectors of all-zeros and all-ones are materialized with special
4143 // instructions rather than being loaded.
4144 return !ISD::isBuildVectorAllZeros(N) &&
4145 !ISD::isBuildVectorAllOnes(N);
4148 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4149 /// match movlp{s|d}. The lower half elements should come from lower half of
4150 /// V1 (and in order), and the upper half elements should come from the upper
4151 /// half of V2 (and in order). And since V1 will become the source of the
4152 /// MOVLP, it must be either a vector load or a scalar load to vector.
4153 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4154 ShuffleVectorSDNode *Op) {
4155 EVT VT = Op->getValueType(0);
4156 if (VT.getSizeInBits() != 128)
4159 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4161 // Is V2 is a vector load, don't do this transformation. We will try to use
4162 // load folding shufps op.
4163 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4166 unsigned NumElems = VT.getVectorNumElements();
4168 if (NumElems != 2 && NumElems != 4)
4170 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4171 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4173 for (unsigned i = NumElems/2; i != NumElems; ++i)
4174 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4179 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4181 static bool isSplatVector(SDNode *N) {
4182 if (N->getOpcode() != ISD::BUILD_VECTOR)
4185 SDValue SplatValue = N->getOperand(0);
4186 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4187 if (N->getOperand(i) != SplatValue)
4192 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4193 /// to an zero vector.
4194 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4195 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4196 SDValue V1 = N->getOperand(0);
4197 SDValue V2 = N->getOperand(1);
4198 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4199 for (unsigned i = 0; i != NumElems; ++i) {
4200 int Idx = N->getMaskElt(i);
4201 if (Idx >= (int)NumElems) {
4202 unsigned Opc = V2.getOpcode();
4203 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4205 if (Opc != ISD::BUILD_VECTOR ||
4206 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4208 } else if (Idx >= 0) {
4209 unsigned Opc = V1.getOpcode();
4210 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4212 if (Opc != ISD::BUILD_VECTOR ||
4213 !X86::isZeroNode(V1.getOperand(Idx)))
4220 /// getZeroVector - Returns a vector of specified type with all zero elements.
4222 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4224 assert(VT.isVector() && "Expected a vector type");
4226 // Always build SSE zero vectors as <4 x i32> bitcasted
4227 // to their dest type. This ensures they get CSE'd.
4229 if (VT.getSizeInBits() == 128) { // SSE
4230 if (HasXMMInt) { // SSE2
4231 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4232 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4234 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4235 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4237 } else if (VT.getSizeInBits() == 256) { // AVX
4238 // 256-bit logic and arithmetic instructions in AVX are
4239 // all floating-point, no support for integer ops. Default
4240 // to emitting fp zeroed vectors then.
4241 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4242 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4243 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4245 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4248 /// getOnesVector - Returns a vector of specified type with all bits set.
4249 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4250 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4251 /// Then bitcast to their original type, ensuring they get CSE'd.
4252 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4254 assert(VT.isVector() && "Expected a vector type");
4255 assert((VT.is128BitVector() || VT.is256BitVector())
4256 && "Expected a 128-bit or 256-bit vector type");
4258 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4260 if (VT.getSizeInBits() == 256) {
4261 if (HasAVX2) { // AVX2
4262 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4263 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4265 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4266 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4267 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4268 Vec = Insert128BitVector(InsV, Vec,
4269 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4272 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4278 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4279 /// that point to V2 points to its first element.
4280 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4281 EVT VT = SVOp->getValueType(0);
4282 unsigned NumElems = VT.getVectorNumElements();
4284 bool Changed = false;
4285 SmallVector<int, 8> MaskVec;
4286 SVOp->getMask(MaskVec);
4288 for (unsigned i = 0; i != NumElems; ++i) {
4289 if (MaskVec[i] > (int)NumElems) {
4290 MaskVec[i] = NumElems;
4295 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4296 SVOp->getOperand(1), &MaskVec[0]);
4297 return SDValue(SVOp, 0);
4300 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4301 /// operation of specified width.
4302 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4304 unsigned NumElems = VT.getVectorNumElements();
4305 SmallVector<int, 8> Mask;
4306 Mask.push_back(NumElems);
4307 for (unsigned i = 1; i != NumElems; ++i)
4309 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4312 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4313 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4315 unsigned NumElems = VT.getVectorNumElements();
4316 SmallVector<int, 8> Mask;
4317 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4319 Mask.push_back(i + NumElems);
4321 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4324 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4325 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4327 unsigned NumElems = VT.getVectorNumElements();
4328 unsigned Half = NumElems/2;
4329 SmallVector<int, 8> Mask;
4330 for (unsigned i = 0; i != Half; ++i) {
4331 Mask.push_back(i + Half);
4332 Mask.push_back(i + NumElems + Half);
4334 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4337 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4338 // a generic shuffle instruction because the target has no such instructions.
4339 // Generate shuffles which repeat i16 and i8 several times until they can be
4340 // represented by v4f32 and then be manipulated by target suported shuffles.
4341 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4342 EVT VT = V.getValueType();
4343 int NumElems = VT.getVectorNumElements();
4344 DebugLoc dl = V.getDebugLoc();
4346 while (NumElems > 4) {
4347 if (EltNo < NumElems/2) {
4348 V = getUnpackl(DAG, dl, VT, V, V);
4350 V = getUnpackh(DAG, dl, VT, V, V);
4351 EltNo -= NumElems/2;
4358 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4359 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4360 EVT VT = V.getValueType();
4361 DebugLoc dl = V.getDebugLoc();
4362 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4363 && "Vector size not supported");
4365 if (VT.getSizeInBits() == 128) {
4366 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4367 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4368 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4371 // To use VPERMILPS to splat scalars, the second half of indicies must
4372 // refer to the higher part, which is a duplication of the lower one,
4373 // because VPERMILPS can only handle in-lane permutations.
4374 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4375 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4377 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4378 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4382 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4385 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4386 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4387 EVT SrcVT = SV->getValueType(0);
4388 SDValue V1 = SV->getOperand(0);
4389 DebugLoc dl = SV->getDebugLoc();
4391 int EltNo = SV->getSplatIndex();
4392 int NumElems = SrcVT.getVectorNumElements();
4393 unsigned Size = SrcVT.getSizeInBits();
4395 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4396 "Unknown how to promote splat for type");
4398 // Extract the 128-bit part containing the splat element and update
4399 // the splat element index when it refers to the higher register.
4401 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4402 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4404 EltNo -= NumElems/2;
4407 // All i16 and i8 vector types can't be used directly by a generic shuffle
4408 // instruction because the target has no such instruction. Generate shuffles
4409 // which repeat i16 and i8 several times until they fit in i32, and then can
4410 // be manipulated by target suported shuffles.
4411 EVT EltVT = SrcVT.getVectorElementType();
4412 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4413 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4415 // Recreate the 256-bit vector and place the same 128-bit vector
4416 // into the low and high part. This is necessary because we want
4417 // to use VPERM* to shuffle the vectors
4419 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4420 DAG.getConstant(0, MVT::i32), DAG, dl);
4421 V1 = Insert128BitVector(InsV, V1,
4422 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4425 return getLegalSplat(DAG, V1, EltNo);
4428 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4429 /// vector of zero or undef vector. This produces a shuffle where the low
4430 /// element of V2 is swizzled into the zero/undef vector, landing at element
4431 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4432 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4433 bool isZero, bool HasXMMInt,
4434 SelectionDAG &DAG) {
4435 EVT VT = V2.getValueType();
4437 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4438 unsigned NumElems = VT.getVectorNumElements();
4439 SmallVector<int, 16> MaskVec;
4440 for (unsigned i = 0; i != NumElems; ++i)
4441 // If this is the insertion idx, put the low elt of V2 here.
4442 MaskVec.push_back(i == Idx ? NumElems : i);
4443 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4446 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4447 /// element of the result of the vector shuffle.
4448 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4451 return SDValue(); // Limit search depth.
4453 SDValue V = SDValue(N, 0);
4454 EVT VT = V.getValueType();
4455 unsigned Opcode = V.getOpcode();
4457 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4458 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4459 Index = SV->getMaskElt(Index);
4462 return DAG.getUNDEF(VT.getVectorElementType());
4464 int NumElems = VT.getVectorNumElements();
4465 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4466 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4469 // Recurse into target specific vector shuffles to find scalars.
4470 if (isTargetShuffle(Opcode)) {
4471 int NumElems = VT.getVectorNumElements();
4472 SmallVector<unsigned, 16> ShuffleMask;
4476 case X86ISD::SHUFPS:
4477 case X86ISD::SHUFPD:
4478 ImmN = N->getOperand(N->getNumOperands()-1);
4479 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4482 case X86ISD::UNPCKH:
4483 DecodeUNPCKHMask(VT, ShuffleMask);
4485 case X86ISD::UNPCKL:
4486 DecodeUNPCKLMask(VT, ShuffleMask);
4488 case X86ISD::MOVHLPS:
4489 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4491 case X86ISD::MOVLHPS:
4492 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4494 case X86ISD::PSHUFD:
4495 ImmN = N->getOperand(N->getNumOperands()-1);
4496 DecodePSHUFMask(NumElems,
4497 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4500 case X86ISD::PSHUFHW:
4501 ImmN = N->getOperand(N->getNumOperands()-1);
4502 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4505 case X86ISD::PSHUFLW:
4506 ImmN = N->getOperand(N->getNumOperands()-1);
4507 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4511 case X86ISD::MOVSD: {
4512 // The index 0 always comes from the first element of the second source,
4513 // this is why MOVSS and MOVSD are used in the first place. The other
4514 // elements come from the other positions of the first source vector.
4515 unsigned OpNum = (Index == 0) ? 1 : 0;
4516 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4519 case X86ISD::VPERMILP:
4520 ImmN = N->getOperand(N->getNumOperands()-1);
4521 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4524 case X86ISD::VPERM2X128:
4525 ImmN = N->getOperand(N->getNumOperands()-1);
4526 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4529 case X86ISD::MOVDDUP:
4530 case X86ISD::MOVLHPD:
4531 case X86ISD::MOVLPD:
4532 case X86ISD::MOVLPS:
4533 case X86ISD::MOVSHDUP:
4534 case X86ISD::MOVSLDUP:
4535 case X86ISD::PALIGN:
4536 return SDValue(); // Not yet implemented.
4538 assert(0 && "unknown target shuffle node");
4542 Index = ShuffleMask[Index];
4544 return DAG.getUNDEF(VT.getVectorElementType());
4546 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4547 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4551 // Actual nodes that may contain scalar elements
4552 if (Opcode == ISD::BITCAST) {
4553 V = V.getOperand(0);
4554 EVT SrcVT = V.getValueType();
4555 unsigned NumElems = VT.getVectorNumElements();
4557 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4561 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4562 return (Index == 0) ? V.getOperand(0)
4563 : DAG.getUNDEF(VT.getVectorElementType());
4565 if (V.getOpcode() == ISD::BUILD_VECTOR)
4566 return V.getOperand(Index);
4571 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4572 /// shuffle operation which come from a consecutively from a zero. The
4573 /// search can start in two different directions, from left or right.
4575 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4576 bool ZerosFromLeft, SelectionDAG &DAG) {
4579 while (i < NumElems) {
4580 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4581 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4582 if (!(Elt.getNode() &&
4583 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4591 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4592 /// MaskE correspond consecutively to elements from one of the vector operands,
4593 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4595 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4596 int OpIdx, int NumElems, unsigned &OpNum) {
4597 bool SeenV1 = false;
4598 bool SeenV2 = false;
4600 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4601 int Idx = SVOp->getMaskElt(i);
4602 // Ignore undef indicies
4611 // Only accept consecutive elements from the same vector
4612 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4616 OpNum = SeenV1 ? 0 : 1;
4620 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4621 /// logical left shift of a vector.
4622 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4623 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4624 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4625 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4626 false /* check zeros from right */, DAG);
4632 // Considering the elements in the mask that are not consecutive zeros,
4633 // check if they consecutively come from only one of the source vectors.
4635 // V1 = {X, A, B, C} 0
4637 // vector_shuffle V1, V2 <1, 2, 3, X>
4639 if (!isShuffleMaskConsecutive(SVOp,
4640 0, // Mask Start Index
4641 NumElems-NumZeros-1, // Mask End Index
4642 NumZeros, // Where to start looking in the src vector
4643 NumElems, // Number of elements in vector
4644 OpSrc)) // Which source operand ?
4649 ShVal = SVOp->getOperand(OpSrc);
4653 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4654 /// logical left shift of a vector.
4655 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4656 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4657 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4658 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4659 true /* check zeros from left */, DAG);
4665 // Considering the elements in the mask that are not consecutive zeros,
4666 // check if they consecutively come from only one of the source vectors.
4668 // 0 { A, B, X, X } = V2
4670 // vector_shuffle V1, V2 <X, X, 4, 5>
4672 if (!isShuffleMaskConsecutive(SVOp,
4673 NumZeros, // Mask Start Index
4674 NumElems-1, // Mask End Index
4675 0, // Where to start looking in the src vector
4676 NumElems, // Number of elements in vector
4677 OpSrc)) // Which source operand ?
4682 ShVal = SVOp->getOperand(OpSrc);
4686 /// isVectorShift - Returns true if the shuffle can be implemented as a
4687 /// logical left or right shift of a vector.
4688 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4689 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4690 // Although the logic below support any bitwidth size, there are no
4691 // shift instructions which handle more than 128-bit vectors.
4692 if (SVOp->getValueType(0).getSizeInBits() > 128)
4695 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4696 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4702 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4704 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4705 unsigned NumNonZero, unsigned NumZero,
4707 const TargetLowering &TLI) {
4711 DebugLoc dl = Op.getDebugLoc();
4714 for (unsigned i = 0; i < 16; ++i) {
4715 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4716 if (ThisIsNonZero && First) {
4718 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4720 V = DAG.getUNDEF(MVT::v8i16);
4725 SDValue ThisElt(0, 0), LastElt(0, 0);
4726 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4727 if (LastIsNonZero) {
4728 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4729 MVT::i16, Op.getOperand(i-1));
4731 if (ThisIsNonZero) {
4732 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4733 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4734 ThisElt, DAG.getConstant(8, MVT::i8));
4736 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4740 if (ThisElt.getNode())
4741 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4742 DAG.getIntPtrConstant(i/2));
4746 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4749 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4751 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4752 unsigned NumNonZero, unsigned NumZero,
4754 const TargetLowering &TLI) {
4758 DebugLoc dl = Op.getDebugLoc();
4761 for (unsigned i = 0; i < 8; ++i) {
4762 bool isNonZero = (NonZeros & (1 << i)) != 0;
4766 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4768 V = DAG.getUNDEF(MVT::v8i16);
4771 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4772 MVT::v8i16, V, Op.getOperand(i),
4773 DAG.getIntPtrConstant(i));
4780 /// getVShift - Return a vector logical shift node.
4782 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4783 unsigned NumBits, SelectionDAG &DAG,
4784 const TargetLowering &TLI, DebugLoc dl) {
4785 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4786 EVT ShVT = MVT::v2i64;
4787 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4788 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4789 return DAG.getNode(ISD::BITCAST, dl, VT,
4790 DAG.getNode(Opc, dl, ShVT, SrcOp,
4791 DAG.getConstant(NumBits,
4792 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4796 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4797 SelectionDAG &DAG) const {
4799 // Check if the scalar load can be widened into a vector load. And if
4800 // the address is "base + cst" see if the cst can be "absorbed" into
4801 // the shuffle mask.
4802 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4803 SDValue Ptr = LD->getBasePtr();
4804 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4806 EVT PVT = LD->getValueType(0);
4807 if (PVT != MVT::i32 && PVT != MVT::f32)
4812 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4813 FI = FINode->getIndex();
4815 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4816 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4817 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4818 Offset = Ptr.getConstantOperandVal(1);
4819 Ptr = Ptr.getOperand(0);
4824 // FIXME: 256-bit vector instructions don't require a strict alignment,
4825 // improve this code to support it better.
4826 unsigned RequiredAlign = VT.getSizeInBits()/8;
4827 SDValue Chain = LD->getChain();
4828 // Make sure the stack object alignment is at least 16 or 32.
4829 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4830 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4831 if (MFI->isFixedObjectIndex(FI)) {
4832 // Can't change the alignment. FIXME: It's possible to compute
4833 // the exact stack offset and reference FI + adjust offset instead.
4834 // If someone *really* cares about this. That's the way to implement it.
4837 MFI->setObjectAlignment(FI, RequiredAlign);
4841 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4842 // Ptr + (Offset & ~15).
4845 if ((Offset % RequiredAlign) & 3)
4847 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4849 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4850 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4852 int EltNo = (Offset - StartOffset) >> 2;
4853 int NumElems = VT.getVectorNumElements();
4855 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4856 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4857 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4858 LD->getPointerInfo().getWithOffset(StartOffset),
4859 false, false, false, 0);
4861 // Canonicalize it to a v4i32 or v8i32 shuffle.
4862 SmallVector<int, 8> Mask;
4863 for (int i = 0; i < NumElems; ++i)
4864 Mask.push_back(EltNo);
4866 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4867 return DAG.getNode(ISD::BITCAST, dl, NVT,
4868 DAG.getVectorShuffle(CanonVT, dl, V1,
4869 DAG.getUNDEF(CanonVT),&Mask[0]));
4875 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4876 /// vector of type 'VT', see if the elements can be replaced by a single large
4877 /// load which has the same value as a build_vector whose operands are 'elts'.
4879 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4881 /// FIXME: we'd also like to handle the case where the last elements are zero
4882 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4883 /// There's even a handy isZeroNode for that purpose.
4884 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4885 DebugLoc &DL, SelectionDAG &DAG) {
4886 EVT EltVT = VT.getVectorElementType();
4887 unsigned NumElems = Elts.size();
4889 LoadSDNode *LDBase = NULL;
4890 unsigned LastLoadedElt = -1U;
4892 // For each element in the initializer, see if we've found a load or an undef.
4893 // If we don't find an initial load element, or later load elements are
4894 // non-consecutive, bail out.
4895 for (unsigned i = 0; i < NumElems; ++i) {
4896 SDValue Elt = Elts[i];
4898 if (!Elt.getNode() ||
4899 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4902 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4904 LDBase = cast<LoadSDNode>(Elt.getNode());
4908 if (Elt.getOpcode() == ISD::UNDEF)
4911 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4912 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4917 // If we have found an entire vector of loads and undefs, then return a large
4918 // load of the entire vector width starting at the base pointer. If we found
4919 // consecutive loads for the low half, generate a vzext_load node.
4920 if (LastLoadedElt == NumElems - 1) {
4921 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4922 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4923 LDBase->getPointerInfo(),
4924 LDBase->isVolatile(), LDBase->isNonTemporal(),
4925 LDBase->isInvariant(), 0);
4926 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4927 LDBase->getPointerInfo(),
4928 LDBase->isVolatile(), LDBase->isNonTemporal(),
4929 LDBase->isInvariant(), LDBase->getAlignment());
4930 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4931 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4932 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4933 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4935 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4936 LDBase->getPointerInfo(),
4937 LDBase->getAlignment(),
4938 false/*isVolatile*/, true/*ReadMem*/,
4940 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4945 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4946 /// a vbroadcast node. We support two patterns:
4947 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4948 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4950 /// The scalar load node is returned when a pattern is found,
4951 /// or SDValue() otherwise.
4952 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4953 EVT VT = Op.getValueType();
4956 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4957 V = V.getOperand(0);
4959 //A suspected load to be broadcasted.
4962 switch (V.getOpcode()) {
4964 // Unknown pattern found.
4967 case ISD::BUILD_VECTOR: {
4968 // The BUILD_VECTOR node must be a splat.
4969 if (!isSplatVector(V.getNode()))
4972 Ld = V.getOperand(0);
4974 // The suspected load node has several users. Make sure that all
4975 // of its users are from the BUILD_VECTOR node.
4976 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4981 case ISD::VECTOR_SHUFFLE: {
4982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4984 // Shuffles must have a splat mask where the first element is
4986 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4989 SDValue Sc = Op.getOperand(0);
4990 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4993 Ld = Sc.getOperand(0);
4995 // The scalar_to_vector node and the suspected
4996 // load node must have exactly one user.
4997 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5003 // The scalar source must be a normal load.
5004 if (!ISD::isNormalLoad(Ld.getNode()))
5007 bool Is256 = VT.getSizeInBits() == 256;
5008 bool Is128 = VT.getSizeInBits() == 128;
5009 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5012 // VBroadcast to YMM
5013 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5014 ScalarSize == 32 || ScalarSize == 64 ))
5017 // VBroadcast to XMM
5018 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5019 ScalarSize == 16 || ScalarSize == 64 ))
5023 // VBroadcast to YMM
5024 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5027 // VBroadcast to XMM
5028 if (Is128 && (ScalarSize == 32))
5032 // Unsupported broadcast.
5037 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5038 DebugLoc dl = Op.getDebugLoc();
5040 EVT VT = Op.getValueType();
5041 EVT ExtVT = VT.getVectorElementType();
5042 unsigned NumElems = Op.getNumOperands();
5044 // Vectors containing all zeros can be matched by pxor and xorps later
5045 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5046 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5047 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5048 if (Op.getValueType() == MVT::v4i32 ||
5049 Op.getValueType() == MVT::v8i32)
5052 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5055 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5056 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5057 // vpcmpeqd on 256-bit vectors.
5058 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5059 if (Op.getValueType() == MVT::v4i32 ||
5060 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5063 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5066 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5067 if (Subtarget->hasAVX() && LD.getNode())
5068 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5070 unsigned EVTBits = ExtVT.getSizeInBits();
5072 unsigned NumZero = 0;
5073 unsigned NumNonZero = 0;
5074 unsigned NonZeros = 0;
5075 bool IsAllConstants = true;
5076 SmallSet<SDValue, 8> Values;
5077 for (unsigned i = 0; i < NumElems; ++i) {
5078 SDValue Elt = Op.getOperand(i);
5079 if (Elt.getOpcode() == ISD::UNDEF)
5082 if (Elt.getOpcode() != ISD::Constant &&
5083 Elt.getOpcode() != ISD::ConstantFP)
5084 IsAllConstants = false;
5085 if (X86::isZeroNode(Elt))
5088 NonZeros |= (1 << i);
5093 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5094 if (NumNonZero == 0)
5095 return DAG.getUNDEF(VT);
5097 // Special case for single non-zero, non-undef, element.
5098 if (NumNonZero == 1) {
5099 unsigned Idx = CountTrailingZeros_32(NonZeros);
5100 SDValue Item = Op.getOperand(Idx);
5102 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5103 // the value are obviously zero, truncate the value to i32 and do the
5104 // insertion that way. Only do this if the value is non-constant or if the
5105 // value is a constant being inserted into element 0. It is cheaper to do
5106 // a constant pool load than it is to do a movd + shuffle.
5107 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5108 (!IsAllConstants || Idx == 0)) {
5109 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5111 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5112 EVT VecVT = MVT::v4i32;
5113 unsigned VecElts = 4;
5115 // Truncate the value (which may itself be a constant) to i32, and
5116 // convert it to a vector with movd (S2V+shuffle to zero extend).
5117 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5118 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5119 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5120 Subtarget->hasXMMInt(), DAG);
5122 // Now we have our 32-bit value zero extended in the low element of
5123 // a vector. If Idx != 0, swizzle it into place.
5125 SmallVector<int, 4> Mask;
5126 Mask.push_back(Idx);
5127 for (unsigned i = 1; i != VecElts; ++i)
5129 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5130 DAG.getUNDEF(Item.getValueType()),
5133 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5137 // If we have a constant or non-constant insertion into the low element of
5138 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5139 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5140 // depending on what the source datatype is.
5143 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5144 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5145 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5146 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5147 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5148 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5150 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5151 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5152 unsigned NumBits = VT.getSizeInBits();
5153 assert((NumBits == 128 || NumBits == 256) &&
5154 "Expected an SSE or AVX value type!");
5155 EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5156 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5157 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5158 Subtarget->hasXMMInt(), DAG);
5159 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5163 // Is it a vector logical left shift?
5164 if (NumElems == 2 && Idx == 1 &&
5165 X86::isZeroNode(Op.getOperand(0)) &&
5166 !X86::isZeroNode(Op.getOperand(1))) {
5167 unsigned NumBits = VT.getSizeInBits();
5168 return getVShift(true, VT,
5169 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5170 VT, Op.getOperand(1)),
5171 NumBits/2, DAG, *this, dl);
5174 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5177 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5178 // is a non-constant being inserted into an element other than the low one,
5179 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5180 // movd/movss) to move this into the low element, then shuffle it into
5182 if (EVTBits == 32) {
5183 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5185 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5186 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5187 Subtarget->hasXMMInt(), DAG);
5188 SmallVector<int, 8> MaskVec;
5189 for (unsigned i = 0; i < NumElems; i++)
5190 MaskVec.push_back(i == Idx ? 0 : 1);
5191 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5195 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5196 if (Values.size() == 1) {
5197 if (EVTBits == 32) {
5198 // Instead of a shuffle like this:
5199 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5200 // Check if it's possible to issue this instead.
5201 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5202 unsigned Idx = CountTrailingZeros_32(NonZeros);
5203 SDValue Item = Op.getOperand(Idx);
5204 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5205 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5210 // A vector full of immediates; various special cases are already
5211 // handled, so this is best done with a single constant-pool load.
5215 // For AVX-length vectors, build the individual 128-bit pieces and use
5216 // shuffles to put them in place.
5217 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5218 SmallVector<SDValue, 32> V;
5219 for (unsigned i = 0; i < NumElems; ++i)
5220 V.push_back(Op.getOperand(i));
5222 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5224 // Build both the lower and upper subvector.
5225 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5226 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5229 // Recreate the wider vector with the lower and upper part.
5230 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5231 DAG.getConstant(0, MVT::i32), DAG, dl);
5232 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5236 // Let legalizer expand 2-wide build_vectors.
5237 if (EVTBits == 64) {
5238 if (NumNonZero == 1) {
5239 // One half is zero or undef.
5240 unsigned Idx = CountTrailingZeros_32(NonZeros);
5241 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5242 Op.getOperand(Idx));
5243 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5244 Subtarget->hasXMMInt(), DAG);
5249 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5250 if (EVTBits == 8 && NumElems == 16) {
5251 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5253 if (V.getNode()) return V;
5256 if (EVTBits == 16 && NumElems == 8) {
5257 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5259 if (V.getNode()) return V;
5262 // If element VT is == 32 bits, turn it into a number of shuffles.
5263 SmallVector<SDValue, 8> V;
5265 if (NumElems == 4 && NumZero > 0) {
5266 for (unsigned i = 0; i < 4; ++i) {
5267 bool isZero = !(NonZeros & (1 << i));
5269 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5271 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5274 for (unsigned i = 0; i < 2; ++i) {
5275 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5278 V[i] = V[i*2]; // Must be a zero vector.
5281 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5284 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5287 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5292 SmallVector<int, 8> MaskVec;
5293 bool Reverse = (NonZeros & 0x3) == 2;
5294 for (unsigned i = 0; i < 2; ++i)
5295 MaskVec.push_back(Reverse ? 1-i : i);
5296 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5297 for (unsigned i = 0; i < 2; ++i)
5298 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5299 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5302 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5303 // Check for a build vector of consecutive loads.
5304 for (unsigned i = 0; i < NumElems; ++i)
5305 V[i] = Op.getOperand(i);
5307 // Check for elements which are consecutive loads.
5308 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5312 // For SSE 4.1, use insertps to put the high elements into the low element.
5313 if (getSubtarget()->hasSSE41orAVX()) {
5315 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5316 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5318 Result = DAG.getUNDEF(VT);
5320 for (unsigned i = 1; i < NumElems; ++i) {
5321 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5322 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5323 Op.getOperand(i), DAG.getIntPtrConstant(i));
5328 // Otherwise, expand into a number of unpckl*, start by extending each of
5329 // our (non-undef) elements to the full vector width with the element in the
5330 // bottom slot of the vector (which generates no code for SSE).
5331 for (unsigned i = 0; i < NumElems; ++i) {
5332 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5333 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5335 V[i] = DAG.getUNDEF(VT);
5338 // Next, we iteratively mix elements, e.g. for v4f32:
5339 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5340 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5341 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5342 unsigned EltStride = NumElems >> 1;
5343 while (EltStride != 0) {
5344 for (unsigned i = 0; i < EltStride; ++i) {
5345 // If V[i+EltStride] is undef and this is the first round of mixing,
5346 // then it is safe to just drop this shuffle: V[i] is already in the
5347 // right place, the one element (since it's the first round) being
5348 // inserted as undef can be dropped. This isn't safe for successive
5349 // rounds because they will permute elements within both vectors.
5350 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5351 EltStride == NumElems/2)
5354 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5363 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5364 // them in a MMX register. This is better than doing a stack convert.
5365 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5366 DebugLoc dl = Op.getDebugLoc();
5367 EVT ResVT = Op.getValueType();
5369 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5370 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5372 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5373 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5374 InVec = Op.getOperand(1);
5375 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5376 unsigned NumElts = ResVT.getVectorNumElements();
5377 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5378 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5379 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5381 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5382 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5383 Mask[0] = 0; Mask[1] = 2;
5384 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5386 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5389 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5390 // to create 256-bit vectors from two other 128-bit ones.
5391 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5392 DebugLoc dl = Op.getDebugLoc();
5393 EVT ResVT = Op.getValueType();
5395 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5397 SDValue V1 = Op.getOperand(0);
5398 SDValue V2 = Op.getOperand(1);
5399 unsigned NumElems = ResVT.getVectorNumElements();
5401 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5402 DAG.getConstant(0, MVT::i32), DAG, dl);
5403 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5408 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5409 EVT ResVT = Op.getValueType();
5411 assert(Op.getNumOperands() == 2);
5412 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5413 "Unsupported CONCAT_VECTORS for value type");
5415 // We support concatenate two MMX registers and place them in a MMX register.
5416 // This is better than doing a stack convert.
5417 if (ResVT.is128BitVector())
5418 return LowerMMXCONCAT_VECTORS(Op, DAG);
5420 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5421 // from two other 128-bit ones.
5422 return LowerAVXCONCAT_VECTORS(Op, DAG);
5425 // v8i16 shuffles - Prefer shuffles in the following order:
5426 // 1. [all] pshuflw, pshufhw, optional move
5427 // 2. [ssse3] 1 x pshufb
5428 // 3. [ssse3] 2 x pshufb + 1 x por
5429 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5431 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5432 SelectionDAG &DAG) const {
5433 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5434 SDValue V1 = SVOp->getOperand(0);
5435 SDValue V2 = SVOp->getOperand(1);
5436 DebugLoc dl = SVOp->getDebugLoc();
5437 SmallVector<int, 8> MaskVals;
5439 // Determine if more than 1 of the words in each of the low and high quadwords
5440 // of the result come from the same quadword of one of the two inputs. Undef
5441 // mask values count as coming from any quadword, for better codegen.
5442 unsigned LoQuad[] = { 0, 0, 0, 0 };
5443 unsigned HiQuad[] = { 0, 0, 0, 0 };
5444 BitVector InputQuads(4);
5445 for (unsigned i = 0; i < 8; ++i) {
5446 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5447 int EltIdx = SVOp->getMaskElt(i);
5448 MaskVals.push_back(EltIdx);
5457 InputQuads.set(EltIdx / 4);
5460 int BestLoQuad = -1;
5461 unsigned MaxQuad = 1;
5462 for (unsigned i = 0; i < 4; ++i) {
5463 if (LoQuad[i] > MaxQuad) {
5465 MaxQuad = LoQuad[i];
5469 int BestHiQuad = -1;
5471 for (unsigned i = 0; i < 4; ++i) {
5472 if (HiQuad[i] > MaxQuad) {
5474 MaxQuad = HiQuad[i];
5478 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5479 // of the two input vectors, shuffle them into one input vector so only a
5480 // single pshufb instruction is necessary. If There are more than 2 input
5481 // quads, disable the next transformation since it does not help SSSE3.
5482 bool V1Used = InputQuads[0] || InputQuads[1];
5483 bool V2Used = InputQuads[2] || InputQuads[3];
5484 if (Subtarget->hasSSSE3orAVX()) {
5485 if (InputQuads.count() == 2 && V1Used && V2Used) {
5486 BestLoQuad = InputQuads.find_first();
5487 BestHiQuad = InputQuads.find_next(BestLoQuad);
5489 if (InputQuads.count() > 2) {
5495 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5496 // the shuffle mask. If a quad is scored as -1, that means that it contains
5497 // words from all 4 input quadwords.
5499 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5500 SmallVector<int, 8> MaskV;
5501 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5502 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5503 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5504 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5505 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5506 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5508 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5509 // source words for the shuffle, to aid later transformations.
5510 bool AllWordsInNewV = true;
5511 bool InOrder[2] = { true, true };
5512 for (unsigned i = 0; i != 8; ++i) {
5513 int idx = MaskVals[i];
5515 InOrder[i/4] = false;
5516 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5518 AllWordsInNewV = false;
5522 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5523 if (AllWordsInNewV) {
5524 for (int i = 0; i != 8; ++i) {
5525 int idx = MaskVals[i];
5528 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5529 if ((idx != i) && idx < 4)
5531 if ((idx != i) && idx > 3)
5540 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5541 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5542 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5543 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5544 unsigned TargetMask = 0;
5545 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5546 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5547 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5548 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5549 V1 = NewV.getOperand(0);
5550 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5554 // If we have SSSE3, and all words of the result are from 1 input vector,
5555 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5556 // is present, fall back to case 4.
5557 if (Subtarget->hasSSSE3orAVX()) {
5558 SmallVector<SDValue,16> pshufbMask;
5560 // If we have elements from both input vectors, set the high bit of the
5561 // shuffle mask element to zero out elements that come from V2 in the V1
5562 // mask, and elements that come from V1 in the V2 mask, so that the two
5563 // results can be OR'd together.
5564 bool TwoInputs = V1Used && V2Used;
5565 for (unsigned i = 0; i != 8; ++i) {
5566 int EltIdx = MaskVals[i] * 2;
5567 if (TwoInputs && (EltIdx >= 16)) {
5568 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5569 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5572 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5573 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5575 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5576 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5577 DAG.getNode(ISD::BUILD_VECTOR, dl,
5578 MVT::v16i8, &pshufbMask[0], 16));
5580 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5582 // Calculate the shuffle mask for the second input, shuffle it, and
5583 // OR it with the first shuffled input.
5585 for (unsigned i = 0; i != 8; ++i) {
5586 int EltIdx = MaskVals[i] * 2;
5588 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5589 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5592 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5593 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5595 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5596 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5597 DAG.getNode(ISD::BUILD_VECTOR, dl,
5598 MVT::v16i8, &pshufbMask[0], 16));
5599 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5600 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5603 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5604 // and update MaskVals with new element order.
5605 BitVector InOrder(8);
5606 if (BestLoQuad >= 0) {
5607 SmallVector<int, 8> MaskV;
5608 for (int i = 0; i != 4; ++i) {
5609 int idx = MaskVals[i];
5611 MaskV.push_back(-1);
5613 } else if ((idx / 4) == BestLoQuad) {
5614 MaskV.push_back(idx & 3);
5617 MaskV.push_back(-1);
5620 for (unsigned i = 4; i != 8; ++i)
5622 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5625 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5626 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5628 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5632 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5633 // and update MaskVals with the new element order.
5634 if (BestHiQuad >= 0) {
5635 SmallVector<int, 8> MaskV;
5636 for (unsigned i = 0; i != 4; ++i)
5638 for (unsigned i = 4; i != 8; ++i) {
5639 int idx = MaskVals[i];
5641 MaskV.push_back(-1);
5643 } else if ((idx / 4) == BestHiQuad) {
5644 MaskV.push_back((idx & 3) + 4);
5647 MaskV.push_back(-1);
5650 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5653 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5654 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5656 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5660 // In case BestHi & BestLo were both -1, which means each quadword has a word
5661 // from each of the four input quadwords, calculate the InOrder bitvector now
5662 // before falling through to the insert/extract cleanup.
5663 if (BestLoQuad == -1 && BestHiQuad == -1) {
5665 for (int i = 0; i != 8; ++i)
5666 if (MaskVals[i] < 0 || MaskVals[i] == i)
5670 // The other elements are put in the right place using pextrw and pinsrw.
5671 for (unsigned i = 0; i != 8; ++i) {
5674 int EltIdx = MaskVals[i];
5677 SDValue ExtOp = (EltIdx < 8)
5678 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5679 DAG.getIntPtrConstant(EltIdx))
5680 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5681 DAG.getIntPtrConstant(EltIdx - 8));
5682 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5683 DAG.getIntPtrConstant(i));
5688 // v16i8 shuffles - Prefer shuffles in the following order:
5689 // 1. [ssse3] 1 x pshufb
5690 // 2. [ssse3] 2 x pshufb + 1 x por
5691 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5693 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5695 const X86TargetLowering &TLI) {
5696 SDValue V1 = SVOp->getOperand(0);
5697 SDValue V2 = SVOp->getOperand(1);
5698 DebugLoc dl = SVOp->getDebugLoc();
5699 SmallVector<int, 16> MaskVals;
5700 SVOp->getMask(MaskVals);
5702 // If we have SSSE3, case 1 is generated when all result bytes come from
5703 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5704 // present, fall back to case 3.
5705 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5708 for (unsigned i = 0; i < 16; ++i) {
5709 int EltIdx = MaskVals[i];
5718 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5719 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5720 SmallVector<SDValue,16> pshufbMask;
5722 // If all result elements are from one input vector, then only translate
5723 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5725 // Otherwise, we have elements from both input vectors, and must zero out
5726 // elements that come from V2 in the first mask, and V1 in the second mask
5727 // so that we can OR them together.
5728 bool TwoInputs = !(V1Only || V2Only);
5729 for (unsigned i = 0; i != 16; ++i) {
5730 int EltIdx = MaskVals[i];
5731 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5732 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5735 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5737 // If all the elements are from V2, assign it to V1 and return after
5738 // building the first pshufb.
5741 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5742 DAG.getNode(ISD::BUILD_VECTOR, dl,
5743 MVT::v16i8, &pshufbMask[0], 16));
5747 // Calculate the shuffle mask for the second input, shuffle it, and
5748 // OR it with the first shuffled input.
5750 for (unsigned i = 0; i != 16; ++i) {
5751 int EltIdx = MaskVals[i];
5753 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5756 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5758 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5759 DAG.getNode(ISD::BUILD_VECTOR, dl,
5760 MVT::v16i8, &pshufbMask[0], 16));
5761 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5764 // No SSSE3 - Calculate in place words and then fix all out of place words
5765 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5766 // the 16 different words that comprise the two doublequadword input vectors.
5767 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5768 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5769 SDValue NewV = V2Only ? V2 : V1;
5770 for (int i = 0; i != 8; ++i) {
5771 int Elt0 = MaskVals[i*2];
5772 int Elt1 = MaskVals[i*2+1];
5774 // This word of the result is all undef, skip it.
5775 if (Elt0 < 0 && Elt1 < 0)
5778 // This word of the result is already in the correct place, skip it.
5779 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5781 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5784 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5785 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5788 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5789 // using a single extract together, load it and store it.
5790 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5791 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5792 DAG.getIntPtrConstant(Elt1 / 2));
5793 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5794 DAG.getIntPtrConstant(i));
5798 // If Elt1 is defined, extract it from the appropriate source. If the
5799 // source byte is not also odd, shift the extracted word left 8 bits
5800 // otherwise clear the bottom 8 bits if we need to do an or.
5802 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5803 DAG.getIntPtrConstant(Elt1 / 2));
5804 if ((Elt1 & 1) == 0)
5805 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5807 TLI.getShiftAmountTy(InsElt.getValueType())));
5809 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5810 DAG.getConstant(0xFF00, MVT::i16));
5812 // If Elt0 is defined, extract it from the appropriate source. If the
5813 // source byte is not also even, shift the extracted word right 8 bits. If
5814 // Elt1 was also defined, OR the extracted values together before
5815 // inserting them in the result.
5817 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5818 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5819 if ((Elt0 & 1) != 0)
5820 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5822 TLI.getShiftAmountTy(InsElt0.getValueType())));
5824 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5825 DAG.getConstant(0x00FF, MVT::i16));
5826 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5829 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5830 DAG.getIntPtrConstant(i));
5832 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5835 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5836 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5837 /// done when every pair / quad of shuffle mask elements point to elements in
5838 /// the right sequence. e.g.
5839 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5841 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5842 SelectionDAG &DAG, DebugLoc dl) {
5843 EVT VT = SVOp->getValueType(0);
5844 SDValue V1 = SVOp->getOperand(0);
5845 SDValue V2 = SVOp->getOperand(1);
5846 unsigned NumElems = VT.getVectorNumElements();
5847 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5849 switch (VT.getSimpleVT().SimpleTy) {
5850 default: assert(false && "Unexpected!");
5851 case MVT::v4f32: NewVT = MVT::v2f64; break;
5852 case MVT::v4i32: NewVT = MVT::v2i64; break;
5853 case MVT::v8i16: NewVT = MVT::v4i32; break;
5854 case MVT::v16i8: NewVT = MVT::v4i32; break;
5857 int Scale = NumElems / NewWidth;
5858 SmallVector<int, 8> MaskVec;
5859 for (unsigned i = 0; i < NumElems; i += Scale) {
5861 for (int j = 0; j < Scale; ++j) {
5862 int EltIdx = SVOp->getMaskElt(i+j);
5866 StartIdx = EltIdx - (EltIdx % Scale);
5867 if (EltIdx != StartIdx + j)
5871 MaskVec.push_back(-1);
5873 MaskVec.push_back(StartIdx / Scale);
5876 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5877 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5878 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5881 /// getVZextMovL - Return a zero-extending vector move low node.
5883 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5884 SDValue SrcOp, SelectionDAG &DAG,
5885 const X86Subtarget *Subtarget, DebugLoc dl) {
5886 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5887 LoadSDNode *LD = NULL;
5888 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5889 LD = dyn_cast<LoadSDNode>(SrcOp);
5891 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5893 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5894 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5895 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5896 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5897 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5899 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5900 return DAG.getNode(ISD::BITCAST, dl, VT,
5901 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5902 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5910 return DAG.getNode(ISD::BITCAST, dl, VT,
5911 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5912 DAG.getNode(ISD::BITCAST, dl,
5916 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5917 /// shuffle node referes to only one lane in the sources.
5918 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5919 EVT VT = SVOp->getValueType(0);
5920 int NumElems = VT.getVectorNumElements();
5921 int HalfSize = NumElems/2;
5922 SmallVector<int, 16> M;
5924 bool MatchA = false, MatchB = false;
5926 for (int l = 0; l < NumElems*2; l += HalfSize) {
5927 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5933 for (int l = 0; l < NumElems*2; l += HalfSize) {
5934 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5940 return MatchA && MatchB;
5943 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5944 /// which could not be matched by any known target speficic shuffle
5946 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5947 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5948 // If each half of a vector shuffle node referes to only one lane in the
5949 // source vectors, extract each used 128-bit lane and shuffle them using
5950 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5951 // the work to the legalizer.
5952 DebugLoc dl = SVOp->getDebugLoc();
5953 EVT VT = SVOp->getValueType(0);
5954 int NumElems = VT.getVectorNumElements();
5955 int HalfSize = NumElems/2;
5957 // Extract the reference for each half
5958 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5959 int FstVecOpNum = 0, SndVecOpNum = 0;
5960 for (int i = 0; i < HalfSize; ++i) {
5961 int Elt = SVOp->getMaskElt(i);
5962 if (SVOp->getMaskElt(i) < 0)
5964 FstVecOpNum = Elt/NumElems;
5965 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5968 for (int i = HalfSize; i < NumElems; ++i) {
5969 int Elt = SVOp->getMaskElt(i);
5970 if (SVOp->getMaskElt(i) < 0)
5972 SndVecOpNum = Elt/NumElems;
5973 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5977 // Extract the subvectors
5978 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5979 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5980 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5981 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5983 // Generate 128-bit shuffles
5984 SmallVector<int, 16> MaskV1, MaskV2;
5985 for (int i = 0; i < HalfSize; ++i) {
5986 int Elt = SVOp->getMaskElt(i);
5987 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5989 for (int i = HalfSize; i < NumElems; ++i) {
5990 int Elt = SVOp->getMaskElt(i);
5991 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5994 EVT NVT = V1.getValueType();
5995 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5996 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5998 // Concatenate the result back
5999 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6000 DAG.getConstant(0, MVT::i32), DAG, dl);
6001 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6008 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6009 /// 4 elements, and match them with several different shuffle types.
6011 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6012 SDValue V1 = SVOp->getOperand(0);
6013 SDValue V2 = SVOp->getOperand(1);
6014 DebugLoc dl = SVOp->getDebugLoc();
6015 EVT VT = SVOp->getValueType(0);
6017 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6019 SmallVector<std::pair<int, int>, 8> Locs;
6021 SmallVector<int, 8> Mask1(4U, -1);
6022 SmallVector<int, 8> PermMask;
6023 SVOp->getMask(PermMask);
6027 for (unsigned i = 0; i != 4; ++i) {
6028 int Idx = PermMask[i];
6030 Locs[i] = std::make_pair(-1, -1);
6032 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6034 Locs[i] = std::make_pair(0, NumLo);
6038 Locs[i] = std::make_pair(1, NumHi);
6040 Mask1[2+NumHi] = Idx;
6046 if (NumLo <= 2 && NumHi <= 2) {
6047 // If no more than two elements come from either vector. This can be
6048 // implemented with two shuffles. First shuffle gather the elements.
6049 // The second shuffle, which takes the first shuffle as both of its
6050 // vector operands, put the elements into the right order.
6051 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6053 SmallVector<int, 8> Mask2(4U, -1);
6055 for (unsigned i = 0; i != 4; ++i) {
6056 if (Locs[i].first == -1)
6059 unsigned Idx = (i < 2) ? 0 : 4;
6060 Idx += Locs[i].first * 2 + Locs[i].second;
6065 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6066 } else if (NumLo == 3 || NumHi == 3) {
6067 // Otherwise, we must have three elements from one vector, call it X, and
6068 // one element from the other, call it Y. First, use a shufps to build an
6069 // intermediate vector with the one element from Y and the element from X
6070 // that will be in the same half in the final destination (the indexes don't
6071 // matter). Then, use a shufps to build the final vector, taking the half
6072 // containing the element from Y from the intermediate, and the other half
6075 // Normalize it so the 3 elements come from V1.
6076 CommuteVectorShuffleMask(PermMask, 4);
6080 // Find the element from V2.
6082 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6083 int Val = PermMask[HiIndex];
6090 Mask1[0] = PermMask[HiIndex];
6092 Mask1[2] = PermMask[HiIndex^1];
6094 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6097 Mask1[0] = PermMask[0];
6098 Mask1[1] = PermMask[1];
6099 Mask1[2] = HiIndex & 1 ? 6 : 4;
6100 Mask1[3] = HiIndex & 1 ? 4 : 6;
6101 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6103 Mask1[0] = HiIndex & 1 ? 2 : 0;
6104 Mask1[1] = HiIndex & 1 ? 0 : 2;
6105 Mask1[2] = PermMask[2];
6106 Mask1[3] = PermMask[3];
6111 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6115 // Break it into (shuffle shuffle_hi, shuffle_lo).
6118 SmallVector<int,8> LoMask(4U, -1);
6119 SmallVector<int,8> HiMask(4U, -1);
6121 SmallVector<int,8> *MaskPtr = &LoMask;
6122 unsigned MaskIdx = 0;
6125 for (unsigned i = 0; i != 4; ++i) {
6132 int Idx = PermMask[i];
6134 Locs[i] = std::make_pair(-1, -1);
6135 } else if (Idx < 4) {
6136 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6137 (*MaskPtr)[LoIdx] = Idx;
6140 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6141 (*MaskPtr)[HiIdx] = Idx;
6146 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6147 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6148 SmallVector<int, 8> MaskOps;
6149 for (unsigned i = 0; i != 4; ++i) {
6150 if (Locs[i].first == -1) {
6151 MaskOps.push_back(-1);
6153 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6154 MaskOps.push_back(Idx);
6157 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6160 static bool MayFoldVectorLoad(SDValue V) {
6161 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6162 V = V.getOperand(0);
6163 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6164 V = V.getOperand(0);
6165 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6166 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6167 // BUILD_VECTOR (load), undef
6168 V = V.getOperand(0);
6174 // FIXME: the version above should always be used. Since there's
6175 // a bug where several vector shuffles can't be folded because the
6176 // DAG is not updated during lowering and a node claims to have two
6177 // uses while it only has one, use this version, and let isel match
6178 // another instruction if the load really happens to have more than
6179 // one use. Remove this version after this bug get fixed.
6180 // rdar://8434668, PR8156
6181 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6182 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6183 V = V.getOperand(0);
6184 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6185 V = V.getOperand(0);
6186 if (ISD::isNormalLoad(V.getNode()))
6191 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6192 /// a vector extract, and if both can be later optimized into a single load.
6193 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6194 /// here because otherwise a target specific shuffle node is going to be
6195 /// emitted for this shuffle, and the optimization not done.
6196 /// FIXME: This is probably not the best approach, but fix the problem
6197 /// until the right path is decided.
6199 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6200 const TargetLowering &TLI) {
6201 EVT VT = V.getValueType();
6202 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6204 // Be sure that the vector shuffle is present in a pattern like this:
6205 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6209 SDNode *N = *V.getNode()->use_begin();
6210 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6213 SDValue EltNo = N->getOperand(1);
6214 if (!isa<ConstantSDNode>(EltNo))
6217 // If the bit convert changed the number of elements, it is unsafe
6218 // to examine the mask.
6219 bool HasShuffleIntoBitcast = false;
6220 if (V.getOpcode() == ISD::BITCAST) {
6221 EVT SrcVT = V.getOperand(0).getValueType();
6222 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6224 V = V.getOperand(0);
6225 HasShuffleIntoBitcast = true;
6228 // Select the input vector, guarding against out of range extract vector.
6229 unsigned NumElems = VT.getVectorNumElements();
6230 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6231 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6232 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6234 // Skip one more bit_convert if necessary
6235 if (V.getOpcode() == ISD::BITCAST)
6236 V = V.getOperand(0);
6238 if (ISD::isNormalLoad(V.getNode())) {
6239 // Is the original load suitable?
6240 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6242 // FIXME: avoid the multi-use bug that is preventing lots of
6243 // of foldings to be detected, this is still wrong of course, but
6244 // give the temporary desired behavior, and if it happens that
6245 // the load has real more uses, during isel it will not fold, and
6246 // will generate poor code.
6247 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6250 if (!HasShuffleIntoBitcast)
6253 // If there's a bitcast before the shuffle, check if the load type and
6254 // alignment is valid.
6255 unsigned Align = LN0->getAlignment();
6257 TLI.getTargetData()->getABITypeAlignment(
6258 VT.getTypeForEVT(*DAG.getContext()));
6260 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6268 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6269 EVT VT = Op.getValueType();
6271 // Canonizalize to v2f64.
6272 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6273 return DAG.getNode(ISD::BITCAST, dl, VT,
6274 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6279 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6281 SDValue V1 = Op.getOperand(0);
6282 SDValue V2 = Op.getOperand(1);
6283 EVT VT = Op.getValueType();
6285 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6287 if (HasXMMInt && VT == MVT::v2f64)
6288 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6290 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6291 return DAG.getNode(ISD::BITCAST, dl, VT,
6292 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6293 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6294 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6298 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6299 SDValue V1 = Op.getOperand(0);
6300 SDValue V2 = Op.getOperand(1);
6301 EVT VT = Op.getValueType();
6303 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6304 "unsupported shuffle type");
6306 if (V2.getOpcode() == ISD::UNDEF)
6310 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6313 static inline unsigned getSHUFPOpcode(EVT VT) {
6314 switch(VT.getSimpleVT().SimpleTy) {
6315 case MVT::v8i32: // Use fp unit for int unpack.
6317 case MVT::v4i32: // Use fp unit for int unpack.
6318 case MVT::v4f32: return X86ISD::SHUFPS;
6319 case MVT::v4i64: // Use fp unit for int unpack.
6321 case MVT::v2i64: // Use fp unit for int unpack.
6322 case MVT::v2f64: return X86ISD::SHUFPD;
6324 llvm_unreachable("Unknown type for shufp*");
6330 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6331 SDValue V1 = Op.getOperand(0);
6332 SDValue V2 = Op.getOperand(1);
6333 EVT VT = Op.getValueType();
6334 unsigned NumElems = VT.getVectorNumElements();
6336 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6337 // operand of these instructions is only memory, so check if there's a
6338 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6340 bool CanFoldLoad = false;
6342 // Trivial case, when V2 comes from a load.
6343 if (MayFoldVectorLoad(V2))
6346 // When V1 is a load, it can be folded later into a store in isel, example:
6347 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6349 // (MOVLPSmr addr:$src1, VR128:$src2)
6350 // So, recognize this potential and also use MOVLPS or MOVLPD
6351 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6356 if (HasXMMInt && NumElems == 2)
6357 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6360 // If we don't care about the second element, procede to use movss.
6361 if (SVOp->getMaskElt(1) != -1)
6362 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6365 // movl and movlp will both match v2i64, but v2i64 is never matched by
6366 // movl earlier because we make it strict to avoid messing with the movlp load
6367 // folding logic (see the code above getMOVLP call). Match it here then,
6368 // this is horrible, but will stay like this until we move all shuffle
6369 // matching to x86 specific nodes. Note that for the 1st condition all
6370 // types are matched with movsd.
6372 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6373 // as to remove this logic from here, as much as possible
6374 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6375 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6376 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6379 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6381 // Invert the operand order and use SHUFPS to match it.
6382 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6383 X86::getShuffleSHUFImmediate(SVOp), DAG);
6387 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6388 const TargetLowering &TLI,
6389 const X86Subtarget *Subtarget) {
6390 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6391 EVT VT = Op.getValueType();
6392 DebugLoc dl = Op.getDebugLoc();
6393 SDValue V1 = Op.getOperand(0);
6394 SDValue V2 = Op.getOperand(1);
6396 if (isZeroShuffle(SVOp))
6397 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6399 // Handle splat operations
6400 if (SVOp->isSplat()) {
6401 unsigned NumElem = VT.getVectorNumElements();
6402 int Size = VT.getSizeInBits();
6403 // Special case, this is the only place now where it's allowed to return
6404 // a vector_shuffle operation without using a target specific node, because
6405 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6406 // this be moved to DAGCombine instead?
6407 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6410 // Use vbroadcast whenever the splat comes from a foldable load
6411 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6412 if (Subtarget->hasAVX() && LD.getNode())
6413 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6415 // Handle splats by matching through known shuffle masks
6416 if ((Size == 128 && NumElem <= 4) ||
6417 (Size == 256 && NumElem < 8))
6420 // All remaning splats are promoted to target supported vector shuffles.
6421 return PromoteSplat(SVOp, DAG);
6424 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6426 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6427 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6428 if (NewOp.getNode())
6429 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6430 } else if ((VT == MVT::v4i32 ||
6431 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6432 // FIXME: Figure out a cleaner way to do this.
6433 // Try to make use of movq to zero out the top part.
6434 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6435 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6436 if (NewOp.getNode()) {
6437 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6438 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6439 DAG, Subtarget, dl);
6441 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6442 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6443 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6444 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6445 DAG, Subtarget, dl);
6452 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6453 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6454 SDValue V1 = Op.getOperand(0);
6455 SDValue V2 = Op.getOperand(1);
6456 EVT VT = Op.getValueType();
6457 DebugLoc dl = Op.getDebugLoc();
6458 unsigned NumElems = VT.getVectorNumElements();
6459 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6460 bool V1IsSplat = false;
6461 bool V2IsSplat = false;
6462 bool HasXMMInt = Subtarget->hasXMMInt();
6463 bool HasAVX = Subtarget->hasAVX();
6464 bool HasAVX2 = Subtarget->hasAVX2();
6465 MachineFunction &MF = DAG.getMachineFunction();
6466 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6468 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6470 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6472 // Vector shuffle lowering takes 3 steps:
6474 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6475 // narrowing and commutation of operands should be handled.
6476 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6478 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6479 // so the shuffle can be broken into other shuffles and the legalizer can
6480 // try the lowering again.
6482 // The general idea is that no vector_shuffle operation should be left to
6483 // be matched during isel, all of them must be converted to a target specific
6486 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6487 // narrowing and commutation of operands should be handled. The actual code
6488 // doesn't include all of those, work in progress...
6489 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6490 if (NewOp.getNode())
6493 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6494 // unpckh_undef). Only use pshufd if speed is more important than size.
6495 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6496 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6497 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6498 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6500 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6501 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6502 return getMOVDDup(Op, dl, V1, DAG);
6504 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6505 return getMOVHighToLow(Op, dl, DAG);
6507 // Use to match splats
6508 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6509 (VT == MVT::v2f64 || VT == MVT::v2i64))
6510 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6512 if (X86::isPSHUFDMask(SVOp)) {
6513 // The actual implementation will match the mask in the if above and then
6514 // during isel it can match several different instructions, not only pshufd
6515 // as its name says, sad but true, emulate the behavior for now...
6516 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6517 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6519 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6521 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6522 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6524 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6528 // Check if this can be converted into a logical shift.
6529 bool isLeft = false;
6532 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6533 if (isShift && ShVal.hasOneUse()) {
6534 // If the shifted value has multiple uses, it may be cheaper to use
6535 // v_set0 + movlhps or movhlps, etc.
6536 EVT EltVT = VT.getVectorElementType();
6537 ShAmt *= EltVT.getSizeInBits();
6538 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6541 if (X86::isMOVLMask(SVOp)) {
6542 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6543 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6544 if (!X86::isMOVLPMask(SVOp)) {
6545 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6546 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6548 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6549 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6553 // FIXME: fold these into legal mask.
6554 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6555 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6557 if (X86::isMOVHLPSMask(SVOp))
6558 return getMOVHighToLow(Op, dl, DAG);
6560 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6561 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6563 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6564 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6566 if (X86::isMOVLPMask(SVOp))
6567 return getMOVLP(Op, dl, DAG, HasXMMInt);
6569 if (ShouldXformToMOVHLPS(SVOp) ||
6570 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6571 return CommuteVectorShuffle(SVOp, DAG);
6574 // No better options. Use a vshl / vsrl.
6575 EVT EltVT = VT.getVectorElementType();
6576 ShAmt *= EltVT.getSizeInBits();
6577 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6580 bool Commuted = false;
6581 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6582 // 1,1,1,1 -> v8i16 though.
6583 V1IsSplat = isSplatVector(V1.getNode());
6584 V2IsSplat = isSplatVector(V2.getNode());
6586 // Canonicalize the splat or undef, if present, to be on the RHS.
6587 if (V1IsSplat && !V2IsSplat) {
6588 Op = CommuteVectorShuffle(SVOp, DAG);
6589 SVOp = cast<ShuffleVectorSDNode>(Op);
6590 V1 = SVOp->getOperand(0);
6591 V2 = SVOp->getOperand(1);
6592 std::swap(V1IsSplat, V2IsSplat);
6596 SmallVector<int, 32> M;
6599 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6600 // Shuffling low element of v1 into undef, just return v1.
6603 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6604 // the instruction selector will not match, so get a canonical MOVL with
6605 // swapped operands to undo the commute.
6606 return getMOVL(DAG, dl, VT, V2, V1);
6609 if (isUNPCKLMask(M, VT, HasAVX2))
6610 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6612 if (isUNPCKHMask(M, VT, HasAVX2))
6613 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6616 // Normalize mask so all entries that point to V2 points to its first
6617 // element then try to match unpck{h|l} again. If match, return a
6618 // new vector_shuffle with the corrected mask.
6619 SDValue NewMask = NormalizeMask(SVOp, DAG);
6620 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6621 if (NSVOp != SVOp) {
6622 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6624 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6631 // Commute is back and try unpck* again.
6632 // FIXME: this seems wrong.
6633 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6634 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6636 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6637 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6639 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6640 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6643 // Normalize the node to match x86 shuffle ops if needed
6644 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6645 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6646 return CommuteVectorShuffle(SVOp, DAG);
6648 // The checks below are all present in isShuffleMaskLegal, but they are
6649 // inlined here right now to enable us to directly emit target specific
6650 // nodes, and remove one by one until they don't return Op anymore.
6652 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6653 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6654 getShufflePALIGNRImmediate(SVOp),
6657 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6658 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6659 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6660 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6663 if (isPSHUFHWMask(M, VT))
6664 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6665 X86::getShufflePSHUFHWImmediate(SVOp),
6668 if (isPSHUFLWMask(M, VT))
6669 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6670 X86::getShufflePSHUFLWImmediate(SVOp),
6673 if (isSHUFPMask(M, VT))
6674 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6675 X86::getShuffleSHUFImmediate(SVOp), DAG);
6677 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6678 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6679 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6680 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6682 //===--------------------------------------------------------------------===//
6683 // Generate target specific nodes for 128 or 256-bit shuffles only
6684 // supported in the AVX instruction set.
6687 // Handle VMOVDDUPY permutations
6688 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6689 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6691 // Handle VPERMILPS/D* permutations
6692 if (isVPERMILPMask(M, VT, HasAVX))
6693 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6694 getShuffleVPERMILPImmediate(SVOp), DAG);
6696 // Handle VPERM2F128/VPERM2I128 permutations
6697 if (isVPERM2X128Mask(M, VT, HasAVX))
6698 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6699 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6701 // Handle VSHUFPS/DY permutations
6702 if (isVSHUFPYMask(M, VT, HasAVX))
6703 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6704 getShuffleVSHUFPYImmediate(SVOp), DAG);
6706 //===--------------------------------------------------------------------===//
6707 // Since no target specific shuffle was selected for this generic one,
6708 // lower it into other known shuffles. FIXME: this isn't true yet, but
6709 // this is the plan.
6712 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6713 if (VT == MVT::v8i16) {
6714 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6715 if (NewOp.getNode())
6719 if (VT == MVT::v16i8) {
6720 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6721 if (NewOp.getNode())
6725 // Handle all 128-bit wide vectors with 4 elements, and match them with
6726 // several different shuffle types.
6727 if (NumElems == 4 && VT.getSizeInBits() == 128)
6728 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6730 // Handle general 256-bit shuffles
6731 if (VT.is256BitVector())
6732 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6738 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6739 SelectionDAG &DAG) const {
6740 EVT VT = Op.getValueType();
6741 DebugLoc dl = Op.getDebugLoc();
6743 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6746 if (VT.getSizeInBits() == 8) {
6747 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6748 Op.getOperand(0), Op.getOperand(1));
6749 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6750 DAG.getValueType(VT));
6751 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6752 } else if (VT.getSizeInBits() == 16) {
6753 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6754 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6756 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6757 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6758 DAG.getNode(ISD::BITCAST, dl,
6762 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6763 Op.getOperand(0), Op.getOperand(1));
6764 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6765 DAG.getValueType(VT));
6766 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6767 } else if (VT == MVT::f32) {
6768 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6769 // the result back to FR32 register. It's only worth matching if the
6770 // result has a single use which is a store or a bitcast to i32. And in
6771 // the case of a store, it's not worth it if the index is a constant 0,
6772 // because a MOVSSmr can be used instead, which is smaller and faster.
6773 if (!Op.hasOneUse())
6775 SDNode *User = *Op.getNode()->use_begin();
6776 if ((User->getOpcode() != ISD::STORE ||
6777 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6778 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6779 (User->getOpcode() != ISD::BITCAST ||
6780 User->getValueType(0) != MVT::i32))
6782 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6783 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6786 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6787 } else if (VT == MVT::i32 || VT == MVT::i64) {
6788 // ExtractPS/pextrq works with constant index.
6789 if (isa<ConstantSDNode>(Op.getOperand(1)))
6797 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6798 SelectionDAG &DAG) const {
6799 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6802 SDValue Vec = Op.getOperand(0);
6803 EVT VecVT = Vec.getValueType();
6805 // If this is a 256-bit vector result, first extract the 128-bit vector and
6806 // then extract the element from the 128-bit vector.
6807 if (VecVT.getSizeInBits() == 256) {
6808 DebugLoc dl = Op.getNode()->getDebugLoc();
6809 unsigned NumElems = VecVT.getVectorNumElements();
6810 SDValue Idx = Op.getOperand(1);
6811 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6813 // Get the 128-bit vector.
6814 bool Upper = IdxVal >= NumElems/2;
6815 Vec = Extract128BitVector(Vec,
6816 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6818 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6819 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6822 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6824 if (Subtarget->hasSSE41orAVX()) {
6825 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6830 EVT VT = Op.getValueType();
6831 DebugLoc dl = Op.getDebugLoc();
6832 // TODO: handle v16i8.
6833 if (VT.getSizeInBits() == 16) {
6834 SDValue Vec = Op.getOperand(0);
6835 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6837 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6838 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6839 DAG.getNode(ISD::BITCAST, dl,
6842 // Transform it so it match pextrw which produces a 32-bit result.
6843 EVT EltVT = MVT::i32;
6844 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6845 Op.getOperand(0), Op.getOperand(1));
6846 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6847 DAG.getValueType(VT));
6848 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6849 } else if (VT.getSizeInBits() == 32) {
6850 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6854 // SHUFPS the element to the lowest double word, then movss.
6855 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6856 EVT VVT = Op.getOperand(0).getValueType();
6857 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6858 DAG.getUNDEF(VVT), Mask);
6859 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6860 DAG.getIntPtrConstant(0));
6861 } else if (VT.getSizeInBits() == 64) {
6862 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6863 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6864 // to match extract_elt for f64.
6865 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6869 // UNPCKHPD the element to the lowest double word, then movsd.
6870 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6871 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6872 int Mask[2] = { 1, -1 };
6873 EVT VVT = Op.getOperand(0).getValueType();
6874 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6875 DAG.getUNDEF(VVT), Mask);
6876 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6877 DAG.getIntPtrConstant(0));
6884 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6885 SelectionDAG &DAG) const {
6886 EVT VT = Op.getValueType();
6887 EVT EltVT = VT.getVectorElementType();
6888 DebugLoc dl = Op.getDebugLoc();
6890 SDValue N0 = Op.getOperand(0);
6891 SDValue N1 = Op.getOperand(1);
6892 SDValue N2 = Op.getOperand(2);
6894 if (VT.getSizeInBits() == 256)
6897 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6898 isa<ConstantSDNode>(N2)) {
6900 if (VT == MVT::v8i16)
6901 Opc = X86ISD::PINSRW;
6902 else if (VT == MVT::v16i8)
6903 Opc = X86ISD::PINSRB;
6905 Opc = X86ISD::PINSRB;
6907 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6909 if (N1.getValueType() != MVT::i32)
6910 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6911 if (N2.getValueType() != MVT::i32)
6912 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6913 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6914 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6915 // Bits [7:6] of the constant are the source select. This will always be
6916 // zero here. The DAG Combiner may combine an extract_elt index into these
6917 // bits. For example (insert (extract, 3), 2) could be matched by putting
6918 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6919 // Bits [5:4] of the constant are the destination select. This is the
6920 // value of the incoming immediate.
6921 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6922 // combine either bitwise AND or insert of float 0.0 to set these bits.
6923 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6924 // Create this as a scalar to vector..
6925 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6926 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6927 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6928 isa<ConstantSDNode>(N2)) {
6929 // PINSR* works with constant index.
6936 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6937 EVT VT = Op.getValueType();
6938 EVT EltVT = VT.getVectorElementType();
6940 DebugLoc dl = Op.getDebugLoc();
6941 SDValue N0 = Op.getOperand(0);
6942 SDValue N1 = Op.getOperand(1);
6943 SDValue N2 = Op.getOperand(2);
6945 // If this is a 256-bit vector result, first extract the 128-bit vector,
6946 // insert the element into the extracted half and then place it back.
6947 if (VT.getSizeInBits() == 256) {
6948 if (!isa<ConstantSDNode>(N2))
6951 // Get the desired 128-bit vector half.
6952 unsigned NumElems = VT.getVectorNumElements();
6953 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6954 bool Upper = IdxVal >= NumElems/2;
6955 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6956 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6958 // Insert the element into the desired half.
6959 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6960 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6962 // Insert the changed part back to the 256-bit vector
6963 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6966 if (Subtarget->hasSSE41orAVX())
6967 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6969 if (EltVT == MVT::i8)
6972 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6973 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6974 // as its second argument.
6975 if (N1.getValueType() != MVT::i32)
6976 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6977 if (N2.getValueType() != MVT::i32)
6978 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6979 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6985 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6986 LLVMContext *Context = DAG.getContext();
6987 DebugLoc dl = Op.getDebugLoc();
6988 EVT OpVT = Op.getValueType();
6990 // If this is a 256-bit vector result, first insert into a 128-bit
6991 // vector and then insert into the 256-bit vector.
6992 if (OpVT.getSizeInBits() > 128) {
6993 // Insert into a 128-bit vector.
6994 EVT VT128 = EVT::getVectorVT(*Context,
6995 OpVT.getVectorElementType(),
6996 OpVT.getVectorNumElements() / 2);
6998 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7000 // Insert the 128-bit vector.
7001 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7002 DAG.getConstant(0, MVT::i32),
7006 if (Op.getValueType() == MVT::v1i64 &&
7007 Op.getOperand(0).getValueType() == MVT::i64)
7008 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7010 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7011 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7012 "Expected an SSE type!");
7013 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7014 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7017 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7018 // a simple subregister reference or explicit instructions to grab
7019 // upper bits of a vector.
7021 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7022 if (Subtarget->hasAVX()) {
7023 DebugLoc dl = Op.getNode()->getDebugLoc();
7024 SDValue Vec = Op.getNode()->getOperand(0);
7025 SDValue Idx = Op.getNode()->getOperand(1);
7027 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7028 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7029 return Extract128BitVector(Vec, Idx, DAG, dl);
7035 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7036 // simple superregister reference or explicit instructions to insert
7037 // the upper bits of a vector.
7039 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7040 if (Subtarget->hasAVX()) {
7041 DebugLoc dl = Op.getNode()->getDebugLoc();
7042 SDValue Vec = Op.getNode()->getOperand(0);
7043 SDValue SubVec = Op.getNode()->getOperand(1);
7044 SDValue Idx = Op.getNode()->getOperand(2);
7046 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7047 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7048 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7054 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7055 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7056 // one of the above mentioned nodes. It has to be wrapped because otherwise
7057 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7058 // be used to form addressing mode. These wrapped nodes will be selected
7061 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7062 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7064 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7066 unsigned char OpFlag = 0;
7067 unsigned WrapperKind = X86ISD::Wrapper;
7068 CodeModel::Model M = getTargetMachine().getCodeModel();
7070 if (Subtarget->isPICStyleRIPRel() &&
7071 (M == CodeModel::Small || M == CodeModel::Kernel))
7072 WrapperKind = X86ISD::WrapperRIP;
7073 else if (Subtarget->isPICStyleGOT())
7074 OpFlag = X86II::MO_GOTOFF;
7075 else if (Subtarget->isPICStyleStubPIC())
7076 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7078 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7080 CP->getOffset(), OpFlag);
7081 DebugLoc DL = CP->getDebugLoc();
7082 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7083 // With PIC, the address is actually $g + Offset.
7085 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7086 DAG.getNode(X86ISD::GlobalBaseReg,
7087 DebugLoc(), getPointerTy()),
7094 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7095 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7097 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7099 unsigned char OpFlag = 0;
7100 unsigned WrapperKind = X86ISD::Wrapper;
7101 CodeModel::Model M = getTargetMachine().getCodeModel();
7103 if (Subtarget->isPICStyleRIPRel() &&
7104 (M == CodeModel::Small || M == CodeModel::Kernel))
7105 WrapperKind = X86ISD::WrapperRIP;
7106 else if (Subtarget->isPICStyleGOT())
7107 OpFlag = X86II::MO_GOTOFF;
7108 else if (Subtarget->isPICStyleStubPIC())
7109 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7111 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7113 DebugLoc DL = JT->getDebugLoc();
7114 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7116 // With PIC, the address is actually $g + Offset.
7118 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7119 DAG.getNode(X86ISD::GlobalBaseReg,
7120 DebugLoc(), getPointerTy()),
7127 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7128 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7130 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7132 unsigned char OpFlag = 0;
7133 unsigned WrapperKind = X86ISD::Wrapper;
7134 CodeModel::Model M = getTargetMachine().getCodeModel();
7136 if (Subtarget->isPICStyleRIPRel() &&
7137 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7138 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7139 OpFlag = X86II::MO_GOTPCREL;
7140 WrapperKind = X86ISD::WrapperRIP;
7141 } else if (Subtarget->isPICStyleGOT()) {
7142 OpFlag = X86II::MO_GOT;
7143 } else if (Subtarget->isPICStyleStubPIC()) {
7144 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7145 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7146 OpFlag = X86II::MO_DARWIN_NONLAZY;
7149 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7151 DebugLoc DL = Op.getDebugLoc();
7152 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7155 // With PIC, the address is actually $g + Offset.
7156 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7157 !Subtarget->is64Bit()) {
7158 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7159 DAG.getNode(X86ISD::GlobalBaseReg,
7160 DebugLoc(), getPointerTy()),
7164 // For symbols that require a load from a stub to get the address, emit the
7166 if (isGlobalStubReference(OpFlag))
7167 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7168 MachinePointerInfo::getGOT(), false, false, false, 0);
7174 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7175 // Create the TargetBlockAddressAddress node.
7176 unsigned char OpFlags =
7177 Subtarget->ClassifyBlockAddressReference();
7178 CodeModel::Model M = getTargetMachine().getCodeModel();
7179 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7180 DebugLoc dl = Op.getDebugLoc();
7181 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7182 /*isTarget=*/true, OpFlags);
7184 if (Subtarget->isPICStyleRIPRel() &&
7185 (M == CodeModel::Small || M == CodeModel::Kernel))
7186 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7188 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7190 // With PIC, the address is actually $g + Offset.
7191 if (isGlobalRelativeToPICBase(OpFlags)) {
7192 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7193 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7201 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7203 SelectionDAG &DAG) const {
7204 // Create the TargetGlobalAddress node, folding in the constant
7205 // offset if it is legal.
7206 unsigned char OpFlags =
7207 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7208 CodeModel::Model M = getTargetMachine().getCodeModel();
7210 if (OpFlags == X86II::MO_NO_FLAG &&
7211 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7212 // A direct static reference to a global.
7213 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7216 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7219 if (Subtarget->isPICStyleRIPRel() &&
7220 (M == CodeModel::Small || M == CodeModel::Kernel))
7221 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7223 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7225 // With PIC, the address is actually $g + Offset.
7226 if (isGlobalRelativeToPICBase(OpFlags)) {
7227 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7228 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7232 // For globals that require a load from a stub to get the address, emit the
7234 if (isGlobalStubReference(OpFlags))
7235 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7236 MachinePointerInfo::getGOT(), false, false, false, 0);
7238 // If there was a non-zero offset that we didn't fold, create an explicit
7241 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7242 DAG.getConstant(Offset, getPointerTy()));
7248 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7249 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7250 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7251 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7255 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7256 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7257 unsigned char OperandFlags) {
7258 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7259 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7260 DebugLoc dl = GA->getDebugLoc();
7261 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7262 GA->getValueType(0),
7266 SDValue Ops[] = { Chain, TGA, *InFlag };
7267 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7269 SDValue Ops[] = { Chain, TGA };
7270 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7273 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7274 MFI->setAdjustsStack(true);
7276 SDValue Flag = Chain.getValue(1);
7277 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7280 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7282 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7285 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7286 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7287 DAG.getNode(X86ISD::GlobalBaseReg,
7288 DebugLoc(), PtrVT), InFlag);
7289 InFlag = Chain.getValue(1);
7291 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7294 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7296 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7298 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7299 X86::RAX, X86II::MO_TLSGD);
7302 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7303 // "local exec" model.
7304 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7305 const EVT PtrVT, TLSModel::Model model,
7307 DebugLoc dl = GA->getDebugLoc();
7309 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7310 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7311 is64Bit ? 257 : 256));
7313 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7314 DAG.getIntPtrConstant(0),
7315 MachinePointerInfo(Ptr),
7316 false, false, false, 0);
7318 unsigned char OperandFlags = 0;
7319 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7321 unsigned WrapperKind = X86ISD::Wrapper;
7322 if (model == TLSModel::LocalExec) {
7323 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7324 } else if (is64Bit) {
7325 assert(model == TLSModel::InitialExec);
7326 OperandFlags = X86II::MO_GOTTPOFF;
7327 WrapperKind = X86ISD::WrapperRIP;
7329 assert(model == TLSModel::InitialExec);
7330 OperandFlags = X86II::MO_INDNTPOFF;
7333 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7336 GA->getValueType(0),
7337 GA->getOffset(), OperandFlags);
7338 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7340 if (model == TLSModel::InitialExec)
7341 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7342 MachinePointerInfo::getGOT(), false, false, false, 0);
7344 // The address of the thread local variable is the add of the thread
7345 // pointer with the offset of the variable.
7346 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7350 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7352 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7353 const GlobalValue *GV = GA->getGlobal();
7355 if (Subtarget->isTargetELF()) {
7356 // TODO: implement the "local dynamic" model
7357 // TODO: implement the "initial exec"model for pic executables
7359 // If GV is an alias then use the aliasee for determining
7360 // thread-localness.
7361 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7362 GV = GA->resolveAliasedGlobal(false);
7364 TLSModel::Model model
7365 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7368 case TLSModel::GeneralDynamic:
7369 case TLSModel::LocalDynamic: // not implemented
7370 if (Subtarget->is64Bit())
7371 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7372 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7374 case TLSModel::InitialExec:
7375 case TLSModel::LocalExec:
7376 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7377 Subtarget->is64Bit());
7379 } else if (Subtarget->isTargetDarwin()) {
7380 // Darwin only has one model of TLS. Lower to that.
7381 unsigned char OpFlag = 0;
7382 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7383 X86ISD::WrapperRIP : X86ISD::Wrapper;
7385 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7387 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7388 !Subtarget->is64Bit();
7390 OpFlag = X86II::MO_TLVP_PIC_BASE;
7392 OpFlag = X86II::MO_TLVP;
7393 DebugLoc DL = Op.getDebugLoc();
7394 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7395 GA->getValueType(0),
7396 GA->getOffset(), OpFlag);
7397 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7399 // With PIC32, the address is actually $g + Offset.
7401 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7402 DAG.getNode(X86ISD::GlobalBaseReg,
7403 DebugLoc(), getPointerTy()),
7406 // Lowering the machine isd will make sure everything is in the right
7408 SDValue Chain = DAG.getEntryNode();
7409 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7410 SDValue Args[] = { Chain, Offset };
7411 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7413 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7414 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7415 MFI->setAdjustsStack(true);
7417 // And our return value (tls address) is in the standard call return value
7419 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7420 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7425 "TLS not implemented for this target.");
7427 llvm_unreachable("Unreachable");
7432 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7433 /// take a 2 x i32 value to shift plus a shift amount.
7434 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7435 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7436 EVT VT = Op.getValueType();
7437 unsigned VTBits = VT.getSizeInBits();
7438 DebugLoc dl = Op.getDebugLoc();
7439 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7440 SDValue ShOpLo = Op.getOperand(0);
7441 SDValue ShOpHi = Op.getOperand(1);
7442 SDValue ShAmt = Op.getOperand(2);
7443 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7444 DAG.getConstant(VTBits - 1, MVT::i8))
7445 : DAG.getConstant(0, VT);
7448 if (Op.getOpcode() == ISD::SHL_PARTS) {
7449 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7450 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7452 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7453 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7456 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7457 DAG.getConstant(VTBits, MVT::i8));
7458 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7459 AndNode, DAG.getConstant(0, MVT::i8));
7462 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7463 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7464 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7466 if (Op.getOpcode() == ISD::SHL_PARTS) {
7467 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7468 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7470 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7471 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7474 SDValue Ops[2] = { Lo, Hi };
7475 return DAG.getMergeValues(Ops, 2, dl);
7478 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7479 SelectionDAG &DAG) const {
7480 EVT SrcVT = Op.getOperand(0).getValueType();
7482 if (SrcVT.isVector())
7485 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7486 "Unknown SINT_TO_FP to lower!");
7488 // These are really Legal; return the operand so the caller accepts it as
7490 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7492 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7493 Subtarget->is64Bit()) {
7497 DebugLoc dl = Op.getDebugLoc();
7498 unsigned Size = SrcVT.getSizeInBits()/8;
7499 MachineFunction &MF = DAG.getMachineFunction();
7500 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7501 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7502 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7504 MachinePointerInfo::getFixedStack(SSFI),
7506 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7509 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7511 SelectionDAG &DAG) const {
7513 DebugLoc DL = Op.getDebugLoc();
7515 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7517 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7519 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7521 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7523 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7524 MachineMemOperand *MMO;
7526 int SSFI = FI->getIndex();
7528 DAG.getMachineFunction()
7529 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7530 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7532 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7533 StackSlot = StackSlot.getOperand(1);
7535 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7536 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7538 Tys, Ops, array_lengthof(Ops),
7542 Chain = Result.getValue(1);
7543 SDValue InFlag = Result.getValue(2);
7545 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7546 // shouldn't be necessary except that RFP cannot be live across
7547 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7548 MachineFunction &MF = DAG.getMachineFunction();
7549 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7550 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7551 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7552 Tys = DAG.getVTList(MVT::Other);
7554 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7556 MachineMemOperand *MMO =
7557 DAG.getMachineFunction()
7558 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7559 MachineMemOperand::MOStore, SSFISize, SSFISize);
7561 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7562 Ops, array_lengthof(Ops),
7563 Op.getValueType(), MMO);
7564 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7565 MachinePointerInfo::getFixedStack(SSFI),
7566 false, false, false, 0);
7572 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7573 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7574 SelectionDAG &DAG) const {
7575 // This algorithm is not obvious. Here it is in C code, more or less:
7577 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7578 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7579 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7581 // Copy ints to xmm registers.
7582 __m128i xh = _mm_cvtsi32_si128( hi );
7583 __m128i xl = _mm_cvtsi32_si128( lo );
7585 // Combine into low half of a single xmm register.
7586 __m128i x = _mm_unpacklo_epi32( xh, xl );
7590 // Merge in appropriate exponents to give the integer bits the right
7592 x = _mm_unpacklo_epi32( x, exp );
7594 // Subtract away the biases to deal with the IEEE-754 double precision
7596 d = _mm_sub_pd( (__m128d) x, bias );
7598 // All conversions up to here are exact. The correctly rounded result is
7599 // calculated using the current rounding mode using the following
7601 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7602 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7603 // store doesn't really need to be here (except
7604 // maybe to zero the other double)
7609 DebugLoc dl = Op.getDebugLoc();
7610 LLVMContext *Context = DAG.getContext();
7612 // Build some magic constants.
7613 SmallVector<Constant*,4> CV0;
7614 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7615 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7616 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7617 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7618 Constant *C0 = ConstantVector::get(CV0);
7619 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7621 SmallVector<Constant*,2> CV1;
7623 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7625 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7626 Constant *C1 = ConstantVector::get(CV1);
7627 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7629 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7630 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7632 DAG.getIntPtrConstant(1)));
7633 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7634 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7636 DAG.getIntPtrConstant(0)));
7637 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7638 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7639 MachinePointerInfo::getConstantPool(),
7640 false, false, false, 16);
7641 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7642 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7643 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7644 MachinePointerInfo::getConstantPool(),
7645 false, false, false, 16);
7646 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7648 // Add the halves; easiest way is to swap them into another reg first.
7649 int ShufMask[2] = { 1, -1 };
7650 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7651 DAG.getUNDEF(MVT::v2f64), ShufMask);
7652 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7653 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7654 DAG.getIntPtrConstant(0));
7657 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7658 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7659 SelectionDAG &DAG) const {
7660 DebugLoc dl = Op.getDebugLoc();
7661 // FP constant to bias correct the final result.
7662 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7665 // Load the 32-bit value into an XMM register.
7666 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7669 // Zero out the upper parts of the register.
7670 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7673 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7674 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7675 DAG.getIntPtrConstant(0));
7677 // Or the load with the bias.
7678 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7679 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7680 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7682 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7683 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7684 MVT::v2f64, Bias)));
7685 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7686 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7687 DAG.getIntPtrConstant(0));
7689 // Subtract the bias.
7690 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7692 // Handle final rounding.
7693 EVT DestVT = Op.getValueType();
7695 if (DestVT.bitsLT(MVT::f64)) {
7696 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7697 DAG.getIntPtrConstant(0));
7698 } else if (DestVT.bitsGT(MVT::f64)) {
7699 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7702 // Handle final rounding.
7706 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7707 SelectionDAG &DAG) const {
7708 SDValue N0 = Op.getOperand(0);
7709 DebugLoc dl = Op.getDebugLoc();
7711 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7712 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7713 // the optimization here.
7714 if (DAG.SignBitIsZero(N0))
7715 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7717 EVT SrcVT = N0.getValueType();
7718 EVT DstVT = Op.getValueType();
7719 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7720 return LowerUINT_TO_FP_i64(Op, DAG);
7721 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7722 return LowerUINT_TO_FP_i32(Op, DAG);
7724 // Make a 64-bit buffer, and use it to build an FILD.
7725 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7726 if (SrcVT == MVT::i32) {
7727 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7728 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7729 getPointerTy(), StackSlot, WordOff);
7730 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7731 StackSlot, MachinePointerInfo(),
7733 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7734 OffsetSlot, MachinePointerInfo(),
7736 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7740 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7741 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7742 StackSlot, MachinePointerInfo(),
7744 // For i64 source, we need to add the appropriate power of 2 if the input
7745 // was negative. This is the same as the optimization in
7746 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7747 // we must be careful to do the computation in x87 extended precision, not
7748 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7749 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7750 MachineMemOperand *MMO =
7751 DAG.getMachineFunction()
7752 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7753 MachineMemOperand::MOLoad, 8, 8);
7755 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7756 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7757 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7760 APInt FF(32, 0x5F800000ULL);
7762 // Check whether the sign bit is set.
7763 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7764 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7767 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7768 SDValue FudgePtr = DAG.getConstantPool(
7769 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7772 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7773 SDValue Zero = DAG.getIntPtrConstant(0);
7774 SDValue Four = DAG.getIntPtrConstant(4);
7775 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7777 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7779 // Load the value out, extending it from f32 to f80.
7780 // FIXME: Avoid the extend by constructing the right constant pool?
7781 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7782 FudgePtr, MachinePointerInfo::getConstantPool(),
7783 MVT::f32, false, false, 4);
7784 // Extend everything to 80 bits to force it to be done on x87.
7785 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7786 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7789 std::pair<SDValue,SDValue> X86TargetLowering::
7790 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7791 DebugLoc DL = Op.getDebugLoc();
7793 EVT DstTy = Op.getValueType();
7796 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7800 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7801 DstTy.getSimpleVT() >= MVT::i16 &&
7802 "Unknown FP_TO_SINT to lower!");
7804 // These are really Legal.
7805 if (DstTy == MVT::i32 &&
7806 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7807 return std::make_pair(SDValue(), SDValue());
7808 if (Subtarget->is64Bit() &&
7809 DstTy == MVT::i64 &&
7810 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7811 return std::make_pair(SDValue(), SDValue());
7813 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7815 MachineFunction &MF = DAG.getMachineFunction();
7816 unsigned MemSize = DstTy.getSizeInBits()/8;
7817 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7818 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7823 switch (DstTy.getSimpleVT().SimpleTy) {
7824 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7825 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7826 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7827 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7830 SDValue Chain = DAG.getEntryNode();
7831 SDValue Value = Op.getOperand(0);
7832 EVT TheVT = Op.getOperand(0).getValueType();
7833 if (isScalarFPTypeInSSEReg(TheVT)) {
7834 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7835 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7836 MachinePointerInfo::getFixedStack(SSFI),
7838 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7840 Chain, StackSlot, DAG.getValueType(TheVT)
7843 MachineMemOperand *MMO =
7844 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7845 MachineMemOperand::MOLoad, MemSize, MemSize);
7846 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7848 Chain = Value.getValue(1);
7849 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7850 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7853 MachineMemOperand *MMO =
7854 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7855 MachineMemOperand::MOStore, MemSize, MemSize);
7857 // Build the FP_TO_INT*_IN_MEM
7858 SDValue Ops[] = { Chain, Value, StackSlot };
7859 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7860 Ops, 3, DstTy, MMO);
7862 return std::make_pair(FIST, StackSlot);
7865 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7866 SelectionDAG &DAG) const {
7867 if (Op.getValueType().isVector())
7870 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7871 SDValue FIST = Vals.first, StackSlot = Vals.second;
7872 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7873 if (FIST.getNode() == 0) return Op;
7876 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7877 FIST, StackSlot, MachinePointerInfo(),
7878 false, false, false, 0);
7881 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7882 SelectionDAG &DAG) const {
7883 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7884 SDValue FIST = Vals.first, StackSlot = Vals.second;
7885 assert(FIST.getNode() && "Unexpected failure");
7888 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7889 FIST, StackSlot, MachinePointerInfo(),
7890 false, false, false, 0);
7893 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7894 SelectionDAG &DAG) const {
7895 LLVMContext *Context = DAG.getContext();
7896 DebugLoc dl = Op.getDebugLoc();
7897 EVT VT = Op.getValueType();
7900 EltVT = VT.getVectorElementType();
7901 SmallVector<Constant*,4> CV;
7902 if (EltVT == MVT::f64) {
7903 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7906 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7909 Constant *C = ConstantVector::get(CV);
7910 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7911 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7912 MachinePointerInfo::getConstantPool(),
7913 false, false, false, 16);
7914 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7917 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7918 LLVMContext *Context = DAG.getContext();
7919 DebugLoc dl = Op.getDebugLoc();
7920 EVT VT = Op.getValueType();
7922 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7923 if (VT.isVector()) {
7924 EltVT = VT.getVectorElementType();
7925 NumElts = VT.getVectorNumElements();
7927 SmallVector<Constant*,8> CV;
7928 if (EltVT == MVT::f64) {
7929 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7930 CV.assign(NumElts, C);
7932 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7933 CV.assign(NumElts, C);
7935 Constant *C = ConstantVector::get(CV);
7936 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7937 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7938 MachinePointerInfo::getConstantPool(),
7939 false, false, false, 16);
7940 if (VT.isVector()) {
7941 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7942 return DAG.getNode(ISD::BITCAST, dl, VT,
7943 DAG.getNode(ISD::XOR, dl, XORVT,
7944 DAG.getNode(ISD::BITCAST, dl, XORVT,
7946 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7948 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7952 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7953 LLVMContext *Context = DAG.getContext();
7954 SDValue Op0 = Op.getOperand(0);
7955 SDValue Op1 = Op.getOperand(1);
7956 DebugLoc dl = Op.getDebugLoc();
7957 EVT VT = Op.getValueType();
7958 EVT SrcVT = Op1.getValueType();
7960 // If second operand is smaller, extend it first.
7961 if (SrcVT.bitsLT(VT)) {
7962 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7965 // And if it is bigger, shrink it first.
7966 if (SrcVT.bitsGT(VT)) {
7967 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7971 // At this point the operands and the result should have the same
7972 // type, and that won't be f80 since that is not custom lowered.
7974 // First get the sign bit of second operand.
7975 SmallVector<Constant*,4> CV;
7976 if (SrcVT == MVT::f64) {
7977 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7978 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7980 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7981 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7982 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7983 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7985 Constant *C = ConstantVector::get(CV);
7986 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7987 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7988 MachinePointerInfo::getConstantPool(),
7989 false, false, false, 16);
7990 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7992 // Shift sign bit right or left if the two operands have different types.
7993 if (SrcVT.bitsGT(VT)) {
7994 // Op0 is MVT::f32, Op1 is MVT::f64.
7995 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7996 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7997 DAG.getConstant(32, MVT::i32));
7998 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7999 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8000 DAG.getIntPtrConstant(0));
8003 // Clear first operand sign bit.
8005 if (VT == MVT::f64) {
8006 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8007 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8009 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8010 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8011 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8012 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8014 C = ConstantVector::get(CV);
8015 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8016 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8017 MachinePointerInfo::getConstantPool(),
8018 false, false, false, 16);
8019 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8021 // Or the value with the sign bit.
8022 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8025 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8026 SDValue N0 = Op.getOperand(0);
8027 DebugLoc dl = Op.getDebugLoc();
8028 EVT VT = Op.getValueType();
8030 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8031 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8032 DAG.getConstant(1, VT));
8033 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8036 /// Emit nodes that will be selected as "test Op0,Op0", or something
8038 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8039 SelectionDAG &DAG) const {
8040 DebugLoc dl = Op.getDebugLoc();
8042 // CF and OF aren't always set the way we want. Determine which
8043 // of these we need.
8044 bool NeedCF = false;
8045 bool NeedOF = false;
8048 case X86::COND_A: case X86::COND_AE:
8049 case X86::COND_B: case X86::COND_BE:
8052 case X86::COND_G: case X86::COND_GE:
8053 case X86::COND_L: case X86::COND_LE:
8054 case X86::COND_O: case X86::COND_NO:
8059 // See if we can use the EFLAGS value from the operand instead of
8060 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8061 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8062 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8063 // Emit a CMP with 0, which is the TEST pattern.
8064 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8065 DAG.getConstant(0, Op.getValueType()));
8067 unsigned Opcode = 0;
8068 unsigned NumOperands = 0;
8069 switch (Op.getNode()->getOpcode()) {
8071 // Due to an isel shortcoming, be conservative if this add is likely to be
8072 // selected as part of a load-modify-store instruction. When the root node
8073 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8074 // uses of other nodes in the match, such as the ADD in this case. This
8075 // leads to the ADD being left around and reselected, with the result being
8076 // two adds in the output. Alas, even if none our users are stores, that
8077 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8078 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8079 // climbing the DAG back to the root, and it doesn't seem to be worth the
8081 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8082 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8083 if (UI->getOpcode() != ISD::CopyToReg &&
8084 UI->getOpcode() != ISD::SETCC &&
8085 UI->getOpcode() != ISD::STORE)
8088 if (ConstantSDNode *C =
8089 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8090 // An add of one will be selected as an INC.
8091 if (C->getAPIntValue() == 1) {
8092 Opcode = X86ISD::INC;
8097 // An add of negative one (subtract of one) will be selected as a DEC.
8098 if (C->getAPIntValue().isAllOnesValue()) {
8099 Opcode = X86ISD::DEC;
8105 // Otherwise use a regular EFLAGS-setting add.
8106 Opcode = X86ISD::ADD;
8110 // If the primary and result isn't used, don't bother using X86ISD::AND,
8111 // because a TEST instruction will be better.
8112 bool NonFlagUse = false;
8113 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8114 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8116 unsigned UOpNo = UI.getOperandNo();
8117 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8118 // Look pass truncate.
8119 UOpNo = User->use_begin().getOperandNo();
8120 User = *User->use_begin();
8123 if (User->getOpcode() != ISD::BRCOND &&
8124 User->getOpcode() != ISD::SETCC &&
8125 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8138 // Due to the ISEL shortcoming noted above, be conservative if this op is
8139 // likely to be selected as part of a load-modify-store instruction.
8140 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8141 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8142 if (UI->getOpcode() == ISD::STORE)
8145 // Otherwise use a regular EFLAGS-setting instruction.
8146 switch (Op.getNode()->getOpcode()) {
8147 default: llvm_unreachable("unexpected operator!");
8148 case ISD::SUB: Opcode = X86ISD::SUB; break;
8149 case ISD::OR: Opcode = X86ISD::OR; break;
8150 case ISD::XOR: Opcode = X86ISD::XOR; break;
8151 case ISD::AND: Opcode = X86ISD::AND; break;
8163 return SDValue(Op.getNode(), 1);
8170 // Emit a CMP with 0, which is the TEST pattern.
8171 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8172 DAG.getConstant(0, Op.getValueType()));
8174 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8175 SmallVector<SDValue, 4> Ops;
8176 for (unsigned i = 0; i != NumOperands; ++i)
8177 Ops.push_back(Op.getOperand(i));
8179 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8180 DAG.ReplaceAllUsesWith(Op, New);
8181 return SDValue(New.getNode(), 1);
8184 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8186 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8187 SelectionDAG &DAG) const {
8188 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8189 if (C->getAPIntValue() == 0)
8190 return EmitTest(Op0, X86CC, DAG);
8192 DebugLoc dl = Op0.getDebugLoc();
8193 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8196 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8197 /// if it's possible.
8198 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8199 DebugLoc dl, SelectionDAG &DAG) const {
8200 SDValue Op0 = And.getOperand(0);
8201 SDValue Op1 = And.getOperand(1);
8202 if (Op0.getOpcode() == ISD::TRUNCATE)
8203 Op0 = Op0.getOperand(0);
8204 if (Op1.getOpcode() == ISD::TRUNCATE)
8205 Op1 = Op1.getOperand(0);
8208 if (Op1.getOpcode() == ISD::SHL)
8209 std::swap(Op0, Op1);
8210 if (Op0.getOpcode() == ISD::SHL) {
8211 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8212 if (And00C->getZExtValue() == 1) {
8213 // If we looked past a truncate, check that it's only truncating away
8215 unsigned BitWidth = Op0.getValueSizeInBits();
8216 unsigned AndBitWidth = And.getValueSizeInBits();
8217 if (BitWidth > AndBitWidth) {
8218 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8219 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8220 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8224 RHS = Op0.getOperand(1);
8226 } else if (Op1.getOpcode() == ISD::Constant) {
8227 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8228 uint64_t AndRHSVal = AndRHS->getZExtValue();
8229 SDValue AndLHS = Op0;
8231 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8232 LHS = AndLHS.getOperand(0);
8233 RHS = AndLHS.getOperand(1);
8236 // Use BT if the immediate can't be encoded in a TEST instruction.
8237 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8239 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8243 if (LHS.getNode()) {
8244 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8245 // instruction. Since the shift amount is in-range-or-undefined, we know
8246 // that doing a bittest on the i32 value is ok. We extend to i32 because
8247 // the encoding for the i16 version is larger than the i32 version.
8248 // Also promote i16 to i32 for performance / code size reason.
8249 if (LHS.getValueType() == MVT::i8 ||
8250 LHS.getValueType() == MVT::i16)
8251 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8253 // If the operand types disagree, extend the shift amount to match. Since
8254 // BT ignores high bits (like shifts) we can use anyextend.
8255 if (LHS.getValueType() != RHS.getValueType())
8256 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8258 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8259 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8260 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8261 DAG.getConstant(Cond, MVT::i8), BT);
8267 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8269 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8271 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8272 SDValue Op0 = Op.getOperand(0);
8273 SDValue Op1 = Op.getOperand(1);
8274 DebugLoc dl = Op.getDebugLoc();
8275 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8277 // Optimize to BT if possible.
8278 // Lower (X & (1 << N)) == 0 to BT(X, N).
8279 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8280 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8281 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8282 Op1.getOpcode() == ISD::Constant &&
8283 cast<ConstantSDNode>(Op1)->isNullValue() &&
8284 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8285 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8286 if (NewSetCC.getNode())
8290 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8292 if (Op1.getOpcode() == ISD::Constant &&
8293 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8294 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8295 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8297 // If the input is a setcc, then reuse the input setcc or use a new one with
8298 // the inverted condition.
8299 if (Op0.getOpcode() == X86ISD::SETCC) {
8300 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8301 bool Invert = (CC == ISD::SETNE) ^
8302 cast<ConstantSDNode>(Op1)->isNullValue();
8303 if (!Invert) return Op0;
8305 CCode = X86::GetOppositeBranchCondition(CCode);
8306 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8307 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8311 bool isFP = Op1.getValueType().isFloatingPoint();
8312 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8313 if (X86CC == X86::COND_INVALID)
8316 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8317 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8318 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8321 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8322 // ones, and then concatenate the result back.
8323 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8324 EVT VT = Op.getValueType();
8326 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8327 "Unsupported value type for operation");
8329 int NumElems = VT.getVectorNumElements();
8330 DebugLoc dl = Op.getDebugLoc();
8331 SDValue CC = Op.getOperand(2);
8332 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8333 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8335 // Extract the LHS vectors
8336 SDValue LHS = Op.getOperand(0);
8337 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8338 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8340 // Extract the RHS vectors
8341 SDValue RHS = Op.getOperand(1);
8342 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8343 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8345 // Issue the operation on the smaller types and concatenate the result back
8346 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8347 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8348 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8349 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8350 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8354 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8356 SDValue Op0 = Op.getOperand(0);
8357 SDValue Op1 = Op.getOperand(1);
8358 SDValue CC = Op.getOperand(2);
8359 EVT VT = Op.getValueType();
8360 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8361 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8362 DebugLoc dl = Op.getDebugLoc();
8366 EVT EltVT = Op0.getValueType().getVectorElementType();
8367 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8369 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8372 // SSE Condition code mapping:
8381 switch (SetCCOpcode) {
8384 case ISD::SETEQ: SSECC = 0; break;
8386 case ISD::SETGT: Swap = true; // Fallthrough
8388 case ISD::SETOLT: SSECC = 1; break;
8390 case ISD::SETGE: Swap = true; // Fallthrough
8392 case ISD::SETOLE: SSECC = 2; break;
8393 case ISD::SETUO: SSECC = 3; break;
8395 case ISD::SETNE: SSECC = 4; break;
8396 case ISD::SETULE: Swap = true;
8397 case ISD::SETUGE: SSECC = 5; break;
8398 case ISD::SETULT: Swap = true;
8399 case ISD::SETUGT: SSECC = 6; break;
8400 case ISD::SETO: SSECC = 7; break;
8403 std::swap(Op0, Op1);
8405 // In the two special cases we can't handle, emit two comparisons.
8407 if (SetCCOpcode == ISD::SETUEQ) {
8409 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8410 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8411 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8412 } else if (SetCCOpcode == ISD::SETONE) {
8414 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8415 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8416 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8418 llvm_unreachable("Illegal FP comparison");
8420 // Handle all other FP comparisons here.
8421 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8424 // Break 256-bit integer vector compare into smaller ones.
8425 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8426 return Lower256IntVSETCC(Op, DAG);
8428 // We are handling one of the integer comparisons here. Since SSE only has
8429 // GT and EQ comparisons for integer, swapping operands and multiple
8430 // operations may be required for some comparisons.
8431 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8432 bool Swap = false, Invert = false, FlipSigns = false;
8434 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8436 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8437 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8438 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8439 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8442 switch (SetCCOpcode) {
8444 case ISD::SETNE: Invert = true;
8445 case ISD::SETEQ: Opc = EQOpc; break;
8446 case ISD::SETLT: Swap = true;
8447 case ISD::SETGT: Opc = GTOpc; break;
8448 case ISD::SETGE: Swap = true;
8449 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8450 case ISD::SETULT: Swap = true;
8451 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8452 case ISD::SETUGE: Swap = true;
8453 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8456 std::swap(Op0, Op1);
8458 // Check that the operation in question is available (most are plain SSE2,
8459 // but PCMPGTQ and PCMPEQQ have different requirements).
8460 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8462 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8465 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8466 // bits of the inputs before performing those operations.
8468 EVT EltVT = VT.getVectorElementType();
8469 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8471 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8472 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8474 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8475 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8478 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8480 // If the logical-not of the result is required, perform that now.
8482 Result = DAG.getNOT(dl, Result, VT);
8487 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8488 static bool isX86LogicalCmp(SDValue Op) {
8489 unsigned Opc = Op.getNode()->getOpcode();
8490 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8492 if (Op.getResNo() == 1 &&
8493 (Opc == X86ISD::ADD ||
8494 Opc == X86ISD::SUB ||
8495 Opc == X86ISD::ADC ||
8496 Opc == X86ISD::SBB ||
8497 Opc == X86ISD::SMUL ||
8498 Opc == X86ISD::UMUL ||
8499 Opc == X86ISD::INC ||
8500 Opc == X86ISD::DEC ||
8501 Opc == X86ISD::OR ||
8502 Opc == X86ISD::XOR ||
8503 Opc == X86ISD::AND))
8506 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8512 static bool isZero(SDValue V) {
8513 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8514 return C && C->isNullValue();
8517 static bool isAllOnes(SDValue V) {
8518 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8519 return C && C->isAllOnesValue();
8522 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8523 bool addTest = true;
8524 SDValue Cond = Op.getOperand(0);
8525 SDValue Op1 = Op.getOperand(1);
8526 SDValue Op2 = Op.getOperand(2);
8527 DebugLoc DL = Op.getDebugLoc();
8530 if (Cond.getOpcode() == ISD::SETCC) {
8531 SDValue NewCond = LowerSETCC(Cond, DAG);
8532 if (NewCond.getNode())
8536 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8537 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8538 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8539 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8540 if (Cond.getOpcode() == X86ISD::SETCC &&
8541 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8542 isZero(Cond.getOperand(1).getOperand(1))) {
8543 SDValue Cmp = Cond.getOperand(1);
8545 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8547 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8548 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8549 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8551 SDValue CmpOp0 = Cmp.getOperand(0);
8552 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8553 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8555 SDValue Res = // Res = 0 or -1.
8556 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8557 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8559 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8560 Res = DAG.getNOT(DL, Res, Res.getValueType());
8562 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8563 if (N2C == 0 || !N2C->isNullValue())
8564 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8569 // Look past (and (setcc_carry (cmp ...)), 1).
8570 if (Cond.getOpcode() == ISD::AND &&
8571 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8572 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8573 if (C && C->getAPIntValue() == 1)
8574 Cond = Cond.getOperand(0);
8577 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8578 // setting operand in place of the X86ISD::SETCC.
8579 unsigned CondOpcode = Cond.getOpcode();
8580 if (CondOpcode == X86ISD::SETCC ||
8581 CondOpcode == X86ISD::SETCC_CARRY) {
8582 CC = Cond.getOperand(0);
8584 SDValue Cmp = Cond.getOperand(1);
8585 unsigned Opc = Cmp.getOpcode();
8586 EVT VT = Op.getValueType();
8588 bool IllegalFPCMov = false;
8589 if (VT.isFloatingPoint() && !VT.isVector() &&
8590 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8591 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8593 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8594 Opc == X86ISD::BT) { // FIXME
8598 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8599 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8600 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8601 Cond.getOperand(0).getValueType() != MVT::i8)) {
8602 SDValue LHS = Cond.getOperand(0);
8603 SDValue RHS = Cond.getOperand(1);
8607 switch (CondOpcode) {
8608 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8609 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8610 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8611 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8612 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8613 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8614 default: llvm_unreachable("unexpected overflowing operator");
8616 if (CondOpcode == ISD::UMULO)
8617 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8620 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8622 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8624 if (CondOpcode == ISD::UMULO)
8625 Cond = X86Op.getValue(2);
8627 Cond = X86Op.getValue(1);
8629 CC = DAG.getConstant(X86Cond, MVT::i8);
8634 // Look pass the truncate.
8635 if (Cond.getOpcode() == ISD::TRUNCATE)
8636 Cond = Cond.getOperand(0);
8638 // We know the result of AND is compared against zero. Try to match
8640 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8641 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8642 if (NewSetCC.getNode()) {
8643 CC = NewSetCC.getOperand(0);
8644 Cond = NewSetCC.getOperand(1);
8651 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8652 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8655 // a < b ? -1 : 0 -> RES = ~setcc_carry
8656 // a < b ? 0 : -1 -> RES = setcc_carry
8657 // a >= b ? -1 : 0 -> RES = setcc_carry
8658 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8659 if (Cond.getOpcode() == X86ISD::CMP) {
8660 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8662 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8663 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8664 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8665 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8666 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8667 return DAG.getNOT(DL, Res, Res.getValueType());
8672 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8673 // condition is true.
8674 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8675 SDValue Ops[] = { Op2, Op1, CC, Cond };
8676 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8679 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8680 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8681 // from the AND / OR.
8682 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8683 Opc = Op.getOpcode();
8684 if (Opc != ISD::OR && Opc != ISD::AND)
8686 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8687 Op.getOperand(0).hasOneUse() &&
8688 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8689 Op.getOperand(1).hasOneUse());
8692 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8693 // 1 and that the SETCC node has a single use.
8694 static bool isXor1OfSetCC(SDValue Op) {
8695 if (Op.getOpcode() != ISD::XOR)
8697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8698 if (N1C && N1C->getAPIntValue() == 1) {
8699 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8700 Op.getOperand(0).hasOneUse();
8705 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8706 bool addTest = true;
8707 SDValue Chain = Op.getOperand(0);
8708 SDValue Cond = Op.getOperand(1);
8709 SDValue Dest = Op.getOperand(2);
8710 DebugLoc dl = Op.getDebugLoc();
8712 bool Inverted = false;
8714 if (Cond.getOpcode() == ISD::SETCC) {
8715 // Check for setcc([su]{add,sub,mul}o == 0).
8716 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8717 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8718 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8719 Cond.getOperand(0).getResNo() == 1 &&
8720 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8721 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8722 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8723 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8724 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8725 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8727 Cond = Cond.getOperand(0);
8729 SDValue NewCond = LowerSETCC(Cond, DAG);
8730 if (NewCond.getNode())
8735 // FIXME: LowerXALUO doesn't handle these!!
8736 else if (Cond.getOpcode() == X86ISD::ADD ||
8737 Cond.getOpcode() == X86ISD::SUB ||
8738 Cond.getOpcode() == X86ISD::SMUL ||
8739 Cond.getOpcode() == X86ISD::UMUL)
8740 Cond = LowerXALUO(Cond, DAG);
8743 // Look pass (and (setcc_carry (cmp ...)), 1).
8744 if (Cond.getOpcode() == ISD::AND &&
8745 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8746 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8747 if (C && C->getAPIntValue() == 1)
8748 Cond = Cond.getOperand(0);
8751 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8752 // setting operand in place of the X86ISD::SETCC.
8753 unsigned CondOpcode = Cond.getOpcode();
8754 if (CondOpcode == X86ISD::SETCC ||
8755 CondOpcode == X86ISD::SETCC_CARRY) {
8756 CC = Cond.getOperand(0);
8758 SDValue Cmp = Cond.getOperand(1);
8759 unsigned Opc = Cmp.getOpcode();
8760 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8761 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8765 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8769 // These can only come from an arithmetic instruction with overflow,
8770 // e.g. SADDO, UADDO.
8771 Cond = Cond.getNode()->getOperand(1);
8777 CondOpcode = Cond.getOpcode();
8778 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8779 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8780 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8781 Cond.getOperand(0).getValueType() != MVT::i8)) {
8782 SDValue LHS = Cond.getOperand(0);
8783 SDValue RHS = Cond.getOperand(1);
8787 switch (CondOpcode) {
8788 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8789 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8790 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8791 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8792 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8793 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8794 default: llvm_unreachable("unexpected overflowing operator");
8797 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8798 if (CondOpcode == ISD::UMULO)
8799 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8802 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8804 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8806 if (CondOpcode == ISD::UMULO)
8807 Cond = X86Op.getValue(2);
8809 Cond = X86Op.getValue(1);
8811 CC = DAG.getConstant(X86Cond, MVT::i8);
8815 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8816 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8817 if (CondOpc == ISD::OR) {
8818 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8819 // two branches instead of an explicit OR instruction with a
8821 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8822 isX86LogicalCmp(Cmp)) {
8823 CC = Cond.getOperand(0).getOperand(0);
8824 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8825 Chain, Dest, CC, Cmp);
8826 CC = Cond.getOperand(1).getOperand(0);
8830 } else { // ISD::AND
8831 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8832 // two branches instead of an explicit AND instruction with a
8833 // separate test. However, we only do this if this block doesn't
8834 // have a fall-through edge, because this requires an explicit
8835 // jmp when the condition is false.
8836 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8837 isX86LogicalCmp(Cmp) &&
8838 Op.getNode()->hasOneUse()) {
8839 X86::CondCode CCode =
8840 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8841 CCode = X86::GetOppositeBranchCondition(CCode);
8842 CC = DAG.getConstant(CCode, MVT::i8);
8843 SDNode *User = *Op.getNode()->use_begin();
8844 // Look for an unconditional branch following this conditional branch.
8845 // We need this because we need to reverse the successors in order
8846 // to implement FCMP_OEQ.
8847 if (User->getOpcode() == ISD::BR) {
8848 SDValue FalseBB = User->getOperand(1);
8850 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8851 assert(NewBR == User);
8855 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8856 Chain, Dest, CC, Cmp);
8857 X86::CondCode CCode =
8858 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8859 CCode = X86::GetOppositeBranchCondition(CCode);
8860 CC = DAG.getConstant(CCode, MVT::i8);
8866 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8867 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8868 // It should be transformed during dag combiner except when the condition
8869 // is set by a arithmetics with overflow node.
8870 X86::CondCode CCode =
8871 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8872 CCode = X86::GetOppositeBranchCondition(CCode);
8873 CC = DAG.getConstant(CCode, MVT::i8);
8874 Cond = Cond.getOperand(0).getOperand(1);
8876 } else if (Cond.getOpcode() == ISD::SETCC &&
8877 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8878 // For FCMP_OEQ, we can emit
8879 // two branches instead of an explicit AND instruction with a
8880 // separate test. However, we only do this if this block doesn't
8881 // have a fall-through edge, because this requires an explicit
8882 // jmp when the condition is false.
8883 if (Op.getNode()->hasOneUse()) {
8884 SDNode *User = *Op.getNode()->use_begin();
8885 // Look for an unconditional branch following this conditional branch.
8886 // We need this because we need to reverse the successors in order
8887 // to implement FCMP_OEQ.
8888 if (User->getOpcode() == ISD::BR) {
8889 SDValue FalseBB = User->getOperand(1);
8891 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8892 assert(NewBR == User);
8896 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8897 Cond.getOperand(0), Cond.getOperand(1));
8898 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8899 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8900 Chain, Dest, CC, Cmp);
8901 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8906 } else if (Cond.getOpcode() == ISD::SETCC &&
8907 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8908 // For FCMP_UNE, we can emit
8909 // two branches instead of an explicit AND instruction with a
8910 // separate test. However, we only do this if this block doesn't
8911 // have a fall-through edge, because this requires an explicit
8912 // jmp when the condition is false.
8913 if (Op.getNode()->hasOneUse()) {
8914 SDNode *User = *Op.getNode()->use_begin();
8915 // Look for an unconditional branch following this conditional branch.
8916 // We need this because we need to reverse the successors in order
8917 // to implement FCMP_UNE.
8918 if (User->getOpcode() == ISD::BR) {
8919 SDValue FalseBB = User->getOperand(1);
8921 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8922 assert(NewBR == User);
8925 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8926 Cond.getOperand(0), Cond.getOperand(1));
8927 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8928 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8929 Chain, Dest, CC, Cmp);
8930 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8940 // Look pass the truncate.
8941 if (Cond.getOpcode() == ISD::TRUNCATE)
8942 Cond = Cond.getOperand(0);
8944 // We know the result of AND is compared against zero. Try to match
8946 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8947 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8948 if (NewSetCC.getNode()) {
8949 CC = NewSetCC.getOperand(0);
8950 Cond = NewSetCC.getOperand(1);
8957 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8958 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8960 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8961 Chain, Dest, CC, Cond);
8965 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8966 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8967 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8968 // that the guard pages used by the OS virtual memory manager are allocated in
8969 // correct sequence.
8971 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8972 SelectionDAG &DAG) const {
8973 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8974 getTargetMachine().Options.EnableSegmentedStacks) &&
8975 "This should be used only on Windows targets or when segmented stacks "
8977 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8978 DebugLoc dl = Op.getDebugLoc();
8981 SDValue Chain = Op.getOperand(0);
8982 SDValue Size = Op.getOperand(1);
8983 // FIXME: Ensure alignment here
8985 bool Is64Bit = Subtarget->is64Bit();
8986 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8988 if (getTargetMachine().Options.EnableSegmentedStacks) {
8989 MachineFunction &MF = DAG.getMachineFunction();
8990 MachineRegisterInfo &MRI = MF.getRegInfo();
8993 // The 64 bit implementation of segmented stacks needs to clobber both r10
8994 // r11. This makes it impossible to use it along with nested parameters.
8995 const Function *F = MF.getFunction();
8997 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8999 if (I->hasNestAttr())
9000 report_fatal_error("Cannot use segmented stacks with functions that "
9001 "have nested arguments.");
9004 const TargetRegisterClass *AddrRegClass =
9005 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9006 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9007 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9008 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9009 DAG.getRegister(Vreg, SPTy));
9010 SDValue Ops1[2] = { Value, Chain };
9011 return DAG.getMergeValues(Ops1, 2, dl);
9014 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9016 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9017 Flag = Chain.getValue(1);
9018 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9020 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9021 Flag = Chain.getValue(1);
9023 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9025 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9026 return DAG.getMergeValues(Ops1, 2, dl);
9030 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9031 MachineFunction &MF = DAG.getMachineFunction();
9032 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9034 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9035 DebugLoc DL = Op.getDebugLoc();
9037 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9038 // vastart just stores the address of the VarArgsFrameIndex slot into the
9039 // memory location argument.
9040 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9042 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9043 MachinePointerInfo(SV), false, false, 0);
9047 // gp_offset (0 - 6 * 8)
9048 // fp_offset (48 - 48 + 8 * 16)
9049 // overflow_arg_area (point to parameters coming in memory).
9051 SmallVector<SDValue, 8> MemOps;
9052 SDValue FIN = Op.getOperand(1);
9054 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9055 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9057 FIN, MachinePointerInfo(SV), false, false, 0);
9058 MemOps.push_back(Store);
9061 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9062 FIN, DAG.getIntPtrConstant(4));
9063 Store = DAG.getStore(Op.getOperand(0), DL,
9064 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9066 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9067 MemOps.push_back(Store);
9069 // Store ptr to overflow_arg_area
9070 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9071 FIN, DAG.getIntPtrConstant(4));
9072 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9074 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9075 MachinePointerInfo(SV, 8),
9077 MemOps.push_back(Store);
9079 // Store ptr to reg_save_area.
9080 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9081 FIN, DAG.getIntPtrConstant(8));
9082 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9084 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9085 MachinePointerInfo(SV, 16), false, false, 0);
9086 MemOps.push_back(Store);
9087 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9088 &MemOps[0], MemOps.size());
9091 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9092 assert(Subtarget->is64Bit() &&
9093 "LowerVAARG only handles 64-bit va_arg!");
9094 assert((Subtarget->isTargetLinux() ||
9095 Subtarget->isTargetDarwin()) &&
9096 "Unhandled target in LowerVAARG");
9097 assert(Op.getNode()->getNumOperands() == 4);
9098 SDValue Chain = Op.getOperand(0);
9099 SDValue SrcPtr = Op.getOperand(1);
9100 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9101 unsigned Align = Op.getConstantOperandVal(3);
9102 DebugLoc dl = Op.getDebugLoc();
9104 EVT ArgVT = Op.getNode()->getValueType(0);
9105 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9106 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9109 // Decide which area this value should be read from.
9110 // TODO: Implement the AMD64 ABI in its entirety. This simple
9111 // selection mechanism works only for the basic types.
9112 if (ArgVT == MVT::f80) {
9113 llvm_unreachable("va_arg for f80 not yet implemented");
9114 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9115 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9116 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9117 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9119 llvm_unreachable("Unhandled argument type in LowerVAARG");
9123 // Sanity Check: Make sure using fp_offset makes sense.
9124 assert(!getTargetMachine().Options.UseSoftFloat &&
9125 !(DAG.getMachineFunction()
9126 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9127 Subtarget->hasXMM());
9130 // Insert VAARG_64 node into the DAG
9131 // VAARG_64 returns two values: Variable Argument Address, Chain
9132 SmallVector<SDValue, 11> InstOps;
9133 InstOps.push_back(Chain);
9134 InstOps.push_back(SrcPtr);
9135 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9136 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9137 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9138 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9139 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9140 VTs, &InstOps[0], InstOps.size(),
9142 MachinePointerInfo(SV),
9147 Chain = VAARG.getValue(1);
9149 // Load the next argument and return it
9150 return DAG.getLoad(ArgVT, dl,
9153 MachinePointerInfo(),
9154 false, false, false, 0);
9157 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9158 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9159 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9160 SDValue Chain = Op.getOperand(0);
9161 SDValue DstPtr = Op.getOperand(1);
9162 SDValue SrcPtr = Op.getOperand(2);
9163 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9164 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9165 DebugLoc DL = Op.getDebugLoc();
9167 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9168 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9170 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9174 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9175 DebugLoc dl = Op.getDebugLoc();
9176 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9178 default: return SDValue(); // Don't custom lower most intrinsics.
9179 // Comparison intrinsics.
9180 case Intrinsic::x86_sse_comieq_ss:
9181 case Intrinsic::x86_sse_comilt_ss:
9182 case Intrinsic::x86_sse_comile_ss:
9183 case Intrinsic::x86_sse_comigt_ss:
9184 case Intrinsic::x86_sse_comige_ss:
9185 case Intrinsic::x86_sse_comineq_ss:
9186 case Intrinsic::x86_sse_ucomieq_ss:
9187 case Intrinsic::x86_sse_ucomilt_ss:
9188 case Intrinsic::x86_sse_ucomile_ss:
9189 case Intrinsic::x86_sse_ucomigt_ss:
9190 case Intrinsic::x86_sse_ucomige_ss:
9191 case Intrinsic::x86_sse_ucomineq_ss:
9192 case Intrinsic::x86_sse2_comieq_sd:
9193 case Intrinsic::x86_sse2_comilt_sd:
9194 case Intrinsic::x86_sse2_comile_sd:
9195 case Intrinsic::x86_sse2_comigt_sd:
9196 case Intrinsic::x86_sse2_comige_sd:
9197 case Intrinsic::x86_sse2_comineq_sd:
9198 case Intrinsic::x86_sse2_ucomieq_sd:
9199 case Intrinsic::x86_sse2_ucomilt_sd:
9200 case Intrinsic::x86_sse2_ucomile_sd:
9201 case Intrinsic::x86_sse2_ucomigt_sd:
9202 case Intrinsic::x86_sse2_ucomige_sd:
9203 case Intrinsic::x86_sse2_ucomineq_sd: {
9205 ISD::CondCode CC = ISD::SETCC_INVALID;
9208 case Intrinsic::x86_sse_comieq_ss:
9209 case Intrinsic::x86_sse2_comieq_sd:
9213 case Intrinsic::x86_sse_comilt_ss:
9214 case Intrinsic::x86_sse2_comilt_sd:
9218 case Intrinsic::x86_sse_comile_ss:
9219 case Intrinsic::x86_sse2_comile_sd:
9223 case Intrinsic::x86_sse_comigt_ss:
9224 case Intrinsic::x86_sse2_comigt_sd:
9228 case Intrinsic::x86_sse_comige_ss:
9229 case Intrinsic::x86_sse2_comige_sd:
9233 case Intrinsic::x86_sse_comineq_ss:
9234 case Intrinsic::x86_sse2_comineq_sd:
9238 case Intrinsic::x86_sse_ucomieq_ss:
9239 case Intrinsic::x86_sse2_ucomieq_sd:
9240 Opc = X86ISD::UCOMI;
9243 case Intrinsic::x86_sse_ucomilt_ss:
9244 case Intrinsic::x86_sse2_ucomilt_sd:
9245 Opc = X86ISD::UCOMI;
9248 case Intrinsic::x86_sse_ucomile_ss:
9249 case Intrinsic::x86_sse2_ucomile_sd:
9250 Opc = X86ISD::UCOMI;
9253 case Intrinsic::x86_sse_ucomigt_ss:
9254 case Intrinsic::x86_sse2_ucomigt_sd:
9255 Opc = X86ISD::UCOMI;
9258 case Intrinsic::x86_sse_ucomige_ss:
9259 case Intrinsic::x86_sse2_ucomige_sd:
9260 Opc = X86ISD::UCOMI;
9263 case Intrinsic::x86_sse_ucomineq_ss:
9264 case Intrinsic::x86_sse2_ucomineq_sd:
9265 Opc = X86ISD::UCOMI;
9270 SDValue LHS = Op.getOperand(1);
9271 SDValue RHS = Op.getOperand(2);
9272 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9273 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9274 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9275 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9276 DAG.getConstant(X86CC, MVT::i8), Cond);
9277 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9279 // Arithmetic intrinsics.
9280 case Intrinsic::x86_sse3_hadd_ps:
9281 case Intrinsic::x86_sse3_hadd_pd:
9282 case Intrinsic::x86_avx_hadd_ps_256:
9283 case Intrinsic::x86_avx_hadd_pd_256:
9284 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9285 Op.getOperand(1), Op.getOperand(2));
9286 case Intrinsic::x86_sse3_hsub_ps:
9287 case Intrinsic::x86_sse3_hsub_pd:
9288 case Intrinsic::x86_avx_hsub_ps_256:
9289 case Intrinsic::x86_avx_hsub_pd_256:
9290 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9291 Op.getOperand(1), Op.getOperand(2));
9292 case Intrinsic::x86_avx2_psllv_d:
9293 case Intrinsic::x86_avx2_psllv_q:
9294 case Intrinsic::x86_avx2_psllv_d_256:
9295 case Intrinsic::x86_avx2_psllv_q_256:
9296 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9297 Op.getOperand(1), Op.getOperand(2));
9298 case Intrinsic::x86_avx2_psrlv_d:
9299 case Intrinsic::x86_avx2_psrlv_q:
9300 case Intrinsic::x86_avx2_psrlv_d_256:
9301 case Intrinsic::x86_avx2_psrlv_q_256:
9302 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9303 Op.getOperand(1), Op.getOperand(2));
9304 case Intrinsic::x86_avx2_psrav_d:
9305 case Intrinsic::x86_avx2_psrav_d_256:
9306 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9307 Op.getOperand(1), Op.getOperand(2));
9309 // ptest and testp intrinsics. The intrinsic these come from are designed to
9310 // return an integer value, not just an instruction so lower it to the ptest
9311 // or testp pattern and a setcc for the result.
9312 case Intrinsic::x86_sse41_ptestz:
9313 case Intrinsic::x86_sse41_ptestc:
9314 case Intrinsic::x86_sse41_ptestnzc:
9315 case Intrinsic::x86_avx_ptestz_256:
9316 case Intrinsic::x86_avx_ptestc_256:
9317 case Intrinsic::x86_avx_ptestnzc_256:
9318 case Intrinsic::x86_avx_vtestz_ps:
9319 case Intrinsic::x86_avx_vtestc_ps:
9320 case Intrinsic::x86_avx_vtestnzc_ps:
9321 case Intrinsic::x86_avx_vtestz_pd:
9322 case Intrinsic::x86_avx_vtestc_pd:
9323 case Intrinsic::x86_avx_vtestnzc_pd:
9324 case Intrinsic::x86_avx_vtestz_ps_256:
9325 case Intrinsic::x86_avx_vtestc_ps_256:
9326 case Intrinsic::x86_avx_vtestnzc_ps_256:
9327 case Intrinsic::x86_avx_vtestz_pd_256:
9328 case Intrinsic::x86_avx_vtestc_pd_256:
9329 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9330 bool IsTestPacked = false;
9333 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9334 case Intrinsic::x86_avx_vtestz_ps:
9335 case Intrinsic::x86_avx_vtestz_pd:
9336 case Intrinsic::x86_avx_vtestz_ps_256:
9337 case Intrinsic::x86_avx_vtestz_pd_256:
9338 IsTestPacked = true; // Fallthrough
9339 case Intrinsic::x86_sse41_ptestz:
9340 case Intrinsic::x86_avx_ptestz_256:
9342 X86CC = X86::COND_E;
9344 case Intrinsic::x86_avx_vtestc_ps:
9345 case Intrinsic::x86_avx_vtestc_pd:
9346 case Intrinsic::x86_avx_vtestc_ps_256:
9347 case Intrinsic::x86_avx_vtestc_pd_256:
9348 IsTestPacked = true; // Fallthrough
9349 case Intrinsic::x86_sse41_ptestc:
9350 case Intrinsic::x86_avx_ptestc_256:
9352 X86CC = X86::COND_B;
9354 case Intrinsic::x86_avx_vtestnzc_ps:
9355 case Intrinsic::x86_avx_vtestnzc_pd:
9356 case Intrinsic::x86_avx_vtestnzc_ps_256:
9357 case Intrinsic::x86_avx_vtestnzc_pd_256:
9358 IsTestPacked = true; // Fallthrough
9359 case Intrinsic::x86_sse41_ptestnzc:
9360 case Intrinsic::x86_avx_ptestnzc_256:
9362 X86CC = X86::COND_A;
9366 SDValue LHS = Op.getOperand(1);
9367 SDValue RHS = Op.getOperand(2);
9368 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9369 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9370 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9371 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9372 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9375 // Fix vector shift instructions where the last operand is a non-immediate
9377 case Intrinsic::x86_avx2_pslli_w:
9378 case Intrinsic::x86_avx2_pslli_d:
9379 case Intrinsic::x86_avx2_pslli_q:
9380 case Intrinsic::x86_avx2_psrli_w:
9381 case Intrinsic::x86_avx2_psrli_d:
9382 case Intrinsic::x86_avx2_psrli_q:
9383 case Intrinsic::x86_avx2_psrai_w:
9384 case Intrinsic::x86_avx2_psrai_d:
9385 case Intrinsic::x86_sse2_pslli_w:
9386 case Intrinsic::x86_sse2_pslli_d:
9387 case Intrinsic::x86_sse2_pslli_q:
9388 case Intrinsic::x86_sse2_psrli_w:
9389 case Intrinsic::x86_sse2_psrli_d:
9390 case Intrinsic::x86_sse2_psrli_q:
9391 case Intrinsic::x86_sse2_psrai_w:
9392 case Intrinsic::x86_sse2_psrai_d:
9393 case Intrinsic::x86_mmx_pslli_w:
9394 case Intrinsic::x86_mmx_pslli_d:
9395 case Intrinsic::x86_mmx_pslli_q:
9396 case Intrinsic::x86_mmx_psrli_w:
9397 case Intrinsic::x86_mmx_psrli_d:
9398 case Intrinsic::x86_mmx_psrli_q:
9399 case Intrinsic::x86_mmx_psrai_w:
9400 case Intrinsic::x86_mmx_psrai_d: {
9401 SDValue ShAmt = Op.getOperand(2);
9402 if (isa<ConstantSDNode>(ShAmt))
9405 unsigned NewIntNo = 0;
9406 EVT ShAmtVT = MVT::v4i32;
9408 case Intrinsic::x86_sse2_pslli_w:
9409 NewIntNo = Intrinsic::x86_sse2_psll_w;
9411 case Intrinsic::x86_sse2_pslli_d:
9412 NewIntNo = Intrinsic::x86_sse2_psll_d;
9414 case Intrinsic::x86_sse2_pslli_q:
9415 NewIntNo = Intrinsic::x86_sse2_psll_q;
9417 case Intrinsic::x86_sse2_psrli_w:
9418 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9420 case Intrinsic::x86_sse2_psrli_d:
9421 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9423 case Intrinsic::x86_sse2_psrli_q:
9424 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9426 case Intrinsic::x86_sse2_psrai_w:
9427 NewIntNo = Intrinsic::x86_sse2_psra_w;
9429 case Intrinsic::x86_sse2_psrai_d:
9430 NewIntNo = Intrinsic::x86_sse2_psra_d;
9432 case Intrinsic::x86_avx2_pslli_w:
9433 NewIntNo = Intrinsic::x86_avx2_psll_w;
9435 case Intrinsic::x86_avx2_pslli_d:
9436 NewIntNo = Intrinsic::x86_avx2_psll_d;
9438 case Intrinsic::x86_avx2_pslli_q:
9439 NewIntNo = Intrinsic::x86_avx2_psll_q;
9441 case Intrinsic::x86_avx2_psrli_w:
9442 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9444 case Intrinsic::x86_avx2_psrli_d:
9445 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9447 case Intrinsic::x86_avx2_psrli_q:
9448 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9450 case Intrinsic::x86_avx2_psrai_w:
9451 NewIntNo = Intrinsic::x86_avx2_psra_w;
9453 case Intrinsic::x86_avx2_psrai_d:
9454 NewIntNo = Intrinsic::x86_avx2_psra_d;
9457 ShAmtVT = MVT::v2i32;
9459 case Intrinsic::x86_mmx_pslli_w:
9460 NewIntNo = Intrinsic::x86_mmx_psll_w;
9462 case Intrinsic::x86_mmx_pslli_d:
9463 NewIntNo = Intrinsic::x86_mmx_psll_d;
9465 case Intrinsic::x86_mmx_pslli_q:
9466 NewIntNo = Intrinsic::x86_mmx_psll_q;
9468 case Intrinsic::x86_mmx_psrli_w:
9469 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9471 case Intrinsic::x86_mmx_psrli_d:
9472 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9474 case Intrinsic::x86_mmx_psrli_q:
9475 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9477 case Intrinsic::x86_mmx_psrai_w:
9478 NewIntNo = Intrinsic::x86_mmx_psra_w;
9480 case Intrinsic::x86_mmx_psrai_d:
9481 NewIntNo = Intrinsic::x86_mmx_psra_d;
9483 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9489 // The vector shift intrinsics with scalars uses 32b shift amounts but
9490 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9494 ShOps[1] = DAG.getConstant(0, MVT::i32);
9495 if (ShAmtVT == MVT::v4i32) {
9496 ShOps[2] = DAG.getUNDEF(MVT::i32);
9497 ShOps[3] = DAG.getUNDEF(MVT::i32);
9498 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9500 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9501 // FIXME this must be lowered to get rid of the invalid type.
9504 EVT VT = Op.getValueType();
9505 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9506 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9507 DAG.getConstant(NewIntNo, MVT::i32),
9508 Op.getOperand(1), ShAmt);
9513 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9514 SelectionDAG &DAG) const {
9515 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9516 MFI->setReturnAddressIsTaken(true);
9518 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9519 DebugLoc dl = Op.getDebugLoc();
9522 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9524 DAG.getConstant(TD->getPointerSize(),
9525 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9526 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9527 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9529 MachinePointerInfo(), false, false, false, 0);
9532 // Just load the return address.
9533 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9534 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9535 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9538 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9539 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9540 MFI->setFrameAddressIsTaken(true);
9542 EVT VT = Op.getValueType();
9543 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9544 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9545 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9546 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9548 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9549 MachinePointerInfo(),
9550 false, false, false, 0);
9554 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9555 SelectionDAG &DAG) const {
9556 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9559 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9560 MachineFunction &MF = DAG.getMachineFunction();
9561 SDValue Chain = Op.getOperand(0);
9562 SDValue Offset = Op.getOperand(1);
9563 SDValue Handler = Op.getOperand(2);
9564 DebugLoc dl = Op.getDebugLoc();
9566 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9567 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9569 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9571 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9572 DAG.getIntPtrConstant(TD->getPointerSize()));
9573 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9574 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9576 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9577 MF.getRegInfo().addLiveOut(StoreAddrReg);
9579 return DAG.getNode(X86ISD::EH_RETURN, dl,
9581 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9584 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9585 SelectionDAG &DAG) const {
9586 return Op.getOperand(0);
9589 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9590 SelectionDAG &DAG) const {
9591 SDValue Root = Op.getOperand(0);
9592 SDValue Trmp = Op.getOperand(1); // trampoline
9593 SDValue FPtr = Op.getOperand(2); // nested function
9594 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9595 DebugLoc dl = Op.getDebugLoc();
9597 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9599 if (Subtarget->is64Bit()) {
9600 SDValue OutChains[6];
9602 // Large code-model.
9603 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9604 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9606 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9607 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9609 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9611 // Load the pointer to the nested function into R11.
9612 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9613 SDValue Addr = Trmp;
9614 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9615 Addr, MachinePointerInfo(TrmpAddr),
9618 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9619 DAG.getConstant(2, MVT::i64));
9620 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9621 MachinePointerInfo(TrmpAddr, 2),
9624 // Load the 'nest' parameter value into R10.
9625 // R10 is specified in X86CallingConv.td
9626 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9627 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9628 DAG.getConstant(10, MVT::i64));
9629 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9630 Addr, MachinePointerInfo(TrmpAddr, 10),
9633 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9634 DAG.getConstant(12, MVT::i64));
9635 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9636 MachinePointerInfo(TrmpAddr, 12),
9639 // Jump to the nested function.
9640 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9641 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9642 DAG.getConstant(20, MVT::i64));
9643 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9644 Addr, MachinePointerInfo(TrmpAddr, 20),
9647 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9648 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9649 DAG.getConstant(22, MVT::i64));
9650 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9651 MachinePointerInfo(TrmpAddr, 22),
9654 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9656 const Function *Func =
9657 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9658 CallingConv::ID CC = Func->getCallingConv();
9663 llvm_unreachable("Unsupported calling convention");
9664 case CallingConv::C:
9665 case CallingConv::X86_StdCall: {
9666 // Pass 'nest' parameter in ECX.
9667 // Must be kept in sync with X86CallingConv.td
9670 // Check that ECX wasn't needed by an 'inreg' parameter.
9671 FunctionType *FTy = Func->getFunctionType();
9672 const AttrListPtr &Attrs = Func->getAttributes();
9674 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9675 unsigned InRegCount = 0;
9678 for (FunctionType::param_iterator I = FTy->param_begin(),
9679 E = FTy->param_end(); I != E; ++I, ++Idx)
9680 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9681 // FIXME: should only count parameters that are lowered to integers.
9682 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9684 if (InRegCount > 2) {
9685 report_fatal_error("Nest register in use - reduce number of inreg"
9691 case CallingConv::X86_FastCall:
9692 case CallingConv::X86_ThisCall:
9693 case CallingConv::Fast:
9694 // Pass 'nest' parameter in EAX.
9695 // Must be kept in sync with X86CallingConv.td
9700 SDValue OutChains[4];
9703 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9704 DAG.getConstant(10, MVT::i32));
9705 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9707 // This is storing the opcode for MOV32ri.
9708 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9709 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9710 OutChains[0] = DAG.getStore(Root, dl,
9711 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9712 Trmp, MachinePointerInfo(TrmpAddr),
9715 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9716 DAG.getConstant(1, MVT::i32));
9717 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9718 MachinePointerInfo(TrmpAddr, 1),
9721 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9722 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9723 DAG.getConstant(5, MVT::i32));
9724 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9725 MachinePointerInfo(TrmpAddr, 5),
9728 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9729 DAG.getConstant(6, MVT::i32));
9730 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9731 MachinePointerInfo(TrmpAddr, 6),
9734 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9738 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9739 SelectionDAG &DAG) const {
9741 The rounding mode is in bits 11:10 of FPSR, and has the following
9748 FLT_ROUNDS, on the other hand, expects the following:
9755 To perform the conversion, we do:
9756 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9759 MachineFunction &MF = DAG.getMachineFunction();
9760 const TargetMachine &TM = MF.getTarget();
9761 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9762 unsigned StackAlignment = TFI.getStackAlignment();
9763 EVT VT = Op.getValueType();
9764 DebugLoc DL = Op.getDebugLoc();
9766 // Save FP Control Word to stack slot
9767 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9768 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9771 MachineMemOperand *MMO =
9772 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9773 MachineMemOperand::MOStore, 2, 2);
9775 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9776 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9777 DAG.getVTList(MVT::Other),
9778 Ops, 2, MVT::i16, MMO);
9780 // Load FP Control Word from stack slot
9781 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9782 MachinePointerInfo(), false, false, false, 0);
9784 // Transform as necessary
9786 DAG.getNode(ISD::SRL, DL, MVT::i16,
9787 DAG.getNode(ISD::AND, DL, MVT::i16,
9788 CWD, DAG.getConstant(0x800, MVT::i16)),
9789 DAG.getConstant(11, MVT::i8));
9791 DAG.getNode(ISD::SRL, DL, MVT::i16,
9792 DAG.getNode(ISD::AND, DL, MVT::i16,
9793 CWD, DAG.getConstant(0x400, MVT::i16)),
9794 DAG.getConstant(9, MVT::i8));
9797 DAG.getNode(ISD::AND, DL, MVT::i16,
9798 DAG.getNode(ISD::ADD, DL, MVT::i16,
9799 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9800 DAG.getConstant(1, MVT::i16)),
9801 DAG.getConstant(3, MVT::i16));
9804 return DAG.getNode((VT.getSizeInBits() < 16 ?
9805 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9808 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9809 EVT VT = Op.getValueType();
9811 unsigned NumBits = VT.getSizeInBits();
9812 DebugLoc dl = Op.getDebugLoc();
9814 Op = Op.getOperand(0);
9815 if (VT == MVT::i8) {
9816 // Zero extend to i32 since there is not an i8 bsr.
9818 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9821 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9822 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9823 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9825 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9828 DAG.getConstant(NumBits+NumBits-1, OpVT),
9829 DAG.getConstant(X86::COND_E, MVT::i8),
9832 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9834 // Finally xor with NumBits-1.
9835 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9838 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9842 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9843 EVT VT = Op.getValueType();
9845 unsigned NumBits = VT.getSizeInBits();
9846 DebugLoc dl = Op.getDebugLoc();
9848 Op = Op.getOperand(0);
9849 if (VT == MVT::i8) {
9851 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9854 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9855 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9856 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9858 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9861 DAG.getConstant(NumBits, OpVT),
9862 DAG.getConstant(X86::COND_E, MVT::i8),
9865 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9868 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9872 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9873 // ones, and then concatenate the result back.
9874 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9875 EVT VT = Op.getValueType();
9877 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9878 "Unsupported value type for operation");
9880 int NumElems = VT.getVectorNumElements();
9881 DebugLoc dl = Op.getDebugLoc();
9882 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9883 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9885 // Extract the LHS vectors
9886 SDValue LHS = Op.getOperand(0);
9887 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9888 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9890 // Extract the RHS vectors
9891 SDValue RHS = Op.getOperand(1);
9892 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9893 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9895 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9896 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9898 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9899 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9900 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9903 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9904 assert(Op.getValueType().getSizeInBits() == 256 &&
9905 Op.getValueType().isInteger() &&
9906 "Only handle AVX 256-bit vector integer operation");
9907 return Lower256IntArith(Op, DAG);
9910 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9911 assert(Op.getValueType().getSizeInBits() == 256 &&
9912 Op.getValueType().isInteger() &&
9913 "Only handle AVX 256-bit vector integer operation");
9914 return Lower256IntArith(Op, DAG);
9917 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9918 EVT VT = Op.getValueType();
9920 // Decompose 256-bit ops into smaller 128-bit ops.
9921 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9922 return Lower256IntArith(Op, DAG);
9924 DebugLoc dl = Op.getDebugLoc();
9926 SDValue A = Op.getOperand(0);
9927 SDValue B = Op.getOperand(1);
9929 if (VT == MVT::v4i64) {
9930 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9932 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9933 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9934 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9935 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9936 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9938 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9939 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9940 // return AloBlo + AloBhi + AhiBlo;
9942 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9943 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9944 A, DAG.getConstant(32, MVT::i32));
9945 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9946 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9947 B, DAG.getConstant(32, MVT::i32));
9948 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9949 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9951 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9952 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9954 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9955 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9957 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9958 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9959 AloBhi, DAG.getConstant(32, MVT::i32));
9960 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9961 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9962 AhiBlo, DAG.getConstant(32, MVT::i32));
9963 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9964 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9968 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9970 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9971 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9972 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9973 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9974 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9976 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9977 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9978 // return AloBlo + AloBhi + AhiBlo;
9980 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9981 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9982 A, DAG.getConstant(32, MVT::i32));
9983 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9984 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9985 B, DAG.getConstant(32, MVT::i32));
9986 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9987 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9989 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9990 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9992 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9993 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9995 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9996 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9997 AloBhi, DAG.getConstant(32, MVT::i32));
9998 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9999 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10000 AhiBlo, DAG.getConstant(32, MVT::i32));
10001 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10002 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10006 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10008 EVT VT = Op.getValueType();
10009 DebugLoc dl = Op.getDebugLoc();
10010 SDValue R = Op.getOperand(0);
10011 SDValue Amt = Op.getOperand(1);
10012 LLVMContext *Context = DAG.getContext();
10014 if (!Subtarget->hasXMMInt())
10017 // Optimize shl/srl/sra with constant shift amount.
10018 if (isSplatVector(Amt.getNode())) {
10019 SDValue SclrAmt = Amt->getOperand(0);
10020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10021 uint64_t ShiftAmt = C->getZExtValue();
10023 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10024 // Make a large shift.
10026 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10027 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10028 R, DAG.getConstant(ShiftAmt, MVT::i32));
10029 // Zero out the rightmost bits.
10030 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10032 return DAG.getNode(ISD::AND, dl, VT, SHL,
10033 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10036 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10037 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10038 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10039 R, DAG.getConstant(ShiftAmt, MVT::i32));
10041 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10042 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10043 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10044 R, DAG.getConstant(ShiftAmt, MVT::i32));
10046 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10047 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10048 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10049 R, DAG.getConstant(ShiftAmt, MVT::i32));
10051 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10052 // Make a large shift.
10054 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10055 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10056 R, DAG.getConstant(ShiftAmt, MVT::i32));
10057 // Zero out the leftmost bits.
10058 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10060 return DAG.getNode(ISD::AND, dl, VT, SRL,
10061 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10064 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10065 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10066 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10067 R, DAG.getConstant(ShiftAmt, MVT::i32));
10069 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10071 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10072 R, DAG.getConstant(ShiftAmt, MVT::i32));
10074 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10075 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10076 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10077 R, DAG.getConstant(ShiftAmt, MVT::i32));
10079 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10081 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10082 R, DAG.getConstant(ShiftAmt, MVT::i32));
10084 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10086 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10087 R, DAG.getConstant(ShiftAmt, MVT::i32));
10089 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10090 if (ShiftAmt == 7) {
10091 // R s>> 7 === R s< 0
10092 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10093 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10096 // R s>> a === ((R u>> a) ^ m) - m
10097 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10098 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10100 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10101 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10102 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10106 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10107 if (Op.getOpcode() == ISD::SHL) {
10108 // Make a large shift.
10110 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10111 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10112 R, DAG.getConstant(ShiftAmt, MVT::i32));
10113 // Zero out the rightmost bits.
10114 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10116 return DAG.getNode(ISD::AND, dl, VT, SHL,
10117 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10119 if (Op.getOpcode() == ISD::SRL) {
10120 // Make a large shift.
10122 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10123 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10124 R, DAG.getConstant(ShiftAmt, MVT::i32));
10125 // Zero out the leftmost bits.
10126 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10128 return DAG.getNode(ISD::AND, dl, VT, SRL,
10129 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10131 if (Op.getOpcode() == ISD::SRA) {
10132 if (ShiftAmt == 7) {
10133 // R s>> 7 === R s< 0
10134 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10135 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10138 // R s>> a === ((R u>> a) ^ m) - m
10139 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10140 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10142 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10143 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10144 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10151 // Lower SHL with variable shift amount.
10152 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10153 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10154 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10155 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10157 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10159 std::vector<Constant*> CV(4, CI);
10160 Constant *C = ConstantVector::get(CV);
10161 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10162 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10163 MachinePointerInfo::getConstantPool(),
10164 false, false, false, 16);
10166 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10167 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10168 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10169 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10171 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10172 assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10173 "Need SSE2 for pslli/pcmpeq.");
10176 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10177 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10178 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10180 // Turn 'a' into a mask suitable for VSELECT
10181 SDValue VSelM = DAG.getConstant(0x80, VT);
10182 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10183 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10184 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10187 SDValue CM1 = DAG.getConstant(0x0f, VT);
10188 SDValue CM2 = DAG.getConstant(0x3f, VT);
10190 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10191 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10192 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10193 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10194 DAG.getConstant(4, MVT::i32));
10195 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10198 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10199 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10200 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10201 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10204 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10205 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10206 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10207 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10208 DAG.getConstant(2, MVT::i32));
10209 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10212 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10213 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10214 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10215 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10218 // return VSELECT(r, r+r, a);
10219 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10220 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10224 // Decompose 256-bit shifts into smaller 128-bit shifts.
10225 if (VT.getSizeInBits() == 256) {
10226 int NumElems = VT.getVectorNumElements();
10227 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10228 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10230 // Extract the two vectors
10231 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10232 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10235 // Recreate the shift amount vectors
10236 SDValue Amt1, Amt2;
10237 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10238 // Constant shift amount
10239 SmallVector<SDValue, 4> Amt1Csts;
10240 SmallVector<SDValue, 4> Amt2Csts;
10241 for (int i = 0; i < NumElems/2; ++i)
10242 Amt1Csts.push_back(Amt->getOperand(i));
10243 for (int i = NumElems/2; i < NumElems; ++i)
10244 Amt2Csts.push_back(Amt->getOperand(i));
10246 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10247 &Amt1Csts[0], NumElems/2);
10248 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10249 &Amt2Csts[0], NumElems/2);
10251 // Variable shift amount
10252 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10253 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10257 // Issue new vector shifts for the smaller types
10258 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10259 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10261 // Concatenate the result back
10262 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10268 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10269 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10270 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10271 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10272 // has only one use.
10273 SDNode *N = Op.getNode();
10274 SDValue LHS = N->getOperand(0);
10275 SDValue RHS = N->getOperand(1);
10276 unsigned BaseOp = 0;
10278 DebugLoc DL = Op.getDebugLoc();
10279 switch (Op.getOpcode()) {
10280 default: llvm_unreachable("Unknown ovf instruction!");
10282 // A subtract of one will be selected as a INC. Note that INC doesn't
10283 // set CF, so we can't do this for UADDO.
10284 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10286 BaseOp = X86ISD::INC;
10287 Cond = X86::COND_O;
10290 BaseOp = X86ISD::ADD;
10291 Cond = X86::COND_O;
10294 BaseOp = X86ISD::ADD;
10295 Cond = X86::COND_B;
10298 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10299 // set CF, so we can't do this for USUBO.
10300 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10302 BaseOp = X86ISD::DEC;
10303 Cond = X86::COND_O;
10306 BaseOp = X86ISD::SUB;
10307 Cond = X86::COND_O;
10310 BaseOp = X86ISD::SUB;
10311 Cond = X86::COND_B;
10314 BaseOp = X86ISD::SMUL;
10315 Cond = X86::COND_O;
10317 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10318 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10320 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10323 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10324 DAG.getConstant(X86::COND_O, MVT::i32),
10325 SDValue(Sum.getNode(), 2));
10327 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10331 // Also sets EFLAGS.
10332 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10333 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10336 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10337 DAG.getConstant(Cond, MVT::i32),
10338 SDValue(Sum.getNode(), 1));
10340 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10343 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10344 DebugLoc dl = Op.getDebugLoc();
10345 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10346 EVT VT = Op.getValueType();
10348 if (Subtarget->hasXMMInt() && VT.isVector()) {
10349 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10350 ExtraVT.getScalarType().getSizeInBits();
10351 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10353 unsigned SHLIntrinsicsID = 0;
10354 unsigned SRAIntrinsicsID = 0;
10355 switch (VT.getSimpleVT().SimpleTy) {
10359 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10360 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10363 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10364 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10368 if (!Subtarget->hasAVX())
10370 if (!Subtarget->hasAVX2()) {
10371 // needs to be split
10372 int NumElems = VT.getVectorNumElements();
10373 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10374 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10376 // Extract the LHS vectors
10377 SDValue LHS = Op.getOperand(0);
10378 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10379 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10381 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10382 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10384 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10385 int ExtraNumElems = ExtraVT.getVectorNumElements();
10386 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10388 SDValue Extra = DAG.getValueType(ExtraVT);
10390 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10391 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10393 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10395 if (VT == MVT::v8i32) {
10396 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10397 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10399 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10400 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10404 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10405 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10406 Op.getOperand(0), ShAmt);
10408 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10409 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10417 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10418 DebugLoc dl = Op.getDebugLoc();
10420 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10421 // There isn't any reason to disable it if the target processor supports it.
10422 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10423 SDValue Chain = Op.getOperand(0);
10424 SDValue Zero = DAG.getConstant(0, MVT::i32);
10426 DAG.getRegister(X86::ESP, MVT::i32), // Base
10427 DAG.getTargetConstant(1, MVT::i8), // Scale
10428 DAG.getRegister(0, MVT::i32), // Index
10429 DAG.getTargetConstant(0, MVT::i32), // Disp
10430 DAG.getRegister(0, MVT::i32), // Segment.
10435 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10436 array_lengthof(Ops));
10437 return SDValue(Res, 0);
10440 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10442 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10444 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10445 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10446 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10447 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10449 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10450 if (!Op1 && !Op2 && !Op3 && Op4)
10451 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10453 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10454 if (Op1 && !Op2 && !Op3 && !Op4)
10455 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10457 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10459 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10462 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10463 SelectionDAG &DAG) const {
10464 DebugLoc dl = Op.getDebugLoc();
10465 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10466 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10467 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10468 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10470 // The only fence that needs an instruction is a sequentially-consistent
10471 // cross-thread fence.
10472 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10473 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10474 // no-sse2). There isn't any reason to disable it if the target processor
10476 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10477 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10479 SDValue Chain = Op.getOperand(0);
10480 SDValue Zero = DAG.getConstant(0, MVT::i32);
10482 DAG.getRegister(X86::ESP, MVT::i32), // Base
10483 DAG.getTargetConstant(1, MVT::i8), // Scale
10484 DAG.getRegister(0, MVT::i32), // Index
10485 DAG.getTargetConstant(0, MVT::i32), // Disp
10486 DAG.getRegister(0, MVT::i32), // Segment.
10491 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10492 array_lengthof(Ops));
10493 return SDValue(Res, 0);
10496 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10497 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10501 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10502 EVT T = Op.getValueType();
10503 DebugLoc DL = Op.getDebugLoc();
10506 switch(T.getSimpleVT().SimpleTy) {
10508 assert(false && "Invalid value type!");
10509 case MVT::i8: Reg = X86::AL; size = 1; break;
10510 case MVT::i16: Reg = X86::AX; size = 2; break;
10511 case MVT::i32: Reg = X86::EAX; size = 4; break;
10513 assert(Subtarget->is64Bit() && "Node not type legal!");
10514 Reg = X86::RAX; size = 8;
10517 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10518 Op.getOperand(2), SDValue());
10519 SDValue Ops[] = { cpIn.getValue(0),
10522 DAG.getTargetConstant(size, MVT::i8),
10523 cpIn.getValue(1) };
10524 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10525 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10526 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10529 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10533 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10534 SelectionDAG &DAG) const {
10535 assert(Subtarget->is64Bit() && "Result not type legalized?");
10536 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10537 SDValue TheChain = Op.getOperand(0);
10538 DebugLoc dl = Op.getDebugLoc();
10539 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10540 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10541 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10543 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10544 DAG.getConstant(32, MVT::i8));
10546 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10549 return DAG.getMergeValues(Ops, 2, dl);
10552 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10553 SelectionDAG &DAG) const {
10554 EVT SrcVT = Op.getOperand(0).getValueType();
10555 EVT DstVT = Op.getValueType();
10556 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10557 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10558 assert((DstVT == MVT::i64 ||
10559 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10560 "Unexpected custom BITCAST");
10561 // i64 <=> MMX conversions are Legal.
10562 if (SrcVT==MVT::i64 && DstVT.isVector())
10564 if (DstVT==MVT::i64 && SrcVT.isVector())
10566 // MMX <=> MMX conversions are Legal.
10567 if (SrcVT.isVector() && DstVT.isVector())
10569 // All other conversions need to be expanded.
10573 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10574 SDNode *Node = Op.getNode();
10575 DebugLoc dl = Node->getDebugLoc();
10576 EVT T = Node->getValueType(0);
10577 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10578 DAG.getConstant(0, T), Node->getOperand(2));
10579 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10580 cast<AtomicSDNode>(Node)->getMemoryVT(),
10581 Node->getOperand(0),
10582 Node->getOperand(1), negOp,
10583 cast<AtomicSDNode>(Node)->getSrcValue(),
10584 cast<AtomicSDNode>(Node)->getAlignment(),
10585 cast<AtomicSDNode>(Node)->getOrdering(),
10586 cast<AtomicSDNode>(Node)->getSynchScope());
10589 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10590 SDNode *Node = Op.getNode();
10591 DebugLoc dl = Node->getDebugLoc();
10592 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10594 // Convert seq_cst store -> xchg
10595 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10596 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10597 // (The only way to get a 16-byte store is cmpxchg16b)
10598 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10599 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10600 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10601 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10602 cast<AtomicSDNode>(Node)->getMemoryVT(),
10603 Node->getOperand(0),
10604 Node->getOperand(1), Node->getOperand(2),
10605 cast<AtomicSDNode>(Node)->getMemOperand(),
10606 cast<AtomicSDNode>(Node)->getOrdering(),
10607 cast<AtomicSDNode>(Node)->getSynchScope());
10608 return Swap.getValue(1);
10610 // Other atomic stores have a simple pattern.
10614 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10615 EVT VT = Op.getNode()->getValueType(0);
10617 // Let legalize expand this if it isn't a legal type yet.
10618 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10621 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10624 bool ExtraOp = false;
10625 switch (Op.getOpcode()) {
10626 default: assert(0 && "Invalid code");
10627 case ISD::ADDC: Opc = X86ISD::ADD; break;
10628 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10629 case ISD::SUBC: Opc = X86ISD::SUB; break;
10630 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10634 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10636 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10637 Op.getOperand(1), Op.getOperand(2));
10640 /// LowerOperation - Provide custom lowering hooks for some operations.
10642 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10643 switch (Op.getOpcode()) {
10644 default: llvm_unreachable("Should not custom lower this!");
10645 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10646 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10647 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10648 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10649 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10650 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10651 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10652 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10653 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10654 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10655 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10656 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10657 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10658 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10659 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10660 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10661 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10662 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10663 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10664 case ISD::SHL_PARTS:
10665 case ISD::SRA_PARTS:
10666 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10667 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10668 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10669 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10670 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10671 case ISD::FABS: return LowerFABS(Op, DAG);
10672 case ISD::FNEG: return LowerFNEG(Op, DAG);
10673 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10674 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10675 case ISD::SETCC: return LowerSETCC(Op, DAG);
10676 case ISD::SELECT: return LowerSELECT(Op, DAG);
10677 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10678 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10679 case ISD::VASTART: return LowerVASTART(Op, DAG);
10680 case ISD::VAARG: return LowerVAARG(Op, DAG);
10681 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10682 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10683 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10684 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10685 case ISD::FRAME_TO_ARGS_OFFSET:
10686 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10687 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10688 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10689 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10690 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10691 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10692 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10693 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10694 case ISD::MUL: return LowerMUL(Op, DAG);
10697 case ISD::SHL: return LowerShift(Op, DAG);
10703 case ISD::UMULO: return LowerXALUO(Op, DAG);
10704 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10705 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10709 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10710 case ISD::ADD: return LowerADD(Op, DAG);
10711 case ISD::SUB: return LowerSUB(Op, DAG);
10715 static void ReplaceATOMIC_LOAD(SDNode *Node,
10716 SmallVectorImpl<SDValue> &Results,
10717 SelectionDAG &DAG) {
10718 DebugLoc dl = Node->getDebugLoc();
10719 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10721 // Convert wide load -> cmpxchg8b/cmpxchg16b
10722 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10723 // (The only way to get a 16-byte load is cmpxchg16b)
10724 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10725 SDValue Zero = DAG.getConstant(0, VT);
10726 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10727 Node->getOperand(0),
10728 Node->getOperand(1), Zero, Zero,
10729 cast<AtomicSDNode>(Node)->getMemOperand(),
10730 cast<AtomicSDNode>(Node)->getOrdering(),
10731 cast<AtomicSDNode>(Node)->getSynchScope());
10732 Results.push_back(Swap.getValue(0));
10733 Results.push_back(Swap.getValue(1));
10736 void X86TargetLowering::
10737 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10738 SelectionDAG &DAG, unsigned NewOp) const {
10739 DebugLoc dl = Node->getDebugLoc();
10740 assert (Node->getValueType(0) == MVT::i64 &&
10741 "Only know how to expand i64 atomics");
10743 SDValue Chain = Node->getOperand(0);
10744 SDValue In1 = Node->getOperand(1);
10745 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10746 Node->getOperand(2), DAG.getIntPtrConstant(0));
10747 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10748 Node->getOperand(2), DAG.getIntPtrConstant(1));
10749 SDValue Ops[] = { Chain, In1, In2L, In2H };
10750 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10752 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10753 cast<MemSDNode>(Node)->getMemOperand());
10754 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10755 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10756 Results.push_back(Result.getValue(2));
10759 /// ReplaceNodeResults - Replace a node with an illegal result type
10760 /// with a new node built out of custom code.
10761 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10762 SmallVectorImpl<SDValue>&Results,
10763 SelectionDAG &DAG) const {
10764 DebugLoc dl = N->getDebugLoc();
10765 switch (N->getOpcode()) {
10767 assert(false && "Do not know how to custom type legalize this operation!");
10769 case ISD::SIGN_EXTEND_INREG:
10774 // We don't want to expand or promote these.
10776 case ISD::FP_TO_SINT: {
10777 std::pair<SDValue,SDValue> Vals =
10778 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10779 SDValue FIST = Vals.first, StackSlot = Vals.second;
10780 if (FIST.getNode() != 0) {
10781 EVT VT = N->getValueType(0);
10782 // Return a load from the stack slot.
10783 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10784 MachinePointerInfo(),
10785 false, false, false, 0));
10789 case ISD::READCYCLECOUNTER: {
10790 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10791 SDValue TheChain = N->getOperand(0);
10792 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10793 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10795 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10797 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10798 SDValue Ops[] = { eax, edx };
10799 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10800 Results.push_back(edx.getValue(1));
10803 case ISD::ATOMIC_CMP_SWAP: {
10804 EVT T = N->getValueType(0);
10805 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10806 bool Regs64bit = T == MVT::i128;
10807 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10808 SDValue cpInL, cpInH;
10809 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10810 DAG.getConstant(0, HalfT));
10811 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10812 DAG.getConstant(1, HalfT));
10813 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10814 Regs64bit ? X86::RAX : X86::EAX,
10816 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10817 Regs64bit ? X86::RDX : X86::EDX,
10818 cpInH, cpInL.getValue(1));
10819 SDValue swapInL, swapInH;
10820 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10821 DAG.getConstant(0, HalfT));
10822 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10823 DAG.getConstant(1, HalfT));
10824 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10825 Regs64bit ? X86::RBX : X86::EBX,
10826 swapInL, cpInH.getValue(1));
10827 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10828 Regs64bit ? X86::RCX : X86::ECX,
10829 swapInH, swapInL.getValue(1));
10830 SDValue Ops[] = { swapInH.getValue(0),
10832 swapInH.getValue(1) };
10833 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10834 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10835 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10836 X86ISD::LCMPXCHG8_DAG;
10837 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10839 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10840 Regs64bit ? X86::RAX : X86::EAX,
10841 HalfT, Result.getValue(1));
10842 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10843 Regs64bit ? X86::RDX : X86::EDX,
10844 HalfT, cpOutL.getValue(2));
10845 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10846 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10847 Results.push_back(cpOutH.getValue(1));
10850 case ISD::ATOMIC_LOAD_ADD:
10851 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10853 case ISD::ATOMIC_LOAD_AND:
10854 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10856 case ISD::ATOMIC_LOAD_NAND:
10857 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10859 case ISD::ATOMIC_LOAD_OR:
10860 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10862 case ISD::ATOMIC_LOAD_SUB:
10863 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10865 case ISD::ATOMIC_LOAD_XOR:
10866 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10868 case ISD::ATOMIC_SWAP:
10869 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10871 case ISD::ATOMIC_LOAD:
10872 ReplaceATOMIC_LOAD(N, Results, DAG);
10876 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10878 default: return NULL;
10879 case X86ISD::BSF: return "X86ISD::BSF";
10880 case X86ISD::BSR: return "X86ISD::BSR";
10881 case X86ISD::SHLD: return "X86ISD::SHLD";
10882 case X86ISD::SHRD: return "X86ISD::SHRD";
10883 case X86ISD::FAND: return "X86ISD::FAND";
10884 case X86ISD::FOR: return "X86ISD::FOR";
10885 case X86ISD::FXOR: return "X86ISD::FXOR";
10886 case X86ISD::FSRL: return "X86ISD::FSRL";
10887 case X86ISD::FILD: return "X86ISD::FILD";
10888 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10889 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10890 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10891 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10892 case X86ISD::FLD: return "X86ISD::FLD";
10893 case X86ISD::FST: return "X86ISD::FST";
10894 case X86ISD::CALL: return "X86ISD::CALL";
10895 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10896 case X86ISD::BT: return "X86ISD::BT";
10897 case X86ISD::CMP: return "X86ISD::CMP";
10898 case X86ISD::COMI: return "X86ISD::COMI";
10899 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10900 case X86ISD::SETCC: return "X86ISD::SETCC";
10901 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10902 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10903 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10904 case X86ISD::CMOV: return "X86ISD::CMOV";
10905 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10906 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10907 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10908 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10909 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10910 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10911 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10912 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10913 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10914 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10915 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10916 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10917 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10918 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10919 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10920 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10921 case X86ISD::HADD: return "X86ISD::HADD";
10922 case X86ISD::HSUB: return "X86ISD::HSUB";
10923 case X86ISD::FHADD: return "X86ISD::FHADD";
10924 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10925 case X86ISD::FMAX: return "X86ISD::FMAX";
10926 case X86ISD::FMIN: return "X86ISD::FMIN";
10927 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10928 case X86ISD::FRCP: return "X86ISD::FRCP";
10929 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10930 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10931 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10932 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10933 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10934 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10935 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10936 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10937 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10938 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10939 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10940 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10941 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10942 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10943 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10944 case X86ISD::VSHL: return "X86ISD::VSHL";
10945 case X86ISD::VSRL: return "X86ISD::VSRL";
10946 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10947 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10948 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10949 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10950 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10951 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10952 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10953 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10954 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10955 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10956 case X86ISD::ADD: return "X86ISD::ADD";
10957 case X86ISD::SUB: return "X86ISD::SUB";
10958 case X86ISD::ADC: return "X86ISD::ADC";
10959 case X86ISD::SBB: return "X86ISD::SBB";
10960 case X86ISD::SMUL: return "X86ISD::SMUL";
10961 case X86ISD::UMUL: return "X86ISD::UMUL";
10962 case X86ISD::INC: return "X86ISD::INC";
10963 case X86ISD::DEC: return "X86ISD::DEC";
10964 case X86ISD::OR: return "X86ISD::OR";
10965 case X86ISD::XOR: return "X86ISD::XOR";
10966 case X86ISD::AND: return "X86ISD::AND";
10967 case X86ISD::ANDN: return "X86ISD::ANDN";
10968 case X86ISD::BLSI: return "X86ISD::BLSI";
10969 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
10970 case X86ISD::BLSR: return "X86ISD::BLSR";
10971 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10972 case X86ISD::PTEST: return "X86ISD::PTEST";
10973 case X86ISD::TESTP: return "X86ISD::TESTP";
10974 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10975 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10976 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10977 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10978 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10979 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10980 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10981 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10982 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10983 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10984 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10985 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10986 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10987 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10988 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10989 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10990 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10991 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10992 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10993 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10994 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
10995 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
10996 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10997 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
10998 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
10999 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11000 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11001 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11002 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11003 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11007 // isLegalAddressingMode - Return true if the addressing mode represented
11008 // by AM is legal for this target, for a load/store of the specified type.
11009 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11011 // X86 supports extremely general addressing modes.
11012 CodeModel::Model M = getTargetMachine().getCodeModel();
11013 Reloc::Model R = getTargetMachine().getRelocationModel();
11015 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11016 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11021 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11023 // If a reference to this global requires an extra load, we can't fold it.
11024 if (isGlobalStubReference(GVFlags))
11027 // If BaseGV requires a register for the PIC base, we cannot also have a
11028 // BaseReg specified.
11029 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11032 // If lower 4G is not available, then we must use rip-relative addressing.
11033 if ((M != CodeModel::Small || R != Reloc::Static) &&
11034 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11038 switch (AM.Scale) {
11044 // These scales always work.
11049 // These scales are formed with basereg+scalereg. Only accept if there is
11054 default: // Other stuff never works.
11062 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11063 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11065 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11066 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11067 if (NumBits1 <= NumBits2)
11072 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11073 if (!VT1.isInteger() || !VT2.isInteger())
11075 unsigned NumBits1 = VT1.getSizeInBits();
11076 unsigned NumBits2 = VT2.getSizeInBits();
11077 if (NumBits1 <= NumBits2)
11082 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11083 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11084 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11087 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11088 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11089 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11092 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11093 // i16 instructions are longer (0x66 prefix) and potentially slower.
11094 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11097 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11098 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11099 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11100 /// are assumed to be legal.
11102 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11104 // Very little shuffling can be done for 64-bit vectors right now.
11105 if (VT.getSizeInBits() == 64)
11108 // FIXME: pshufb, blends, shifts.
11109 return (VT.getVectorNumElements() == 2 ||
11110 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11111 isMOVLMask(M, VT) ||
11112 isSHUFPMask(M, VT) ||
11113 isPSHUFDMask(M, VT) ||
11114 isPSHUFHWMask(M, VT) ||
11115 isPSHUFLWMask(M, VT) ||
11116 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11117 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11118 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11119 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11120 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11124 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11126 unsigned NumElts = VT.getVectorNumElements();
11127 // FIXME: This collection of masks seems suspect.
11130 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11131 return (isMOVLMask(Mask, VT) ||
11132 isCommutedMOVLMask(Mask, VT, true) ||
11133 isSHUFPMask(Mask, VT) ||
11134 isSHUFPMask(Mask, VT, /* Commuted */ true));
11139 //===----------------------------------------------------------------------===//
11140 // X86 Scheduler Hooks
11141 //===----------------------------------------------------------------------===//
11143 // private utility function
11144 MachineBasicBlock *
11145 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11146 MachineBasicBlock *MBB,
11153 TargetRegisterClass *RC,
11154 bool invSrc) const {
11155 // For the atomic bitwise operator, we generate
11158 // ld t1 = [bitinstr.addr]
11159 // op t2 = t1, [bitinstr.val]
11161 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11163 // fallthrough -->nextMBB
11164 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11165 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11166 MachineFunction::iterator MBBIter = MBB;
11169 /// First build the CFG
11170 MachineFunction *F = MBB->getParent();
11171 MachineBasicBlock *thisMBB = MBB;
11172 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11173 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11174 F->insert(MBBIter, newMBB);
11175 F->insert(MBBIter, nextMBB);
11177 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11178 nextMBB->splice(nextMBB->begin(), thisMBB,
11179 llvm::next(MachineBasicBlock::iterator(bInstr)),
11181 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11183 // Update thisMBB to fall through to newMBB
11184 thisMBB->addSuccessor(newMBB);
11186 // newMBB jumps to itself and fall through to nextMBB
11187 newMBB->addSuccessor(nextMBB);
11188 newMBB->addSuccessor(newMBB);
11190 // Insert instructions into newMBB based on incoming instruction
11191 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11192 "unexpected number of operands");
11193 DebugLoc dl = bInstr->getDebugLoc();
11194 MachineOperand& destOper = bInstr->getOperand(0);
11195 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11196 int numArgs = bInstr->getNumOperands() - 1;
11197 for (int i=0; i < numArgs; ++i)
11198 argOpers[i] = &bInstr->getOperand(i+1);
11200 // x86 address has 4 operands: base, index, scale, and displacement
11201 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11202 int valArgIndx = lastAddrIndx + 1;
11204 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11205 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11206 for (int i=0; i <= lastAddrIndx; ++i)
11207 (*MIB).addOperand(*argOpers[i]);
11209 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11211 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11216 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11217 assert((argOpers[valArgIndx]->isReg() ||
11218 argOpers[valArgIndx]->isImm()) &&
11219 "invalid operand");
11220 if (argOpers[valArgIndx]->isReg())
11221 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11223 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11225 (*MIB).addOperand(*argOpers[valArgIndx]);
11227 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11230 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11231 for (int i=0; i <= lastAddrIndx; ++i)
11232 (*MIB).addOperand(*argOpers[i]);
11234 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11235 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11236 bInstr->memoperands_end());
11238 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11239 MIB.addReg(EAXreg);
11242 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11244 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11248 // private utility function: 64 bit atomics on 32 bit host.
11249 MachineBasicBlock *
11250 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11251 MachineBasicBlock *MBB,
11256 bool invSrc) const {
11257 // For the atomic bitwise operator, we generate
11258 // thisMBB (instructions are in pairs, except cmpxchg8b)
11259 // ld t1,t2 = [bitinstr.addr]
11261 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11262 // op t5, t6 <- out1, out2, [bitinstr.val]
11263 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11264 // mov ECX, EBX <- t5, t6
11265 // mov EAX, EDX <- t1, t2
11266 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11267 // mov t3, t4 <- EAX, EDX
11269 // result in out1, out2
11270 // fallthrough -->nextMBB
11272 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11273 const unsigned LoadOpc = X86::MOV32rm;
11274 const unsigned NotOpc = X86::NOT32r;
11275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11276 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11277 MachineFunction::iterator MBBIter = MBB;
11280 /// First build the CFG
11281 MachineFunction *F = MBB->getParent();
11282 MachineBasicBlock *thisMBB = MBB;
11283 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11284 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11285 F->insert(MBBIter, newMBB);
11286 F->insert(MBBIter, nextMBB);
11288 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11289 nextMBB->splice(nextMBB->begin(), thisMBB,
11290 llvm::next(MachineBasicBlock::iterator(bInstr)),
11292 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11294 // Update thisMBB to fall through to newMBB
11295 thisMBB->addSuccessor(newMBB);
11297 // newMBB jumps to itself and fall through to nextMBB
11298 newMBB->addSuccessor(nextMBB);
11299 newMBB->addSuccessor(newMBB);
11301 DebugLoc dl = bInstr->getDebugLoc();
11302 // Insert instructions into newMBB based on incoming instruction
11303 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11304 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11305 "unexpected number of operands");
11306 MachineOperand& dest1Oper = bInstr->getOperand(0);
11307 MachineOperand& dest2Oper = bInstr->getOperand(1);
11308 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11309 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11310 argOpers[i] = &bInstr->getOperand(i+2);
11312 // We use some of the operands multiple times, so conservatively just
11313 // clear any kill flags that might be present.
11314 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11315 argOpers[i]->setIsKill(false);
11318 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11319 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11321 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11322 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11323 for (int i=0; i <= lastAddrIndx; ++i)
11324 (*MIB).addOperand(*argOpers[i]);
11325 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11326 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11327 // add 4 to displacement.
11328 for (int i=0; i <= lastAddrIndx-2; ++i)
11329 (*MIB).addOperand(*argOpers[i]);
11330 MachineOperand newOp3 = *(argOpers[3]);
11331 if (newOp3.isImm())
11332 newOp3.setImm(newOp3.getImm()+4);
11334 newOp3.setOffset(newOp3.getOffset()+4);
11335 (*MIB).addOperand(newOp3);
11336 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11338 // t3/4 are defined later, at the bottom of the loop
11339 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11340 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11341 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11342 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11343 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11344 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11346 // The subsequent operations should be using the destination registers of
11347 //the PHI instructions.
11349 t1 = F->getRegInfo().createVirtualRegister(RC);
11350 t2 = F->getRegInfo().createVirtualRegister(RC);
11351 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11352 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11354 t1 = dest1Oper.getReg();
11355 t2 = dest2Oper.getReg();
11358 int valArgIndx = lastAddrIndx + 1;
11359 assert((argOpers[valArgIndx]->isReg() ||
11360 argOpers[valArgIndx]->isImm()) &&
11361 "invalid operand");
11362 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11363 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11364 if (argOpers[valArgIndx]->isReg())
11365 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11367 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11368 if (regOpcL != X86::MOV32rr)
11370 (*MIB).addOperand(*argOpers[valArgIndx]);
11371 assert(argOpers[valArgIndx + 1]->isReg() ==
11372 argOpers[valArgIndx]->isReg());
11373 assert(argOpers[valArgIndx + 1]->isImm() ==
11374 argOpers[valArgIndx]->isImm());
11375 if (argOpers[valArgIndx + 1]->isReg())
11376 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11378 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11379 if (regOpcH != X86::MOV32rr)
11381 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11383 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11385 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11388 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11390 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11393 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11394 for (int i=0; i <= lastAddrIndx; ++i)
11395 (*MIB).addOperand(*argOpers[i]);
11397 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11398 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11399 bInstr->memoperands_end());
11401 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11402 MIB.addReg(X86::EAX);
11403 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11404 MIB.addReg(X86::EDX);
11407 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11409 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11413 // private utility function
11414 MachineBasicBlock *
11415 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11416 MachineBasicBlock *MBB,
11417 unsigned cmovOpc) const {
11418 // For the atomic min/max operator, we generate
11421 // ld t1 = [min/max.addr]
11422 // mov t2 = [min/max.val]
11424 // cmov[cond] t2 = t1
11426 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11428 // fallthrough -->nextMBB
11430 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11431 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11432 MachineFunction::iterator MBBIter = MBB;
11435 /// First build the CFG
11436 MachineFunction *F = MBB->getParent();
11437 MachineBasicBlock *thisMBB = MBB;
11438 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11439 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11440 F->insert(MBBIter, newMBB);
11441 F->insert(MBBIter, nextMBB);
11443 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11444 nextMBB->splice(nextMBB->begin(), thisMBB,
11445 llvm::next(MachineBasicBlock::iterator(mInstr)),
11447 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11449 // Update thisMBB to fall through to newMBB
11450 thisMBB->addSuccessor(newMBB);
11452 // newMBB jumps to newMBB and fall through to nextMBB
11453 newMBB->addSuccessor(nextMBB);
11454 newMBB->addSuccessor(newMBB);
11456 DebugLoc dl = mInstr->getDebugLoc();
11457 // Insert instructions into newMBB based on incoming instruction
11458 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11459 "unexpected number of operands");
11460 MachineOperand& destOper = mInstr->getOperand(0);
11461 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11462 int numArgs = mInstr->getNumOperands() - 1;
11463 for (int i=0; i < numArgs; ++i)
11464 argOpers[i] = &mInstr->getOperand(i+1);
11466 // x86 address has 4 operands: base, index, scale, and displacement
11467 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11468 int valArgIndx = lastAddrIndx + 1;
11470 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11471 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11472 for (int i=0; i <= lastAddrIndx; ++i)
11473 (*MIB).addOperand(*argOpers[i]);
11475 // We only support register and immediate values
11476 assert((argOpers[valArgIndx]->isReg() ||
11477 argOpers[valArgIndx]->isImm()) &&
11478 "invalid operand");
11480 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11481 if (argOpers[valArgIndx]->isReg())
11482 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11484 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11485 (*MIB).addOperand(*argOpers[valArgIndx]);
11487 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11490 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11495 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11496 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11500 // Cmp and exchange if none has modified the memory location
11501 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11502 for (int i=0; i <= lastAddrIndx; ++i)
11503 (*MIB).addOperand(*argOpers[i]);
11505 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11506 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11507 mInstr->memoperands_end());
11509 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11510 MIB.addReg(X86::EAX);
11513 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11515 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11519 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11520 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11521 // in the .td file.
11522 MachineBasicBlock *
11523 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11524 unsigned numArgs, bool memArg) const {
11525 assert(Subtarget->hasSSE42orAVX() &&
11526 "Target must have SSE4.2 or AVX features enabled");
11528 DebugLoc dl = MI->getDebugLoc();
11529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11531 if (!Subtarget->hasAVX()) {
11533 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11535 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11538 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11540 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11543 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11544 for (unsigned i = 0; i < numArgs; ++i) {
11545 MachineOperand &Op = MI->getOperand(i+1);
11546 if (!(Op.isReg() && Op.isImplicit()))
11547 MIB.addOperand(Op);
11549 BuildMI(*BB, MI, dl,
11550 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11551 MI->getOperand(0).getReg())
11552 .addReg(X86::XMM0);
11554 MI->eraseFromParent();
11558 MachineBasicBlock *
11559 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11560 DebugLoc dl = MI->getDebugLoc();
11561 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11563 // Address into RAX/EAX, other two args into ECX, EDX.
11564 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11565 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11566 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11567 for (int i = 0; i < X86::AddrNumOperands; ++i)
11568 MIB.addOperand(MI->getOperand(i));
11570 unsigned ValOps = X86::AddrNumOperands;
11571 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11572 .addReg(MI->getOperand(ValOps).getReg());
11573 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11574 .addReg(MI->getOperand(ValOps+1).getReg());
11576 // The instruction doesn't actually take any operands though.
11577 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11579 MI->eraseFromParent(); // The pseudo is gone now.
11583 MachineBasicBlock *
11584 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11585 DebugLoc dl = MI->getDebugLoc();
11586 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11588 // First arg in ECX, the second in EAX.
11589 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11590 .addReg(MI->getOperand(0).getReg());
11591 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11592 .addReg(MI->getOperand(1).getReg());
11594 // The instruction doesn't actually take any operands though.
11595 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11597 MI->eraseFromParent(); // The pseudo is gone now.
11601 MachineBasicBlock *
11602 X86TargetLowering::EmitVAARG64WithCustomInserter(
11604 MachineBasicBlock *MBB) const {
11605 // Emit va_arg instruction on X86-64.
11607 // Operands to this pseudo-instruction:
11608 // 0 ) Output : destination address (reg)
11609 // 1-5) Input : va_list address (addr, i64mem)
11610 // 6 ) ArgSize : Size (in bytes) of vararg type
11611 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11612 // 8 ) Align : Alignment of type
11613 // 9 ) EFLAGS (implicit-def)
11615 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11616 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11618 unsigned DestReg = MI->getOperand(0).getReg();
11619 MachineOperand &Base = MI->getOperand(1);
11620 MachineOperand &Scale = MI->getOperand(2);
11621 MachineOperand &Index = MI->getOperand(3);
11622 MachineOperand &Disp = MI->getOperand(4);
11623 MachineOperand &Segment = MI->getOperand(5);
11624 unsigned ArgSize = MI->getOperand(6).getImm();
11625 unsigned ArgMode = MI->getOperand(7).getImm();
11626 unsigned Align = MI->getOperand(8).getImm();
11628 // Memory Reference
11629 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11630 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11631 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11633 // Machine Information
11634 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11635 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11636 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11637 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11638 DebugLoc DL = MI->getDebugLoc();
11640 // struct va_list {
11643 // i64 overflow_area (address)
11644 // i64 reg_save_area (address)
11646 // sizeof(va_list) = 24
11647 // alignment(va_list) = 8
11649 unsigned TotalNumIntRegs = 6;
11650 unsigned TotalNumXMMRegs = 8;
11651 bool UseGPOffset = (ArgMode == 1);
11652 bool UseFPOffset = (ArgMode == 2);
11653 unsigned MaxOffset = TotalNumIntRegs * 8 +
11654 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11656 /* Align ArgSize to a multiple of 8 */
11657 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11658 bool NeedsAlign = (Align > 8);
11660 MachineBasicBlock *thisMBB = MBB;
11661 MachineBasicBlock *overflowMBB;
11662 MachineBasicBlock *offsetMBB;
11663 MachineBasicBlock *endMBB;
11665 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11666 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11667 unsigned OffsetReg = 0;
11669 if (!UseGPOffset && !UseFPOffset) {
11670 // If we only pull from the overflow region, we don't create a branch.
11671 // We don't need to alter control flow.
11672 OffsetDestReg = 0; // unused
11673 OverflowDestReg = DestReg;
11676 overflowMBB = thisMBB;
11679 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11680 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11681 // If not, pull from overflow_area. (branch to overflowMBB)
11686 // offsetMBB overflowMBB
11691 // Registers for the PHI in endMBB
11692 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11693 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11695 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11696 MachineFunction *MF = MBB->getParent();
11697 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11698 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11699 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11701 MachineFunction::iterator MBBIter = MBB;
11704 // Insert the new basic blocks
11705 MF->insert(MBBIter, offsetMBB);
11706 MF->insert(MBBIter, overflowMBB);
11707 MF->insert(MBBIter, endMBB);
11709 // Transfer the remainder of MBB and its successor edges to endMBB.
11710 endMBB->splice(endMBB->begin(), thisMBB,
11711 llvm::next(MachineBasicBlock::iterator(MI)),
11713 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11715 // Make offsetMBB and overflowMBB successors of thisMBB
11716 thisMBB->addSuccessor(offsetMBB);
11717 thisMBB->addSuccessor(overflowMBB);
11719 // endMBB is a successor of both offsetMBB and overflowMBB
11720 offsetMBB->addSuccessor(endMBB);
11721 overflowMBB->addSuccessor(endMBB);
11723 // Load the offset value into a register
11724 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11725 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11729 .addDisp(Disp, UseFPOffset ? 4 : 0)
11730 .addOperand(Segment)
11731 .setMemRefs(MMOBegin, MMOEnd);
11733 // Check if there is enough room left to pull this argument.
11734 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11736 .addImm(MaxOffset + 8 - ArgSizeA8);
11738 // Branch to "overflowMBB" if offset >= max
11739 // Fall through to "offsetMBB" otherwise
11740 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11741 .addMBB(overflowMBB);
11744 // In offsetMBB, emit code to use the reg_save_area.
11746 assert(OffsetReg != 0);
11748 // Read the reg_save_area address.
11749 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11750 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11755 .addOperand(Segment)
11756 .setMemRefs(MMOBegin, MMOEnd);
11758 // Zero-extend the offset
11759 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11760 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11763 .addImm(X86::sub_32bit);
11765 // Add the offset to the reg_save_area to get the final address.
11766 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11767 .addReg(OffsetReg64)
11768 .addReg(RegSaveReg);
11770 // Compute the offset for the next argument
11771 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11772 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11774 .addImm(UseFPOffset ? 16 : 8);
11776 // Store it back into the va_list.
11777 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11781 .addDisp(Disp, UseFPOffset ? 4 : 0)
11782 .addOperand(Segment)
11783 .addReg(NextOffsetReg)
11784 .setMemRefs(MMOBegin, MMOEnd);
11787 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11792 // Emit code to use overflow area
11795 // Load the overflow_area address into a register.
11796 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11797 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11802 .addOperand(Segment)
11803 .setMemRefs(MMOBegin, MMOEnd);
11805 // If we need to align it, do so. Otherwise, just copy the address
11806 // to OverflowDestReg.
11808 // Align the overflow address
11809 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11810 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11812 // aligned_addr = (addr + (align-1)) & ~(align-1)
11813 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11814 .addReg(OverflowAddrReg)
11817 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11819 .addImm(~(uint64_t)(Align-1));
11821 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11822 .addReg(OverflowAddrReg);
11825 // Compute the next overflow address after this argument.
11826 // (the overflow address should be kept 8-byte aligned)
11827 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11828 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11829 .addReg(OverflowDestReg)
11830 .addImm(ArgSizeA8);
11832 // Store the new overflow address.
11833 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11838 .addOperand(Segment)
11839 .addReg(NextAddrReg)
11840 .setMemRefs(MMOBegin, MMOEnd);
11842 // If we branched, emit the PHI to the front of endMBB.
11844 BuildMI(*endMBB, endMBB->begin(), DL,
11845 TII->get(X86::PHI), DestReg)
11846 .addReg(OffsetDestReg).addMBB(offsetMBB)
11847 .addReg(OverflowDestReg).addMBB(overflowMBB);
11850 // Erase the pseudo instruction
11851 MI->eraseFromParent();
11856 MachineBasicBlock *
11857 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11859 MachineBasicBlock *MBB) const {
11860 // Emit code to save XMM registers to the stack. The ABI says that the
11861 // number of registers to save is given in %al, so it's theoretically
11862 // possible to do an indirect jump trick to avoid saving all of them,
11863 // however this code takes a simpler approach and just executes all
11864 // of the stores if %al is non-zero. It's less code, and it's probably
11865 // easier on the hardware branch predictor, and stores aren't all that
11866 // expensive anyway.
11868 // Create the new basic blocks. One block contains all the XMM stores,
11869 // and one block is the final destination regardless of whether any
11870 // stores were performed.
11871 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11872 MachineFunction *F = MBB->getParent();
11873 MachineFunction::iterator MBBIter = MBB;
11875 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11876 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11877 F->insert(MBBIter, XMMSaveMBB);
11878 F->insert(MBBIter, EndMBB);
11880 // Transfer the remainder of MBB and its successor edges to EndMBB.
11881 EndMBB->splice(EndMBB->begin(), MBB,
11882 llvm::next(MachineBasicBlock::iterator(MI)),
11884 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11886 // The original block will now fall through to the XMM save block.
11887 MBB->addSuccessor(XMMSaveMBB);
11888 // The XMMSaveMBB will fall through to the end block.
11889 XMMSaveMBB->addSuccessor(EndMBB);
11891 // Now add the instructions.
11892 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11893 DebugLoc DL = MI->getDebugLoc();
11895 unsigned CountReg = MI->getOperand(0).getReg();
11896 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11897 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11899 if (!Subtarget->isTargetWin64()) {
11900 // If %al is 0, branch around the XMM save block.
11901 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11902 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11903 MBB->addSuccessor(EndMBB);
11906 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11907 // In the XMM save block, save all the XMM argument registers.
11908 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11909 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11910 MachineMemOperand *MMO =
11911 F->getMachineMemOperand(
11912 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11913 MachineMemOperand::MOStore,
11914 /*Size=*/16, /*Align=*/16);
11915 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11916 .addFrameIndex(RegSaveFrameIndex)
11917 .addImm(/*Scale=*/1)
11918 .addReg(/*IndexReg=*/0)
11919 .addImm(/*Disp=*/Offset)
11920 .addReg(/*Segment=*/0)
11921 .addReg(MI->getOperand(i).getReg())
11922 .addMemOperand(MMO);
11925 MI->eraseFromParent(); // The pseudo instruction is gone now.
11930 MachineBasicBlock *
11931 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11932 MachineBasicBlock *BB) const {
11933 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11934 DebugLoc DL = MI->getDebugLoc();
11936 // To "insert" a SELECT_CC instruction, we actually have to insert the
11937 // diamond control-flow pattern. The incoming instruction knows the
11938 // destination vreg to set, the condition code register to branch on, the
11939 // true/false values to select between, and a branch opcode to use.
11940 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11941 MachineFunction::iterator It = BB;
11947 // cmpTY ccX, r1, r2
11949 // fallthrough --> copy0MBB
11950 MachineBasicBlock *thisMBB = BB;
11951 MachineFunction *F = BB->getParent();
11952 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11953 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11954 F->insert(It, copy0MBB);
11955 F->insert(It, sinkMBB);
11957 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11958 // live into the sink and copy blocks.
11959 if (!MI->killsRegister(X86::EFLAGS)) {
11960 copy0MBB->addLiveIn(X86::EFLAGS);
11961 sinkMBB->addLiveIn(X86::EFLAGS);
11964 // Transfer the remainder of BB and its successor edges to sinkMBB.
11965 sinkMBB->splice(sinkMBB->begin(), BB,
11966 llvm::next(MachineBasicBlock::iterator(MI)),
11968 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11970 // Add the true and fallthrough blocks as its successors.
11971 BB->addSuccessor(copy0MBB);
11972 BB->addSuccessor(sinkMBB);
11974 // Create the conditional branch instruction.
11976 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11977 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11980 // %FalseValue = ...
11981 // # fallthrough to sinkMBB
11982 copy0MBB->addSuccessor(sinkMBB);
11985 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11987 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11988 TII->get(X86::PHI), MI->getOperand(0).getReg())
11989 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11990 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11992 MI->eraseFromParent(); // The pseudo instruction is gone now.
11996 MachineBasicBlock *
11997 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11998 bool Is64Bit) const {
11999 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12000 DebugLoc DL = MI->getDebugLoc();
12001 MachineFunction *MF = BB->getParent();
12002 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12004 assert(getTargetMachine().Options.EnableSegmentedStacks);
12006 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12007 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12010 // ... [Till the alloca]
12011 // If stacklet is not large enough, jump to mallocMBB
12014 // Allocate by subtracting from RSP
12015 // Jump to continueMBB
12018 // Allocate by call to runtime
12022 // [rest of original BB]
12025 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12026 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12027 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12029 MachineRegisterInfo &MRI = MF->getRegInfo();
12030 const TargetRegisterClass *AddrRegClass =
12031 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12033 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12034 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12035 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12036 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12037 sizeVReg = MI->getOperand(1).getReg(),
12038 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12040 MachineFunction::iterator MBBIter = BB;
12043 MF->insert(MBBIter, bumpMBB);
12044 MF->insert(MBBIter, mallocMBB);
12045 MF->insert(MBBIter, continueMBB);
12047 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12048 (MachineBasicBlock::iterator(MI)), BB->end());
12049 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12051 // Add code to the main basic block to check if the stack limit has been hit,
12052 // and if so, jump to mallocMBB otherwise to bumpMBB.
12053 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12054 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12055 .addReg(tmpSPVReg).addReg(sizeVReg);
12056 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12057 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12058 .addReg(SPLimitVReg);
12059 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12061 // bumpMBB simply decreases the stack pointer, since we know the current
12062 // stacklet has enough space.
12063 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12064 .addReg(SPLimitVReg);
12065 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12066 .addReg(SPLimitVReg);
12067 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12069 // Calls into a routine in libgcc to allocate more space from the heap.
12071 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12073 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12074 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12076 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12078 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12079 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12080 .addExternalSymbol("__morestack_allocate_stack_space");
12084 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12087 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12088 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12089 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12091 // Set up the CFG correctly.
12092 BB->addSuccessor(bumpMBB);
12093 BB->addSuccessor(mallocMBB);
12094 mallocMBB->addSuccessor(continueMBB);
12095 bumpMBB->addSuccessor(continueMBB);
12097 // Take care of the PHI nodes.
12098 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12099 MI->getOperand(0).getReg())
12100 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12101 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12103 // Delete the original pseudo instruction.
12104 MI->eraseFromParent();
12107 return continueMBB;
12110 MachineBasicBlock *
12111 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12112 MachineBasicBlock *BB) const {
12113 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12114 DebugLoc DL = MI->getDebugLoc();
12116 assert(!Subtarget->isTargetEnvMacho());
12118 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12119 // non-trivial part is impdef of ESP.
12121 if (Subtarget->isTargetWin64()) {
12122 if (Subtarget->isTargetCygMing()) {
12123 // ___chkstk(Mingw64):
12124 // Clobbers R10, R11, RAX and EFLAGS.
12126 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12127 .addExternalSymbol("___chkstk")
12128 .addReg(X86::RAX, RegState::Implicit)
12129 .addReg(X86::RSP, RegState::Implicit)
12130 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12131 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12132 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12134 // __chkstk(MSVCRT): does not update stack pointer.
12135 // Clobbers R10, R11 and EFLAGS.
12136 // FIXME: RAX(allocated size) might be reused and not killed.
12137 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12138 .addExternalSymbol("__chkstk")
12139 .addReg(X86::RAX, RegState::Implicit)
12140 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12141 // RAX has the offset to subtracted from RSP.
12142 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12147 const char *StackProbeSymbol =
12148 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12150 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12151 .addExternalSymbol(StackProbeSymbol)
12152 .addReg(X86::EAX, RegState::Implicit)
12153 .addReg(X86::ESP, RegState::Implicit)
12154 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12155 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12156 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12159 MI->eraseFromParent(); // The pseudo instruction is gone now.
12163 MachineBasicBlock *
12164 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12165 MachineBasicBlock *BB) const {
12166 // This is pretty easy. We're taking the value that we received from
12167 // our load from the relocation, sticking it in either RDI (x86-64)
12168 // or EAX and doing an indirect call. The return value will then
12169 // be in the normal return register.
12170 const X86InstrInfo *TII
12171 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12172 DebugLoc DL = MI->getDebugLoc();
12173 MachineFunction *F = BB->getParent();
12175 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12176 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12178 if (Subtarget->is64Bit()) {
12179 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12180 TII->get(X86::MOV64rm), X86::RDI)
12182 .addImm(0).addReg(0)
12183 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12184 MI->getOperand(3).getTargetFlags())
12186 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12187 addDirectMem(MIB, X86::RDI);
12188 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12189 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12190 TII->get(X86::MOV32rm), X86::EAX)
12192 .addImm(0).addReg(0)
12193 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12194 MI->getOperand(3).getTargetFlags())
12196 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12197 addDirectMem(MIB, X86::EAX);
12199 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12200 TII->get(X86::MOV32rm), X86::EAX)
12201 .addReg(TII->getGlobalBaseReg(F))
12202 .addImm(0).addReg(0)
12203 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12204 MI->getOperand(3).getTargetFlags())
12206 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12207 addDirectMem(MIB, X86::EAX);
12210 MI->eraseFromParent(); // The pseudo instruction is gone now.
12214 MachineBasicBlock *
12215 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12216 MachineBasicBlock *BB) const {
12217 switch (MI->getOpcode()) {
12218 default: assert(0 && "Unexpected instr type to insert");
12219 case X86::TAILJMPd64:
12220 case X86::TAILJMPr64:
12221 case X86::TAILJMPm64:
12222 assert(0 && "TAILJMP64 would not be touched here.");
12223 case X86::TCRETURNdi64:
12224 case X86::TCRETURNri64:
12225 case X86::TCRETURNmi64:
12226 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12227 // On AMD64, additional defs should be added before register allocation.
12228 if (!Subtarget->isTargetWin64()) {
12229 MI->addRegisterDefined(X86::RSI);
12230 MI->addRegisterDefined(X86::RDI);
12231 MI->addRegisterDefined(X86::XMM6);
12232 MI->addRegisterDefined(X86::XMM7);
12233 MI->addRegisterDefined(X86::XMM8);
12234 MI->addRegisterDefined(X86::XMM9);
12235 MI->addRegisterDefined(X86::XMM10);
12236 MI->addRegisterDefined(X86::XMM11);
12237 MI->addRegisterDefined(X86::XMM12);
12238 MI->addRegisterDefined(X86::XMM13);
12239 MI->addRegisterDefined(X86::XMM14);
12240 MI->addRegisterDefined(X86::XMM15);
12243 case X86::WIN_ALLOCA:
12244 return EmitLoweredWinAlloca(MI, BB);
12245 case X86::SEG_ALLOCA_32:
12246 return EmitLoweredSegAlloca(MI, BB, false);
12247 case X86::SEG_ALLOCA_64:
12248 return EmitLoweredSegAlloca(MI, BB, true);
12249 case X86::TLSCall_32:
12250 case X86::TLSCall_64:
12251 return EmitLoweredTLSCall(MI, BB);
12252 case X86::CMOV_GR8:
12253 case X86::CMOV_FR32:
12254 case X86::CMOV_FR64:
12255 case X86::CMOV_V4F32:
12256 case X86::CMOV_V2F64:
12257 case X86::CMOV_V2I64:
12258 case X86::CMOV_V8F32:
12259 case X86::CMOV_V4F64:
12260 case X86::CMOV_V4I64:
12261 case X86::CMOV_GR16:
12262 case X86::CMOV_GR32:
12263 case X86::CMOV_RFP32:
12264 case X86::CMOV_RFP64:
12265 case X86::CMOV_RFP80:
12266 return EmitLoweredSelect(MI, BB);
12268 case X86::FP32_TO_INT16_IN_MEM:
12269 case X86::FP32_TO_INT32_IN_MEM:
12270 case X86::FP32_TO_INT64_IN_MEM:
12271 case X86::FP64_TO_INT16_IN_MEM:
12272 case X86::FP64_TO_INT32_IN_MEM:
12273 case X86::FP64_TO_INT64_IN_MEM:
12274 case X86::FP80_TO_INT16_IN_MEM:
12275 case X86::FP80_TO_INT32_IN_MEM:
12276 case X86::FP80_TO_INT64_IN_MEM: {
12277 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12278 DebugLoc DL = MI->getDebugLoc();
12280 // Change the floating point control register to use "round towards zero"
12281 // mode when truncating to an integer value.
12282 MachineFunction *F = BB->getParent();
12283 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12284 addFrameReference(BuildMI(*BB, MI, DL,
12285 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12287 // Load the old value of the high byte of the control word...
12289 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12290 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12293 // Set the high part to be round to zero...
12294 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12297 // Reload the modified control word now...
12298 addFrameReference(BuildMI(*BB, MI, DL,
12299 TII->get(X86::FLDCW16m)), CWFrameIdx);
12301 // Restore the memory image of control word to original value
12302 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12305 // Get the X86 opcode to use.
12307 switch (MI->getOpcode()) {
12308 default: llvm_unreachable("illegal opcode!");
12309 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12310 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12311 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12312 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12313 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12314 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12315 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12316 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12317 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12321 MachineOperand &Op = MI->getOperand(0);
12323 AM.BaseType = X86AddressMode::RegBase;
12324 AM.Base.Reg = Op.getReg();
12326 AM.BaseType = X86AddressMode::FrameIndexBase;
12327 AM.Base.FrameIndex = Op.getIndex();
12329 Op = MI->getOperand(1);
12331 AM.Scale = Op.getImm();
12332 Op = MI->getOperand(2);
12334 AM.IndexReg = Op.getImm();
12335 Op = MI->getOperand(3);
12336 if (Op.isGlobal()) {
12337 AM.GV = Op.getGlobal();
12339 AM.Disp = Op.getImm();
12341 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12342 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12344 // Reload the original control word now.
12345 addFrameReference(BuildMI(*BB, MI, DL,
12346 TII->get(X86::FLDCW16m)), CWFrameIdx);
12348 MI->eraseFromParent(); // The pseudo instruction is gone now.
12351 // String/text processing lowering.
12352 case X86::PCMPISTRM128REG:
12353 case X86::VPCMPISTRM128REG:
12354 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12355 case X86::PCMPISTRM128MEM:
12356 case X86::VPCMPISTRM128MEM:
12357 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12358 case X86::PCMPESTRM128REG:
12359 case X86::VPCMPESTRM128REG:
12360 return EmitPCMP(MI, BB, 5, false /* in mem */);
12361 case X86::PCMPESTRM128MEM:
12362 case X86::VPCMPESTRM128MEM:
12363 return EmitPCMP(MI, BB, 5, true /* in mem */);
12365 // Thread synchronization.
12367 return EmitMonitor(MI, BB);
12369 return EmitMwait(MI, BB);
12371 // Atomic Lowering.
12372 case X86::ATOMAND32:
12373 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12374 X86::AND32ri, X86::MOV32rm,
12376 X86::NOT32r, X86::EAX,
12377 X86::GR32RegisterClass);
12378 case X86::ATOMOR32:
12379 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12380 X86::OR32ri, X86::MOV32rm,
12382 X86::NOT32r, X86::EAX,
12383 X86::GR32RegisterClass);
12384 case X86::ATOMXOR32:
12385 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12386 X86::XOR32ri, X86::MOV32rm,
12388 X86::NOT32r, X86::EAX,
12389 X86::GR32RegisterClass);
12390 case X86::ATOMNAND32:
12391 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12392 X86::AND32ri, X86::MOV32rm,
12394 X86::NOT32r, X86::EAX,
12395 X86::GR32RegisterClass, true);
12396 case X86::ATOMMIN32:
12397 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12398 case X86::ATOMMAX32:
12399 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12400 case X86::ATOMUMIN32:
12401 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12402 case X86::ATOMUMAX32:
12403 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12405 case X86::ATOMAND16:
12406 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12407 X86::AND16ri, X86::MOV16rm,
12409 X86::NOT16r, X86::AX,
12410 X86::GR16RegisterClass);
12411 case X86::ATOMOR16:
12412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12413 X86::OR16ri, X86::MOV16rm,
12415 X86::NOT16r, X86::AX,
12416 X86::GR16RegisterClass);
12417 case X86::ATOMXOR16:
12418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12419 X86::XOR16ri, X86::MOV16rm,
12421 X86::NOT16r, X86::AX,
12422 X86::GR16RegisterClass);
12423 case X86::ATOMNAND16:
12424 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12425 X86::AND16ri, X86::MOV16rm,
12427 X86::NOT16r, X86::AX,
12428 X86::GR16RegisterClass, true);
12429 case X86::ATOMMIN16:
12430 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12431 case X86::ATOMMAX16:
12432 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12433 case X86::ATOMUMIN16:
12434 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12435 case X86::ATOMUMAX16:
12436 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12438 case X86::ATOMAND8:
12439 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12440 X86::AND8ri, X86::MOV8rm,
12442 X86::NOT8r, X86::AL,
12443 X86::GR8RegisterClass);
12445 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12446 X86::OR8ri, X86::MOV8rm,
12448 X86::NOT8r, X86::AL,
12449 X86::GR8RegisterClass);
12450 case X86::ATOMXOR8:
12451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12452 X86::XOR8ri, X86::MOV8rm,
12454 X86::NOT8r, X86::AL,
12455 X86::GR8RegisterClass);
12456 case X86::ATOMNAND8:
12457 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12458 X86::AND8ri, X86::MOV8rm,
12460 X86::NOT8r, X86::AL,
12461 X86::GR8RegisterClass, true);
12462 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12463 // This group is for 64-bit host.
12464 case X86::ATOMAND64:
12465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12466 X86::AND64ri32, X86::MOV64rm,
12468 X86::NOT64r, X86::RAX,
12469 X86::GR64RegisterClass);
12470 case X86::ATOMOR64:
12471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12472 X86::OR64ri32, X86::MOV64rm,
12474 X86::NOT64r, X86::RAX,
12475 X86::GR64RegisterClass);
12476 case X86::ATOMXOR64:
12477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12478 X86::XOR64ri32, X86::MOV64rm,
12480 X86::NOT64r, X86::RAX,
12481 X86::GR64RegisterClass);
12482 case X86::ATOMNAND64:
12483 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12484 X86::AND64ri32, X86::MOV64rm,
12486 X86::NOT64r, X86::RAX,
12487 X86::GR64RegisterClass, true);
12488 case X86::ATOMMIN64:
12489 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12490 case X86::ATOMMAX64:
12491 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12492 case X86::ATOMUMIN64:
12493 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12494 case X86::ATOMUMAX64:
12495 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12497 // This group does 64-bit operations on a 32-bit host.
12498 case X86::ATOMAND6432:
12499 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12500 X86::AND32rr, X86::AND32rr,
12501 X86::AND32ri, X86::AND32ri,
12503 case X86::ATOMOR6432:
12504 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12505 X86::OR32rr, X86::OR32rr,
12506 X86::OR32ri, X86::OR32ri,
12508 case X86::ATOMXOR6432:
12509 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12510 X86::XOR32rr, X86::XOR32rr,
12511 X86::XOR32ri, X86::XOR32ri,
12513 case X86::ATOMNAND6432:
12514 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12515 X86::AND32rr, X86::AND32rr,
12516 X86::AND32ri, X86::AND32ri,
12518 case X86::ATOMADD6432:
12519 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12520 X86::ADD32rr, X86::ADC32rr,
12521 X86::ADD32ri, X86::ADC32ri,
12523 case X86::ATOMSUB6432:
12524 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12525 X86::SUB32rr, X86::SBB32rr,
12526 X86::SUB32ri, X86::SBB32ri,
12528 case X86::ATOMSWAP6432:
12529 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12530 X86::MOV32rr, X86::MOV32rr,
12531 X86::MOV32ri, X86::MOV32ri,
12533 case X86::VASTART_SAVE_XMM_REGS:
12534 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12536 case X86::VAARG_64:
12537 return EmitVAARG64WithCustomInserter(MI, BB);
12541 //===----------------------------------------------------------------------===//
12542 // X86 Optimization Hooks
12543 //===----------------------------------------------------------------------===//
12545 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12549 const SelectionDAG &DAG,
12550 unsigned Depth) const {
12551 unsigned Opc = Op.getOpcode();
12552 assert((Opc >= ISD::BUILTIN_OP_END ||
12553 Opc == ISD::INTRINSIC_WO_CHAIN ||
12554 Opc == ISD::INTRINSIC_W_CHAIN ||
12555 Opc == ISD::INTRINSIC_VOID) &&
12556 "Should use MaskedValueIsZero if you don't know whether Op"
12557 " is a target node!");
12559 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12573 // These nodes' second result is a boolean.
12574 if (Op.getResNo() == 0)
12577 case X86ISD::SETCC:
12578 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12579 Mask.getBitWidth() - 1);
12581 case ISD::INTRINSIC_WO_CHAIN: {
12582 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12583 unsigned NumLoBits = 0;
12586 case Intrinsic::x86_sse_movmsk_ps:
12587 case Intrinsic::x86_avx_movmsk_ps_256:
12588 case Intrinsic::x86_sse2_movmsk_pd:
12589 case Intrinsic::x86_avx_movmsk_pd_256:
12590 case Intrinsic::x86_mmx_pmovmskb:
12591 case Intrinsic::x86_sse2_pmovmskb_128: {
12592 // High bits of movmskp{s|d}, pmovmskb are known zero.
12594 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12595 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12596 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12597 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12598 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12599 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12601 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12602 Mask.getBitWidth() - NumLoBits);
12611 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12612 unsigned Depth) const {
12613 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12614 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12615 return Op.getValueType().getScalarType().getSizeInBits();
12621 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12622 /// node is a GlobalAddress + offset.
12623 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12624 const GlobalValue* &GA,
12625 int64_t &Offset) const {
12626 if (N->getOpcode() == X86ISD::Wrapper) {
12627 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12628 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12629 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12633 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12636 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12637 /// same as extracting the high 128-bit part of 256-bit vector and then
12638 /// inserting the result into the low part of a new 256-bit vector
12639 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12640 EVT VT = SVOp->getValueType(0);
12641 int NumElems = VT.getVectorNumElements();
12643 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12644 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12645 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12646 SVOp->getMaskElt(j) >= 0)
12652 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12653 /// same as extracting the low 128-bit part of 256-bit vector and then
12654 /// inserting the result into the high part of a new 256-bit vector
12655 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12656 EVT VT = SVOp->getValueType(0);
12657 int NumElems = VT.getVectorNumElements();
12659 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12660 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12661 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12662 SVOp->getMaskElt(j) >= 0)
12668 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12669 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12670 TargetLowering::DAGCombinerInfo &DCI) {
12671 DebugLoc dl = N->getDebugLoc();
12672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12673 SDValue V1 = SVOp->getOperand(0);
12674 SDValue V2 = SVOp->getOperand(1);
12675 EVT VT = SVOp->getValueType(0);
12676 int NumElems = VT.getVectorNumElements();
12678 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12679 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12683 // V UNDEF BUILD_VECTOR UNDEF
12685 // CONCAT_VECTOR CONCAT_VECTOR
12688 // RESULT: V + zero extended
12690 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12691 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12692 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12695 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12698 // To match the shuffle mask, the first half of the mask should
12699 // be exactly the first vector, and all the rest a splat with the
12700 // first element of the second one.
12701 for (int i = 0; i < NumElems/2; ++i)
12702 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12703 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12706 // Emit a zeroed vector and insert the desired subvector on its
12708 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12709 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12710 DAG.getConstant(0, MVT::i32), DAG, dl);
12711 return DCI.CombineTo(N, InsV);
12714 //===--------------------------------------------------------------------===//
12715 // Combine some shuffles into subvector extracts and inserts:
12718 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12719 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12720 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12722 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12723 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12724 return DCI.CombineTo(N, InsV);
12727 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12728 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12729 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12730 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12731 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12732 return DCI.CombineTo(N, InsV);
12738 /// PerformShuffleCombine - Performs several different shuffle combines.
12739 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12740 TargetLowering::DAGCombinerInfo &DCI,
12741 const X86Subtarget *Subtarget) {
12742 DebugLoc dl = N->getDebugLoc();
12743 EVT VT = N->getValueType(0);
12745 // Don't create instructions with illegal types after legalize types has run.
12746 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12747 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12750 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12751 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12752 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12753 return PerformShuffleCombine256(N, DAG, DCI);
12755 // Only handle 128 wide vector from here on.
12756 if (VT.getSizeInBits() != 128)
12759 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12760 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12761 // consecutive, non-overlapping, and in the right order.
12762 SmallVector<SDValue, 16> Elts;
12763 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12764 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12766 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12769 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12770 /// generation and convert it from being a bunch of shuffles and extracts
12771 /// to a simple store and scalar loads to extract the elements.
12772 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12773 const TargetLowering &TLI) {
12774 SDValue InputVector = N->getOperand(0);
12776 // Only operate on vectors of 4 elements, where the alternative shuffling
12777 // gets to be more expensive.
12778 if (InputVector.getValueType() != MVT::v4i32)
12781 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12782 // single use which is a sign-extend or zero-extend, and all elements are
12784 SmallVector<SDNode *, 4> Uses;
12785 unsigned ExtractedElements = 0;
12786 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12787 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12788 if (UI.getUse().getResNo() != InputVector.getResNo())
12791 SDNode *Extract = *UI;
12792 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12795 if (Extract->getValueType(0) != MVT::i32)
12797 if (!Extract->hasOneUse())
12799 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12800 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12802 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12805 // Record which element was extracted.
12806 ExtractedElements |=
12807 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12809 Uses.push_back(Extract);
12812 // If not all the elements were used, this may not be worthwhile.
12813 if (ExtractedElements != 15)
12816 // Ok, we've now decided to do the transformation.
12817 DebugLoc dl = InputVector.getDebugLoc();
12819 // Store the value to a temporary stack slot.
12820 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12821 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12822 MachinePointerInfo(), false, false, 0);
12824 // Replace each use (extract) with a load of the appropriate element.
12825 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12826 UE = Uses.end(); UI != UE; ++UI) {
12827 SDNode *Extract = *UI;
12829 // cOMpute the element's address.
12830 SDValue Idx = Extract->getOperand(1);
12832 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12833 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12834 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12836 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12837 StackPtr, OffsetVal);
12839 // Load the scalar.
12840 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12841 ScalarAddr, MachinePointerInfo(),
12842 false, false, false, 0);
12844 // Replace the exact with the load.
12845 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12848 // The replacement was made in place; don't return anything.
12852 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12854 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12855 const X86Subtarget *Subtarget) {
12856 DebugLoc DL = N->getDebugLoc();
12857 SDValue Cond = N->getOperand(0);
12858 // Get the LHS/RHS of the select.
12859 SDValue LHS = N->getOperand(1);
12860 SDValue RHS = N->getOperand(2);
12861 EVT VT = LHS.getValueType();
12863 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12864 // instructions match the semantics of the common C idiom x<y?x:y but not
12865 // x<=y?x:y, because of how they handle negative zero (which can be
12866 // ignored in unsafe-math mode).
12867 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12868 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12869 (Subtarget->hasXMMInt() ||
12870 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12871 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12873 unsigned Opcode = 0;
12874 // Check for x CC y ? x : y.
12875 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12876 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12880 // Converting this to a min would handle NaNs incorrectly, and swapping
12881 // the operands would cause it to handle comparisons between positive
12882 // and negative zero incorrectly.
12883 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12884 if (!DAG.getTarget().Options.UnsafeFPMath &&
12885 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12887 std::swap(LHS, RHS);
12889 Opcode = X86ISD::FMIN;
12892 // Converting this to a min would handle comparisons between positive
12893 // and negative zero incorrectly.
12894 if (!DAG.getTarget().Options.UnsafeFPMath &&
12895 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12897 Opcode = X86ISD::FMIN;
12900 // Converting this to a min would handle both negative zeros and NaNs
12901 // incorrectly, but we can swap the operands to fix both.
12902 std::swap(LHS, RHS);
12906 Opcode = X86ISD::FMIN;
12910 // Converting this to a max would handle comparisons between positive
12911 // and negative zero incorrectly.
12912 if (!DAG.getTarget().Options.UnsafeFPMath &&
12913 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12915 Opcode = X86ISD::FMAX;
12918 // Converting this to a max would handle NaNs incorrectly, and swapping
12919 // the operands would cause it to handle comparisons between positive
12920 // and negative zero incorrectly.
12921 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12922 if (!DAG.getTarget().Options.UnsafeFPMath &&
12923 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12925 std::swap(LHS, RHS);
12927 Opcode = X86ISD::FMAX;
12930 // Converting this to a max would handle both negative zeros and NaNs
12931 // incorrectly, but we can swap the operands to fix both.
12932 std::swap(LHS, RHS);
12936 Opcode = X86ISD::FMAX;
12939 // Check for x CC y ? y : x -- a min/max with reversed arms.
12940 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12941 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12945 // Converting this to a min would handle comparisons between positive
12946 // and negative zero incorrectly, and swapping the operands would
12947 // cause it to handle NaNs incorrectly.
12948 if (!DAG.getTarget().Options.UnsafeFPMath &&
12949 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12950 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12952 std::swap(LHS, RHS);
12954 Opcode = X86ISD::FMIN;
12957 // Converting this to a min would handle NaNs incorrectly.
12958 if (!DAG.getTarget().Options.UnsafeFPMath &&
12959 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12961 Opcode = X86ISD::FMIN;
12964 // Converting this to a min would handle both negative zeros and NaNs
12965 // incorrectly, but we can swap the operands to fix both.
12966 std::swap(LHS, RHS);
12970 Opcode = X86ISD::FMIN;
12974 // Converting this to a max would handle NaNs incorrectly.
12975 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12977 Opcode = X86ISD::FMAX;
12980 // Converting this to a max would handle comparisons between positive
12981 // and negative zero incorrectly, and swapping the operands would
12982 // cause it to handle NaNs incorrectly.
12983 if (!DAG.getTarget().Options.UnsafeFPMath &&
12984 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12985 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12987 std::swap(LHS, RHS);
12989 Opcode = X86ISD::FMAX;
12992 // Converting this to a max would handle both negative zeros and NaNs
12993 // incorrectly, but we can swap the operands to fix both.
12994 std::swap(LHS, RHS);
12998 Opcode = X86ISD::FMAX;
13004 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13007 // If this is a select between two integer constants, try to do some
13009 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13010 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13011 // Don't do this for crazy integer types.
13012 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13013 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13014 // so that TrueC (the true value) is larger than FalseC.
13015 bool NeedsCondInvert = false;
13017 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13018 // Efficiently invertible.
13019 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13020 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13021 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13022 NeedsCondInvert = true;
13023 std::swap(TrueC, FalseC);
13026 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13027 if (FalseC->getAPIntValue() == 0 &&
13028 TrueC->getAPIntValue().isPowerOf2()) {
13029 if (NeedsCondInvert) // Invert the condition if needed.
13030 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13031 DAG.getConstant(1, Cond.getValueType()));
13033 // Zero extend the condition if needed.
13034 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13036 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13037 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13038 DAG.getConstant(ShAmt, MVT::i8));
13041 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13042 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13043 if (NeedsCondInvert) // Invert the condition if needed.
13044 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13045 DAG.getConstant(1, Cond.getValueType()));
13047 // Zero extend the condition if needed.
13048 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13049 FalseC->getValueType(0), Cond);
13050 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13051 SDValue(FalseC, 0));
13054 // Optimize cases that will turn into an LEA instruction. This requires
13055 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13056 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13057 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13058 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13060 bool isFastMultiplier = false;
13062 switch ((unsigned char)Diff) {
13064 case 1: // result = add base, cond
13065 case 2: // result = lea base( , cond*2)
13066 case 3: // result = lea base(cond, cond*2)
13067 case 4: // result = lea base( , cond*4)
13068 case 5: // result = lea base(cond, cond*4)
13069 case 8: // result = lea base( , cond*8)
13070 case 9: // result = lea base(cond, cond*8)
13071 isFastMultiplier = true;
13076 if (isFastMultiplier) {
13077 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13078 if (NeedsCondInvert) // Invert the condition if needed.
13079 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13080 DAG.getConstant(1, Cond.getValueType()));
13082 // Zero extend the condition if needed.
13083 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13085 // Scale the condition by the difference.
13087 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13088 DAG.getConstant(Diff, Cond.getValueType()));
13090 // Add the base if non-zero.
13091 if (FalseC->getAPIntValue() != 0)
13092 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13093 SDValue(FalseC, 0));
13103 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13104 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13105 TargetLowering::DAGCombinerInfo &DCI) {
13106 DebugLoc DL = N->getDebugLoc();
13108 // If the flag operand isn't dead, don't touch this CMOV.
13109 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13112 SDValue FalseOp = N->getOperand(0);
13113 SDValue TrueOp = N->getOperand(1);
13114 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13115 SDValue Cond = N->getOperand(3);
13116 if (CC == X86::COND_E || CC == X86::COND_NE) {
13117 switch (Cond.getOpcode()) {
13121 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13122 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13123 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13127 // If this is a select between two integer constants, try to do some
13128 // optimizations. Note that the operands are ordered the opposite of SELECT
13130 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13131 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13132 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13133 // larger than FalseC (the false value).
13134 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13135 CC = X86::GetOppositeBranchCondition(CC);
13136 std::swap(TrueC, FalseC);
13139 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13140 // This is efficient for any integer data type (including i8/i16) and
13142 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13143 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13144 DAG.getConstant(CC, MVT::i8), Cond);
13146 // Zero extend the condition if needed.
13147 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13149 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13150 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13151 DAG.getConstant(ShAmt, MVT::i8));
13152 if (N->getNumValues() == 2) // Dead flag value?
13153 return DCI.CombineTo(N, Cond, SDValue());
13157 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13158 // for any integer data type, including i8/i16.
13159 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13160 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13161 DAG.getConstant(CC, MVT::i8), Cond);
13163 // Zero extend the condition if needed.
13164 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13165 FalseC->getValueType(0), Cond);
13166 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13167 SDValue(FalseC, 0));
13169 if (N->getNumValues() == 2) // Dead flag value?
13170 return DCI.CombineTo(N, Cond, SDValue());
13174 // Optimize cases that will turn into an LEA instruction. This requires
13175 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13176 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13177 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13178 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13180 bool isFastMultiplier = false;
13182 switch ((unsigned char)Diff) {
13184 case 1: // result = add base, cond
13185 case 2: // result = lea base( , cond*2)
13186 case 3: // result = lea base(cond, cond*2)
13187 case 4: // result = lea base( , cond*4)
13188 case 5: // result = lea base(cond, cond*4)
13189 case 8: // result = lea base( , cond*8)
13190 case 9: // result = lea base(cond, cond*8)
13191 isFastMultiplier = true;
13196 if (isFastMultiplier) {
13197 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13198 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13199 DAG.getConstant(CC, MVT::i8), Cond);
13200 // Zero extend the condition if needed.
13201 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13203 // Scale the condition by the difference.
13205 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13206 DAG.getConstant(Diff, Cond.getValueType()));
13208 // Add the base if non-zero.
13209 if (FalseC->getAPIntValue() != 0)
13210 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13211 SDValue(FalseC, 0));
13212 if (N->getNumValues() == 2) // Dead flag value?
13213 return DCI.CombineTo(N, Cond, SDValue());
13223 /// PerformMulCombine - Optimize a single multiply with constant into two
13224 /// in order to implement it with two cheaper instructions, e.g.
13225 /// LEA + SHL, LEA + LEA.
13226 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13227 TargetLowering::DAGCombinerInfo &DCI) {
13228 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13231 EVT VT = N->getValueType(0);
13232 if (VT != MVT::i64)
13235 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13238 uint64_t MulAmt = C->getZExtValue();
13239 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13242 uint64_t MulAmt1 = 0;
13243 uint64_t MulAmt2 = 0;
13244 if ((MulAmt % 9) == 0) {
13246 MulAmt2 = MulAmt / 9;
13247 } else if ((MulAmt % 5) == 0) {
13249 MulAmt2 = MulAmt / 5;
13250 } else if ((MulAmt % 3) == 0) {
13252 MulAmt2 = MulAmt / 3;
13255 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13256 DebugLoc DL = N->getDebugLoc();
13258 if (isPowerOf2_64(MulAmt2) &&
13259 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13260 // If second multiplifer is pow2, issue it first. We want the multiply by
13261 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13263 std::swap(MulAmt1, MulAmt2);
13266 if (isPowerOf2_64(MulAmt1))
13267 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13268 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13270 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13271 DAG.getConstant(MulAmt1, VT));
13273 if (isPowerOf2_64(MulAmt2))
13274 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13275 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13277 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13278 DAG.getConstant(MulAmt2, VT));
13280 // Do not add new nodes to DAG combiner worklist.
13281 DCI.CombineTo(N, NewMul, false);
13286 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13287 SDValue N0 = N->getOperand(0);
13288 SDValue N1 = N->getOperand(1);
13289 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13290 EVT VT = N0.getValueType();
13292 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13293 // since the result of setcc_c is all zero's or all ones.
13294 if (VT.isInteger() && !VT.isVector() &&
13295 N1C && N0.getOpcode() == ISD::AND &&
13296 N0.getOperand(1).getOpcode() == ISD::Constant) {
13297 SDValue N00 = N0.getOperand(0);
13298 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13299 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13300 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13301 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13302 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13303 APInt ShAmt = N1C->getAPIntValue();
13304 Mask = Mask.shl(ShAmt);
13306 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13307 N00, DAG.getConstant(Mask, VT));
13312 // Hardware support for vector shifts is sparse which makes us scalarize the
13313 // vector operations in many cases. Also, on sandybridge ADD is faster than
13315 // (shl V, 1) -> add V,V
13316 if (isSplatVector(N1.getNode())) {
13317 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13318 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13319 // We shift all of the values by one. In many cases we do not have
13320 // hardware support for this operation. This is better expressed as an ADD
13322 if (N1C && (1 == N1C->getZExtValue())) {
13323 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13330 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13332 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13333 const X86Subtarget *Subtarget) {
13334 EVT VT = N->getValueType(0);
13335 if (N->getOpcode() == ISD::SHL) {
13336 SDValue V = PerformSHLCombine(N, DAG);
13337 if (V.getNode()) return V;
13340 // On X86 with SSE2 support, we can transform this to a vector shift if
13341 // all elements are shifted by the same amount. We can't do this in legalize
13342 // because the a constant vector is typically transformed to a constant pool
13343 // so we have no knowledge of the shift amount.
13344 if (!Subtarget->hasXMMInt())
13347 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13348 (!Subtarget->hasAVX2() ||
13349 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13352 SDValue ShAmtOp = N->getOperand(1);
13353 EVT EltVT = VT.getVectorElementType();
13354 DebugLoc DL = N->getDebugLoc();
13355 SDValue BaseShAmt = SDValue();
13356 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13357 unsigned NumElts = VT.getVectorNumElements();
13359 for (; i != NumElts; ++i) {
13360 SDValue Arg = ShAmtOp.getOperand(i);
13361 if (Arg.getOpcode() == ISD::UNDEF) continue;
13365 for (; i != NumElts; ++i) {
13366 SDValue Arg = ShAmtOp.getOperand(i);
13367 if (Arg.getOpcode() == ISD::UNDEF) continue;
13368 if (Arg != BaseShAmt) {
13372 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13373 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13374 SDValue InVec = ShAmtOp.getOperand(0);
13375 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13376 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13378 for (; i != NumElts; ++i) {
13379 SDValue Arg = InVec.getOperand(i);
13380 if (Arg.getOpcode() == ISD::UNDEF) continue;
13384 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13386 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13387 if (C->getZExtValue() == SplatIdx)
13388 BaseShAmt = InVec.getOperand(1);
13391 if (BaseShAmt.getNode() == 0)
13392 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13393 DAG.getIntPtrConstant(0));
13397 // The shift amount is an i32.
13398 if (EltVT.bitsGT(MVT::i32))
13399 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13400 else if (EltVT.bitsLT(MVT::i32))
13401 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13403 // The shift amount is identical so we can do a vector shift.
13404 SDValue ValOp = N->getOperand(0);
13405 switch (N->getOpcode()) {
13407 llvm_unreachable("Unknown shift opcode!");
13410 if (VT == MVT::v2i64)
13411 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13412 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13414 if (VT == MVT::v4i32)
13415 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13416 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13418 if (VT == MVT::v8i16)
13419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13420 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13422 if (VT == MVT::v4i64)
13423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13424 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13426 if (VT == MVT::v8i32)
13427 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13428 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13430 if (VT == MVT::v16i16)
13431 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13432 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13436 if (VT == MVT::v4i32)
13437 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13438 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13440 if (VT == MVT::v8i16)
13441 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13442 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13444 if (VT == MVT::v8i32)
13445 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13446 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13448 if (VT == MVT::v16i16)
13449 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13450 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13454 if (VT == MVT::v2i64)
13455 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13456 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13458 if (VT == MVT::v4i32)
13459 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13460 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13462 if (VT == MVT::v8i16)
13463 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13464 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13466 if (VT == MVT::v4i64)
13467 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13468 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13470 if (VT == MVT::v8i32)
13471 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13472 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13474 if (VT == MVT::v16i16)
13475 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13476 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13484 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13485 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13486 // and friends. Likewise for OR -> CMPNEQSS.
13487 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13488 TargetLowering::DAGCombinerInfo &DCI,
13489 const X86Subtarget *Subtarget) {
13492 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13493 // we're requiring SSE2 for both.
13494 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13495 SDValue N0 = N->getOperand(0);
13496 SDValue N1 = N->getOperand(1);
13497 SDValue CMP0 = N0->getOperand(1);
13498 SDValue CMP1 = N1->getOperand(1);
13499 DebugLoc DL = N->getDebugLoc();
13501 // The SETCCs should both refer to the same CMP.
13502 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13505 SDValue CMP00 = CMP0->getOperand(0);
13506 SDValue CMP01 = CMP0->getOperand(1);
13507 EVT VT = CMP00.getValueType();
13509 if (VT == MVT::f32 || VT == MVT::f64) {
13510 bool ExpectingFlags = false;
13511 // Check for any users that want flags:
13512 for (SDNode::use_iterator UI = N->use_begin(),
13514 !ExpectingFlags && UI != UE; ++UI)
13515 switch (UI->getOpcode()) {
13520 ExpectingFlags = true;
13522 case ISD::CopyToReg:
13523 case ISD::SIGN_EXTEND:
13524 case ISD::ZERO_EXTEND:
13525 case ISD::ANY_EXTEND:
13529 if (!ExpectingFlags) {
13530 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13531 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13533 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13534 X86::CondCode tmp = cc0;
13539 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13540 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13541 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13542 X86ISD::NodeType NTOperator = is64BitFP ?
13543 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13544 // FIXME: need symbolic constants for these magic numbers.
13545 // See X86ATTInstPrinter.cpp:printSSECC().
13546 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13547 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13548 DAG.getConstant(x86cc, MVT::i8));
13549 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13551 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13552 DAG.getConstant(1, MVT::i32));
13553 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13554 return OneBitOfTruth;
13562 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13563 /// so it can be folded inside ANDNP.
13564 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13565 EVT VT = N->getValueType(0);
13567 // Match direct AllOnes for 128 and 256-bit vectors
13568 if (ISD::isBuildVectorAllOnes(N))
13571 // Look through a bit convert.
13572 if (N->getOpcode() == ISD::BITCAST)
13573 N = N->getOperand(0).getNode();
13575 // Sometimes the operand may come from a insert_subvector building a 256-bit
13577 if (VT.getSizeInBits() == 256 &&
13578 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13579 SDValue V1 = N->getOperand(0);
13580 SDValue V2 = N->getOperand(1);
13582 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13583 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13584 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13585 ISD::isBuildVectorAllOnes(V2.getNode()))
13592 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13593 TargetLowering::DAGCombinerInfo &DCI,
13594 const X86Subtarget *Subtarget) {
13595 if (DCI.isBeforeLegalizeOps())
13598 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13602 EVT VT = N->getValueType(0);
13604 // Create ANDN, BLSI, and BLSR instructions
13605 // BLSI is X & (-X)
13606 // BLSR is X & (X-1)
13607 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13608 SDValue N0 = N->getOperand(0);
13609 SDValue N1 = N->getOperand(1);
13610 DebugLoc DL = N->getDebugLoc();
13612 // Check LHS for not
13613 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13614 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13615 // Check RHS for not
13616 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13617 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13619 // Check LHS for neg
13620 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13621 isZero(N0.getOperand(0)))
13622 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13624 // Check RHS for neg
13625 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13626 isZero(N1.getOperand(0)))
13627 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13629 // Check LHS for X-1
13630 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13631 isAllOnes(N0.getOperand(1)))
13632 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13634 // Check RHS for X-1
13635 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13636 isAllOnes(N1.getOperand(1)))
13637 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13642 // Want to form ANDNP nodes:
13643 // 1) In the hopes of then easily combining them with OR and AND nodes
13644 // to form PBLEND/PSIGN.
13645 // 2) To match ANDN packed intrinsics
13646 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13649 SDValue N0 = N->getOperand(0);
13650 SDValue N1 = N->getOperand(1);
13651 DebugLoc DL = N->getDebugLoc();
13653 // Check LHS for vnot
13654 if (N0.getOpcode() == ISD::XOR &&
13655 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13656 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13657 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13659 // Check RHS for vnot
13660 if (N1.getOpcode() == ISD::XOR &&
13661 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13662 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13663 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13668 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13669 TargetLowering::DAGCombinerInfo &DCI,
13670 const X86Subtarget *Subtarget) {
13671 if (DCI.isBeforeLegalizeOps())
13674 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13678 EVT VT = N->getValueType(0);
13680 SDValue N0 = N->getOperand(0);
13681 SDValue N1 = N->getOperand(1);
13683 // look for psign/blend
13684 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13685 if (!Subtarget->hasSSSE3orAVX() ||
13686 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13689 // Canonicalize pandn to RHS
13690 if (N0.getOpcode() == X86ISD::ANDNP)
13692 // or (and (m, x), (pandn m, y))
13693 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13694 SDValue Mask = N1.getOperand(0);
13695 SDValue X = N1.getOperand(1);
13697 if (N0.getOperand(0) == Mask)
13698 Y = N0.getOperand(1);
13699 if (N0.getOperand(1) == Mask)
13700 Y = N0.getOperand(0);
13702 // Check to see if the mask appeared in both the AND and ANDNP and
13706 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13707 if (Mask.getOpcode() != ISD::BITCAST ||
13708 X.getOpcode() != ISD::BITCAST ||
13709 Y.getOpcode() != ISD::BITCAST)
13712 // Look through mask bitcast.
13713 Mask = Mask.getOperand(0);
13714 EVT MaskVT = Mask.getValueType();
13716 // Validate that the Mask operand is a vector sra node. The sra node
13717 // will be an intrinsic.
13718 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13721 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13722 // there is no psrai.b
13723 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13724 case Intrinsic::x86_sse2_psrai_w:
13725 case Intrinsic::x86_sse2_psrai_d:
13726 case Intrinsic::x86_avx2_psrai_w:
13727 case Intrinsic::x86_avx2_psrai_d:
13729 default: return SDValue();
13732 // Check that the SRA is all signbits.
13733 SDValue SraC = Mask.getOperand(2);
13734 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13735 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13736 if ((SraAmt + 1) != EltBits)
13739 DebugLoc DL = N->getDebugLoc();
13741 // Now we know we at least have a plendvb with the mask val. See if
13742 // we can form a psignb/w/d.
13743 // psign = x.type == y.type == mask.type && y = sub(0, x);
13744 X = X.getOperand(0);
13745 Y = Y.getOperand(0);
13746 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13747 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13748 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13749 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13750 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13751 Mask.getOperand(1));
13752 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13754 // PBLENDVB only available on SSE 4.1
13755 if (!Subtarget->hasSSE41orAVX())
13758 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13760 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13761 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13762 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13763 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13764 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13768 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13771 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13772 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13774 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13776 if (!N0.hasOneUse() || !N1.hasOneUse())
13779 SDValue ShAmt0 = N0.getOperand(1);
13780 if (ShAmt0.getValueType() != MVT::i8)
13782 SDValue ShAmt1 = N1.getOperand(1);
13783 if (ShAmt1.getValueType() != MVT::i8)
13785 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13786 ShAmt0 = ShAmt0.getOperand(0);
13787 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13788 ShAmt1 = ShAmt1.getOperand(0);
13790 DebugLoc DL = N->getDebugLoc();
13791 unsigned Opc = X86ISD::SHLD;
13792 SDValue Op0 = N0.getOperand(0);
13793 SDValue Op1 = N1.getOperand(0);
13794 if (ShAmt0.getOpcode() == ISD::SUB) {
13795 Opc = X86ISD::SHRD;
13796 std::swap(Op0, Op1);
13797 std::swap(ShAmt0, ShAmt1);
13800 unsigned Bits = VT.getSizeInBits();
13801 if (ShAmt1.getOpcode() == ISD::SUB) {
13802 SDValue Sum = ShAmt1.getOperand(0);
13803 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13804 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13805 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13806 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13807 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13808 return DAG.getNode(Opc, DL, VT,
13810 DAG.getNode(ISD::TRUNCATE, DL,
13813 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13814 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13816 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13817 return DAG.getNode(Opc, DL, VT,
13818 N0.getOperand(0), N1.getOperand(0),
13819 DAG.getNode(ISD::TRUNCATE, DL,
13826 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13827 TargetLowering::DAGCombinerInfo &DCI,
13828 const X86Subtarget *Subtarget) {
13829 if (DCI.isBeforeLegalizeOps())
13832 EVT VT = N->getValueType(0);
13834 if (VT != MVT::i32 && VT != MVT::i64)
13837 // Create BLSMSK instructions by finding X ^ (X-1)
13838 SDValue N0 = N->getOperand(0);
13839 SDValue N1 = N->getOperand(1);
13840 DebugLoc DL = N->getDebugLoc();
13842 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13843 isAllOnes(N0.getOperand(1)))
13844 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13846 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13847 isAllOnes(N1.getOperand(1)))
13848 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13853 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13854 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13855 const X86Subtarget *Subtarget) {
13856 LoadSDNode *Ld = cast<LoadSDNode>(N);
13857 EVT RegVT = Ld->getValueType(0);
13858 EVT MemVT = Ld->getMemoryVT();
13859 DebugLoc dl = Ld->getDebugLoc();
13860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13862 ISD::LoadExtType Ext = Ld->getExtensionType();
13864 // If this is a vector EXT Load then attempt to optimize it using a
13865 // shuffle. We need SSE4 for the shuffles.
13866 // TODO: It is possible to support ZExt by zeroing the undef values
13867 // during the shuffle phase or after the shuffle.
13868 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13869 assert(MemVT != RegVT && "Cannot extend to the same type");
13870 assert(MemVT.isVector() && "Must load a vector from memory");
13872 unsigned NumElems = RegVT.getVectorNumElements();
13873 unsigned RegSz = RegVT.getSizeInBits();
13874 unsigned MemSz = MemVT.getSizeInBits();
13875 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13876 // All sizes must be a power of two
13877 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13879 // Attempt to load the original value using a single load op.
13880 // Find a scalar type which is equal to the loaded word size.
13881 MVT SclrLoadTy = MVT::i8;
13882 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13883 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13884 MVT Tp = (MVT::SimpleValueType)tp;
13885 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13891 // Proceed if a load word is found.
13892 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13894 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13895 RegSz/SclrLoadTy.getSizeInBits());
13897 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13898 RegSz/MemVT.getScalarType().getSizeInBits());
13899 // Can't shuffle using an illegal type.
13900 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13902 // Perform a single load.
13903 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13905 Ld->getPointerInfo(), Ld->isVolatile(),
13906 Ld->isNonTemporal(), Ld->isInvariant(),
13907 Ld->getAlignment());
13909 // Insert the word loaded into a vector.
13910 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13911 LoadUnitVecVT, ScalarLoad);
13913 // Bitcast the loaded value to a vector of the original element type, in
13914 // the size of the target vector type.
13915 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13916 unsigned SizeRatio = RegSz/MemSz;
13918 // Redistribute the loaded elements into the different locations.
13919 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13920 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13922 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13923 DAG.getUNDEF(SlicedVec.getValueType()),
13924 ShuffleVec.data());
13926 // Bitcast to the requested type.
13927 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13928 // Replace the original load with the new sequence
13929 // and return the new chain.
13930 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13931 return SDValue(ScalarLoad.getNode(), 1);
13937 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13938 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13939 const X86Subtarget *Subtarget) {
13940 StoreSDNode *St = cast<StoreSDNode>(N);
13941 EVT VT = St->getValue().getValueType();
13942 EVT StVT = St->getMemoryVT();
13943 DebugLoc dl = St->getDebugLoc();
13944 SDValue StoredVal = St->getOperand(1);
13945 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13947 // If we are saving a concatenation of two XMM registers, perform two stores.
13948 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13949 // 128-bit ones. If in the future the cost becomes only one memory access the
13950 // first version would be better.
13951 if (VT.getSizeInBits() == 256 &&
13952 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13953 StoredVal.getNumOperands() == 2) {
13955 SDValue Value0 = StoredVal.getOperand(0);
13956 SDValue Value1 = StoredVal.getOperand(1);
13958 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13959 SDValue Ptr0 = St->getBasePtr();
13960 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13962 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13963 St->getPointerInfo(), St->isVolatile(),
13964 St->isNonTemporal(), St->getAlignment());
13965 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13966 St->getPointerInfo(), St->isVolatile(),
13967 St->isNonTemporal(), St->getAlignment());
13968 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13971 // Optimize trunc store (of multiple scalars) to shuffle and store.
13972 // First, pack all of the elements in one place. Next, store to memory
13973 // in fewer chunks.
13974 if (St->isTruncatingStore() && VT.isVector()) {
13975 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13976 unsigned NumElems = VT.getVectorNumElements();
13977 assert(StVT != VT && "Cannot truncate to the same type");
13978 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13979 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13981 // From, To sizes and ElemCount must be pow of two
13982 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13983 // We are going to use the original vector elt for storing.
13984 // Accumulated smaller vector elements must be a multiple of the store size.
13985 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13987 unsigned SizeRatio = FromSz / ToSz;
13989 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13991 // Create a type on which we perform the shuffle
13992 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13993 StVT.getScalarType(), NumElems*SizeRatio);
13995 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13997 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13998 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13999 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14001 // Can't shuffle using an illegal type
14002 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14004 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14005 DAG.getUNDEF(WideVec.getValueType()),
14006 ShuffleVec.data());
14007 // At this point all of the data is stored at the bottom of the
14008 // register. We now need to save it to mem.
14010 // Find the largest store unit
14011 MVT StoreType = MVT::i8;
14012 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14013 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14014 MVT Tp = (MVT::SimpleValueType)tp;
14015 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14019 // Bitcast the original vector into a vector of store-size units
14020 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14021 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14022 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14023 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14024 SmallVector<SDValue, 8> Chains;
14025 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14026 TLI.getPointerTy());
14027 SDValue Ptr = St->getBasePtr();
14029 // Perform one or more big stores into memory.
14030 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14031 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14032 StoreType, ShuffWide,
14033 DAG.getIntPtrConstant(i));
14034 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14035 St->getPointerInfo(), St->isVolatile(),
14036 St->isNonTemporal(), St->getAlignment());
14037 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14038 Chains.push_back(Ch);
14041 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14046 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14047 // the FP state in cases where an emms may be missing.
14048 // A preferable solution to the general problem is to figure out the right
14049 // places to insert EMMS. This qualifies as a quick hack.
14051 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14052 if (VT.getSizeInBits() != 64)
14055 const Function *F = DAG.getMachineFunction().getFunction();
14056 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14057 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14058 && Subtarget->hasXMMInt();
14059 if ((VT.isVector() ||
14060 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14061 isa<LoadSDNode>(St->getValue()) &&
14062 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14063 St->getChain().hasOneUse() && !St->isVolatile()) {
14064 SDNode* LdVal = St->getValue().getNode();
14065 LoadSDNode *Ld = 0;
14066 int TokenFactorIndex = -1;
14067 SmallVector<SDValue, 8> Ops;
14068 SDNode* ChainVal = St->getChain().getNode();
14069 // Must be a store of a load. We currently handle two cases: the load
14070 // is a direct child, and it's under an intervening TokenFactor. It is
14071 // possible to dig deeper under nested TokenFactors.
14072 if (ChainVal == LdVal)
14073 Ld = cast<LoadSDNode>(St->getChain());
14074 else if (St->getValue().hasOneUse() &&
14075 ChainVal->getOpcode() == ISD::TokenFactor) {
14076 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14077 if (ChainVal->getOperand(i).getNode() == LdVal) {
14078 TokenFactorIndex = i;
14079 Ld = cast<LoadSDNode>(St->getValue());
14081 Ops.push_back(ChainVal->getOperand(i));
14085 if (!Ld || !ISD::isNormalLoad(Ld))
14088 // If this is not the MMX case, i.e. we are just turning i64 load/store
14089 // into f64 load/store, avoid the transformation if there are multiple
14090 // uses of the loaded value.
14091 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14094 DebugLoc LdDL = Ld->getDebugLoc();
14095 DebugLoc StDL = N->getDebugLoc();
14096 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14097 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14099 if (Subtarget->is64Bit() || F64IsLegal) {
14100 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14101 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14102 Ld->getPointerInfo(), Ld->isVolatile(),
14103 Ld->isNonTemporal(), Ld->isInvariant(),
14104 Ld->getAlignment());
14105 SDValue NewChain = NewLd.getValue(1);
14106 if (TokenFactorIndex != -1) {
14107 Ops.push_back(NewChain);
14108 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14111 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14112 St->getPointerInfo(),
14113 St->isVolatile(), St->isNonTemporal(),
14114 St->getAlignment());
14117 // Otherwise, lower to two pairs of 32-bit loads / stores.
14118 SDValue LoAddr = Ld->getBasePtr();
14119 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14120 DAG.getConstant(4, MVT::i32));
14122 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14123 Ld->getPointerInfo(),
14124 Ld->isVolatile(), Ld->isNonTemporal(),
14125 Ld->isInvariant(), Ld->getAlignment());
14126 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14127 Ld->getPointerInfo().getWithOffset(4),
14128 Ld->isVolatile(), Ld->isNonTemporal(),
14130 MinAlign(Ld->getAlignment(), 4));
14132 SDValue NewChain = LoLd.getValue(1);
14133 if (TokenFactorIndex != -1) {
14134 Ops.push_back(LoLd);
14135 Ops.push_back(HiLd);
14136 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14140 LoAddr = St->getBasePtr();
14141 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14142 DAG.getConstant(4, MVT::i32));
14144 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14145 St->getPointerInfo(),
14146 St->isVolatile(), St->isNonTemporal(),
14147 St->getAlignment());
14148 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14149 St->getPointerInfo().getWithOffset(4),
14151 St->isNonTemporal(),
14152 MinAlign(St->getAlignment(), 4));
14153 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14158 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14159 /// and return the operands for the horizontal operation in LHS and RHS. A
14160 /// horizontal operation performs the binary operation on successive elements
14161 /// of its first operand, then on successive elements of its second operand,
14162 /// returning the resulting values in a vector. For example, if
14163 /// A = < float a0, float a1, float a2, float a3 >
14165 /// B = < float b0, float b1, float b2, float b3 >
14166 /// then the result of doing a horizontal operation on A and B is
14167 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14168 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14169 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14170 /// set to A, RHS to B, and the routine returns 'true'.
14171 /// Note that the binary operation should have the property that if one of the
14172 /// operands is UNDEF then the result is UNDEF.
14173 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14174 // Look for the following pattern: if
14175 // A = < float a0, float a1, float a2, float a3 >
14176 // B = < float b0, float b1, float b2, float b3 >
14178 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14179 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14180 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14181 // which is A horizontal-op B.
14183 // At least one of the operands should be a vector shuffle.
14184 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14185 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14188 EVT VT = LHS.getValueType();
14190 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14191 "Unsupported vector type for horizontal add/sub");
14193 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14194 // operate independently on 128-bit lanes.
14195 unsigned NumElts = VT.getVectorNumElements();
14196 unsigned NumLanes = VT.getSizeInBits()/128;
14197 unsigned NumLaneElts = NumElts / NumLanes;
14198 assert((NumLaneElts % 2 == 0) &&
14199 "Vector type should have an even number of elements in each lane");
14200 unsigned HalfLaneElts = NumLaneElts/2;
14202 // View LHS in the form
14203 // LHS = VECTOR_SHUFFLE A, B, LMask
14204 // If LHS is not a shuffle then pretend it is the shuffle
14205 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14206 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14209 SmallVector<int, 16> LMask(NumElts);
14210 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14211 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14212 A = LHS.getOperand(0);
14213 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14214 B = LHS.getOperand(1);
14215 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14217 if (LHS.getOpcode() != ISD::UNDEF)
14219 for (unsigned i = 0; i != NumElts; ++i)
14223 // Likewise, view RHS in the form
14224 // RHS = VECTOR_SHUFFLE C, D, RMask
14226 SmallVector<int, 16> RMask(NumElts);
14227 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14228 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14229 C = RHS.getOperand(0);
14230 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14231 D = RHS.getOperand(1);
14232 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14234 if (RHS.getOpcode() != ISD::UNDEF)
14236 for (unsigned i = 0; i != NumElts; ++i)
14240 // Check that the shuffles are both shuffling the same vectors.
14241 if (!(A == C && B == D) && !(A == D && B == C))
14244 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14245 if (!A.getNode() && !B.getNode())
14248 // If A and B occur in reverse order in RHS, then "swap" them (which means
14249 // rewriting the mask).
14251 CommuteVectorShuffleMask(RMask, NumElts);
14253 // At this point LHS and RHS are equivalent to
14254 // LHS = VECTOR_SHUFFLE A, B, LMask
14255 // RHS = VECTOR_SHUFFLE A, B, RMask
14256 // Check that the masks correspond to performing a horizontal operation.
14257 for (unsigned i = 0; i != NumElts; ++i) {
14258 int LIdx = LMask[i], RIdx = RMask[i];
14260 // Ignore any UNDEF components.
14261 if (LIdx < 0 || RIdx < 0 ||
14262 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14263 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14266 // Check that successive elements are being operated on. If not, this is
14267 // not a horizontal operation.
14268 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14269 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14270 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14271 if (!(LIdx == Index && RIdx == Index + 1) &&
14272 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14276 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14277 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14281 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14282 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14283 const X86Subtarget *Subtarget) {
14284 EVT VT = N->getValueType(0);
14285 SDValue LHS = N->getOperand(0);
14286 SDValue RHS = N->getOperand(1);
14288 // Try to synthesize horizontal adds from adds of shuffles.
14289 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14290 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14291 isHorizontalBinOp(LHS, RHS, true))
14292 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14296 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14297 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14298 const X86Subtarget *Subtarget) {
14299 EVT VT = N->getValueType(0);
14300 SDValue LHS = N->getOperand(0);
14301 SDValue RHS = N->getOperand(1);
14303 // Try to synthesize horizontal subs from subs of shuffles.
14304 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14305 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14306 isHorizontalBinOp(LHS, RHS, false))
14307 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14311 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14312 /// X86ISD::FXOR nodes.
14313 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14314 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14315 // F[X]OR(0.0, x) -> x
14316 // F[X]OR(x, 0.0) -> x
14317 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14318 if (C->getValueAPF().isPosZero())
14319 return N->getOperand(1);
14320 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14321 if (C->getValueAPF().isPosZero())
14322 return N->getOperand(0);
14326 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14327 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14328 // FAND(0.0, x) -> 0.0
14329 // FAND(x, 0.0) -> 0.0
14330 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14331 if (C->getValueAPF().isPosZero())
14332 return N->getOperand(0);
14333 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14334 if (C->getValueAPF().isPosZero())
14335 return N->getOperand(1);
14339 static SDValue PerformBTCombine(SDNode *N,
14341 TargetLowering::DAGCombinerInfo &DCI) {
14342 // BT ignores high bits in the bit index operand.
14343 SDValue Op1 = N->getOperand(1);
14344 if (Op1.hasOneUse()) {
14345 unsigned BitWidth = Op1.getValueSizeInBits();
14346 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14347 APInt KnownZero, KnownOne;
14348 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14349 !DCI.isBeforeLegalizeOps());
14350 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14351 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14352 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14353 DCI.CommitTargetLoweringOpt(TLO);
14358 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14359 SDValue Op = N->getOperand(0);
14360 if (Op.getOpcode() == ISD::BITCAST)
14361 Op = Op.getOperand(0);
14362 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14363 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14364 VT.getVectorElementType().getSizeInBits() ==
14365 OpVT.getVectorElementType().getSizeInBits()) {
14366 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14371 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14372 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14373 // (and (i32 x86isd::setcc_carry), 1)
14374 // This eliminates the zext. This transformation is necessary because
14375 // ISD::SETCC is always legalized to i8.
14376 DebugLoc dl = N->getDebugLoc();
14377 SDValue N0 = N->getOperand(0);
14378 EVT VT = N->getValueType(0);
14379 if (N0.getOpcode() == ISD::AND &&
14381 N0.getOperand(0).hasOneUse()) {
14382 SDValue N00 = N0.getOperand(0);
14383 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14386 if (!C || C->getZExtValue() != 1)
14388 return DAG.getNode(ISD::AND, dl, VT,
14389 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14390 N00.getOperand(0), N00.getOperand(1)),
14391 DAG.getConstant(1, VT));
14397 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14398 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14399 unsigned X86CC = N->getConstantOperandVal(0);
14400 SDValue EFLAG = N->getOperand(1);
14401 DebugLoc DL = N->getDebugLoc();
14403 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14404 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14406 if (X86CC == X86::COND_B)
14407 return DAG.getNode(ISD::AND, DL, MVT::i8,
14408 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14409 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14410 DAG.getConstant(1, MVT::i8));
14415 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14416 const X86TargetLowering *XTLI) {
14417 SDValue Op0 = N->getOperand(0);
14418 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14419 // a 32-bit target where SSE doesn't support i64->FP operations.
14420 if (Op0.getOpcode() == ISD::LOAD) {
14421 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14422 EVT VT = Ld->getValueType(0);
14423 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14424 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14425 !XTLI->getSubtarget()->is64Bit() &&
14426 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14427 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14428 Ld->getChain(), Op0, DAG);
14429 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14436 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14437 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14438 X86TargetLowering::DAGCombinerInfo &DCI) {
14439 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14440 // the result is either zero or one (depending on the input carry bit).
14441 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14442 if (X86::isZeroNode(N->getOperand(0)) &&
14443 X86::isZeroNode(N->getOperand(1)) &&
14444 // We don't have a good way to replace an EFLAGS use, so only do this when
14446 SDValue(N, 1).use_empty()) {
14447 DebugLoc DL = N->getDebugLoc();
14448 EVT VT = N->getValueType(0);
14449 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14450 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14451 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14452 DAG.getConstant(X86::COND_B,MVT::i8),
14454 DAG.getConstant(1, VT));
14455 return DCI.CombineTo(N, Res1, CarryOut);
14461 // fold (add Y, (sete X, 0)) -> adc 0, Y
14462 // (add Y, (setne X, 0)) -> sbb -1, Y
14463 // (sub (sete X, 0), Y) -> sbb 0, Y
14464 // (sub (setne X, 0), Y) -> adc -1, Y
14465 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14466 DebugLoc DL = N->getDebugLoc();
14468 // Look through ZExts.
14469 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14470 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14473 SDValue SetCC = Ext.getOperand(0);
14474 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14477 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14478 if (CC != X86::COND_E && CC != X86::COND_NE)
14481 SDValue Cmp = SetCC.getOperand(1);
14482 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14483 !X86::isZeroNode(Cmp.getOperand(1)) ||
14484 !Cmp.getOperand(0).getValueType().isInteger())
14487 SDValue CmpOp0 = Cmp.getOperand(0);
14488 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14489 DAG.getConstant(1, CmpOp0.getValueType()));
14491 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14492 if (CC == X86::COND_NE)
14493 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14494 DL, OtherVal.getValueType(), OtherVal,
14495 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14496 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14497 DL, OtherVal.getValueType(), OtherVal,
14498 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14501 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14502 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14503 const X86Subtarget *Subtarget) {
14504 EVT VT = N->getValueType(0);
14505 SDValue Op0 = N->getOperand(0);
14506 SDValue Op1 = N->getOperand(1);
14508 // Try to synthesize horizontal adds from adds of shuffles.
14509 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14510 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14511 isHorizontalBinOp(Op0, Op1, true))
14512 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14514 return OptimizeConditionalInDecrement(N, DAG);
14517 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14518 const X86Subtarget *Subtarget) {
14519 SDValue Op0 = N->getOperand(0);
14520 SDValue Op1 = N->getOperand(1);
14522 // X86 can't encode an immediate LHS of a sub. See if we can push the
14523 // negation into a preceding instruction.
14524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14525 // If the RHS of the sub is a XOR with one use and a constant, invert the
14526 // immediate. Then add one to the LHS of the sub so we can turn
14527 // X-Y -> X+~Y+1, saving one register.
14528 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14529 isa<ConstantSDNode>(Op1.getOperand(1))) {
14530 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14531 EVT VT = Op0.getValueType();
14532 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14534 DAG.getConstant(~XorC, VT));
14535 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14536 DAG.getConstant(C->getAPIntValue()+1, VT));
14540 // Try to synthesize horizontal adds from adds of shuffles.
14541 EVT VT = N->getValueType(0);
14542 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14543 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14544 isHorizontalBinOp(Op0, Op1, true))
14545 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14547 return OptimizeConditionalInDecrement(N, DAG);
14550 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14551 DAGCombinerInfo &DCI) const {
14552 SelectionDAG &DAG = DCI.DAG;
14553 switch (N->getOpcode()) {
14555 case ISD::EXTRACT_VECTOR_ELT:
14556 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14558 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14559 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14560 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14561 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14562 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14563 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14566 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14567 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14568 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14569 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14570 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14571 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14572 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14573 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14574 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14576 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14577 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14578 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14579 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14580 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14581 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14582 case X86ISD::SHUFPS: // Handle all target specific shuffles
14583 case X86ISD::SHUFPD:
14584 case X86ISD::PALIGN:
14585 case X86ISD::UNPCKH:
14586 case X86ISD::UNPCKL:
14587 case X86ISD::MOVHLPS:
14588 case X86ISD::MOVLHPS:
14589 case X86ISD::PSHUFD:
14590 case X86ISD::PSHUFHW:
14591 case X86ISD::PSHUFLW:
14592 case X86ISD::MOVSS:
14593 case X86ISD::MOVSD:
14594 case X86ISD::VPERMILP:
14595 case X86ISD::VPERM2X128:
14596 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14602 /// isTypeDesirableForOp - Return true if the target has native support for
14603 /// the specified value type and it is 'desirable' to use the type for the
14604 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14605 /// instruction encodings are longer and some i16 instructions are slow.
14606 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14607 if (!isTypeLegal(VT))
14609 if (VT != MVT::i16)
14616 case ISD::SIGN_EXTEND:
14617 case ISD::ZERO_EXTEND:
14618 case ISD::ANY_EXTEND:
14631 /// IsDesirableToPromoteOp - This method query the target whether it is
14632 /// beneficial for dag combiner to promote the specified node. If true, it
14633 /// should return the desired promotion type by reference.
14634 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14635 EVT VT = Op.getValueType();
14636 if (VT != MVT::i16)
14639 bool Promote = false;
14640 bool Commute = false;
14641 switch (Op.getOpcode()) {
14644 LoadSDNode *LD = cast<LoadSDNode>(Op);
14645 // If the non-extending load has a single use and it's not live out, then it
14646 // might be folded.
14647 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14648 Op.hasOneUse()*/) {
14649 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14650 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14651 // The only case where we'd want to promote LOAD (rather then it being
14652 // promoted as an operand is when it's only use is liveout.
14653 if (UI->getOpcode() != ISD::CopyToReg)
14660 case ISD::SIGN_EXTEND:
14661 case ISD::ZERO_EXTEND:
14662 case ISD::ANY_EXTEND:
14667 SDValue N0 = Op.getOperand(0);
14668 // Look out for (store (shl (load), x)).
14669 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14682 SDValue N0 = Op.getOperand(0);
14683 SDValue N1 = Op.getOperand(1);
14684 if (!Commute && MayFoldLoad(N1))
14686 // Avoid disabling potential load folding opportunities.
14687 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14689 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14699 //===----------------------------------------------------------------------===//
14700 // X86 Inline Assembly Support
14701 //===----------------------------------------------------------------------===//
14704 // Helper to match a string separated by whitespace.
14705 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14706 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14708 for (unsigned i = 0, e = args.size(); i != e; ++i) {
14709 StringRef piece(*args[i]);
14710 if (!s.startswith(piece)) // Check if the piece matches.
14713 s = s.substr(piece.size());
14714 StringRef::size_type pos = s.find_first_not_of(" \t");
14715 if (pos == 0) // We matched a prefix.
14723 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14726 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14727 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14729 std::string AsmStr = IA->getAsmString();
14731 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14732 if (!Ty || Ty->getBitWidth() % 16 != 0)
14735 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14736 SmallVector<StringRef, 4> AsmPieces;
14737 SplitString(AsmStr, AsmPieces, ";\n");
14739 switch (AsmPieces.size()) {
14740 default: return false;
14742 // FIXME: this should verify that we are targeting a 486 or better. If not,
14743 // we will turn this bswap into something that will be lowered to logical
14744 // ops instead of emitting the bswap asm. For now, we don't support 486 or
14745 // lower so don't worry about this.
14747 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14748 matchAsm(AsmPieces[0], "bswapl", "$0") ||
14749 matchAsm(AsmPieces[0], "bswapq", "$0") ||
14750 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14751 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14752 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14753 // No need to check constraints, nothing other than the equivalent of
14754 // "=r,0" would be valid here.
14755 return IntrinsicLowering::LowerToByteSwap(CI);
14758 // rorw $$8, ${0:w} --> llvm.bswap.i16
14759 if (CI->getType()->isIntegerTy(16) &&
14760 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14761 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14762 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14764 const std::string &ConstraintsStr = IA->getConstraintString();
14765 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14766 std::sort(AsmPieces.begin(), AsmPieces.end());
14767 if (AsmPieces.size() == 4 &&
14768 AsmPieces[0] == "~{cc}" &&
14769 AsmPieces[1] == "~{dirflag}" &&
14770 AsmPieces[2] == "~{flags}" &&
14771 AsmPieces[3] == "~{fpsr}")
14772 return IntrinsicLowering::LowerToByteSwap(CI);
14776 if (CI->getType()->isIntegerTy(32) &&
14777 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14778 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14779 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14780 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14782 const std::string &ConstraintsStr = IA->getConstraintString();
14783 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14784 std::sort(AsmPieces.begin(), AsmPieces.end());
14785 if (AsmPieces.size() == 4 &&
14786 AsmPieces[0] == "~{cc}" &&
14787 AsmPieces[1] == "~{dirflag}" &&
14788 AsmPieces[2] == "~{flags}" &&
14789 AsmPieces[3] == "~{fpsr}")
14790 return IntrinsicLowering::LowerToByteSwap(CI);
14793 if (CI->getType()->isIntegerTy(64)) {
14794 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14795 if (Constraints.size() >= 2 &&
14796 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14797 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14798 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14799 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14800 matchAsm(AsmPieces[1], "bswap", "%edx") &&
14801 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14802 return IntrinsicLowering::LowerToByteSwap(CI);
14812 /// getConstraintType - Given a constraint letter, return the type of
14813 /// constraint it is for this target.
14814 X86TargetLowering::ConstraintType
14815 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14816 if (Constraint.size() == 1) {
14817 switch (Constraint[0]) {
14828 return C_RegisterClass;
14852 return TargetLowering::getConstraintType(Constraint);
14855 /// Examine constraint type and operand type and determine a weight value.
14856 /// This object must already have been set up with the operand type
14857 /// and the current alternative constraint selected.
14858 TargetLowering::ConstraintWeight
14859 X86TargetLowering::getSingleConstraintMatchWeight(
14860 AsmOperandInfo &info, const char *constraint) const {
14861 ConstraintWeight weight = CW_Invalid;
14862 Value *CallOperandVal = info.CallOperandVal;
14863 // If we don't have a value, we can't do a match,
14864 // but allow it at the lowest weight.
14865 if (CallOperandVal == NULL)
14867 Type *type = CallOperandVal->getType();
14868 // Look at the constraint type.
14869 switch (*constraint) {
14871 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14882 if (CallOperandVal->getType()->isIntegerTy())
14883 weight = CW_SpecificReg;
14888 if (type->isFloatingPointTy())
14889 weight = CW_SpecificReg;
14892 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14893 weight = CW_SpecificReg;
14897 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14898 weight = CW_Register;
14901 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14902 if (C->getZExtValue() <= 31)
14903 weight = CW_Constant;
14907 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14908 if (C->getZExtValue() <= 63)
14909 weight = CW_Constant;
14913 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14914 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14915 weight = CW_Constant;
14919 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14920 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14921 weight = CW_Constant;
14925 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14926 if (C->getZExtValue() <= 3)
14927 weight = CW_Constant;
14931 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14932 if (C->getZExtValue() <= 0xff)
14933 weight = CW_Constant;
14938 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14939 weight = CW_Constant;
14943 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14944 if ((C->getSExtValue() >= -0x80000000LL) &&
14945 (C->getSExtValue() <= 0x7fffffffLL))
14946 weight = CW_Constant;
14950 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14951 if (C->getZExtValue() <= 0xffffffff)
14952 weight = CW_Constant;
14959 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14960 /// with another that has more specific requirements based on the type of the
14961 /// corresponding operand.
14962 const char *X86TargetLowering::
14963 LowerXConstraint(EVT ConstraintVT) const {
14964 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14965 // 'f' like normal targets.
14966 if (ConstraintVT.isFloatingPoint()) {
14967 if (Subtarget->hasXMMInt())
14969 if (Subtarget->hasXMM())
14973 return TargetLowering::LowerXConstraint(ConstraintVT);
14976 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14977 /// vector. If it is invalid, don't add anything to Ops.
14978 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14979 std::string &Constraint,
14980 std::vector<SDValue>&Ops,
14981 SelectionDAG &DAG) const {
14982 SDValue Result(0, 0);
14984 // Only support length 1 constraints for now.
14985 if (Constraint.length() > 1) return;
14987 char ConstraintLetter = Constraint[0];
14988 switch (ConstraintLetter) {
14991 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14992 if (C->getZExtValue() <= 31) {
14993 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15000 if (C->getZExtValue() <= 63) {
15001 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15007 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15008 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15009 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15016 if (C->getZExtValue() <= 255) {
15017 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15023 // 32-bit signed value
15024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15025 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15026 C->getSExtValue())) {
15027 // Widen to 64 bits here to get it sign extended.
15028 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15031 // FIXME gcc accepts some relocatable values here too, but only in certain
15032 // memory models; it's complicated.
15037 // 32-bit unsigned value
15038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15039 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15040 C->getZExtValue())) {
15041 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15045 // FIXME gcc accepts some relocatable values here too, but only in certain
15046 // memory models; it's complicated.
15050 // Literal immediates are always ok.
15051 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15052 // Widen to 64 bits here to get it sign extended.
15053 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15057 // In any sort of PIC mode addresses need to be computed at runtime by
15058 // adding in a register or some sort of table lookup. These can't
15059 // be used as immediates.
15060 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15063 // If we are in non-pic codegen mode, we allow the address of a global (with
15064 // an optional displacement) to be used with 'i'.
15065 GlobalAddressSDNode *GA = 0;
15066 int64_t Offset = 0;
15068 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15070 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15071 Offset += GA->getOffset();
15073 } else if (Op.getOpcode() == ISD::ADD) {
15074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15075 Offset += C->getZExtValue();
15076 Op = Op.getOperand(0);
15079 } else if (Op.getOpcode() == ISD::SUB) {
15080 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15081 Offset += -C->getZExtValue();
15082 Op = Op.getOperand(0);
15087 // Otherwise, this isn't something we can handle, reject it.
15091 const GlobalValue *GV = GA->getGlobal();
15092 // If we require an extra load to get this address, as in PIC mode, we
15093 // can't accept it.
15094 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15095 getTargetMachine())))
15098 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15099 GA->getValueType(0), Offset);
15104 if (Result.getNode()) {
15105 Ops.push_back(Result);
15108 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15111 std::pair<unsigned, const TargetRegisterClass*>
15112 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15114 // First, see if this is a constraint that directly corresponds to an LLVM
15116 if (Constraint.size() == 1) {
15117 // GCC Constraint Letters
15118 switch (Constraint[0]) {
15120 // TODO: Slight differences here in allocation order and leaving
15121 // RIP in the class. Do they matter any more here than they do
15122 // in the normal allocation?
15123 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15124 if (Subtarget->is64Bit()) {
15125 if (VT == MVT::i32 || VT == MVT::f32)
15126 return std::make_pair(0U, X86::GR32RegisterClass);
15127 else if (VT == MVT::i16)
15128 return std::make_pair(0U, X86::GR16RegisterClass);
15129 else if (VT == MVT::i8 || VT == MVT::i1)
15130 return std::make_pair(0U, X86::GR8RegisterClass);
15131 else if (VT == MVT::i64 || VT == MVT::f64)
15132 return std::make_pair(0U, X86::GR64RegisterClass);
15135 // 32-bit fallthrough
15136 case 'Q': // Q_REGS
15137 if (VT == MVT::i32 || VT == MVT::f32)
15138 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15139 else if (VT == MVT::i16)
15140 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15141 else if (VT == MVT::i8 || VT == MVT::i1)
15142 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15143 else if (VT == MVT::i64)
15144 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15146 case 'r': // GENERAL_REGS
15147 case 'l': // INDEX_REGS
15148 if (VT == MVT::i8 || VT == MVT::i1)
15149 return std::make_pair(0U, X86::GR8RegisterClass);
15150 if (VT == MVT::i16)
15151 return std::make_pair(0U, X86::GR16RegisterClass);
15152 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15153 return std::make_pair(0U, X86::GR32RegisterClass);
15154 return std::make_pair(0U, X86::GR64RegisterClass);
15155 case 'R': // LEGACY_REGS
15156 if (VT == MVT::i8 || VT == MVT::i1)
15157 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15158 if (VT == MVT::i16)
15159 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15160 if (VT == MVT::i32 || !Subtarget->is64Bit())
15161 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15162 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15163 case 'f': // FP Stack registers.
15164 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15165 // value to the correct fpstack register class.
15166 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15167 return std::make_pair(0U, X86::RFP32RegisterClass);
15168 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15169 return std::make_pair(0U, X86::RFP64RegisterClass);
15170 return std::make_pair(0U, X86::RFP80RegisterClass);
15171 case 'y': // MMX_REGS if MMX allowed.
15172 if (!Subtarget->hasMMX()) break;
15173 return std::make_pair(0U, X86::VR64RegisterClass);
15174 case 'Y': // SSE_REGS if SSE2 allowed
15175 if (!Subtarget->hasXMMInt()) break;
15177 case 'x': // SSE_REGS if SSE1 allowed
15178 if (!Subtarget->hasXMM()) break;
15180 switch (VT.getSimpleVT().SimpleTy) {
15182 // Scalar SSE types.
15185 return std::make_pair(0U, X86::FR32RegisterClass);
15188 return std::make_pair(0U, X86::FR64RegisterClass);
15196 return std::make_pair(0U, X86::VR128RegisterClass);
15202 // Use the default implementation in TargetLowering to convert the register
15203 // constraint into a member of a register class.
15204 std::pair<unsigned, const TargetRegisterClass*> Res;
15205 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15207 // Not found as a standard register?
15208 if (Res.second == 0) {
15209 // Map st(0) -> st(7) -> ST0
15210 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15211 tolower(Constraint[1]) == 's' &&
15212 tolower(Constraint[2]) == 't' &&
15213 Constraint[3] == '(' &&
15214 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15215 Constraint[5] == ')' &&
15216 Constraint[6] == '}') {
15218 Res.first = X86::ST0+Constraint[4]-'0';
15219 Res.second = X86::RFP80RegisterClass;
15223 // GCC allows "st(0)" to be called just plain "st".
15224 if (StringRef("{st}").equals_lower(Constraint)) {
15225 Res.first = X86::ST0;
15226 Res.second = X86::RFP80RegisterClass;
15231 if (StringRef("{flags}").equals_lower(Constraint)) {
15232 Res.first = X86::EFLAGS;
15233 Res.second = X86::CCRRegisterClass;
15237 // 'A' means EAX + EDX.
15238 if (Constraint == "A") {
15239 Res.first = X86::EAX;
15240 Res.second = X86::GR32_ADRegisterClass;
15246 // Otherwise, check to see if this is a register class of the wrong value
15247 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15248 // turn into {ax},{dx}.
15249 if (Res.second->hasType(VT))
15250 return Res; // Correct type already, nothing to do.
15252 // All of the single-register GCC register classes map their values onto
15253 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15254 // really want an 8-bit or 32-bit register, map to the appropriate register
15255 // class and return the appropriate register.
15256 if (Res.second == X86::GR16RegisterClass) {
15257 if (VT == MVT::i8) {
15258 unsigned DestReg = 0;
15259 switch (Res.first) {
15261 case X86::AX: DestReg = X86::AL; break;
15262 case X86::DX: DestReg = X86::DL; break;
15263 case X86::CX: DestReg = X86::CL; break;
15264 case X86::BX: DestReg = X86::BL; break;
15267 Res.first = DestReg;
15268 Res.second = X86::GR8RegisterClass;
15270 } else if (VT == MVT::i32) {
15271 unsigned DestReg = 0;
15272 switch (Res.first) {
15274 case X86::AX: DestReg = X86::EAX; break;
15275 case X86::DX: DestReg = X86::EDX; break;
15276 case X86::CX: DestReg = X86::ECX; break;
15277 case X86::BX: DestReg = X86::EBX; break;
15278 case X86::SI: DestReg = X86::ESI; break;
15279 case X86::DI: DestReg = X86::EDI; break;
15280 case X86::BP: DestReg = X86::EBP; break;
15281 case X86::SP: DestReg = X86::ESP; break;
15284 Res.first = DestReg;
15285 Res.second = X86::GR32RegisterClass;
15287 } else if (VT == MVT::i64) {
15288 unsigned DestReg = 0;
15289 switch (Res.first) {
15291 case X86::AX: DestReg = X86::RAX; break;
15292 case X86::DX: DestReg = X86::RDX; break;
15293 case X86::CX: DestReg = X86::RCX; break;
15294 case X86::BX: DestReg = X86::RBX; break;
15295 case X86::SI: DestReg = X86::RSI; break;
15296 case X86::DI: DestReg = X86::RDI; break;
15297 case X86::BP: DestReg = X86::RBP; break;
15298 case X86::SP: DestReg = X86::RSP; break;
15301 Res.first = DestReg;
15302 Res.second = X86::GR64RegisterClass;
15305 } else if (Res.second == X86::FR32RegisterClass ||
15306 Res.second == X86::FR64RegisterClass ||
15307 Res.second == X86::VR128RegisterClass) {
15308 // Handle references to XMM physical registers that got mapped into the
15309 // wrong class. This can happen with constraints like {xmm0} where the
15310 // target independent register mapper will just pick the first match it can
15311 // find, ignoring the required type.
15312 if (VT == MVT::f32)
15313 Res.second = X86::FR32RegisterClass;
15314 else if (VT == MVT::f64)
15315 Res.second = X86::FR64RegisterClass;
15316 else if (X86::VR128RegisterClass->hasType(VT))
15317 Res.second = X86::VR128RegisterClass;