1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
56 using namespace dwarf;
58 STATISTIC(NumTailCalls, "Number of tail calls");
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static SDValue Insert128BitVector(SDValue Result,
70 static SDValue Extract128BitVector(SDValue Vec,
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference. Idx is an index in the 128 bits we
78 /// want. It need not be aligned to a 128-bit bounday. That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
84 EVT VT = Vec.getValueType();
85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86 EVT ElVT = VT.getVectorElementType();
87 int Factor = VT.getSizeInBits()/128;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
95 if (isa<ConstantSDNode>(Idx)) {
96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
99 // we can match to VEXTRACTF128.
100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
102 // This is the index of the first element of the 128-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
117 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference. Idx is an index in the 128 bits
120 /// we want. It need not be aligned to a 128-bit bounday. That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
127 if (isa<ConstantSDNode>(Idx)) {
128 EVT VT = Vec.getValueType();
129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131 EVT ElVT = VT.getVectorElementType();
132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133 EVT ResultVT = Result.getValueType();
135 // Insert the relevant 128 bits.
136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
138 // This is the index of the first element of the 128-bit chunk
140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154 bool is64Bit = Subtarget->is64Bit();
156 if (Subtarget->isTargetEnvMacho()) {
158 return new X8664_MachoTargetObjectFile();
159 return new TargetLoweringObjectFileMachO();
162 if (Subtarget->isTargetELF())
163 return new TargetLoweringObjectFileELF();
164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165 return new TargetLoweringObjectFileCOFF();
166 llvm_unreachable("unknown subtarget type");
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<X86Subtarget>();
172 X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
173 X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
176 RegInfo = TM.getRegisterInfo();
177 TD = getTargetData();
179 // Set up the TargetLowering object.
180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
182 // X86 is weird, it always uses i8 for shift amounts and setcc results.
183 setBooleanContents(ZeroOrOneBooleanContent);
184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
187 // For 64-bit since we have so many registers use the ILP scheduler, for
188 // 32-bit code use the register pressure specific scheduling.
189 if (Subtarget->is64Bit())
190 setSchedulingPreference(Sched::ILP);
192 setSchedulingPreference(Sched::RegPressure);
193 setStackPointerRegisterToSaveRestore(X86StackPtr);
195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196 // Setup Windows compiler runtime calls.
197 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199 setLibcallName(RTLIB::SREM_I64, "_allrem");
200 setLibcallName(RTLIB::UREM_I64, "_aullrem");
201 setLibcallName(RTLIB::MUL_I64, "_allmul");
202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
213 if (Subtarget->isTargetDarwin()) {
214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215 setUseUnderscoreSetJmp(false);
216 setUseUnderscoreLongJmp(false);
217 } else if (Subtarget->isTargetMingw()) {
218 // MS runtime is weird: it exports _setjmp, but longjmp!
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(false);
222 setUseUnderscoreSetJmp(true);
223 setUseUnderscoreLongJmp(true);
226 // Set up the register classes.
227 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230 if (Subtarget->is64Bit())
231 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
235 // We don't accept any truncstore of integer registers.
236 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
243 // SETOEQ and SETUNE require checking two conditions.
244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
260 } else if (!UseSoftFloat) {
261 // We have an algorithm for SSE2->double, and we turn this into a
262 // 64-bit FILD followed by conditional FADD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
264 // We have an algorithm for SSE2, and we turn this into a 64-bit
265 // FILD for other targets.
266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
275 // SSE has no i16 to fp conversion, only i32
276 if (X86ScalarSSEf32) {
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 // f32 and f64 cases are Legal, f80 case is not
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
290 // are Legal, f80 is custom lowered.
291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
308 // Handle FP_TO_UINT by promoting the destination to a larger signed
310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
317 } else if (!UseSoftFloat) {
318 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
319 // Expand FP_TO_UINT into a select.
320 // FIXME: We would like to use a Custom expander here eventually to do
321 // the optimal thing for SSE vs. the default expansion in the legalizer.
322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
324 // With SSE3 we can use fisttpll to convert to a signed i64; without
325 // SSE, we're stuck with a fistpll.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0, e = 4; i != e; ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
382 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
383 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
384 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
385 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
386 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
387 if (Subtarget->is64Bit()) {
388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
389 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
392 if (Subtarget->hasPOPCNT()) {
393 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
395 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
396 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
397 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
402 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
403 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
405 // These should be promoted to a larger select which is supported.
406 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
407 // X86 wants to expand cmov itself.
408 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
410 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
413 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
416 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
419 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
422 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
424 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
427 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
428 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
429 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
430 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
433 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
434 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
435 if (Subtarget->is64Bit()) {
436 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
437 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
438 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
439 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
440 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
442 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
443 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
444 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
445 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
446 if (Subtarget->is64Bit()) {
447 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
448 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
449 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
452 if (Subtarget->hasXMM())
453 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
455 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
456 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
458 // On X86 and X86-64, atomic operations are lowered to locked instructions.
459 // Locked instructions, in turn, have implicit fence semantics (all memory
460 // operations are flushed before issuing the locked instruction, and they
461 // are not buffered), so we can fold away the common pattern of
462 // fence-atomic-fence.
463 setShouldFoldAtomicFences(true);
465 // Expand certain atomics
466 for (unsigned i = 0, e = 4; i != e; ++i) {
468 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
469 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
470 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
473 if (!Subtarget->is64Bit()) {
474 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
475 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
477 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
479 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
480 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
481 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
484 if (Subtarget->hasCmpxchg16b()) {
485 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
488 // FIXME - use subtarget debug flags
489 if (!Subtarget->isTargetDarwin() &&
490 !Subtarget->isTargetELF() &&
491 !Subtarget->isTargetCygMing()) {
492 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
495 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
496 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
497 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
498 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
499 if (Subtarget->is64Bit()) {
500 setExceptionPointerRegister(X86::RAX);
501 setExceptionSelectorRegister(X86::RDX);
503 setExceptionPointerRegister(X86::EAX);
504 setExceptionSelectorRegister(X86::EDX);
506 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
507 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
509 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
510 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
512 setOperationAction(ISD::TRAP, MVT::Other, Legal);
514 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
515 setOperationAction(ISD::VASTART , MVT::Other, Custom);
516 setOperationAction(ISD::VAEND , MVT::Other, Expand);
517 if (Subtarget->is64Bit()) {
518 setOperationAction(ISD::VAARG , MVT::Other, Custom);
519 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
521 setOperationAction(ISD::VAARG , MVT::Other, Expand);
522 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
525 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
526 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
528 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
529 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
530 MVT::i64 : MVT::i32, Custom);
531 else if (EnableSegmentedStacks)
532 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
533 MVT::i64 : MVT::i32, Custom);
535 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
536 MVT::i64 : MVT::i32, Expand);
538 if (!UseSoftFloat && X86ScalarSSEf64) {
539 // f32 and f64 use SSE.
540 // Set up the FP register classes.
541 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
542 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
544 // Use ANDPD to simulate FABS.
545 setOperationAction(ISD::FABS , MVT::f64, Custom);
546 setOperationAction(ISD::FABS , MVT::f32, Custom);
548 // Use XORP to simulate FNEG.
549 setOperationAction(ISD::FNEG , MVT::f64, Custom);
550 setOperationAction(ISD::FNEG , MVT::f32, Custom);
552 // Use ANDPD and ORPD to simulate FCOPYSIGN.
553 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
554 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
556 // Lower this to FGETSIGNx86 plus an AND.
557 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
558 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
560 // We don't support sin/cos/fmod
561 setOperationAction(ISD::FSIN , MVT::f64, Expand);
562 setOperationAction(ISD::FCOS , MVT::f64, Expand);
563 setOperationAction(ISD::FSIN , MVT::f32, Expand);
564 setOperationAction(ISD::FCOS , MVT::f32, Expand);
566 // Expand FP immediates into loads from the stack, except for the special
568 addLegalFPImmediate(APFloat(+0.0)); // xorpd
569 addLegalFPImmediate(APFloat(+0.0f)); // xorps
570 } else if (!UseSoftFloat && X86ScalarSSEf32) {
571 // Use SSE for f32, x87 for f64.
572 // Set up the FP register classes.
573 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
574 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
576 // Use ANDPS to simulate FABS.
577 setOperationAction(ISD::FABS , MVT::f32, Custom);
579 // Use XORP to simulate FNEG.
580 setOperationAction(ISD::FNEG , MVT::f32, Custom);
582 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
584 // Use ANDPS and ORPS to simulate FCOPYSIGN.
585 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
586 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
588 // We don't support sin/cos/fmod
589 setOperationAction(ISD::FSIN , MVT::f32, Expand);
590 setOperationAction(ISD::FCOS , MVT::f32, Expand);
592 // Special cases we handle for FP constants.
593 addLegalFPImmediate(APFloat(+0.0f)); // xorps
594 addLegalFPImmediate(APFloat(+0.0)); // FLD0
595 addLegalFPImmediate(APFloat(+1.0)); // FLD1
596 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
600 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
601 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
603 } else if (!UseSoftFloat) {
604 // f32 and f64 in x87.
605 // Set up the FP register classes.
606 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
607 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
609 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
610 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
611 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
612 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
615 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
616 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
618 addLegalFPImmediate(APFloat(+0.0)); // FLD0
619 addLegalFPImmediate(APFloat(+1.0)); // FLD1
620 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
621 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
622 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
623 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
624 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
625 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
628 // We don't support FMA.
629 setOperationAction(ISD::FMA, MVT::f64, Expand);
630 setOperationAction(ISD::FMA, MVT::f32, Expand);
632 // Long double always uses X87.
634 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
635 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
636 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
638 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
639 addLegalFPImmediate(TmpFlt); // FLD0
641 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
644 APFloat TmpFlt2(+1.0);
645 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
647 addLegalFPImmediate(TmpFlt2); // FLD1
648 TmpFlt2.changeSign();
649 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
653 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
654 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
657 setOperationAction(ISD::FMA, MVT::f80, Expand);
660 // Always use a library call for pow.
661 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
662 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
663 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
665 setOperationAction(ISD::FLOG, MVT::f80, Expand);
666 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
667 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
668 setOperationAction(ISD::FEXP, MVT::f80, Expand);
669 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
671 // First set operation action for all vector types to either promote
672 // (for widening) or expand (for scalarization). Then we will selectively
673 // turn on ones that can be effectively codegen'd.
674 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
675 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
676 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
677 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
678 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
679 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
680 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
681 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
682 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
683 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
691 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
693 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
694 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
726 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
731 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
732 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
733 setTruncStoreAction((MVT::SimpleValueType)VT,
734 (MVT::SimpleValueType)InnerVT, Expand);
735 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
736 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
737 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
740 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
741 // with -msoft-float, disable use of MMX as well.
742 if (!UseSoftFloat && Subtarget->hasMMX()) {
743 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
744 // No operations on x86mmx supported, everything uses intrinsics.
747 // MMX-sized vectors (other than x86mmx) are expected to be expanded
748 // into smaller operations.
749 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
750 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
751 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
752 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
753 setOperationAction(ISD::AND, MVT::v8i8, Expand);
754 setOperationAction(ISD::AND, MVT::v4i16, Expand);
755 setOperationAction(ISD::AND, MVT::v2i32, Expand);
756 setOperationAction(ISD::AND, MVT::v1i64, Expand);
757 setOperationAction(ISD::OR, MVT::v8i8, Expand);
758 setOperationAction(ISD::OR, MVT::v4i16, Expand);
759 setOperationAction(ISD::OR, MVT::v2i32, Expand);
760 setOperationAction(ISD::OR, MVT::v1i64, Expand);
761 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
762 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
763 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
764 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
765 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
767 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
768 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
770 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
771 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
772 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
773 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
774 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
775 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
776 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
777 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
779 if (!UseSoftFloat && Subtarget->hasXMM()) {
780 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
782 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
783 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
784 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
785 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
786 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
787 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
788 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
789 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
790 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
791 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
793 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
796 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
797 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
799 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
800 // registers cannot be used even for integer operations.
801 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
802 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
803 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
804 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
806 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
807 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
808 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
809 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
810 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
811 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
812 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
813 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
814 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
815 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
816 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
817 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
818 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
819 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
820 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
821 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
823 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
824 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
825 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
826 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
830 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
834 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
835 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
836 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
837 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
838 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
840 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
841 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
842 EVT VT = (MVT::SimpleValueType)i;
843 // Do not attempt to custom lower non-power-of-2 vectors
844 if (!isPowerOf2_32(VT.getVectorNumElements()))
846 // Do not attempt to custom lower non-128-bit vectors
847 if (!VT.is128BitVector())
849 setOperationAction(ISD::BUILD_VECTOR,
850 VT.getSimpleVT().SimpleTy, Custom);
851 setOperationAction(ISD::VECTOR_SHUFFLE,
852 VT.getSimpleVT().SimpleTy, Custom);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
854 VT.getSimpleVT().SimpleTy, Custom);
857 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
858 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
861 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
862 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
864 if (Subtarget->is64Bit()) {
865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
866 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
869 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
870 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
871 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
874 // Do not attempt to promote non-128-bit vectors
875 if (!VT.is128BitVector())
878 setOperationAction(ISD::AND, SVT, Promote);
879 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
880 setOperationAction(ISD::OR, SVT, Promote);
881 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
882 setOperationAction(ISD::XOR, SVT, Promote);
883 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
884 setOperationAction(ISD::LOAD, SVT, Promote);
885 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
886 setOperationAction(ISD::SELECT, SVT, Promote);
887 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
890 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
892 // Custom lower v2i64 and v2f64 selects.
893 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
894 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
895 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
896 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
898 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
899 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
902 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
903 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
904 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
905 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
906 setOperationAction(ISD::FRINT, MVT::f32, Legal);
907 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
908 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
909 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
910 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
911 setOperationAction(ISD::FRINT, MVT::f64, Legal);
912 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
914 // FIXME: Do we need to handle scalar-to-vector here?
915 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
917 // Can turn SHL into an integer multiply.
918 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
919 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
921 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
922 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
923 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
924 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
925 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
927 // i8 and i16 vectors are custom , because the source register and source
928 // source memory operand types are not the same width. f32 vectors are
929 // custom since the immediate controlling the insert encodes additional
931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
934 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
941 if (Subtarget->is64Bit()) {
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
947 if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
948 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
949 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
950 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
951 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
953 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
954 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
955 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
957 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
958 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
961 if (Subtarget->hasSSE42() || Subtarget->hasAVX())
962 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
964 if (!UseSoftFloat && Subtarget->hasAVX()) {
965 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
966 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
967 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
968 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
969 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
970 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
972 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
973 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
974 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
976 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
977 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
978 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
979 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
980 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
981 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
983 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
984 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
985 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
986 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
987 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
988 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
990 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
991 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
992 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
994 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
995 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
996 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
997 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
998 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
999 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1001 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1002 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1003 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1004 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1006 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1007 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1008 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1009 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1011 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1012 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1014 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1015 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1016 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1017 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1019 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1020 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1021 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1023 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1024 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1025 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1026 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1028 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1029 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1030 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1031 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1033 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1034 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1035 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1036 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1038 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1039 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1040 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1041 // Don't lower v32i8 because there is no 128-bit byte mul
1043 // Custom lower several nodes for 256-bit types.
1044 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1045 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1046 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1049 // Extract subvector is special because the value type
1050 // (result) is 128-bit but the source is 256-bit wide.
1051 if (VT.is128BitVector())
1052 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1054 // Do not attempt to custom lower other non-256-bit vectors
1055 if (!VT.is256BitVector())
1058 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1059 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1060 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1061 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1062 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1063 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1066 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1067 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1068 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1071 // Do not attempt to promote non-256-bit vectors
1072 if (!VT.is256BitVector())
1075 setOperationAction(ISD::AND, SVT, Promote);
1076 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1077 setOperationAction(ISD::OR, SVT, Promote);
1078 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1079 setOperationAction(ISD::XOR, SVT, Promote);
1080 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1081 setOperationAction(ISD::LOAD, SVT, Promote);
1082 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1083 setOperationAction(ISD::SELECT, SVT, Promote);
1084 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1088 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1089 // of this type with custom code.
1090 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1091 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1092 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1095 // We want to custom lower some of our intrinsics.
1096 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1099 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1100 // handle type legalization for these operations here.
1102 // FIXME: We really should do custom legalization for addition and
1103 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1104 // than generic legalization for 64-bit multiplication-with-overflow, though.
1105 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1106 // Add/Sub/Mul with overflow operations are custom lowered.
1108 setOperationAction(ISD::SADDO, VT, Custom);
1109 setOperationAction(ISD::UADDO, VT, Custom);
1110 setOperationAction(ISD::SSUBO, VT, Custom);
1111 setOperationAction(ISD::USUBO, VT, Custom);
1112 setOperationAction(ISD::SMULO, VT, Custom);
1113 setOperationAction(ISD::UMULO, VT, Custom);
1116 // There are no 8-bit 3-address imul/mul instructions
1117 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1118 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1120 if (!Subtarget->is64Bit()) {
1121 // These libcalls are not available in 32-bit.
1122 setLibcallName(RTLIB::SHL_I128, 0);
1123 setLibcallName(RTLIB::SRL_I128, 0);
1124 setLibcallName(RTLIB::SRA_I128, 0);
1127 // We have target-specific dag combine patterns for the following nodes:
1128 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1129 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1130 setTargetDAGCombine(ISD::BUILD_VECTOR);
1131 setTargetDAGCombine(ISD::SELECT);
1132 setTargetDAGCombine(ISD::SHL);
1133 setTargetDAGCombine(ISD::SRA);
1134 setTargetDAGCombine(ISD::SRL);
1135 setTargetDAGCombine(ISD::OR);
1136 setTargetDAGCombine(ISD::AND);
1137 setTargetDAGCombine(ISD::ADD);
1138 setTargetDAGCombine(ISD::SUB);
1139 setTargetDAGCombine(ISD::STORE);
1140 setTargetDAGCombine(ISD::ZERO_EXTEND);
1141 setTargetDAGCombine(ISD::SINT_TO_FP);
1142 if (Subtarget->is64Bit())
1143 setTargetDAGCombine(ISD::MUL);
1145 computeRegisterProperties();
1147 // On Darwin, -Os means optimize for size without hurting performance,
1148 // do not reduce the limit.
1149 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1150 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1151 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1152 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1153 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1154 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1155 setPrefLoopAlignment(16);
1156 benefitFromCodePlacementOpt = true;
1158 setPrefFunctionAlignment(4);
1162 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1163 if (!VT.isVector()) return MVT::i8;
1164 return VT.changeVectorElementTypeToInteger();
1168 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1169 /// the desired ByVal argument alignment.
1170 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1173 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1174 if (VTy->getBitWidth() == 128)
1176 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1177 unsigned EltAlign = 0;
1178 getMaxByValAlign(ATy->getElementType(), EltAlign);
1179 if (EltAlign > MaxAlign)
1180 MaxAlign = EltAlign;
1181 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1182 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1183 unsigned EltAlign = 0;
1184 getMaxByValAlign(STy->getElementType(i), EltAlign);
1185 if (EltAlign > MaxAlign)
1186 MaxAlign = EltAlign;
1194 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1195 /// function arguments in the caller parameter area. For X86, aggregates
1196 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1197 /// are at 4-byte boundaries.
1198 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1199 if (Subtarget->is64Bit()) {
1200 // Max of 8 and alignment of type.
1201 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1208 if (Subtarget->hasXMM())
1209 getMaxByValAlign(Ty, Align);
1213 /// getOptimalMemOpType - Returns the target specific optimal type for load
1214 /// and store operations as a result of memset, memcpy, and memmove
1215 /// lowering. If DstAlign is zero that means it's safe to destination
1216 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1217 /// means there isn't a need to check it against alignment requirement,
1218 /// probably because the source does not need to be loaded. If
1219 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1220 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1221 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1222 /// constant so it does not need to be loaded.
1223 /// It returns EVT::Other if the type should be determined using generic
1224 /// target-independent logic.
1226 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1227 unsigned DstAlign, unsigned SrcAlign,
1228 bool NonScalarIntSafe,
1230 MachineFunction &MF) const {
1231 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1232 // linux. This is because the stack realignment code can't handle certain
1233 // cases like PR2962. This should be removed when PR2962 is fixed.
1234 const Function *F = MF.getFunction();
1235 if (NonScalarIntSafe &&
1236 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1238 (Subtarget->isUnalignedMemAccessFast() ||
1239 ((DstAlign == 0 || DstAlign >= 16) &&
1240 (SrcAlign == 0 || SrcAlign >= 16))) &&
1241 Subtarget->getStackAlignment() >= 16) {
1242 if (Subtarget->hasSSE2())
1244 if (Subtarget->hasSSE1())
1246 } else if (!MemcpyStrSrc && Size >= 8 &&
1247 !Subtarget->is64Bit() &&
1248 Subtarget->getStackAlignment() >= 8 &&
1249 Subtarget->hasXMMInt()) {
1250 // Do not use f64 to lower memcpy if source is string constant. It's
1251 // better to use i32 to avoid the loads.
1255 if (Subtarget->is64Bit() && Size >= 8)
1260 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1261 /// current function. The returned value is a member of the
1262 /// MachineJumpTableInfo::JTEntryKind enum.
1263 unsigned X86TargetLowering::getJumpTableEncoding() const {
1264 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1266 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1267 Subtarget->isPICStyleGOT())
1268 return MachineJumpTableInfo::EK_Custom32;
1270 // Otherwise, use the normal jump table encoding heuristics.
1271 return TargetLowering::getJumpTableEncoding();
1275 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1276 const MachineBasicBlock *MBB,
1277 unsigned uid,MCContext &Ctx) const{
1278 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1279 Subtarget->isPICStyleGOT());
1280 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1282 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1283 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1286 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1288 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1289 SelectionDAG &DAG) const {
1290 if (!Subtarget->is64Bit())
1291 // This doesn't have DebugLoc associated with it, but is not really the
1292 // same as a Register.
1293 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1297 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1298 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1300 const MCExpr *X86TargetLowering::
1301 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1302 MCContext &Ctx) const {
1303 // X86-64 uses RIP relative addressing based on the jump table label.
1304 if (Subtarget->isPICStyleRIPRel())
1305 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1307 // Otherwise, the reference is relative to the PIC base.
1308 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1311 // FIXME: Why this routine is here? Move to RegInfo!
1312 std::pair<const TargetRegisterClass*, uint8_t>
1313 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1314 const TargetRegisterClass *RRC = 0;
1316 switch (VT.getSimpleVT().SimpleTy) {
1318 return TargetLowering::findRepresentativeClass(VT);
1319 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1320 RRC = (Subtarget->is64Bit()
1321 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1324 RRC = X86::VR64RegisterClass;
1326 case MVT::f32: case MVT::f64:
1327 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1328 case MVT::v4f32: case MVT::v2f64:
1329 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1331 RRC = X86::VR128RegisterClass;
1334 return std::make_pair(RRC, Cost);
1337 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1338 unsigned &Offset) const {
1339 if (!Subtarget->isTargetLinux())
1342 if (Subtarget->is64Bit()) {
1343 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1345 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1358 //===----------------------------------------------------------------------===//
1359 // Return Value Calling Convention Implementation
1360 //===----------------------------------------------------------------------===//
1362 #include "X86GenCallingConv.inc"
1365 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1366 MachineFunction &MF, bool isVarArg,
1367 const SmallVectorImpl<ISD::OutputArg> &Outs,
1368 LLVMContext &Context) const {
1369 SmallVector<CCValAssign, 16> RVLocs;
1370 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1372 return CCInfo.CheckReturn(Outs, RetCC_X86);
1376 X86TargetLowering::LowerReturn(SDValue Chain,
1377 CallingConv::ID CallConv, bool isVarArg,
1378 const SmallVectorImpl<ISD::OutputArg> &Outs,
1379 const SmallVectorImpl<SDValue> &OutVals,
1380 DebugLoc dl, SelectionDAG &DAG) const {
1381 MachineFunction &MF = DAG.getMachineFunction();
1382 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1384 SmallVector<CCValAssign, 16> RVLocs;
1385 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1386 RVLocs, *DAG.getContext());
1387 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1389 // Add the regs to the liveout set for the function.
1390 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1391 for (unsigned i = 0; i != RVLocs.size(); ++i)
1392 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1393 MRI.addLiveOut(RVLocs[i].getLocReg());
1397 SmallVector<SDValue, 6> RetOps;
1398 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1399 // Operand #1 = Bytes To Pop
1400 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1403 // Copy the result values into the output registers.
1404 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1405 CCValAssign &VA = RVLocs[i];
1406 assert(VA.isRegLoc() && "Can only return in registers!");
1407 SDValue ValToCopy = OutVals[i];
1408 EVT ValVT = ValToCopy.getValueType();
1410 // If this is x86-64, and we disabled SSE, we can't return FP values,
1411 // or SSE or MMX vectors.
1412 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1413 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1414 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1415 report_fatal_error("SSE register return with SSE disabled");
1417 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1418 // llvm-gcc has never done it right and no one has noticed, so this
1419 // should be OK for now.
1420 if (ValVT == MVT::f64 &&
1421 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1422 report_fatal_error("SSE2 register return with SSE2 disabled");
1424 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1425 // the RET instruction and handled by the FP Stackifier.
1426 if (VA.getLocReg() == X86::ST0 ||
1427 VA.getLocReg() == X86::ST1) {
1428 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1429 // change the value to the FP stack register class.
1430 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1431 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1432 RetOps.push_back(ValToCopy);
1433 // Don't emit a copytoreg.
1437 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1438 // which is returned in RAX / RDX.
1439 if (Subtarget->is64Bit()) {
1440 if (ValVT == MVT::x86mmx) {
1441 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1442 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1443 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1445 // If we don't have SSE2 available, convert to v4f32 so the generated
1446 // register is legal.
1447 if (!Subtarget->hasSSE2())
1448 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1453 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1454 Flag = Chain.getValue(1);
1457 // The x86-64 ABI for returning structs by value requires that we copy
1458 // the sret argument into %rax for the return. We saved the argument into
1459 // a virtual register in the entry block, so now we copy the value out
1461 if (Subtarget->is64Bit() &&
1462 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1463 MachineFunction &MF = DAG.getMachineFunction();
1464 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1465 unsigned Reg = FuncInfo->getSRetReturnReg();
1467 "SRetReturnReg should have been set in LowerFormalArguments().");
1468 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1470 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1471 Flag = Chain.getValue(1);
1473 // RAX now acts like a return value.
1474 MRI.addLiveOut(X86::RAX);
1477 RetOps[0] = Chain; // Update chain.
1479 // Add the flag if we have it.
1481 RetOps.push_back(Flag);
1483 return DAG.getNode(X86ISD::RET_FLAG, dl,
1484 MVT::Other, &RetOps[0], RetOps.size());
1487 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1488 if (N->getNumValues() != 1)
1490 if (!N->hasNUsesOfValue(1, 0))
1493 SDNode *Copy = *N->use_begin();
1494 if (Copy->getOpcode() != ISD::CopyToReg &&
1495 Copy->getOpcode() != ISD::FP_EXTEND)
1498 bool HasRet = false;
1499 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1501 if (UI->getOpcode() != X86ISD::RET_FLAG)
1510 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1511 ISD::NodeType ExtendKind) const {
1513 // TODO: Is this also valid on 32-bit?
1514 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1515 ReturnMVT = MVT::i8;
1517 ReturnMVT = MVT::i32;
1519 EVT MinVT = getRegisterType(Context, ReturnMVT);
1520 return VT.bitsLT(MinVT) ? MinVT : VT;
1523 /// LowerCallResult - Lower the result values of a call into the
1524 /// appropriate copies out of appropriate physical registers.
1527 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1528 CallingConv::ID CallConv, bool isVarArg,
1529 const SmallVectorImpl<ISD::InputArg> &Ins,
1530 DebugLoc dl, SelectionDAG &DAG,
1531 SmallVectorImpl<SDValue> &InVals) const {
1533 // Assign locations to each value returned by this call.
1534 SmallVector<CCValAssign, 16> RVLocs;
1535 bool Is64Bit = Subtarget->is64Bit();
1536 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1537 getTargetMachine(), RVLocs, *DAG.getContext());
1538 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1540 // Copy all of the result registers out of their specified physreg.
1541 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1542 CCValAssign &VA = RVLocs[i];
1543 EVT CopyVT = VA.getValVT();
1545 // If this is x86-64, and we disabled SSE, we can't return FP values
1546 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1547 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1548 report_fatal_error("SSE register return with SSE disabled");
1553 // If this is a call to a function that returns an fp value on the floating
1554 // point stack, we must guarantee the the value is popped from the stack, so
1555 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1556 // if the return value is not used. We use the FpPOP_RETVAL instruction
1558 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1559 // If we prefer to use the value in xmm registers, copy it out as f80 and
1560 // use a truncate to move it from fp stack reg to xmm reg.
1561 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1562 SDValue Ops[] = { Chain, InFlag };
1563 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1564 MVT::Other, MVT::Glue, Ops, 2), 1);
1565 Val = Chain.getValue(0);
1567 // Round the f80 to the right size, which also moves it to the appropriate
1569 if (CopyVT != VA.getValVT())
1570 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1571 // This truncation won't change the value.
1572 DAG.getIntPtrConstant(1));
1574 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1575 CopyVT, InFlag).getValue(1);
1576 Val = Chain.getValue(0);
1578 InFlag = Chain.getValue(2);
1579 InVals.push_back(Val);
1586 //===----------------------------------------------------------------------===//
1587 // C & StdCall & Fast Calling Convention implementation
1588 //===----------------------------------------------------------------------===//
1589 // StdCall calling convention seems to be standard for many Windows' API
1590 // routines and around. It differs from C calling convention just a little:
1591 // callee should clean up the stack, not caller. Symbols should be also
1592 // decorated in some fancy way :) It doesn't support any vector arguments.
1593 // For info on fast calling convention see Fast Calling Convention (tail call)
1594 // implementation LowerX86_32FastCCCallTo.
1596 /// CallIsStructReturn - Determines whether a call uses struct return
1598 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1602 return Outs[0].Flags.isSRet();
1605 /// ArgsAreStructReturn - Determines whether a function uses struct
1606 /// return semantics.
1608 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1612 return Ins[0].Flags.isSRet();
1615 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1616 /// by "Src" to address "Dst" with size and alignment information specified by
1617 /// the specific parameter attribute. The copy will be passed as a byval
1618 /// function parameter.
1620 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1621 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1623 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1625 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1626 /*isVolatile*/false, /*AlwaysInline=*/true,
1627 MachinePointerInfo(), MachinePointerInfo());
1630 /// IsTailCallConvention - Return true if the calling convention is one that
1631 /// supports tail call optimization.
1632 static bool IsTailCallConvention(CallingConv::ID CC) {
1633 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1636 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1637 if (!CI->isTailCall())
1641 CallingConv::ID CalleeCC = CS.getCallingConv();
1642 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1648 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1649 /// a tailcall target by changing its ABI.
1650 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1651 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1655 X86TargetLowering::LowerMemArgument(SDValue Chain,
1656 CallingConv::ID CallConv,
1657 const SmallVectorImpl<ISD::InputArg> &Ins,
1658 DebugLoc dl, SelectionDAG &DAG,
1659 const CCValAssign &VA,
1660 MachineFrameInfo *MFI,
1662 // Create the nodes corresponding to a load from this parameter slot.
1663 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1664 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1665 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1668 // If value is passed by pointer we have address passed instead of the value
1670 if (VA.getLocInfo() == CCValAssign::Indirect)
1671 ValVT = VA.getLocVT();
1673 ValVT = VA.getValVT();
1675 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1676 // changed with more analysis.
1677 // In case of tail call optimization mark all arguments mutable. Since they
1678 // could be overwritten by lowering of arguments in case of a tail call.
1679 if (Flags.isByVal()) {
1680 unsigned Bytes = Flags.getByValSize();
1681 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1682 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1683 return DAG.getFrameIndex(FI, getPointerTy());
1685 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1686 VA.getLocMemOffset(), isImmutable);
1687 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1688 return DAG.getLoad(ValVT, dl, Chain, FIN,
1689 MachinePointerInfo::getFixedStack(FI),
1695 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1696 CallingConv::ID CallConv,
1698 const SmallVectorImpl<ISD::InputArg> &Ins,
1701 SmallVectorImpl<SDValue> &InVals)
1703 MachineFunction &MF = DAG.getMachineFunction();
1704 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1706 const Function* Fn = MF.getFunction();
1707 if (Fn->hasExternalLinkage() &&
1708 Subtarget->isTargetCygMing() &&
1709 Fn->getName() == "main")
1710 FuncInfo->setForceFramePointer(true);
1712 MachineFrameInfo *MFI = MF.getFrameInfo();
1713 bool Is64Bit = Subtarget->is64Bit();
1714 bool IsWin64 = Subtarget->isTargetWin64();
1716 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1717 "Var args not supported with calling convention fastcc or ghc");
1719 // Assign locations to all of the incoming arguments.
1720 SmallVector<CCValAssign, 16> ArgLocs;
1721 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1722 ArgLocs, *DAG.getContext());
1724 // Allocate shadow area for Win64
1726 CCInfo.AllocateStack(32, 8);
1729 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1731 unsigned LastVal = ~0U;
1733 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1734 CCValAssign &VA = ArgLocs[i];
1735 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1737 assert(VA.getValNo() != LastVal &&
1738 "Don't support value assigned to multiple locs yet");
1739 LastVal = VA.getValNo();
1741 if (VA.isRegLoc()) {
1742 EVT RegVT = VA.getLocVT();
1743 TargetRegisterClass *RC = NULL;
1744 if (RegVT == MVT::i32)
1745 RC = X86::GR32RegisterClass;
1746 else if (Is64Bit && RegVT == MVT::i64)
1747 RC = X86::GR64RegisterClass;
1748 else if (RegVT == MVT::f32)
1749 RC = X86::FR32RegisterClass;
1750 else if (RegVT == MVT::f64)
1751 RC = X86::FR64RegisterClass;
1752 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1753 RC = X86::VR256RegisterClass;
1754 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1755 RC = X86::VR128RegisterClass;
1756 else if (RegVT == MVT::x86mmx)
1757 RC = X86::VR64RegisterClass;
1759 llvm_unreachable("Unknown argument type!");
1761 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1762 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1764 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1765 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1767 if (VA.getLocInfo() == CCValAssign::SExt)
1768 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1769 DAG.getValueType(VA.getValVT()));
1770 else if (VA.getLocInfo() == CCValAssign::ZExt)
1771 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1772 DAG.getValueType(VA.getValVT()));
1773 else if (VA.getLocInfo() == CCValAssign::BCvt)
1774 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1776 if (VA.isExtInLoc()) {
1777 // Handle MMX values passed in XMM regs.
1778 if (RegVT.isVector()) {
1779 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1782 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1785 assert(VA.isMemLoc());
1786 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1789 // If value is passed via pointer - do a load.
1790 if (VA.getLocInfo() == CCValAssign::Indirect)
1791 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1792 MachinePointerInfo(), false, false, 0);
1794 InVals.push_back(ArgValue);
1797 // The x86-64 ABI for returning structs by value requires that we copy
1798 // the sret argument into %rax for the return. Save the argument into
1799 // a virtual register so that we can access it from the return points.
1800 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1801 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1802 unsigned Reg = FuncInfo->getSRetReturnReg();
1804 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1805 FuncInfo->setSRetReturnReg(Reg);
1807 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1808 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1811 unsigned StackSize = CCInfo.getNextStackOffset();
1812 // Align stack specially for tail calls.
1813 if (FuncIsMadeTailCallSafe(CallConv))
1814 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1816 // If the function takes variable number of arguments, make a frame index for
1817 // the start of the first vararg value... for expansion of llvm.va_start.
1819 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1820 CallConv != CallingConv::X86_ThisCall)) {
1821 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1824 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1826 // FIXME: We should really autogenerate these arrays
1827 static const unsigned GPR64ArgRegsWin64[] = {
1828 X86::RCX, X86::RDX, X86::R8, X86::R9
1830 static const unsigned GPR64ArgRegs64Bit[] = {
1831 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1833 static const unsigned XMMArgRegs64Bit[] = {
1834 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1835 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1837 const unsigned *GPR64ArgRegs;
1838 unsigned NumXMMRegs = 0;
1841 // The XMM registers which might contain var arg parameters are shadowed
1842 // in their paired GPR. So we only need to save the GPR to their home
1844 TotalNumIntRegs = 4;
1845 GPR64ArgRegs = GPR64ArgRegsWin64;
1847 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1848 GPR64ArgRegs = GPR64ArgRegs64Bit;
1850 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1852 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1855 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1856 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1857 "SSE register cannot be used when SSE is disabled!");
1858 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1859 "SSE register cannot be used when SSE is disabled!");
1860 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1861 // Kernel mode asks for SSE to be disabled, so don't push them
1863 TotalNumXMMRegs = 0;
1866 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1867 // Get to the caller-allocated home save location. Add 8 to account
1868 // for the return address.
1869 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1870 FuncInfo->setRegSaveFrameIndex(
1871 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1872 // Fixup to set vararg frame on shadow area (4 x i64).
1874 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1876 // For X86-64, if there are vararg parameters that are passed via
1877 // registers, then we must store them to their spots on the stack so they
1878 // may be loaded by deferencing the result of va_next.
1879 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1880 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1881 FuncInfo->setRegSaveFrameIndex(
1882 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1886 // Store the integer parameter registers.
1887 SmallVector<SDValue, 8> MemOps;
1888 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1890 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1891 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1892 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1893 DAG.getIntPtrConstant(Offset));
1894 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1895 X86::GR64RegisterClass);
1896 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1898 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1899 MachinePointerInfo::getFixedStack(
1900 FuncInfo->getRegSaveFrameIndex(), Offset),
1902 MemOps.push_back(Store);
1906 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1907 // Now store the XMM (fp + vector) parameter registers.
1908 SmallVector<SDValue, 11> SaveXMMOps;
1909 SaveXMMOps.push_back(Chain);
1911 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1912 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1913 SaveXMMOps.push_back(ALVal);
1915 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1916 FuncInfo->getRegSaveFrameIndex()));
1917 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1918 FuncInfo->getVarArgsFPOffset()));
1920 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1921 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1922 X86::VR128RegisterClass);
1923 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1924 SaveXMMOps.push_back(Val);
1926 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1928 &SaveXMMOps[0], SaveXMMOps.size()));
1931 if (!MemOps.empty())
1932 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1933 &MemOps[0], MemOps.size());
1937 // Some CCs need callee pop.
1938 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1939 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1941 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1942 // If this is an sret function, the return should pop the hidden pointer.
1943 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1944 FuncInfo->setBytesToPopOnReturn(4);
1948 // RegSaveFrameIndex is X86-64 only.
1949 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1950 if (CallConv == CallingConv::X86_FastCall ||
1951 CallConv == CallingConv::X86_ThisCall)
1952 // fastcc functions can't have varargs.
1953 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1956 FuncInfo->setArgumentStackSize(StackSize);
1962 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1963 SDValue StackPtr, SDValue Arg,
1964 DebugLoc dl, SelectionDAG &DAG,
1965 const CCValAssign &VA,
1966 ISD::ArgFlagsTy Flags) const {
1967 unsigned LocMemOffset = VA.getLocMemOffset();
1968 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1969 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1970 if (Flags.isByVal())
1971 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1973 return DAG.getStore(Chain, dl, Arg, PtrOff,
1974 MachinePointerInfo::getStack(LocMemOffset),
1978 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1979 /// optimization is performed and it is required.
1981 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1982 SDValue &OutRetAddr, SDValue Chain,
1983 bool IsTailCall, bool Is64Bit,
1984 int FPDiff, DebugLoc dl) const {
1985 // Adjust the Return address stack slot.
1986 EVT VT = getPointerTy();
1987 OutRetAddr = getReturnAddressFrameIndex(DAG);
1989 // Load the "old" Return address.
1990 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1992 return SDValue(OutRetAddr.getNode(), 1);
1995 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1996 /// optimization is performed and it is required (FPDiff!=0).
1998 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1999 SDValue Chain, SDValue RetAddrFrIdx,
2000 bool Is64Bit, int FPDiff, DebugLoc dl) {
2001 // Store the return address to the appropriate stack slot.
2002 if (!FPDiff) return Chain;
2003 // Calculate the new stack slot for the return address.
2004 int SlotSize = Is64Bit ? 8 : 4;
2005 int NewReturnAddrFI =
2006 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2007 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2008 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2009 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2010 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2016 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2017 CallingConv::ID CallConv, bool isVarArg,
2019 const SmallVectorImpl<ISD::OutputArg> &Outs,
2020 const SmallVectorImpl<SDValue> &OutVals,
2021 const SmallVectorImpl<ISD::InputArg> &Ins,
2022 DebugLoc dl, SelectionDAG &DAG,
2023 SmallVectorImpl<SDValue> &InVals) const {
2024 MachineFunction &MF = DAG.getMachineFunction();
2025 bool Is64Bit = Subtarget->is64Bit();
2026 bool IsWin64 = Subtarget->isTargetWin64();
2027 bool IsStructRet = CallIsStructReturn(Outs);
2028 bool IsSibcall = false;
2031 // Check if it's really possible to do a tail call.
2032 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2033 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2034 Outs, OutVals, Ins, DAG);
2036 // Sibcalls are automatically detected tailcalls which do not require
2038 if (!GuaranteedTailCallOpt && isTailCall)
2045 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2046 "Var args not supported with calling convention fastcc or ghc");
2048 // Analyze operands of the call, assigning locations to each operand.
2049 SmallVector<CCValAssign, 16> ArgLocs;
2050 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2051 ArgLocs, *DAG.getContext());
2053 // Allocate shadow area for Win64
2055 CCInfo.AllocateStack(32, 8);
2058 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2060 // Get a count of how many bytes are to be pushed on the stack.
2061 unsigned NumBytes = CCInfo.getNextStackOffset();
2063 // This is a sibcall. The memory operands are available in caller's
2064 // own caller's stack.
2066 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2067 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2070 if (isTailCall && !IsSibcall) {
2071 // Lower arguments at fp - stackoffset + fpdiff.
2072 unsigned NumBytesCallerPushed =
2073 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2074 FPDiff = NumBytesCallerPushed - NumBytes;
2076 // Set the delta of movement of the returnaddr stackslot.
2077 // But only set if delta is greater than previous delta.
2078 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2079 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2083 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2085 SDValue RetAddrFrIdx;
2086 // Load return address for tail calls.
2087 if (isTailCall && FPDiff)
2088 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2089 Is64Bit, FPDiff, dl);
2091 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2092 SmallVector<SDValue, 8> MemOpChains;
2095 // Walk the register/memloc assignments, inserting copies/loads. In the case
2096 // of tail call optimization arguments are handle later.
2097 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2098 CCValAssign &VA = ArgLocs[i];
2099 EVT RegVT = VA.getLocVT();
2100 SDValue Arg = OutVals[i];
2101 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2102 bool isByVal = Flags.isByVal();
2104 // Promote the value if needed.
2105 switch (VA.getLocInfo()) {
2106 default: llvm_unreachable("Unknown loc info!");
2107 case CCValAssign::Full: break;
2108 case CCValAssign::SExt:
2109 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2111 case CCValAssign::ZExt:
2112 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2114 case CCValAssign::AExt:
2115 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2116 // Special case: passing MMX values in XMM registers.
2117 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2118 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2119 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2121 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2123 case CCValAssign::BCvt:
2124 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2126 case CCValAssign::Indirect: {
2127 // Store the argument.
2128 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2129 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2130 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2131 MachinePointerInfo::getFixedStack(FI),
2138 if (VA.isRegLoc()) {
2139 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2140 if (isVarArg && IsWin64) {
2141 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2142 // shadow reg if callee is a varargs function.
2143 unsigned ShadowReg = 0;
2144 switch (VA.getLocReg()) {
2145 case X86::XMM0: ShadowReg = X86::RCX; break;
2146 case X86::XMM1: ShadowReg = X86::RDX; break;
2147 case X86::XMM2: ShadowReg = X86::R8; break;
2148 case X86::XMM3: ShadowReg = X86::R9; break;
2151 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2153 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2154 assert(VA.isMemLoc());
2155 if (StackPtr.getNode() == 0)
2156 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2157 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2158 dl, DAG, VA, Flags));
2162 if (!MemOpChains.empty())
2163 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2164 &MemOpChains[0], MemOpChains.size());
2166 // Build a sequence of copy-to-reg nodes chained together with token chain
2167 // and flag operands which copy the outgoing args into registers.
2169 // Tail call byval lowering might overwrite argument registers so in case of
2170 // tail call optimization the copies to registers are lowered later.
2172 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2173 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2174 RegsToPass[i].second, InFlag);
2175 InFlag = Chain.getValue(1);
2178 if (Subtarget->isPICStyleGOT()) {
2179 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2182 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2183 DAG.getNode(X86ISD::GlobalBaseReg,
2184 DebugLoc(), getPointerTy()),
2186 InFlag = Chain.getValue(1);
2188 // If we are tail calling and generating PIC/GOT style code load the
2189 // address of the callee into ECX. The value in ecx is used as target of
2190 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2191 // for tail calls on PIC/GOT architectures. Normally we would just put the
2192 // address of GOT into ebx and then call target@PLT. But for tail calls
2193 // ebx would be restored (since ebx is callee saved) before jumping to the
2196 // Note: The actual moving to ECX is done further down.
2197 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2198 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2199 !G->getGlobal()->hasProtectedVisibility())
2200 Callee = LowerGlobalAddress(Callee, DAG);
2201 else if (isa<ExternalSymbolSDNode>(Callee))
2202 Callee = LowerExternalSymbol(Callee, DAG);
2206 if (Is64Bit && isVarArg && !IsWin64) {
2207 // From AMD64 ABI document:
2208 // For calls that may call functions that use varargs or stdargs
2209 // (prototype-less calls or calls to functions containing ellipsis (...) in
2210 // the declaration) %al is used as hidden argument to specify the number
2211 // of SSE registers used. The contents of %al do not need to match exactly
2212 // the number of registers, but must be an ubound on the number of SSE
2213 // registers used and is in the range 0 - 8 inclusive.
2215 // Count the number of XMM registers allocated.
2216 static const unsigned XMMArgRegs[] = {
2217 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2218 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2220 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2221 assert((Subtarget->hasXMM() || !NumXMMRegs)
2222 && "SSE registers cannot be used when SSE is disabled");
2224 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2225 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2226 InFlag = Chain.getValue(1);
2230 // For tail calls lower the arguments to the 'real' stack slot.
2232 // Force all the incoming stack arguments to be loaded from the stack
2233 // before any new outgoing arguments are stored to the stack, because the
2234 // outgoing stack slots may alias the incoming argument stack slots, and
2235 // the alias isn't otherwise explicit. This is slightly more conservative
2236 // than necessary, because it means that each store effectively depends
2237 // on every argument instead of just those arguments it would clobber.
2238 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2240 SmallVector<SDValue, 8> MemOpChains2;
2243 // Do not flag preceding copytoreg stuff together with the following stuff.
2245 if (GuaranteedTailCallOpt) {
2246 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247 CCValAssign &VA = ArgLocs[i];
2250 assert(VA.isMemLoc());
2251 SDValue Arg = OutVals[i];
2252 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2253 // Create frame index.
2254 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2255 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2256 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2257 FIN = DAG.getFrameIndex(FI, getPointerTy());
2259 if (Flags.isByVal()) {
2260 // Copy relative to framepointer.
2261 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2262 if (StackPtr.getNode() == 0)
2263 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2265 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2267 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2271 // Store relative to framepointer.
2272 MemOpChains2.push_back(
2273 DAG.getStore(ArgChain, dl, Arg, FIN,
2274 MachinePointerInfo::getFixedStack(FI),
2280 if (!MemOpChains2.empty())
2281 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2282 &MemOpChains2[0], MemOpChains2.size());
2284 // Copy arguments to their registers.
2285 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2286 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2287 RegsToPass[i].second, InFlag);
2288 InFlag = Chain.getValue(1);
2292 // Store the return address to the appropriate stack slot.
2293 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2297 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2298 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2299 // In the 64-bit large code model, we have to make all calls
2300 // through a register, since the call instruction's 32-bit
2301 // pc-relative offset may not be large enough to hold the whole
2303 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2304 // If the callee is a GlobalAddress node (quite common, every direct call
2305 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2308 // We should use extra load for direct calls to dllimported functions in
2310 const GlobalValue *GV = G->getGlobal();
2311 if (!GV->hasDLLImportLinkage()) {
2312 unsigned char OpFlags = 0;
2313 bool ExtraLoad = false;
2314 unsigned WrapperKind = ISD::DELETED_NODE;
2316 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2317 // external symbols most go through the PLT in PIC mode. If the symbol
2318 // has hidden or protected visibility, or if it is static or local, then
2319 // we don't need to use the PLT - we can directly call it.
2320 if (Subtarget->isTargetELF() &&
2321 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2322 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2323 OpFlags = X86II::MO_PLT;
2324 } else if (Subtarget->isPICStyleStubAny() &&
2325 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2326 (!Subtarget->getTargetTriple().isMacOSX() ||
2327 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2328 // PC-relative references to external symbols should go through $stub,
2329 // unless we're building with the leopard linker or later, which
2330 // automatically synthesizes these stubs.
2331 OpFlags = X86II::MO_DARWIN_STUB;
2332 } else if (Subtarget->isPICStyleRIPRel() &&
2333 isa<Function>(GV) &&
2334 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2335 // If the function is marked as non-lazy, generate an indirect call
2336 // which loads from the GOT directly. This avoids runtime overhead
2337 // at the cost of eager binding (and one extra byte of encoding).
2338 OpFlags = X86II::MO_GOTPCREL;
2339 WrapperKind = X86ISD::WrapperRIP;
2343 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2344 G->getOffset(), OpFlags);
2346 // Add a wrapper if needed.
2347 if (WrapperKind != ISD::DELETED_NODE)
2348 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2349 // Add extra indirection if needed.
2351 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2352 MachinePointerInfo::getGOT(),
2355 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2356 unsigned char OpFlags = 0;
2358 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2359 // external symbols should go through the PLT.
2360 if (Subtarget->isTargetELF() &&
2361 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2362 OpFlags = X86II::MO_PLT;
2363 } else if (Subtarget->isPICStyleStubAny() &&
2364 (!Subtarget->getTargetTriple().isMacOSX() ||
2365 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2366 // PC-relative references to external symbols should go through $stub,
2367 // unless we're building with the leopard linker or later, which
2368 // automatically synthesizes these stubs.
2369 OpFlags = X86II::MO_DARWIN_STUB;
2372 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2376 // Returns a chain & a flag for retval copy to use.
2377 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2378 SmallVector<SDValue, 8> Ops;
2380 if (!IsSibcall && isTailCall) {
2381 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2382 DAG.getIntPtrConstant(0, true), InFlag);
2383 InFlag = Chain.getValue(1);
2386 Ops.push_back(Chain);
2387 Ops.push_back(Callee);
2390 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2392 // Add argument registers to the end of the list so that they are known live
2394 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2395 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2396 RegsToPass[i].second.getValueType()));
2398 // Add an implicit use GOT pointer in EBX.
2399 if (!isTailCall && Subtarget->isPICStyleGOT())
2400 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2402 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2403 if (Is64Bit && isVarArg && !IsWin64)
2404 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2406 if (InFlag.getNode())
2407 Ops.push_back(InFlag);
2411 //// If this is the first return lowered for this function, add the regs
2412 //// to the liveout set for the function.
2413 // This isn't right, although it's probably harmless on x86; liveouts
2414 // should be computed from returns not tail calls. Consider a void
2415 // function making a tail call to a function returning int.
2416 return DAG.getNode(X86ISD::TC_RETURN, dl,
2417 NodeTys, &Ops[0], Ops.size());
2420 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2421 InFlag = Chain.getValue(1);
2423 // Create the CALLSEQ_END node.
2424 unsigned NumBytesForCalleeToPush;
2425 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2426 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2427 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2428 // If this is a call to a struct-return function, the callee
2429 // pops the hidden struct pointer, so we have to push it back.
2430 // This is common for Darwin/X86, Linux & Mingw32 targets.
2431 NumBytesForCalleeToPush = 4;
2433 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2435 // Returns a flag for retval copy to use.
2437 Chain = DAG.getCALLSEQ_END(Chain,
2438 DAG.getIntPtrConstant(NumBytes, true),
2439 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2442 InFlag = Chain.getValue(1);
2445 // Handle result values, copying them out of physregs into vregs that we
2447 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2448 Ins, dl, DAG, InVals);
2452 //===----------------------------------------------------------------------===//
2453 // Fast Calling Convention (tail call) implementation
2454 //===----------------------------------------------------------------------===//
2456 // Like std call, callee cleans arguments, convention except that ECX is
2457 // reserved for storing the tail called function address. Only 2 registers are
2458 // free for argument passing (inreg). Tail call optimization is performed
2460 // * tailcallopt is enabled
2461 // * caller/callee are fastcc
2462 // On X86_64 architecture with GOT-style position independent code only local
2463 // (within module) calls are supported at the moment.
2464 // To keep the stack aligned according to platform abi the function
2465 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2466 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2467 // If a tail called function callee has more arguments than the caller the
2468 // caller needs to make sure that there is room to move the RETADDR to. This is
2469 // achieved by reserving an area the size of the argument delta right after the
2470 // original REtADDR, but before the saved framepointer or the spilled registers
2471 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2483 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2484 /// for a 16 byte align requirement.
2486 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2487 SelectionDAG& DAG) const {
2488 MachineFunction &MF = DAG.getMachineFunction();
2489 const TargetMachine &TM = MF.getTarget();
2490 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2491 unsigned StackAlignment = TFI.getStackAlignment();
2492 uint64_t AlignMask = StackAlignment - 1;
2493 int64_t Offset = StackSize;
2494 uint64_t SlotSize = TD->getPointerSize();
2495 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2496 // Number smaller than 12 so just add the difference.
2497 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2499 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2500 Offset = ((~AlignMask) & Offset) + StackAlignment +
2501 (StackAlignment-SlotSize);
2506 /// MatchingStackOffset - Return true if the given stack call argument is
2507 /// already available in the same position (relatively) of the caller's
2508 /// incoming argument stack.
2510 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2511 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2512 const X86InstrInfo *TII) {
2513 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2515 if (Arg.getOpcode() == ISD::CopyFromReg) {
2516 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2517 if (!TargetRegisterInfo::isVirtualRegister(VR))
2519 MachineInstr *Def = MRI->getVRegDef(VR);
2522 if (!Flags.isByVal()) {
2523 if (!TII->isLoadFromStackSlot(Def, FI))
2526 unsigned Opcode = Def->getOpcode();
2527 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2528 Def->getOperand(1).isFI()) {
2529 FI = Def->getOperand(1).getIndex();
2530 Bytes = Flags.getByValSize();
2534 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2535 if (Flags.isByVal())
2536 // ByVal argument is passed in as a pointer but it's now being
2537 // dereferenced. e.g.
2538 // define @foo(%struct.X* %A) {
2539 // tail call @bar(%struct.X* byval %A)
2542 SDValue Ptr = Ld->getBasePtr();
2543 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2546 FI = FINode->getIndex();
2547 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2548 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2549 FI = FINode->getIndex();
2550 Bytes = Flags.getByValSize();
2554 assert(FI != INT_MAX);
2555 if (!MFI->isFixedObjectIndex(FI))
2557 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2560 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2561 /// for tail call optimization. Targets which want to do tail call
2562 /// optimization should implement this function.
2564 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2565 CallingConv::ID CalleeCC,
2567 bool isCalleeStructRet,
2568 bool isCallerStructRet,
2569 const SmallVectorImpl<ISD::OutputArg> &Outs,
2570 const SmallVectorImpl<SDValue> &OutVals,
2571 const SmallVectorImpl<ISD::InputArg> &Ins,
2572 SelectionDAG& DAG) const {
2573 if (!IsTailCallConvention(CalleeCC) &&
2574 CalleeCC != CallingConv::C)
2577 // If -tailcallopt is specified, make fastcc functions tail-callable.
2578 const MachineFunction &MF = DAG.getMachineFunction();
2579 const Function *CallerF = DAG.getMachineFunction().getFunction();
2580 CallingConv::ID CallerCC = CallerF->getCallingConv();
2581 bool CCMatch = CallerCC == CalleeCC;
2583 if (GuaranteedTailCallOpt) {
2584 if (IsTailCallConvention(CalleeCC) && CCMatch)
2589 // Look for obvious safe cases to perform tail call optimization that do not
2590 // require ABI changes. This is what gcc calls sibcall.
2592 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2593 // emit a special epilogue.
2594 if (RegInfo->needsStackRealignment(MF))
2597 // Also avoid sibcall optimization if either caller or callee uses struct
2598 // return semantics.
2599 if (isCalleeStructRet || isCallerStructRet)
2602 // An stdcall caller is expected to clean up its arguments; the callee
2603 // isn't going to do that.
2604 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2607 // Do not sibcall optimize vararg calls unless all arguments are passed via
2609 if (isVarArg && !Outs.empty()) {
2611 // Optimizing for varargs on Win64 is unlikely to be safe without
2612 // additional testing.
2613 if (Subtarget->isTargetWin64())
2616 SmallVector<CCValAssign, 16> ArgLocs;
2617 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2618 getTargetMachine(), ArgLocs, *DAG.getContext());
2620 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2621 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2622 if (!ArgLocs[i].isRegLoc())
2626 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2627 // Therefore if it's not used by the call it is not safe to optimize this into
2629 bool Unused = false;
2630 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2637 SmallVector<CCValAssign, 16> RVLocs;
2638 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2639 getTargetMachine(), RVLocs, *DAG.getContext());
2640 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2641 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2642 CCValAssign &VA = RVLocs[i];
2643 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2648 // If the calling conventions do not match, then we'd better make sure the
2649 // results are returned in the same way as what the caller expects.
2651 SmallVector<CCValAssign, 16> RVLocs1;
2652 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2653 getTargetMachine(), RVLocs1, *DAG.getContext());
2654 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2656 SmallVector<CCValAssign, 16> RVLocs2;
2657 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2658 getTargetMachine(), RVLocs2, *DAG.getContext());
2659 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2661 if (RVLocs1.size() != RVLocs2.size())
2663 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2664 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2666 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2668 if (RVLocs1[i].isRegLoc()) {
2669 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2672 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2678 // If the callee takes no arguments then go on to check the results of the
2680 if (!Outs.empty()) {
2681 // Check if stack adjustment is needed. For now, do not do this if any
2682 // argument is passed on the stack.
2683 SmallVector<CCValAssign, 16> ArgLocs;
2684 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2685 getTargetMachine(), ArgLocs, *DAG.getContext());
2687 // Allocate shadow area for Win64
2688 if (Subtarget->isTargetWin64()) {
2689 CCInfo.AllocateStack(32, 8);
2692 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2693 if (CCInfo.getNextStackOffset()) {
2694 MachineFunction &MF = DAG.getMachineFunction();
2695 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2698 // Check if the arguments are already laid out in the right way as
2699 // the caller's fixed stack objects.
2700 MachineFrameInfo *MFI = MF.getFrameInfo();
2701 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2702 const X86InstrInfo *TII =
2703 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2704 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2705 CCValAssign &VA = ArgLocs[i];
2706 SDValue Arg = OutVals[i];
2707 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2708 if (VA.getLocInfo() == CCValAssign::Indirect)
2710 if (!VA.isRegLoc()) {
2711 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2718 // If the tailcall address may be in a register, then make sure it's
2719 // possible to register allocate for it. In 32-bit, the call address can
2720 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2721 // callee-saved registers are restored. These happen to be the same
2722 // registers used to pass 'inreg' arguments so watch out for those.
2723 if (!Subtarget->is64Bit() &&
2724 !isa<GlobalAddressSDNode>(Callee) &&
2725 !isa<ExternalSymbolSDNode>(Callee)) {
2726 unsigned NumInRegs = 0;
2727 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2728 CCValAssign &VA = ArgLocs[i];
2731 unsigned Reg = VA.getLocReg();
2734 case X86::EAX: case X86::EDX: case X86::ECX:
2735 if (++NumInRegs == 3)
2747 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2748 return X86::createFastISel(funcInfo);
2752 //===----------------------------------------------------------------------===//
2753 // Other Lowering Hooks
2754 //===----------------------------------------------------------------------===//
2756 static bool MayFoldLoad(SDValue Op) {
2757 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2760 static bool MayFoldIntoStore(SDValue Op) {
2761 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2764 static bool isTargetShuffle(unsigned Opcode) {
2766 default: return false;
2767 case X86ISD::PSHUFD:
2768 case X86ISD::PSHUFHW:
2769 case X86ISD::PSHUFLW:
2770 case X86ISD::SHUFPD:
2771 case X86ISD::PALIGN:
2772 case X86ISD::SHUFPS:
2773 case X86ISD::MOVLHPS:
2774 case X86ISD::MOVLHPD:
2775 case X86ISD::MOVHLPS:
2776 case X86ISD::MOVLPS:
2777 case X86ISD::MOVLPD:
2778 case X86ISD::MOVSHDUP:
2779 case X86ISD::MOVSLDUP:
2780 case X86ISD::MOVDDUP:
2783 case X86ISD::UNPCKLPS:
2784 case X86ISD::UNPCKLPD:
2785 case X86ISD::VUNPCKLPSY:
2786 case X86ISD::VUNPCKLPDY:
2787 case X86ISD::PUNPCKLWD:
2788 case X86ISD::PUNPCKLBW:
2789 case X86ISD::PUNPCKLDQ:
2790 case X86ISD::PUNPCKLQDQ:
2791 case X86ISD::UNPCKHPS:
2792 case X86ISD::UNPCKHPD:
2793 case X86ISD::VUNPCKHPSY:
2794 case X86ISD::VUNPCKHPDY:
2795 case X86ISD::PUNPCKHWD:
2796 case X86ISD::PUNPCKHBW:
2797 case X86ISD::PUNPCKHDQ:
2798 case X86ISD::PUNPCKHQDQ:
2799 case X86ISD::VPERMILPS:
2800 case X86ISD::VPERMILPSY:
2801 case X86ISD::VPERMILPD:
2802 case X86ISD::VPERMILPDY:
2803 case X86ISD::VPERM2F128:
2809 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2810 SDValue V1, SelectionDAG &DAG) {
2812 default: llvm_unreachable("Unknown x86 shuffle node");
2813 case X86ISD::MOVSHDUP:
2814 case X86ISD::MOVSLDUP:
2815 case X86ISD::MOVDDUP:
2816 return DAG.getNode(Opc, dl, VT, V1);
2822 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2823 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2825 default: llvm_unreachable("Unknown x86 shuffle node");
2826 case X86ISD::PSHUFD:
2827 case X86ISD::PSHUFHW:
2828 case X86ISD::PSHUFLW:
2829 case X86ISD::VPERMILPS:
2830 case X86ISD::VPERMILPSY:
2831 case X86ISD::VPERMILPD:
2832 case X86ISD::VPERMILPDY:
2833 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2839 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2840 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2842 default: llvm_unreachable("Unknown x86 shuffle node");
2843 case X86ISD::PALIGN:
2844 case X86ISD::SHUFPD:
2845 case X86ISD::SHUFPS:
2846 case X86ISD::VPERM2F128:
2847 return DAG.getNode(Opc, dl, VT, V1, V2,
2848 DAG.getConstant(TargetMask, MVT::i8));
2853 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2854 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2856 default: llvm_unreachable("Unknown x86 shuffle node");
2857 case X86ISD::MOVLHPS:
2858 case X86ISD::MOVLHPD:
2859 case X86ISD::MOVHLPS:
2860 case X86ISD::MOVLPS:
2861 case X86ISD::MOVLPD:
2864 case X86ISD::UNPCKLPS:
2865 case X86ISD::UNPCKLPD:
2866 case X86ISD::VUNPCKLPSY:
2867 case X86ISD::VUNPCKLPDY:
2868 case X86ISD::PUNPCKLWD:
2869 case X86ISD::PUNPCKLBW:
2870 case X86ISD::PUNPCKLDQ:
2871 case X86ISD::PUNPCKLQDQ:
2872 case X86ISD::UNPCKHPS:
2873 case X86ISD::UNPCKHPD:
2874 case X86ISD::VUNPCKHPSY:
2875 case X86ISD::VUNPCKHPDY:
2876 case X86ISD::PUNPCKHWD:
2877 case X86ISD::PUNPCKHBW:
2878 case X86ISD::PUNPCKHDQ:
2879 case X86ISD::PUNPCKHQDQ:
2880 return DAG.getNode(Opc, dl, VT, V1, V2);
2885 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2886 MachineFunction &MF = DAG.getMachineFunction();
2887 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2888 int ReturnAddrIndex = FuncInfo->getRAIndex();
2890 if (ReturnAddrIndex == 0) {
2891 // Set up a frame object for the return address.
2892 uint64_t SlotSize = TD->getPointerSize();
2893 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2895 FuncInfo->setRAIndex(ReturnAddrIndex);
2898 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2902 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2903 bool hasSymbolicDisplacement) {
2904 // Offset should fit into 32 bit immediate field.
2905 if (!isInt<32>(Offset))
2908 // If we don't have a symbolic displacement - we don't have any extra
2910 if (!hasSymbolicDisplacement)
2913 // FIXME: Some tweaks might be needed for medium code model.
2914 if (M != CodeModel::Small && M != CodeModel::Kernel)
2917 // For small code model we assume that latest object is 16MB before end of 31
2918 // bits boundary. We may also accept pretty large negative constants knowing
2919 // that all objects are in the positive half of address space.
2920 if (M == CodeModel::Small && Offset < 16*1024*1024)
2923 // For kernel code model we know that all object resist in the negative half
2924 // of 32bits address space. We may not accept negative offsets, since they may
2925 // be just off and we may accept pretty large positive ones.
2926 if (M == CodeModel::Kernel && Offset > 0)
2932 /// isCalleePop - Determines whether the callee is required to pop its
2933 /// own arguments. Callee pop is necessary to support tail calls.
2934 bool X86::isCalleePop(CallingConv::ID CallingConv,
2935 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2939 switch (CallingConv) {
2942 case CallingConv::X86_StdCall:
2944 case CallingConv::X86_FastCall:
2946 case CallingConv::X86_ThisCall:
2948 case CallingConv::Fast:
2950 case CallingConv::GHC:
2955 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2956 /// specific condition code, returning the condition code and the LHS/RHS of the
2957 /// comparison to make.
2958 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2959 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2961 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2962 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2963 // X > -1 -> X == 0, jump !sign.
2964 RHS = DAG.getConstant(0, RHS.getValueType());
2965 return X86::COND_NS;
2966 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2967 // X < 0 -> X == 0, jump on sign.
2969 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2971 RHS = DAG.getConstant(0, RHS.getValueType());
2972 return X86::COND_LE;
2976 switch (SetCCOpcode) {
2977 default: llvm_unreachable("Invalid integer condition!");
2978 case ISD::SETEQ: return X86::COND_E;
2979 case ISD::SETGT: return X86::COND_G;
2980 case ISD::SETGE: return X86::COND_GE;
2981 case ISD::SETLT: return X86::COND_L;
2982 case ISD::SETLE: return X86::COND_LE;
2983 case ISD::SETNE: return X86::COND_NE;
2984 case ISD::SETULT: return X86::COND_B;
2985 case ISD::SETUGT: return X86::COND_A;
2986 case ISD::SETULE: return X86::COND_BE;
2987 case ISD::SETUGE: return X86::COND_AE;
2991 // First determine if it is required or is profitable to flip the operands.
2993 // If LHS is a foldable load, but RHS is not, flip the condition.
2994 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2995 !ISD::isNON_EXTLoad(RHS.getNode())) {
2996 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2997 std::swap(LHS, RHS);
3000 switch (SetCCOpcode) {
3006 std::swap(LHS, RHS);
3010 // On a floating point condition, the flags are set as follows:
3012 // 0 | 0 | 0 | X > Y
3013 // 0 | 0 | 1 | X < Y
3014 // 1 | 0 | 0 | X == Y
3015 // 1 | 1 | 1 | unordered
3016 switch (SetCCOpcode) {
3017 default: llvm_unreachable("Condcode should be pre-legalized away");
3019 case ISD::SETEQ: return X86::COND_E;
3020 case ISD::SETOLT: // flipped
3022 case ISD::SETGT: return X86::COND_A;
3023 case ISD::SETOLE: // flipped
3025 case ISD::SETGE: return X86::COND_AE;
3026 case ISD::SETUGT: // flipped
3028 case ISD::SETLT: return X86::COND_B;
3029 case ISD::SETUGE: // flipped
3031 case ISD::SETLE: return X86::COND_BE;
3033 case ISD::SETNE: return X86::COND_NE;
3034 case ISD::SETUO: return X86::COND_P;
3035 case ISD::SETO: return X86::COND_NP;
3037 case ISD::SETUNE: return X86::COND_INVALID;
3041 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3042 /// code. Current x86 isa includes the following FP cmov instructions:
3043 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3044 static bool hasFPCMov(unsigned X86CC) {
3060 /// isFPImmLegal - Returns true if the target can instruction select the
3061 /// specified FP immediate natively. If false, the legalizer will
3062 /// materialize the FP immediate as a load from a constant pool.
3063 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3064 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3065 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3071 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3072 /// the specified range (L, H].
3073 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3074 return (Val < 0) || (Val >= Low && Val < Hi);
3077 /// isUndefOrInRange - Return true if every element in Mask, begining
3078 /// from position Pos and ending in Pos+Size, falls within the specified
3079 /// range (L, L+Pos]. or is undef.
3080 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3081 int Pos, int Size, int Low, int Hi) {
3082 for (int i = Pos, e = Pos+Size; i != e; ++i)
3083 if (!isUndefOrInRange(Mask[i], Low, Hi))
3088 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3089 /// specified value.
3090 static bool isUndefOrEqual(int Val, int CmpVal) {
3091 if (Val < 0 || Val == CmpVal)
3096 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3097 /// from position Pos and ending in Pos+Size, falls within the specified
3098 /// sequential range (L, L+Pos]. or is undef.
3099 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3100 int Pos, int Size, int Low) {
3101 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3102 if (!isUndefOrEqual(Mask[i], Low))
3107 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3108 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3109 /// the second operand.
3110 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3111 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3112 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3113 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3114 return (Mask[0] < 2 && Mask[1] < 2);
3118 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3119 SmallVector<int, 8> M;
3121 return ::isPSHUFDMask(M, N->getValueType(0));
3124 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3125 /// is suitable for input to PSHUFHW.
3126 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3127 if (VT != MVT::v8i16)
3130 // Lower quadword copied in order or undef.
3131 for (int i = 0; i != 4; ++i)
3132 if (Mask[i] >= 0 && Mask[i] != i)
3135 // Upper quadword shuffled.
3136 for (int i = 4; i != 8; ++i)
3137 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3143 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3144 SmallVector<int, 8> M;
3146 return ::isPSHUFHWMask(M, N->getValueType(0));
3149 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3150 /// is suitable for input to PSHUFLW.
3151 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3152 if (VT != MVT::v8i16)
3155 // Upper quadword copied in order.
3156 for (int i = 4; i != 8; ++i)
3157 if (Mask[i] >= 0 && Mask[i] != i)
3160 // Lower quadword shuffled.
3161 for (int i = 0; i != 4; ++i)
3168 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3169 SmallVector<int, 8> M;
3171 return ::isPSHUFLWMask(M, N->getValueType(0));
3174 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3175 /// is suitable for input to PALIGNR.
3176 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3178 int i, e = VT.getVectorNumElements();
3179 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3182 // Do not handle v2i64 / v2f64 shuffles with palignr.
3183 if (e < 4 || !hasSSSE3)
3186 for (i = 0; i != e; ++i)
3190 // All undef, not a palignr.
3194 // Make sure we're shifting in the right direction.
3198 int s = Mask[i] - i;
3200 // Check the rest of the elements to see if they are consecutive.
3201 for (++i; i != e; ++i) {
3203 if (m >= 0 && m != s+i)
3209 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3210 /// specifies a shuffle of elements that is suitable for input to 256-bit
3212 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3213 const X86Subtarget *Subtarget) {
3214 int NumElems = VT.getVectorNumElements();
3216 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3222 // VSHUFPSY divides the resulting vector into 4 chunks.
3223 // The sources are also splitted into 4 chunks, and each destination
3224 // chunk must come from a different source chunk.
3226 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3227 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3229 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3230 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3232 int QuarterSize = NumElems/4;
3233 int HalfSize = QuarterSize*2;
3234 for (int i = 0; i < QuarterSize; ++i)
3235 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3237 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3238 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3241 // The mask of the second half must be the same as the first but with
3242 // the appropriate offsets. This works in the same way as VPERMILPS
3243 // works with masks.
3244 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3245 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3247 int FstHalfIdx = i-HalfSize;
3248 if (Mask[FstHalfIdx] < 0)
3250 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3253 for (int i = QuarterSize*3; i < NumElems; ++i) {
3254 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3256 int FstHalfIdx = i-HalfSize;
3257 if (Mask[FstHalfIdx] < 0)
3259 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3267 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3268 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3269 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3270 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3271 EVT VT = SVOp->getValueType(0);
3272 int NumElems = VT.getVectorNumElements();
3274 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3275 "Only supports v8i32 and v8f32 types");
3277 int HalfSize = NumElems/2;
3279 for (int i = 0; i != NumElems ; ++i) {
3280 if (SVOp->getMaskElt(i) < 0)
3282 // The mask of the first half must be equal to the second one.
3283 unsigned Shamt = (i%HalfSize)*2;
3284 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3285 Mask |= Elt << Shamt;
3291 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3292 /// specifies a shuffle of elements that is suitable for input to 256-bit
3293 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3294 /// version and the mask of the second half isn't binded with the first
3296 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3297 const X86Subtarget *Subtarget) {
3298 int NumElems = VT.getVectorNumElements();
3300 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3306 // VSHUFPSY divides the resulting vector into 4 chunks.
3307 // The sources are also splitted into 4 chunks, and each destination
3308 // chunk must come from a different source chunk.
3310 // SRC1 => X3 X2 X1 X0
3311 // SRC2 => Y3 Y2 Y1 Y0
3313 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3315 int QuarterSize = NumElems/4;
3316 int HalfSize = QuarterSize*2;
3317 for (int i = 0; i < QuarterSize; ++i)
3318 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3320 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3321 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3323 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3324 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3326 for (int i = QuarterSize*3; i < NumElems; ++i)
3327 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3333 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3334 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3335 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3336 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337 EVT VT = SVOp->getValueType(0);
3338 int NumElems = VT.getVectorNumElements();
3340 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3341 "Only supports v4i64 and v4f64 types");
3343 int HalfSize = NumElems/2;
3345 for (int i = 0; i != NumElems ; ++i) {
3346 if (SVOp->getMaskElt(i) < 0)
3348 int Elt = SVOp->getMaskElt(i) % HalfSize;
3355 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3356 /// specifies a shuffle of elements that is suitable for input to 128-bit
3357 /// SHUFPS and SHUFPD.
3358 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3359 int NumElems = VT.getVectorNumElements();
3361 if (VT.getSizeInBits() != 128)
3364 if (NumElems != 2 && NumElems != 4)
3367 int Half = NumElems / 2;
3368 for (int i = 0; i < Half; ++i)
3369 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3371 for (int i = Half; i < NumElems; ++i)
3372 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3378 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3379 SmallVector<int, 8> M;
3381 return ::isSHUFPMask(M, N->getValueType(0));
3384 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3385 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3386 /// half elements to come from vector 1 (which would equal the dest.) and
3387 /// the upper half to come from vector 2.
3388 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3389 int NumElems = VT.getVectorNumElements();
3391 if (NumElems != 2 && NumElems != 4)
3394 int Half = NumElems / 2;
3395 for (int i = 0; i < Half; ++i)
3396 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3398 for (int i = Half; i < NumElems; ++i)
3399 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3404 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3405 SmallVector<int, 8> M;
3407 return isCommutedSHUFPMask(M, N->getValueType(0));
3410 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3411 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3412 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3413 EVT VT = N->getValueType(0);
3414 unsigned NumElems = VT.getVectorNumElements();
3416 if (VT.getSizeInBits() != 128)
3422 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3423 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3424 isUndefOrEqual(N->getMaskElt(1), 7) &&
3425 isUndefOrEqual(N->getMaskElt(2), 2) &&
3426 isUndefOrEqual(N->getMaskElt(3), 3);
3429 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3430 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3432 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3433 EVT VT = N->getValueType(0);
3434 unsigned NumElems = VT.getVectorNumElements();
3436 if (VT.getSizeInBits() != 128)
3442 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3443 isUndefOrEqual(N->getMaskElt(1), 3) &&
3444 isUndefOrEqual(N->getMaskElt(2), 2) &&
3445 isUndefOrEqual(N->getMaskElt(3), 3);
3448 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3449 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3450 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3451 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3453 if (NumElems != 2 && NumElems != 4)
3456 for (unsigned i = 0; i < NumElems/2; ++i)
3457 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3460 for (unsigned i = NumElems/2; i < NumElems; ++i)
3461 if (!isUndefOrEqual(N->getMaskElt(i), i))
3467 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3468 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3469 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3470 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3472 if ((NumElems != 2 && NumElems != 4)
3473 || N->getValueType(0).getSizeInBits() > 128)
3476 for (unsigned i = 0; i < NumElems/2; ++i)
3477 if (!isUndefOrEqual(N->getMaskElt(i), i))
3480 for (unsigned i = 0; i < NumElems/2; ++i)
3481 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3487 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3488 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3489 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3490 bool V2IsSplat = false) {
3491 int NumElts = VT.getVectorNumElements();
3493 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3494 "Unsupported vector type for unpckh");
3496 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3499 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3500 // independently on 128-bit lanes.
3501 unsigned NumLanes = VT.getSizeInBits()/128;
3502 unsigned NumLaneElts = NumElts/NumLanes;
3505 unsigned End = NumLaneElts;
3506 for (unsigned s = 0; s < NumLanes; ++s) {
3507 for (unsigned i = Start, j = s * NumLaneElts;
3511 int BitI1 = Mask[i+1];
3512 if (!isUndefOrEqual(BitI, j))
3515 if (!isUndefOrEqual(BitI1, NumElts))
3518 if (!isUndefOrEqual(BitI1, j + NumElts))
3522 // Process the next 128 bits.
3523 Start += NumLaneElts;
3530 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3531 SmallVector<int, 8> M;
3533 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3536 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3537 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3538 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3539 bool V2IsSplat = false) {
3540 int NumElts = VT.getVectorNumElements();
3542 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3543 "Unsupported vector type for unpckh");
3545 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3548 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549 // independently on 128-bit lanes.
3550 unsigned NumLanes = VT.getSizeInBits()/128;
3551 unsigned NumLaneElts = NumElts/NumLanes;
3554 unsigned End = NumLaneElts;
3555 for (unsigned l = 0; l != NumLanes; ++l) {
3556 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3557 i != End; i += 2, ++j) {
3559 int BitI1 = Mask[i+1];
3560 if (!isUndefOrEqual(BitI, j))
3563 if (isUndefOrEqual(BitI1, NumElts))
3566 if (!isUndefOrEqual(BitI1, j+NumElts))
3570 // Process the next 128 bits.
3571 Start += NumLaneElts;
3577 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3578 SmallVector<int, 8> M;
3580 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3583 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3584 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3586 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3587 int NumElems = VT.getVectorNumElements();
3588 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3591 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3592 // FIXME: Need a better way to get rid of this, there's no latency difference
3593 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3594 // the former later. We should also remove the "_undef" special mask.
3595 if (NumElems == 4 && VT.getSizeInBits() == 256)
3598 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3599 // independently on 128-bit lanes.
3600 unsigned NumLanes = VT.getSizeInBits() / 128;
3601 unsigned NumLaneElts = NumElems / NumLanes;
3603 for (unsigned s = 0; s < NumLanes; ++s) {
3604 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3605 i != NumLaneElts * (s + 1);
3608 int BitI1 = Mask[i+1];
3610 if (!isUndefOrEqual(BitI, j))
3612 if (!isUndefOrEqual(BitI1, j))
3620 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3621 SmallVector<int, 8> M;
3623 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3626 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3627 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3629 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3630 int NumElems = VT.getVectorNumElements();
3631 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3634 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3636 int BitI1 = Mask[i+1];
3637 if (!isUndefOrEqual(BitI, j))
3639 if (!isUndefOrEqual(BitI1, j))
3645 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3646 SmallVector<int, 8> M;
3648 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3651 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3652 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3653 /// MOVSD, and MOVD, i.e. setting the lowest element.
3654 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3655 if (VT.getVectorElementType().getSizeInBits() < 32)
3658 int NumElts = VT.getVectorNumElements();
3660 if (!isUndefOrEqual(Mask[0], NumElts))
3663 for (int i = 1; i < NumElts; ++i)
3664 if (!isUndefOrEqual(Mask[i], i))
3670 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3671 SmallVector<int, 8> M;
3673 return ::isMOVLMask(M, N->getValueType(0));
3676 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3677 /// as permutations between 128-bit chunks or halves. As an example: this
3679 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3680 /// The first half comes from the second half of V1 and the second half from the
3681 /// the second half of V2.
3682 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3683 const X86Subtarget *Subtarget) {
3684 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3687 // The shuffle result is divided into half A and half B. In total the two
3688 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3689 // B must come from C, D, E or F.
3690 int HalfSize = VT.getVectorNumElements()/2;
3691 bool MatchA = false, MatchB = false;
3693 // Check if A comes from one of C, D, E, F.
3694 for (int Half = 0; Half < 4; ++Half) {
3695 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3701 // Check if B comes from one of C, D, E, F.
3702 for (int Half = 0; Half < 4; ++Half) {
3703 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3709 return MatchA && MatchB;
3712 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3713 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3714 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3716 EVT VT = SVOp->getValueType(0);
3718 int HalfSize = VT.getVectorNumElements()/2;
3720 int FstHalf = 0, SndHalf = 0;
3721 for (int i = 0; i < HalfSize; ++i) {
3722 if (SVOp->getMaskElt(i) > 0) {
3723 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3727 for (int i = HalfSize; i < HalfSize*2; ++i) {
3728 if (SVOp->getMaskElt(i) > 0) {
3729 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3734 return (FstHalf | (SndHalf << 4));
3737 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3738 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3739 /// Note that VPERMIL mask matching is different depending whether theunderlying
3740 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3741 /// to the same elements of the low, but to the higher half of the source.
3742 /// In VPERMILPD the two lanes could be shuffled independently of each other
3743 /// with the same restriction that lanes can't be crossed.
3744 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3745 const X86Subtarget *Subtarget) {
3746 int NumElts = VT.getVectorNumElements();
3747 int NumLanes = VT.getSizeInBits()/128;
3749 if (!Subtarget->hasAVX())
3752 // Match any permutation of 128-bit vector with 64-bit types
3753 if (NumLanes == 1 && NumElts != 2)
3756 // Only match 256-bit with 32 types
3757 if (VT.getSizeInBits() == 256 && NumElts != 4)
3760 // The mask on the high lane is independent of the low. Both can match
3761 // any element in inside its own lane, but can't cross.
3762 int LaneSize = NumElts/NumLanes;
3763 for (int l = 0; l < NumLanes; ++l)
3764 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3765 int LaneStart = l*LaneSize;
3766 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3773 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3774 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3775 /// Note that VPERMIL mask matching is different depending whether theunderlying
3776 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3777 /// to the same elements of the low, but to the higher half of the source.
3778 /// In VPERMILPD the two lanes could be shuffled independently of each other
3779 /// with the same restriction that lanes can't be crossed.
3780 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3781 const X86Subtarget *Subtarget) {
3782 unsigned NumElts = VT.getVectorNumElements();
3783 unsigned NumLanes = VT.getSizeInBits()/128;
3785 if (!Subtarget->hasAVX())
3788 // Match any permutation of 128-bit vector with 32-bit types
3789 if (NumLanes == 1 && NumElts != 4)
3792 // Only match 256-bit with 32 types
3793 if (VT.getSizeInBits() == 256 && NumElts != 8)
3796 // The mask on the high lane should be the same as the low. Actually,
3797 // they can differ if any of the corresponding index in a lane is undef
3798 // and the other stays in range.
3799 int LaneSize = NumElts/NumLanes;
3800 for (int i = 0; i < LaneSize; ++i) {
3801 int HighElt = i+LaneSize;
3802 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3803 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3805 if (!HighValid || !LowValid)
3807 if (Mask[i] < 0 || Mask[HighElt] < 0)
3809 if (Mask[HighElt]-Mask[i] != LaneSize)
3816 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3817 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3818 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3819 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3820 EVT VT = SVOp->getValueType(0);
3822 int NumElts = VT.getVectorNumElements();
3823 int NumLanes = VT.getSizeInBits()/128;
3824 int LaneSize = NumElts/NumLanes;
3826 // Although the mask is equal for both lanes do it twice to get the cases
3827 // where a mask will match because the same mask element is undef on the
3828 // first half but valid on the second. This would get pathological cases
3829 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3831 for (int l = 0; l < NumLanes; ++l) {
3832 for (int i = 0; i < LaneSize; ++i) {
3833 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3836 if (MaskElt >= LaneSize)
3837 MaskElt -= LaneSize;
3838 Mask |= MaskElt << (i*2);
3845 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3846 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3847 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3848 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3849 EVT VT = SVOp->getValueType(0);
3851 int NumElts = VT.getVectorNumElements();
3852 int NumLanes = VT.getSizeInBits()/128;
3855 int LaneSize = NumElts/NumLanes;
3856 for (int l = 0; l < NumLanes; ++l)
3857 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3858 int MaskElt = SVOp->getMaskElt(i);
3861 Mask |= (MaskElt-l*LaneSize) << i;
3867 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3868 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3869 /// element of vector 2 and the other elements to come from vector 1 in order.
3870 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3871 bool V2IsSplat = false, bool V2IsUndef = false) {
3872 int NumOps = VT.getVectorNumElements();
3873 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3876 if (!isUndefOrEqual(Mask[0], 0))
3879 for (int i = 1; i < NumOps; ++i)
3880 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3881 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3882 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3888 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3889 bool V2IsUndef = false) {
3890 SmallVector<int, 8> M;
3892 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3895 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3896 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3897 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3898 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3899 const X86Subtarget *Subtarget) {
3900 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3903 // The second vector must be undef
3904 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3907 EVT VT = N->getValueType(0);
3908 unsigned NumElems = VT.getVectorNumElements();
3910 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3911 (VT.getSizeInBits() == 256 && NumElems != 8))
3914 // "i+1" is the value the indexed mask element must have
3915 for (unsigned i = 0; i < NumElems; i += 2)
3916 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3917 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3923 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3925 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3926 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3927 const X86Subtarget *Subtarget) {
3928 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3931 // The second vector must be undef
3932 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3935 EVT VT = N->getValueType(0);
3936 unsigned NumElems = VT.getVectorNumElements();
3938 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3939 (VT.getSizeInBits() == 256 && NumElems != 8))
3942 // "i" is the value the indexed mask element must have
3943 for (unsigned i = 0; i < NumElems; i += 2)
3944 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3945 !isUndefOrEqual(N->getMaskElt(i+1), i))
3951 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to 256-bit
3953 /// version of MOVDDUP.
3954 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3955 const X86Subtarget *Subtarget) {
3956 EVT VT = N->getValueType(0);
3957 int NumElts = VT.getVectorNumElements();
3958 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3960 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3961 !V2IsUndef || NumElts != 4)
3964 for (int i = 0; i != NumElts/2; ++i)
3965 if (!isUndefOrEqual(N->getMaskElt(i), 0))
3967 for (int i = NumElts/2; i != NumElts; ++i)
3968 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3973 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3974 /// specifies a shuffle of elements that is suitable for input to 128-bit
3975 /// version of MOVDDUP.
3976 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3977 EVT VT = N->getValueType(0);
3979 if (VT.getSizeInBits() != 128)
3982 int e = VT.getVectorNumElements() / 2;
3983 for (int i = 0; i < e; ++i)
3984 if (!isUndefOrEqual(N->getMaskElt(i), i))
3986 for (int i = 0; i < e; ++i)
3987 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3992 /// isVEXTRACTF128Index - Return true if the specified
3993 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3994 /// suitable for input to VEXTRACTF128.
3995 bool X86::isVEXTRACTF128Index(SDNode *N) {
3996 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3999 // The index should be aligned on a 128-bit boundary.
4001 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4003 unsigned VL = N->getValueType(0).getVectorNumElements();
4004 unsigned VBits = N->getValueType(0).getSizeInBits();
4005 unsigned ElSize = VBits / VL;
4006 bool Result = (Index * ElSize) % 128 == 0;
4011 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4012 /// operand specifies a subvector insert that is suitable for input to
4014 bool X86::isVINSERTF128Index(SDNode *N) {
4015 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4018 // The index should be aligned on a 128-bit boundary.
4020 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4022 unsigned VL = N->getValueType(0).getVectorNumElements();
4023 unsigned VBits = N->getValueType(0).getSizeInBits();
4024 unsigned ElSize = VBits / VL;
4025 bool Result = (Index * ElSize) % 128 == 0;
4030 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4031 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4032 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4033 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4034 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4036 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4038 for (int i = 0; i < NumOperands; ++i) {
4039 int Val = SVOp->getMaskElt(NumOperands-i-1);
4040 if (Val < 0) Val = 0;
4041 if (Val >= NumOperands) Val -= NumOperands;
4043 if (i != NumOperands - 1)
4049 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4050 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4051 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4052 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4054 // 8 nodes, but we only care about the last 4.
4055 for (unsigned i = 7; i >= 4; --i) {
4056 int Val = SVOp->getMaskElt(i);
4065 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4067 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4068 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4070 // 8 nodes, but we only care about the first 4.
4071 for (int i = 3; i >= 0; --i) {
4072 int Val = SVOp->getMaskElt(i);
4081 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4083 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4084 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4085 EVT VVT = N->getValueType(0);
4086 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4090 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4091 Val = SVOp->getMaskElt(i);
4095 assert(Val - i > 0 && "PALIGNR imm should be positive");
4096 return (Val - i) * EltSize;
4099 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4100 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4102 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4103 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4104 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4107 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4109 EVT VecVT = N->getOperand(0).getValueType();
4110 EVT ElVT = VecVT.getVectorElementType();
4112 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4113 return Index / NumElemsPerChunk;
4116 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4117 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4119 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4120 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4121 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4124 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4126 EVT VecVT = N->getValueType(0);
4127 EVT ElVT = VecVT.getVectorElementType();
4129 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4130 return Index / NumElemsPerChunk;
4133 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4135 bool X86::isZeroNode(SDValue Elt) {
4136 return ((isa<ConstantSDNode>(Elt) &&
4137 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4138 (isa<ConstantFPSDNode>(Elt) &&
4139 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4142 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4143 /// their permute mask.
4144 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4145 SelectionDAG &DAG) {
4146 EVT VT = SVOp->getValueType(0);
4147 unsigned NumElems = VT.getVectorNumElements();
4148 SmallVector<int, 8> MaskVec;
4150 for (unsigned i = 0; i != NumElems; ++i) {
4151 int idx = SVOp->getMaskElt(i);
4153 MaskVec.push_back(idx);
4154 else if (idx < (int)NumElems)
4155 MaskVec.push_back(idx + NumElems);
4157 MaskVec.push_back(idx - NumElems);
4159 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4160 SVOp->getOperand(0), &MaskVec[0]);
4163 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4164 /// the two vector operands have swapped position.
4165 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4166 unsigned NumElems = VT.getVectorNumElements();
4167 for (unsigned i = 0; i != NumElems; ++i) {
4171 else if (idx < (int)NumElems)
4172 Mask[i] = idx + NumElems;
4174 Mask[i] = idx - NumElems;
4178 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4179 /// match movhlps. The lower half elements should come from upper half of
4180 /// V1 (and in order), and the upper half elements should come from the upper
4181 /// half of V2 (and in order).
4182 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4183 EVT VT = Op->getValueType(0);
4184 if (VT.getSizeInBits() != 128)
4186 if (VT.getVectorNumElements() != 4)
4188 for (unsigned i = 0, e = 2; i != e; ++i)
4189 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4191 for (unsigned i = 2; i != 4; ++i)
4192 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4197 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4198 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4200 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4201 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4203 N = N->getOperand(0).getNode();
4204 if (!ISD::isNON_EXTLoad(N))
4207 *LD = cast<LoadSDNode>(N);
4211 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4212 /// match movlp{s|d}. The lower half elements should come from lower half of
4213 /// V1 (and in order), and the upper half elements should come from the upper
4214 /// half of V2 (and in order). And since V1 will become the source of the
4215 /// MOVLP, it must be either a vector load or a scalar load to vector.
4216 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4217 ShuffleVectorSDNode *Op) {
4218 EVT VT = Op->getValueType(0);
4219 if (VT.getSizeInBits() != 128)
4222 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4224 // Is V2 is a vector load, don't do this transformation. We will try to use
4225 // load folding shufps op.
4226 if (ISD::isNON_EXTLoad(V2))
4229 unsigned NumElems = VT.getVectorNumElements();
4231 if (NumElems != 2 && NumElems != 4)
4233 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4234 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4236 for (unsigned i = NumElems/2; i != NumElems; ++i)
4237 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4242 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4244 static bool isSplatVector(SDNode *N) {
4245 if (N->getOpcode() != ISD::BUILD_VECTOR)
4248 SDValue SplatValue = N->getOperand(0);
4249 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4250 if (N->getOperand(i) != SplatValue)
4255 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4256 /// to an zero vector.
4257 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4258 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4259 SDValue V1 = N->getOperand(0);
4260 SDValue V2 = N->getOperand(1);
4261 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4262 for (unsigned i = 0; i != NumElems; ++i) {
4263 int Idx = N->getMaskElt(i);
4264 if (Idx >= (int)NumElems) {
4265 unsigned Opc = V2.getOpcode();
4266 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4268 if (Opc != ISD::BUILD_VECTOR ||
4269 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4271 } else if (Idx >= 0) {
4272 unsigned Opc = V1.getOpcode();
4273 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4275 if (Opc != ISD::BUILD_VECTOR ||
4276 !X86::isZeroNode(V1.getOperand(Idx)))
4283 /// getZeroVector - Returns a vector of specified type with all zero elements.
4285 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4287 assert(VT.isVector() && "Expected a vector type");
4289 // Always build SSE zero vectors as <4 x i32> bitcasted
4290 // to their dest type. This ensures they get CSE'd.
4292 if (VT.getSizeInBits() == 128) { // SSE
4293 if (HasSSE2) { // SSE2
4294 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4295 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4297 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4298 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4300 } else if (VT.getSizeInBits() == 256) { // AVX
4301 // 256-bit logic and arithmetic instructions in AVX are
4302 // all floating-point, no support for integer ops. Default
4303 // to emitting fp zeroed vectors then.
4304 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4305 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4308 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4311 /// getOnesVector - Returns a vector of specified type with all bits set.
4312 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4313 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4314 /// original type, ensuring they get CSE'd.
4315 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4316 assert(VT.isVector() && "Expected a vector type");
4317 assert((VT.is128BitVector() || VT.is256BitVector())
4318 && "Expected a 128-bit or 256-bit vector type");
4320 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4321 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4322 Cst, Cst, Cst, Cst);
4324 if (VT.is256BitVector()) {
4325 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4326 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4327 Vec = Insert128BitVector(InsV, Vec,
4328 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4331 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4334 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4335 /// that point to V2 points to its first element.
4336 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4337 EVT VT = SVOp->getValueType(0);
4338 unsigned NumElems = VT.getVectorNumElements();
4340 bool Changed = false;
4341 SmallVector<int, 8> MaskVec;
4342 SVOp->getMask(MaskVec);
4344 for (unsigned i = 0; i != NumElems; ++i) {
4345 if (MaskVec[i] > (int)NumElems) {
4346 MaskVec[i] = NumElems;
4351 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4352 SVOp->getOperand(1), &MaskVec[0]);
4353 return SDValue(SVOp, 0);
4356 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4357 /// operation of specified width.
4358 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4360 unsigned NumElems = VT.getVectorNumElements();
4361 SmallVector<int, 8> Mask;
4362 Mask.push_back(NumElems);
4363 for (unsigned i = 1; i != NumElems; ++i)
4365 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4368 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4369 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4371 unsigned NumElems = VT.getVectorNumElements();
4372 SmallVector<int, 8> Mask;
4373 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4375 Mask.push_back(i + NumElems);
4377 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4380 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4381 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4383 unsigned NumElems = VT.getVectorNumElements();
4384 unsigned Half = NumElems/2;
4385 SmallVector<int, 8> Mask;
4386 for (unsigned i = 0; i != Half; ++i) {
4387 Mask.push_back(i + Half);
4388 Mask.push_back(i + NumElems + Half);
4390 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4393 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4394 // a generic shuffle instruction because the target has no such instructions.
4395 // Generate shuffles which repeat i16 and i8 several times until they can be
4396 // represented by v4f32 and then be manipulated by target suported shuffles.
4397 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4398 EVT VT = V.getValueType();
4399 int NumElems = VT.getVectorNumElements();
4400 DebugLoc dl = V.getDebugLoc();
4402 while (NumElems > 4) {
4403 if (EltNo < NumElems/2) {
4404 V = getUnpackl(DAG, dl, VT, V, V);
4406 V = getUnpackh(DAG, dl, VT, V, V);
4407 EltNo -= NumElems/2;
4414 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4415 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4416 EVT VT = V.getValueType();
4417 DebugLoc dl = V.getDebugLoc();
4418 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4419 && "Vector size not supported");
4421 if (VT.getSizeInBits() == 128) {
4422 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4423 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4424 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4427 // To use VPERMILPS to splat scalars, the second half of indicies must
4428 // refer to the higher part, which is a duplication of the lower one,
4429 // because VPERMILPS can only handle in-lane permutations.
4430 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4431 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4433 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4434 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4438 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4441 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4442 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4443 EVT SrcVT = SV->getValueType(0);
4444 SDValue V1 = SV->getOperand(0);
4445 DebugLoc dl = SV->getDebugLoc();
4447 int EltNo = SV->getSplatIndex();
4448 int NumElems = SrcVT.getVectorNumElements();
4449 unsigned Size = SrcVT.getSizeInBits();
4451 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4452 "Unknown how to promote splat for type");
4454 // Extract the 128-bit part containing the splat element and update
4455 // the splat element index when it refers to the higher register.
4457 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4458 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4460 EltNo -= NumElems/2;
4463 // All i16 and i8 vector types can't be used directly by a generic shuffle
4464 // instruction because the target has no such instruction. Generate shuffles
4465 // which repeat i16 and i8 several times until they fit in i32, and then can
4466 // be manipulated by target suported shuffles.
4467 EVT EltVT = SrcVT.getVectorElementType();
4468 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4469 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4471 // Recreate the 256-bit vector and place the same 128-bit vector
4472 // into the low and high part. This is necessary because we want
4473 // to use VPERM* to shuffle the vectors
4475 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4476 DAG.getConstant(0, MVT::i32), DAG, dl);
4477 V1 = Insert128BitVector(InsV, V1,
4478 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4481 return getLegalSplat(DAG, V1, EltNo);
4484 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4485 /// vector of zero or undef vector. This produces a shuffle where the low
4486 /// element of V2 is swizzled into the zero/undef vector, landing at element
4487 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4488 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4489 bool isZero, bool HasSSE2,
4490 SelectionDAG &DAG) {
4491 EVT VT = V2.getValueType();
4493 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4494 unsigned NumElems = VT.getVectorNumElements();
4495 SmallVector<int, 16> MaskVec;
4496 for (unsigned i = 0; i != NumElems; ++i)
4497 // If this is the insertion idx, put the low elt of V2 here.
4498 MaskVec.push_back(i == Idx ? NumElems : i);
4499 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4502 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4503 /// element of the result of the vector shuffle.
4504 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4507 return SDValue(); // Limit search depth.
4509 SDValue V = SDValue(N, 0);
4510 EVT VT = V.getValueType();
4511 unsigned Opcode = V.getOpcode();
4513 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4514 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4515 Index = SV->getMaskElt(Index);
4518 return DAG.getUNDEF(VT.getVectorElementType());
4520 int NumElems = VT.getVectorNumElements();
4521 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4522 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4525 // Recurse into target specific vector shuffles to find scalars.
4526 if (isTargetShuffle(Opcode)) {
4527 int NumElems = VT.getVectorNumElements();
4528 SmallVector<unsigned, 16> ShuffleMask;
4532 case X86ISD::SHUFPS:
4533 case X86ISD::SHUFPD:
4534 ImmN = N->getOperand(N->getNumOperands()-1);
4535 DecodeSHUFPSMask(NumElems,
4536 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4539 case X86ISD::PUNPCKHBW:
4540 case X86ISD::PUNPCKHWD:
4541 case X86ISD::PUNPCKHDQ:
4542 case X86ISD::PUNPCKHQDQ:
4543 DecodePUNPCKHMask(NumElems, ShuffleMask);
4545 case X86ISD::UNPCKHPS:
4546 case X86ISD::UNPCKHPD:
4547 case X86ISD::VUNPCKHPSY:
4548 case X86ISD::VUNPCKHPDY:
4549 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4551 case X86ISD::PUNPCKLBW:
4552 case X86ISD::PUNPCKLWD:
4553 case X86ISD::PUNPCKLDQ:
4554 case X86ISD::PUNPCKLQDQ:
4555 DecodePUNPCKLMask(VT, ShuffleMask);
4557 case X86ISD::UNPCKLPS:
4558 case X86ISD::UNPCKLPD:
4559 case X86ISD::VUNPCKLPSY:
4560 case X86ISD::VUNPCKLPDY:
4561 DecodeUNPCKLPMask(VT, ShuffleMask);
4563 case X86ISD::MOVHLPS:
4564 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4566 case X86ISD::MOVLHPS:
4567 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4569 case X86ISD::PSHUFD:
4570 ImmN = N->getOperand(N->getNumOperands()-1);
4571 DecodePSHUFMask(NumElems,
4572 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4575 case X86ISD::PSHUFHW:
4576 ImmN = N->getOperand(N->getNumOperands()-1);
4577 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4580 case X86ISD::PSHUFLW:
4581 ImmN = N->getOperand(N->getNumOperands()-1);
4582 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4586 case X86ISD::MOVSD: {
4587 // The index 0 always comes from the first element of the second source,
4588 // this is why MOVSS and MOVSD are used in the first place. The other
4589 // elements come from the other positions of the first source vector.
4590 unsigned OpNum = (Index == 0) ? 1 : 0;
4591 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4594 case X86ISD::VPERMILPS:
4595 ImmN = N->getOperand(N->getNumOperands()-1);
4596 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4599 case X86ISD::VPERMILPSY:
4600 ImmN = N->getOperand(N->getNumOperands()-1);
4601 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4604 case X86ISD::VPERMILPD:
4605 ImmN = N->getOperand(N->getNumOperands()-1);
4606 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4609 case X86ISD::VPERMILPDY:
4610 ImmN = N->getOperand(N->getNumOperands()-1);
4611 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4614 case X86ISD::VPERM2F128:
4615 ImmN = N->getOperand(N->getNumOperands()-1);
4616 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4619 case X86ISD::MOVDDUP:
4620 case X86ISD::MOVLHPD:
4621 case X86ISD::MOVLPD:
4622 case X86ISD::MOVLPS:
4623 case X86ISD::MOVSHDUP:
4624 case X86ISD::MOVSLDUP:
4625 case X86ISD::PALIGN:
4626 return SDValue(); // Not yet implemented.
4628 assert(0 && "unknown target shuffle node");
4632 Index = ShuffleMask[Index];
4634 return DAG.getUNDEF(VT.getVectorElementType());
4636 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4637 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4641 // Actual nodes that may contain scalar elements
4642 if (Opcode == ISD::BITCAST) {
4643 V = V.getOperand(0);
4644 EVT SrcVT = V.getValueType();
4645 unsigned NumElems = VT.getVectorNumElements();
4647 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4651 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4652 return (Index == 0) ? V.getOperand(0)
4653 : DAG.getUNDEF(VT.getVectorElementType());
4655 if (V.getOpcode() == ISD::BUILD_VECTOR)
4656 return V.getOperand(Index);
4661 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4662 /// shuffle operation which come from a consecutively from a zero. The
4663 /// search can start in two different directions, from left or right.
4665 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4666 bool ZerosFromLeft, SelectionDAG &DAG) {
4669 while (i < NumElems) {
4670 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4671 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4672 if (!(Elt.getNode() &&
4673 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4681 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4682 /// MaskE correspond consecutively to elements from one of the vector operands,
4683 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4685 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4686 int OpIdx, int NumElems, unsigned &OpNum) {
4687 bool SeenV1 = false;
4688 bool SeenV2 = false;
4690 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4691 int Idx = SVOp->getMaskElt(i);
4692 // Ignore undef indicies
4701 // Only accept consecutive elements from the same vector
4702 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4706 OpNum = SeenV1 ? 0 : 1;
4710 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4711 /// logical left shift of a vector.
4712 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4713 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4714 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4715 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4716 false /* check zeros from right */, DAG);
4722 // Considering the elements in the mask that are not consecutive zeros,
4723 // check if they consecutively come from only one of the source vectors.
4725 // V1 = {X, A, B, C} 0
4727 // vector_shuffle V1, V2 <1, 2, 3, X>
4729 if (!isShuffleMaskConsecutive(SVOp,
4730 0, // Mask Start Index
4731 NumElems-NumZeros-1, // Mask End Index
4732 NumZeros, // Where to start looking in the src vector
4733 NumElems, // Number of elements in vector
4734 OpSrc)) // Which source operand ?
4739 ShVal = SVOp->getOperand(OpSrc);
4743 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4744 /// logical left shift of a vector.
4745 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4746 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4747 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4748 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4749 true /* check zeros from left */, DAG);
4755 // Considering the elements in the mask that are not consecutive zeros,
4756 // check if they consecutively come from only one of the source vectors.
4758 // 0 { A, B, X, X } = V2
4760 // vector_shuffle V1, V2 <X, X, 4, 5>
4762 if (!isShuffleMaskConsecutive(SVOp,
4763 NumZeros, // Mask Start Index
4764 NumElems-1, // Mask End Index
4765 0, // Where to start looking in the src vector
4766 NumElems, // Number of elements in vector
4767 OpSrc)) // Which source operand ?
4772 ShVal = SVOp->getOperand(OpSrc);
4776 /// isVectorShift - Returns true if the shuffle can be implemented as a
4777 /// logical left or right shift of a vector.
4778 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4779 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4780 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4781 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4787 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4789 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4790 unsigned NumNonZero, unsigned NumZero,
4792 const TargetLowering &TLI) {
4796 DebugLoc dl = Op.getDebugLoc();
4799 for (unsigned i = 0; i < 16; ++i) {
4800 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4801 if (ThisIsNonZero && First) {
4803 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4805 V = DAG.getUNDEF(MVT::v8i16);
4810 SDValue ThisElt(0, 0), LastElt(0, 0);
4811 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4812 if (LastIsNonZero) {
4813 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4814 MVT::i16, Op.getOperand(i-1));
4816 if (ThisIsNonZero) {
4817 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4818 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4819 ThisElt, DAG.getConstant(8, MVT::i8));
4821 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4825 if (ThisElt.getNode())
4826 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4827 DAG.getIntPtrConstant(i/2));
4831 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4834 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4836 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4837 unsigned NumNonZero, unsigned NumZero,
4839 const TargetLowering &TLI) {
4843 DebugLoc dl = Op.getDebugLoc();
4846 for (unsigned i = 0; i < 8; ++i) {
4847 bool isNonZero = (NonZeros & (1 << i)) != 0;
4851 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4853 V = DAG.getUNDEF(MVT::v8i16);
4856 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4857 MVT::v8i16, V, Op.getOperand(i),
4858 DAG.getIntPtrConstant(i));
4865 /// getVShift - Return a vector logical shift node.
4867 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4868 unsigned NumBits, SelectionDAG &DAG,
4869 const TargetLowering &TLI, DebugLoc dl) {
4870 EVT ShVT = MVT::v2i64;
4871 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4872 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4873 return DAG.getNode(ISD::BITCAST, dl, VT,
4874 DAG.getNode(Opc, dl, ShVT, SrcOp,
4875 DAG.getConstant(NumBits,
4876 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4880 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4881 SelectionDAG &DAG) const {
4883 // Check if the scalar load can be widened into a vector load. And if
4884 // the address is "base + cst" see if the cst can be "absorbed" into
4885 // the shuffle mask.
4886 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4887 SDValue Ptr = LD->getBasePtr();
4888 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4890 EVT PVT = LD->getValueType(0);
4891 if (PVT != MVT::i32 && PVT != MVT::f32)
4896 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4897 FI = FINode->getIndex();
4899 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4900 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4901 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4902 Offset = Ptr.getConstantOperandVal(1);
4903 Ptr = Ptr.getOperand(0);
4908 // FIXME: 256-bit vector instructions don't require a strict alignment,
4909 // improve this code to support it better.
4910 unsigned RequiredAlign = VT.getSizeInBits()/8;
4911 SDValue Chain = LD->getChain();
4912 // Make sure the stack object alignment is at least 16 or 32.
4913 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4914 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4915 if (MFI->isFixedObjectIndex(FI)) {
4916 // Can't change the alignment. FIXME: It's possible to compute
4917 // the exact stack offset and reference FI + adjust offset instead.
4918 // If someone *really* cares about this. That's the way to implement it.
4921 MFI->setObjectAlignment(FI, RequiredAlign);
4925 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4926 // Ptr + (Offset & ~15).
4929 if ((Offset % RequiredAlign) & 3)
4931 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4933 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4934 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4936 int EltNo = (Offset - StartOffset) >> 2;
4937 int NumElems = VT.getVectorNumElements();
4939 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4940 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4941 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4942 LD->getPointerInfo().getWithOffset(StartOffset),
4945 // Canonicalize it to a v4i32 or v8i32 shuffle.
4946 SmallVector<int, 8> Mask;
4947 for (int i = 0; i < NumElems; ++i)
4948 Mask.push_back(EltNo);
4950 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4951 return DAG.getNode(ISD::BITCAST, dl, NVT,
4952 DAG.getVectorShuffle(CanonVT, dl, V1,
4953 DAG.getUNDEF(CanonVT),&Mask[0]));
4959 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4960 /// vector of type 'VT', see if the elements can be replaced by a single large
4961 /// load which has the same value as a build_vector whose operands are 'elts'.
4963 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4965 /// FIXME: we'd also like to handle the case where the last elements are zero
4966 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4967 /// There's even a handy isZeroNode for that purpose.
4968 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4969 DebugLoc &DL, SelectionDAG &DAG) {
4970 EVT EltVT = VT.getVectorElementType();
4971 unsigned NumElems = Elts.size();
4973 LoadSDNode *LDBase = NULL;
4974 unsigned LastLoadedElt = -1U;
4976 // For each element in the initializer, see if we've found a load or an undef.
4977 // If we don't find an initial load element, or later load elements are
4978 // non-consecutive, bail out.
4979 for (unsigned i = 0; i < NumElems; ++i) {
4980 SDValue Elt = Elts[i];
4982 if (!Elt.getNode() ||
4983 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4986 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4988 LDBase = cast<LoadSDNode>(Elt.getNode());
4992 if (Elt.getOpcode() == ISD::UNDEF)
4995 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4996 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5001 // If we have found an entire vector of loads and undefs, then return a large
5002 // load of the entire vector width starting at the base pointer. If we found
5003 // consecutive loads for the low half, generate a vzext_load node.
5004 if (LastLoadedElt == NumElems - 1) {
5005 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5006 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5007 LDBase->getPointerInfo(),
5008 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5009 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5010 LDBase->getPointerInfo(),
5011 LDBase->isVolatile(), LDBase->isNonTemporal(),
5012 LDBase->getAlignment());
5013 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5014 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5015 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5016 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5018 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5019 LDBase->getPointerInfo(),
5020 LDBase->getAlignment(),
5021 false/*isVolatile*/, true/*ReadMem*/,
5023 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5029 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5030 DebugLoc dl = Op.getDebugLoc();
5032 EVT VT = Op.getValueType();
5033 EVT ExtVT = VT.getVectorElementType();
5034 unsigned NumElems = Op.getNumOperands();
5036 // Vectors containing all zeros can be matched by pxor and xorps later
5037 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5038 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5039 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5040 if (Op.getValueType() == MVT::v4i32 ||
5041 Op.getValueType() == MVT::v8i32)
5044 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
5047 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5048 // vectors or broken into v4i32 operations on 256-bit vectors.
5049 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5050 if (Op.getValueType() == MVT::v4i32)
5053 return getOnesVector(Op.getValueType(), DAG, dl);
5056 unsigned EVTBits = ExtVT.getSizeInBits();
5058 unsigned NumZero = 0;
5059 unsigned NumNonZero = 0;
5060 unsigned NonZeros = 0;
5061 bool IsAllConstants = true;
5062 SmallSet<SDValue, 8> Values;
5063 for (unsigned i = 0; i < NumElems; ++i) {
5064 SDValue Elt = Op.getOperand(i);
5065 if (Elt.getOpcode() == ISD::UNDEF)
5068 if (Elt.getOpcode() != ISD::Constant &&
5069 Elt.getOpcode() != ISD::ConstantFP)
5070 IsAllConstants = false;
5071 if (X86::isZeroNode(Elt))
5074 NonZeros |= (1 << i);
5079 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5080 if (NumNonZero == 0)
5081 return DAG.getUNDEF(VT);
5083 // Special case for single non-zero, non-undef, element.
5084 if (NumNonZero == 1) {
5085 unsigned Idx = CountTrailingZeros_32(NonZeros);
5086 SDValue Item = Op.getOperand(Idx);
5088 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5089 // the value are obviously zero, truncate the value to i32 and do the
5090 // insertion that way. Only do this if the value is non-constant or if the
5091 // value is a constant being inserted into element 0. It is cheaper to do
5092 // a constant pool load than it is to do a movd + shuffle.
5093 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5094 (!IsAllConstants || Idx == 0)) {
5095 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5097 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5098 EVT VecVT = MVT::v4i32;
5099 unsigned VecElts = 4;
5101 // Truncate the value (which may itself be a constant) to i32, and
5102 // convert it to a vector with movd (S2V+shuffle to zero extend).
5103 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5104 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5105 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5106 Subtarget->hasSSE2(), DAG);
5108 // Now we have our 32-bit value zero extended in the low element of
5109 // a vector. If Idx != 0, swizzle it into place.
5111 SmallVector<int, 4> Mask;
5112 Mask.push_back(Idx);
5113 for (unsigned i = 1; i != VecElts; ++i)
5115 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5116 DAG.getUNDEF(Item.getValueType()),
5119 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5123 // If we have a constant or non-constant insertion into the low element of
5124 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5125 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5126 // depending on what the source datatype is.
5129 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5130 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5131 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5132 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5133 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5134 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
5136 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5137 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5138 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5139 EVT MiddleVT = MVT::v4i32;
5140 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5141 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5142 Subtarget->hasSSE2(), DAG);
5143 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5147 // Is it a vector logical left shift?
5148 if (NumElems == 2 && Idx == 1 &&
5149 X86::isZeroNode(Op.getOperand(0)) &&
5150 !X86::isZeroNode(Op.getOperand(1))) {
5151 unsigned NumBits = VT.getSizeInBits();
5152 return getVShift(true, VT,
5153 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5154 VT, Op.getOperand(1)),
5155 NumBits/2, DAG, *this, dl);
5158 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5161 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5162 // is a non-constant being inserted into an element other than the low one,
5163 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5164 // movd/movss) to move this into the low element, then shuffle it into
5166 if (EVTBits == 32) {
5167 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5169 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5170 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5171 Subtarget->hasSSE2(), DAG);
5172 SmallVector<int, 8> MaskVec;
5173 for (unsigned i = 0; i < NumElems; i++)
5174 MaskVec.push_back(i == Idx ? 0 : 1);
5175 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5179 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5180 if (Values.size() == 1) {
5181 if (EVTBits == 32) {
5182 // Instead of a shuffle like this:
5183 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5184 // Check if it's possible to issue this instead.
5185 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5186 unsigned Idx = CountTrailingZeros_32(NonZeros);
5187 SDValue Item = Op.getOperand(Idx);
5188 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5189 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5194 // A vector full of immediates; various special cases are already
5195 // handled, so this is best done with a single constant-pool load.
5199 // For AVX-length vectors, build the individual 128-bit pieces and use
5200 // shuffles to put them in place.
5201 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5202 SmallVector<SDValue, 32> V;
5203 for (unsigned i = 0; i < NumElems; ++i)
5204 V.push_back(Op.getOperand(i));
5206 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5208 // Build both the lower and upper subvector.
5209 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5210 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5213 // Recreate the wider vector with the lower and upper part.
5214 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5215 DAG.getConstant(0, MVT::i32), DAG, dl);
5216 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5220 // Let legalizer expand 2-wide build_vectors.
5221 if (EVTBits == 64) {
5222 if (NumNonZero == 1) {
5223 // One half is zero or undef.
5224 unsigned Idx = CountTrailingZeros_32(NonZeros);
5225 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5226 Op.getOperand(Idx));
5227 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5228 Subtarget->hasSSE2(), DAG);
5233 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5234 if (EVTBits == 8 && NumElems == 16) {
5235 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5237 if (V.getNode()) return V;
5240 if (EVTBits == 16 && NumElems == 8) {
5241 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5243 if (V.getNode()) return V;
5246 // If element VT is == 32 bits, turn it into a number of shuffles.
5247 SmallVector<SDValue, 8> V;
5249 if (NumElems == 4 && NumZero > 0) {
5250 for (unsigned i = 0; i < 4; ++i) {
5251 bool isZero = !(NonZeros & (1 << i));
5253 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5255 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5258 for (unsigned i = 0; i < 2; ++i) {
5259 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5262 V[i] = V[i*2]; // Must be a zero vector.
5265 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5268 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5271 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5276 SmallVector<int, 8> MaskVec;
5277 bool Reverse = (NonZeros & 0x3) == 2;
5278 for (unsigned i = 0; i < 2; ++i)
5279 MaskVec.push_back(Reverse ? 1-i : i);
5280 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5281 for (unsigned i = 0; i < 2; ++i)
5282 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5283 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5286 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5287 // Check for a build vector of consecutive loads.
5288 for (unsigned i = 0; i < NumElems; ++i)
5289 V[i] = Op.getOperand(i);
5291 // Check for elements which are consecutive loads.
5292 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5296 // For SSE 4.1, use insertps to put the high elements into the low element.
5297 if (getSubtarget()->hasSSE41()) {
5299 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5300 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5302 Result = DAG.getUNDEF(VT);
5304 for (unsigned i = 1; i < NumElems; ++i) {
5305 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5306 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5307 Op.getOperand(i), DAG.getIntPtrConstant(i));
5312 // Otherwise, expand into a number of unpckl*, start by extending each of
5313 // our (non-undef) elements to the full vector width with the element in the
5314 // bottom slot of the vector (which generates no code for SSE).
5315 for (unsigned i = 0; i < NumElems; ++i) {
5316 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5317 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5319 V[i] = DAG.getUNDEF(VT);
5322 // Next, we iteratively mix elements, e.g. for v4f32:
5323 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5324 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5325 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5326 unsigned EltStride = NumElems >> 1;
5327 while (EltStride != 0) {
5328 for (unsigned i = 0; i < EltStride; ++i) {
5329 // If V[i+EltStride] is undef and this is the first round of mixing,
5330 // then it is safe to just drop this shuffle: V[i] is already in the
5331 // right place, the one element (since it's the first round) being
5332 // inserted as undef can be dropped. This isn't safe for successive
5333 // rounds because they will permute elements within both vectors.
5334 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5335 EltStride == NumElems/2)
5338 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5347 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5348 // them in a MMX register. This is better than doing a stack convert.
5349 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5350 DebugLoc dl = Op.getDebugLoc();
5351 EVT ResVT = Op.getValueType();
5353 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5354 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5356 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5357 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5358 InVec = Op.getOperand(1);
5359 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5360 unsigned NumElts = ResVT.getVectorNumElements();
5361 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5362 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5363 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5365 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5366 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5367 Mask[0] = 0; Mask[1] = 2;
5368 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5370 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5373 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5374 // to create 256-bit vectors from two other 128-bit ones.
5375 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5376 DebugLoc dl = Op.getDebugLoc();
5377 EVT ResVT = Op.getValueType();
5379 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5381 SDValue V1 = Op.getOperand(0);
5382 SDValue V2 = Op.getOperand(1);
5383 unsigned NumElems = ResVT.getVectorNumElements();
5385 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5386 DAG.getConstant(0, MVT::i32), DAG, dl);
5387 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5392 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5393 EVT ResVT = Op.getValueType();
5395 assert(Op.getNumOperands() == 2);
5396 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5397 "Unsupported CONCAT_VECTORS for value type");
5399 // We support concatenate two MMX registers and place them in a MMX register.
5400 // This is better than doing a stack convert.
5401 if (ResVT.is128BitVector())
5402 return LowerMMXCONCAT_VECTORS(Op, DAG);
5404 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5405 // from two other 128-bit ones.
5406 return LowerAVXCONCAT_VECTORS(Op, DAG);
5409 // v8i16 shuffles - Prefer shuffles in the following order:
5410 // 1. [all] pshuflw, pshufhw, optional move
5411 // 2. [ssse3] 1 x pshufb
5412 // 3. [ssse3] 2 x pshufb + 1 x por
5413 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5415 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5416 SelectionDAG &DAG) const {
5417 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5418 SDValue V1 = SVOp->getOperand(0);
5419 SDValue V2 = SVOp->getOperand(1);
5420 DebugLoc dl = SVOp->getDebugLoc();
5421 SmallVector<int, 8> MaskVals;
5423 // Determine if more than 1 of the words in each of the low and high quadwords
5424 // of the result come from the same quadword of one of the two inputs. Undef
5425 // mask values count as coming from any quadword, for better codegen.
5426 SmallVector<unsigned, 4> LoQuad(4);
5427 SmallVector<unsigned, 4> HiQuad(4);
5428 BitVector InputQuads(4);
5429 for (unsigned i = 0; i < 8; ++i) {
5430 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5431 int EltIdx = SVOp->getMaskElt(i);
5432 MaskVals.push_back(EltIdx);
5441 InputQuads.set(EltIdx / 4);
5444 int BestLoQuad = -1;
5445 unsigned MaxQuad = 1;
5446 for (unsigned i = 0; i < 4; ++i) {
5447 if (LoQuad[i] > MaxQuad) {
5449 MaxQuad = LoQuad[i];
5453 int BestHiQuad = -1;
5455 for (unsigned i = 0; i < 4; ++i) {
5456 if (HiQuad[i] > MaxQuad) {
5458 MaxQuad = HiQuad[i];
5462 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5463 // of the two input vectors, shuffle them into one input vector so only a
5464 // single pshufb instruction is necessary. If There are more than 2 input
5465 // quads, disable the next transformation since it does not help SSSE3.
5466 bool V1Used = InputQuads[0] || InputQuads[1];
5467 bool V2Used = InputQuads[2] || InputQuads[3];
5468 if (Subtarget->hasSSSE3()) {
5469 if (InputQuads.count() == 2 && V1Used && V2Used) {
5470 BestLoQuad = InputQuads.find_first();
5471 BestHiQuad = InputQuads.find_next(BestLoQuad);
5473 if (InputQuads.count() > 2) {
5479 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5480 // the shuffle mask. If a quad is scored as -1, that means that it contains
5481 // words from all 4 input quadwords.
5483 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5484 SmallVector<int, 8> MaskV;
5485 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5486 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5487 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5488 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5489 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5490 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5492 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5493 // source words for the shuffle, to aid later transformations.
5494 bool AllWordsInNewV = true;
5495 bool InOrder[2] = { true, true };
5496 for (unsigned i = 0; i != 8; ++i) {
5497 int idx = MaskVals[i];
5499 InOrder[i/4] = false;
5500 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5502 AllWordsInNewV = false;
5506 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5507 if (AllWordsInNewV) {
5508 for (int i = 0; i != 8; ++i) {
5509 int idx = MaskVals[i];
5512 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5513 if ((idx != i) && idx < 4)
5515 if ((idx != i) && idx > 3)
5524 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5525 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5526 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5527 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5528 unsigned TargetMask = 0;
5529 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5530 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5531 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5532 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5533 V1 = NewV.getOperand(0);
5534 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5538 // If we have SSSE3, and all words of the result are from 1 input vector,
5539 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5540 // is present, fall back to case 4.
5541 if (Subtarget->hasSSSE3()) {
5542 SmallVector<SDValue,16> pshufbMask;
5544 // If we have elements from both input vectors, set the high bit of the
5545 // shuffle mask element to zero out elements that come from V2 in the V1
5546 // mask, and elements that come from V1 in the V2 mask, so that the two
5547 // results can be OR'd together.
5548 bool TwoInputs = V1Used && V2Used;
5549 for (unsigned i = 0; i != 8; ++i) {
5550 int EltIdx = MaskVals[i] * 2;
5551 if (TwoInputs && (EltIdx >= 16)) {
5552 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5553 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5556 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5557 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5559 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5560 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5561 DAG.getNode(ISD::BUILD_VECTOR, dl,
5562 MVT::v16i8, &pshufbMask[0], 16));
5564 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5566 // Calculate the shuffle mask for the second input, shuffle it, and
5567 // OR it with the first shuffled input.
5569 for (unsigned i = 0; i != 8; ++i) {
5570 int EltIdx = MaskVals[i] * 2;
5572 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5573 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5576 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5577 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5579 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5580 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5581 DAG.getNode(ISD::BUILD_VECTOR, dl,
5582 MVT::v16i8, &pshufbMask[0], 16));
5583 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5584 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5587 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5588 // and update MaskVals with new element order.
5589 BitVector InOrder(8);
5590 if (BestLoQuad >= 0) {
5591 SmallVector<int, 8> MaskV;
5592 for (int i = 0; i != 4; ++i) {
5593 int idx = MaskVals[i];
5595 MaskV.push_back(-1);
5597 } else if ((idx / 4) == BestLoQuad) {
5598 MaskV.push_back(idx & 3);
5601 MaskV.push_back(-1);
5604 for (unsigned i = 4; i != 8; ++i)
5606 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5609 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5610 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5612 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5616 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5617 // and update MaskVals with the new element order.
5618 if (BestHiQuad >= 0) {
5619 SmallVector<int, 8> MaskV;
5620 for (unsigned i = 0; i != 4; ++i)
5622 for (unsigned i = 4; i != 8; ++i) {
5623 int idx = MaskVals[i];
5625 MaskV.push_back(-1);
5627 } else if ((idx / 4) == BestHiQuad) {
5628 MaskV.push_back((idx & 3) + 4);
5631 MaskV.push_back(-1);
5634 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5637 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5638 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5640 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5644 // In case BestHi & BestLo were both -1, which means each quadword has a word
5645 // from each of the four input quadwords, calculate the InOrder bitvector now
5646 // before falling through to the insert/extract cleanup.
5647 if (BestLoQuad == -1 && BestHiQuad == -1) {
5649 for (int i = 0; i != 8; ++i)
5650 if (MaskVals[i] < 0 || MaskVals[i] == i)
5654 // The other elements are put in the right place using pextrw and pinsrw.
5655 for (unsigned i = 0; i != 8; ++i) {
5658 int EltIdx = MaskVals[i];
5661 SDValue ExtOp = (EltIdx < 8)
5662 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5663 DAG.getIntPtrConstant(EltIdx))
5664 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5665 DAG.getIntPtrConstant(EltIdx - 8));
5666 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5667 DAG.getIntPtrConstant(i));
5672 // v16i8 shuffles - Prefer shuffles in the following order:
5673 // 1. [ssse3] 1 x pshufb
5674 // 2. [ssse3] 2 x pshufb + 1 x por
5675 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5677 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5679 const X86TargetLowering &TLI) {
5680 SDValue V1 = SVOp->getOperand(0);
5681 SDValue V2 = SVOp->getOperand(1);
5682 DebugLoc dl = SVOp->getDebugLoc();
5683 SmallVector<int, 16> MaskVals;
5684 SVOp->getMask(MaskVals);
5686 // If we have SSSE3, case 1 is generated when all result bytes come from
5687 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5688 // present, fall back to case 3.
5689 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5692 for (unsigned i = 0; i < 16; ++i) {
5693 int EltIdx = MaskVals[i];
5702 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5703 if (TLI.getSubtarget()->hasSSSE3()) {
5704 SmallVector<SDValue,16> pshufbMask;
5706 // If all result elements are from one input vector, then only translate
5707 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5709 // Otherwise, we have elements from both input vectors, and must zero out
5710 // elements that come from V2 in the first mask, and V1 in the second mask
5711 // so that we can OR them together.
5712 bool TwoInputs = !(V1Only || V2Only);
5713 for (unsigned i = 0; i != 16; ++i) {
5714 int EltIdx = MaskVals[i];
5715 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5716 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5719 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5721 // If all the elements are from V2, assign it to V1 and return after
5722 // building the first pshufb.
5725 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5726 DAG.getNode(ISD::BUILD_VECTOR, dl,
5727 MVT::v16i8, &pshufbMask[0], 16));
5731 // Calculate the shuffle mask for the second input, shuffle it, and
5732 // OR it with the first shuffled input.
5734 for (unsigned i = 0; i != 16; ++i) {
5735 int EltIdx = MaskVals[i];
5737 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5740 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5742 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5743 DAG.getNode(ISD::BUILD_VECTOR, dl,
5744 MVT::v16i8, &pshufbMask[0], 16));
5745 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5748 // No SSSE3 - Calculate in place words and then fix all out of place words
5749 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5750 // the 16 different words that comprise the two doublequadword input vectors.
5751 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5752 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5753 SDValue NewV = V2Only ? V2 : V1;
5754 for (int i = 0; i != 8; ++i) {
5755 int Elt0 = MaskVals[i*2];
5756 int Elt1 = MaskVals[i*2+1];
5758 // This word of the result is all undef, skip it.
5759 if (Elt0 < 0 && Elt1 < 0)
5762 // This word of the result is already in the correct place, skip it.
5763 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5765 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5768 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5769 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5772 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5773 // using a single extract together, load it and store it.
5774 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5775 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5776 DAG.getIntPtrConstant(Elt1 / 2));
5777 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5778 DAG.getIntPtrConstant(i));
5782 // If Elt1 is defined, extract it from the appropriate source. If the
5783 // source byte is not also odd, shift the extracted word left 8 bits
5784 // otherwise clear the bottom 8 bits if we need to do an or.
5786 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5787 DAG.getIntPtrConstant(Elt1 / 2));
5788 if ((Elt1 & 1) == 0)
5789 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5791 TLI.getShiftAmountTy(InsElt.getValueType())));
5793 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5794 DAG.getConstant(0xFF00, MVT::i16));
5796 // If Elt0 is defined, extract it from the appropriate source. If the
5797 // source byte is not also even, shift the extracted word right 8 bits. If
5798 // Elt1 was also defined, OR the extracted values together before
5799 // inserting them in the result.
5801 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5802 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5803 if ((Elt0 & 1) != 0)
5804 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5806 TLI.getShiftAmountTy(InsElt0.getValueType())));
5808 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5809 DAG.getConstant(0x00FF, MVT::i16));
5810 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5813 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5814 DAG.getIntPtrConstant(i));
5816 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5819 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5820 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5821 /// done when every pair / quad of shuffle mask elements point to elements in
5822 /// the right sequence. e.g.
5823 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5825 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5826 SelectionDAG &DAG, DebugLoc dl) {
5827 EVT VT = SVOp->getValueType(0);
5828 SDValue V1 = SVOp->getOperand(0);
5829 SDValue V2 = SVOp->getOperand(1);
5830 unsigned NumElems = VT.getVectorNumElements();
5831 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5833 switch (VT.getSimpleVT().SimpleTy) {
5834 default: assert(false && "Unexpected!");
5835 case MVT::v4f32: NewVT = MVT::v2f64; break;
5836 case MVT::v4i32: NewVT = MVT::v2i64; break;
5837 case MVT::v8i16: NewVT = MVT::v4i32; break;
5838 case MVT::v16i8: NewVT = MVT::v4i32; break;
5841 int Scale = NumElems / NewWidth;
5842 SmallVector<int, 8> MaskVec;
5843 for (unsigned i = 0; i < NumElems; i += Scale) {
5845 for (int j = 0; j < Scale; ++j) {
5846 int EltIdx = SVOp->getMaskElt(i+j);
5850 StartIdx = EltIdx - (EltIdx % Scale);
5851 if (EltIdx != StartIdx + j)
5855 MaskVec.push_back(-1);
5857 MaskVec.push_back(StartIdx / Scale);
5860 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5861 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5862 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5865 /// getVZextMovL - Return a zero-extending vector move low node.
5867 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5868 SDValue SrcOp, SelectionDAG &DAG,
5869 const X86Subtarget *Subtarget, DebugLoc dl) {
5870 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5871 LoadSDNode *LD = NULL;
5872 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5873 LD = dyn_cast<LoadSDNode>(SrcOp);
5875 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5877 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5878 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5879 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5880 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5881 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5883 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5884 return DAG.getNode(ISD::BITCAST, dl, VT,
5885 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5886 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5894 return DAG.getNode(ISD::BITCAST, dl, VT,
5895 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5896 DAG.getNode(ISD::BITCAST, dl,
5900 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5901 /// shuffle node referes to only one lane in the sources.
5902 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5903 EVT VT = SVOp->getValueType(0);
5904 int NumElems = VT.getVectorNumElements();
5905 int HalfSize = NumElems/2;
5906 SmallVector<int, 16> M;
5908 bool MatchA = false, MatchB = false;
5910 for (int l = 0; l < NumElems*2; l += HalfSize) {
5911 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5917 for (int l = 0; l < NumElems*2; l += HalfSize) {
5918 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5924 return MatchA && MatchB;
5927 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5928 /// which could not be matched by any known target speficic shuffle
5930 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5931 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5932 // If each half of a vector shuffle node referes to only one lane in the
5933 // source vectors, extract each used 128-bit lane and shuffle them using
5934 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5935 // the work to the legalizer.
5936 DebugLoc dl = SVOp->getDebugLoc();
5937 EVT VT = SVOp->getValueType(0);
5938 int NumElems = VT.getVectorNumElements();
5939 int HalfSize = NumElems/2;
5941 // Extract the reference for each half
5942 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5943 int FstVecOpNum = 0, SndVecOpNum = 0;
5944 for (int i = 0; i < HalfSize; ++i) {
5945 int Elt = SVOp->getMaskElt(i);
5946 if (SVOp->getMaskElt(i) < 0)
5948 FstVecOpNum = Elt/NumElems;
5949 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5952 for (int i = HalfSize; i < NumElems; ++i) {
5953 int Elt = SVOp->getMaskElt(i);
5954 if (SVOp->getMaskElt(i) < 0)
5956 SndVecOpNum = Elt/NumElems;
5957 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5961 // Extract the subvectors
5962 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5963 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5964 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5965 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5967 // Generate 128-bit shuffles
5968 SmallVector<int, 16> MaskV1, MaskV2;
5969 for (int i = 0; i < HalfSize; ++i) {
5970 int Elt = SVOp->getMaskElt(i);
5971 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5973 for (int i = HalfSize; i < NumElems; ++i) {
5974 int Elt = SVOp->getMaskElt(i);
5975 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5978 EVT NVT = V1.getValueType();
5979 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5980 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5982 // Concatenate the result back
5983 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5984 DAG.getConstant(0, MVT::i32), DAG, dl);
5985 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5992 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5993 /// 4 elements, and match them with several different shuffle types.
5995 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5996 SDValue V1 = SVOp->getOperand(0);
5997 SDValue V2 = SVOp->getOperand(1);
5998 DebugLoc dl = SVOp->getDebugLoc();
5999 EVT VT = SVOp->getValueType(0);
6001 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6003 SmallVector<std::pair<int, int>, 8> Locs;
6005 SmallVector<int, 8> Mask1(4U, -1);
6006 SmallVector<int, 8> PermMask;
6007 SVOp->getMask(PermMask);
6011 for (unsigned i = 0; i != 4; ++i) {
6012 int Idx = PermMask[i];
6014 Locs[i] = std::make_pair(-1, -1);
6016 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6018 Locs[i] = std::make_pair(0, NumLo);
6022 Locs[i] = std::make_pair(1, NumHi);
6024 Mask1[2+NumHi] = Idx;
6030 if (NumLo <= 2 && NumHi <= 2) {
6031 // If no more than two elements come from either vector. This can be
6032 // implemented with two shuffles. First shuffle gather the elements.
6033 // The second shuffle, which takes the first shuffle as both of its
6034 // vector operands, put the elements into the right order.
6035 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6037 SmallVector<int, 8> Mask2(4U, -1);
6039 for (unsigned i = 0; i != 4; ++i) {
6040 if (Locs[i].first == -1)
6043 unsigned Idx = (i < 2) ? 0 : 4;
6044 Idx += Locs[i].first * 2 + Locs[i].second;
6049 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6050 } else if (NumLo == 3 || NumHi == 3) {
6051 // Otherwise, we must have three elements from one vector, call it X, and
6052 // one element from the other, call it Y. First, use a shufps to build an
6053 // intermediate vector with the one element from Y and the element from X
6054 // that will be in the same half in the final destination (the indexes don't
6055 // matter). Then, use a shufps to build the final vector, taking the half
6056 // containing the element from Y from the intermediate, and the other half
6059 // Normalize it so the 3 elements come from V1.
6060 CommuteVectorShuffleMask(PermMask, VT);
6064 // Find the element from V2.
6066 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6067 int Val = PermMask[HiIndex];
6074 Mask1[0] = PermMask[HiIndex];
6076 Mask1[2] = PermMask[HiIndex^1];
6078 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6081 Mask1[0] = PermMask[0];
6082 Mask1[1] = PermMask[1];
6083 Mask1[2] = HiIndex & 1 ? 6 : 4;
6084 Mask1[3] = HiIndex & 1 ? 4 : 6;
6085 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6087 Mask1[0] = HiIndex & 1 ? 2 : 0;
6088 Mask1[1] = HiIndex & 1 ? 0 : 2;
6089 Mask1[2] = PermMask[2];
6090 Mask1[3] = PermMask[3];
6095 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6099 // Break it into (shuffle shuffle_hi, shuffle_lo).
6102 SmallVector<int,8> LoMask(4U, -1);
6103 SmallVector<int,8> HiMask(4U, -1);
6105 SmallVector<int,8> *MaskPtr = &LoMask;
6106 unsigned MaskIdx = 0;
6109 for (unsigned i = 0; i != 4; ++i) {
6116 int Idx = PermMask[i];
6118 Locs[i] = std::make_pair(-1, -1);
6119 } else if (Idx < 4) {
6120 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6121 (*MaskPtr)[LoIdx] = Idx;
6124 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6125 (*MaskPtr)[HiIdx] = Idx;
6130 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6131 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6132 SmallVector<int, 8> MaskOps;
6133 for (unsigned i = 0; i != 4; ++i) {
6134 if (Locs[i].first == -1) {
6135 MaskOps.push_back(-1);
6137 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6138 MaskOps.push_back(Idx);
6141 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6144 static bool MayFoldVectorLoad(SDValue V) {
6145 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6146 V = V.getOperand(0);
6147 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6148 V = V.getOperand(0);
6154 // FIXME: the version above should always be used. Since there's
6155 // a bug where several vector shuffles can't be folded because the
6156 // DAG is not updated during lowering and a node claims to have two
6157 // uses while it only has one, use this version, and let isel match
6158 // another instruction if the load really happens to have more than
6159 // one use. Remove this version after this bug get fixed.
6160 // rdar://8434668, PR8156
6161 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6162 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6163 V = V.getOperand(0);
6164 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6165 V = V.getOperand(0);
6166 if (ISD::isNormalLoad(V.getNode()))
6171 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6172 /// a vector extract, and if both can be later optimized into a single load.
6173 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6174 /// here because otherwise a target specific shuffle node is going to be
6175 /// emitted for this shuffle, and the optimization not done.
6176 /// FIXME: This is probably not the best approach, but fix the problem
6177 /// until the right path is decided.
6179 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6180 const TargetLowering &TLI) {
6181 EVT VT = V.getValueType();
6182 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6184 // Be sure that the vector shuffle is present in a pattern like this:
6185 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6189 SDNode *N = *V.getNode()->use_begin();
6190 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6193 SDValue EltNo = N->getOperand(1);
6194 if (!isa<ConstantSDNode>(EltNo))
6197 // If the bit convert changed the number of elements, it is unsafe
6198 // to examine the mask.
6199 bool HasShuffleIntoBitcast = false;
6200 if (V.getOpcode() == ISD::BITCAST) {
6201 EVT SrcVT = V.getOperand(0).getValueType();
6202 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6204 V = V.getOperand(0);
6205 HasShuffleIntoBitcast = true;
6208 // Select the input vector, guarding against out of range extract vector.
6209 unsigned NumElems = VT.getVectorNumElements();
6210 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6211 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6212 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6214 // Skip one more bit_convert if necessary
6215 if (V.getOpcode() == ISD::BITCAST)
6216 V = V.getOperand(0);
6218 if (ISD::isNormalLoad(V.getNode())) {
6219 // Is the original load suitable?
6220 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6222 // FIXME: avoid the multi-use bug that is preventing lots of
6223 // of foldings to be detected, this is still wrong of course, but
6224 // give the temporary desired behavior, and if it happens that
6225 // the load has real more uses, during isel it will not fold, and
6226 // will generate poor code.
6227 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6230 if (!HasShuffleIntoBitcast)
6233 // If there's a bitcast before the shuffle, check if the load type and
6234 // alignment is valid.
6235 unsigned Align = LN0->getAlignment();
6237 TLI.getTargetData()->getABITypeAlignment(
6238 VT.getTypeForEVT(*DAG.getContext()));
6240 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6248 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6249 EVT VT = Op.getValueType();
6251 // Canonizalize to v2f64.
6252 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6253 return DAG.getNode(ISD::BITCAST, dl, VT,
6254 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6259 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6261 SDValue V1 = Op.getOperand(0);
6262 SDValue V2 = Op.getOperand(1);
6263 EVT VT = Op.getValueType();
6265 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6267 if (HasSSE2 && VT == MVT::v2f64)
6268 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6270 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6271 return DAG.getNode(ISD::BITCAST, dl, VT,
6272 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6273 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6274 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6278 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6279 SDValue V1 = Op.getOperand(0);
6280 SDValue V2 = Op.getOperand(1);
6281 EVT VT = Op.getValueType();
6283 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6284 "unsupported shuffle type");
6286 if (V2.getOpcode() == ISD::UNDEF)
6290 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6293 static inline unsigned getSHUFPOpcode(EVT VT) {
6294 switch(VT.getSimpleVT().SimpleTy) {
6295 case MVT::v8i32: // Use fp unit for int unpack.
6297 case MVT::v4i32: // Use fp unit for int unpack.
6298 case MVT::v4f32: return X86ISD::SHUFPS;
6299 case MVT::v4i64: // Use fp unit for int unpack.
6301 case MVT::v2i64: // Use fp unit for int unpack.
6302 case MVT::v2f64: return X86ISD::SHUFPD;
6304 llvm_unreachable("Unknown type for shufp*");
6310 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6311 SDValue V1 = Op.getOperand(0);
6312 SDValue V2 = Op.getOperand(1);
6313 EVT VT = Op.getValueType();
6314 unsigned NumElems = VT.getVectorNumElements();
6316 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6317 // operand of these instructions is only memory, so check if there's a
6318 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6320 bool CanFoldLoad = false;
6322 // Trivial case, when V2 comes from a load.
6323 if (MayFoldVectorLoad(V2))
6326 // When V1 is a load, it can be folded later into a store in isel, example:
6327 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6329 // (MOVLPSmr addr:$src1, VR128:$src2)
6330 // So, recognize this potential and also use MOVLPS or MOVLPD
6331 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6334 // Both of them can't be memory operations though.
6335 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6336 CanFoldLoad = false;
6339 if (HasSSE2 && NumElems == 2)
6340 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6343 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6346 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6347 // movl and movlp will both match v2i64, but v2i64 is never matched by
6348 // movl earlier because we make it strict to avoid messing with the movlp load
6349 // folding logic (see the code above getMOVLP call). Match it here then,
6350 // this is horrible, but will stay like this until we move all shuffle
6351 // matching to x86 specific nodes. Note that for the 1st condition all
6352 // types are matched with movsd.
6354 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6355 // as to remove this logic from here, as much as possible
6356 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6357 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6358 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6361 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6363 // Invert the operand order and use SHUFPS to match it.
6364 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6365 X86::getShuffleSHUFImmediate(SVOp), DAG);
6368 static inline unsigned getUNPCKLOpcode(EVT VT) {
6369 switch(VT.getSimpleVT().SimpleTy) {
6370 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6371 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6372 case MVT::v4f32: return X86ISD::UNPCKLPS;
6373 case MVT::v2f64: return X86ISD::UNPCKLPD;
6374 case MVT::v8i32: // Use fp unit for int unpack.
6375 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6376 case MVT::v4i64: // Use fp unit for int unpack.
6377 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6378 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6379 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6381 llvm_unreachable("Unknown type for unpckl");
6386 static inline unsigned getUNPCKHOpcode(EVT VT) {
6387 switch(VT.getSimpleVT().SimpleTy) {
6388 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6389 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6390 case MVT::v4f32: return X86ISD::UNPCKHPS;
6391 case MVT::v2f64: return X86ISD::UNPCKHPD;
6392 case MVT::v8i32: // Use fp unit for int unpack.
6393 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6394 case MVT::v4i64: // Use fp unit for int unpack.
6395 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6396 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6397 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6399 llvm_unreachable("Unknown type for unpckh");
6404 static inline unsigned getVPERMILOpcode(EVT VT) {
6405 switch(VT.getSimpleVT().SimpleTy) {
6407 case MVT::v4f32: return X86ISD::VPERMILPS;
6409 case MVT::v2f64: return X86ISD::VPERMILPD;
6411 case MVT::v8f32: return X86ISD::VPERMILPSY;
6413 case MVT::v4f64: return X86ISD::VPERMILPDY;
6415 llvm_unreachable("Unknown type for vpermil");
6420 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6421 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6422 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6423 static bool isVectorBroadcast(SDValue &Op) {
6424 EVT VT = Op.getValueType();
6425 bool Is256 = VT.getSizeInBits() == 256;
6427 assert((VT.getSizeInBits() == 128 || Is256) &&
6428 "Unsupported type for vbroadcast node");
6431 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6432 V = V.getOperand(0);
6434 if (Is256 && !(V.hasOneUse() &&
6435 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6436 V.getOperand(0).getOpcode() == ISD::UNDEF))
6440 V = V.getOperand(1);
6445 // Check the source scalar_to_vector type. 256-bit broadcasts are
6446 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6447 // for 32-bit scalars.
6448 if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6451 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6452 if (ScalarSize != 32 && ScalarSize != 64)
6454 if (!Is256 && ScalarSize == 64)
6457 V = V.getOperand(0);
6458 if (!MayFoldLoad(V))
6461 // Return the load node
6467 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6468 const TargetLowering &TLI,
6469 const X86Subtarget *Subtarget) {
6470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6471 EVT VT = Op.getValueType();
6472 DebugLoc dl = Op.getDebugLoc();
6473 SDValue V1 = Op.getOperand(0);
6474 SDValue V2 = Op.getOperand(1);
6476 if (isZeroShuffle(SVOp))
6477 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6479 // Handle splat operations
6480 if (SVOp->isSplat()) {
6481 unsigned NumElem = VT.getVectorNumElements();
6482 int Size = VT.getSizeInBits();
6483 // Special case, this is the only place now where it's allowed to return
6484 // a vector_shuffle operation without using a target specific node, because
6485 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6486 // this be moved to DAGCombine instead?
6487 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6490 // Use vbroadcast whenever the splat comes from a foldable load
6491 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6492 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6494 // Handle splats by matching through known shuffle masks
6495 if ((Size == 128 && NumElem <= 4) ||
6496 (Size == 256 && NumElem < 8))
6499 // All remaning splats are promoted to target supported vector shuffles.
6500 return PromoteSplat(SVOp, DAG);
6503 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6505 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6506 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6507 if (NewOp.getNode())
6508 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6509 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6510 // FIXME: Figure out a cleaner way to do this.
6511 // Try to make use of movq to zero out the top part.
6512 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6513 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6514 if (NewOp.getNode()) {
6515 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6516 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6517 DAG, Subtarget, dl);
6519 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6520 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6521 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6522 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6523 DAG, Subtarget, dl);
6530 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6531 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6532 SDValue V1 = Op.getOperand(0);
6533 SDValue V2 = Op.getOperand(1);
6534 EVT VT = Op.getValueType();
6535 DebugLoc dl = Op.getDebugLoc();
6536 unsigned NumElems = VT.getVectorNumElements();
6537 bool isMMX = VT.getSizeInBits() == 64;
6538 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6539 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6540 bool V1IsSplat = false;
6541 bool V2IsSplat = false;
6542 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6543 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6544 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6545 MachineFunction &MF = DAG.getMachineFunction();
6546 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6548 // Shuffle operations on MMX not supported.
6552 // Vector shuffle lowering takes 3 steps:
6554 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6555 // narrowing and commutation of operands should be handled.
6556 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6558 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6559 // so the shuffle can be broken into other shuffles and the legalizer can
6560 // try the lowering again.
6562 // The general ideia is that no vector_shuffle operation should be left to
6563 // be matched during isel, all of them must be converted to a target specific
6566 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6567 // narrowing and commutation of operands should be handled. The actual code
6568 // doesn't include all of those, work in progress...
6569 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6570 if (NewOp.getNode())
6573 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6574 // unpckh_undef). Only use pshufd if speed is more important than size.
6575 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6576 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6577 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6578 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6580 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6581 RelaxedMayFoldVectorLoad(V1))
6582 return getMOVDDup(Op, dl, V1, DAG);
6584 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6585 return getMOVHighToLow(Op, dl, DAG);
6587 // Use to match splats
6588 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6589 (VT == MVT::v2f64 || VT == MVT::v2i64))
6590 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6592 if (X86::isPSHUFDMask(SVOp)) {
6593 // The actual implementation will match the mask in the if above and then
6594 // during isel it can match several different instructions, not only pshufd
6595 // as its name says, sad but true, emulate the behavior for now...
6596 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6597 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6599 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6601 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6602 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6604 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6608 // Check if this can be converted into a logical shift.
6609 bool isLeft = false;
6612 bool isShift = getSubtarget()->hasSSE2() &&
6613 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6614 if (isShift && ShVal.hasOneUse()) {
6615 // If the shifted value has multiple uses, it may be cheaper to use
6616 // v_set0 + movlhps or movhlps, etc.
6617 EVT EltVT = VT.getVectorElementType();
6618 ShAmt *= EltVT.getSizeInBits();
6619 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6622 if (X86::isMOVLMask(SVOp)) {
6625 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6626 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6627 if (!X86::isMOVLPMask(SVOp)) {
6628 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6629 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6631 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6632 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6636 // FIXME: fold these into legal mask.
6637 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6638 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6640 if (X86::isMOVHLPSMask(SVOp))
6641 return getMOVHighToLow(Op, dl, DAG);
6643 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6644 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6646 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6647 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6649 if (X86::isMOVLPMask(SVOp))
6650 return getMOVLP(Op, dl, DAG, HasSSE2);
6652 if (ShouldXformToMOVHLPS(SVOp) ||
6653 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6654 return CommuteVectorShuffle(SVOp, DAG);
6657 // No better options. Use a vshl / vsrl.
6658 EVT EltVT = VT.getVectorElementType();
6659 ShAmt *= EltVT.getSizeInBits();
6660 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6663 bool Commuted = false;
6664 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6665 // 1,1,1,1 -> v8i16 though.
6666 V1IsSplat = isSplatVector(V1.getNode());
6667 V2IsSplat = isSplatVector(V2.getNode());
6669 // Canonicalize the splat or undef, if present, to be on the RHS.
6670 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6671 Op = CommuteVectorShuffle(SVOp, DAG);
6672 SVOp = cast<ShuffleVectorSDNode>(Op);
6673 V1 = SVOp->getOperand(0);
6674 V2 = SVOp->getOperand(1);
6675 std::swap(V1IsSplat, V2IsSplat);
6676 std::swap(V1IsUndef, V2IsUndef);
6680 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6681 // Shuffling low element of v1 into undef, just return v1.
6684 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6685 // the instruction selector will not match, so get a canonical MOVL with
6686 // swapped operands to undo the commute.
6687 return getMOVL(DAG, dl, VT, V2, V1);
6690 if (X86::isUNPCKLMask(SVOp))
6691 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6693 if (X86::isUNPCKHMask(SVOp))
6694 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6697 // Normalize mask so all entries that point to V2 points to its first
6698 // element then try to match unpck{h|l} again. If match, return a
6699 // new vector_shuffle with the corrected mask.
6700 SDValue NewMask = NormalizeMask(SVOp, DAG);
6701 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6702 if (NSVOp != SVOp) {
6703 if (X86::isUNPCKLMask(NSVOp, true)) {
6705 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6712 // Commute is back and try unpck* again.
6713 // FIXME: this seems wrong.
6714 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6715 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6717 if (X86::isUNPCKLMask(NewSVOp))
6718 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6720 if (X86::isUNPCKHMask(NewSVOp))
6721 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6724 // Normalize the node to match x86 shuffle ops if needed
6725 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6726 return CommuteVectorShuffle(SVOp, DAG);
6728 // The checks below are all present in isShuffleMaskLegal, but they are
6729 // inlined here right now to enable us to directly emit target specific
6730 // nodes, and remove one by one until they don't return Op anymore.
6731 SmallVector<int, 16> M;
6734 if (isPALIGNRMask(M, VT, HasSSSE3))
6735 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6736 X86::getShufflePALIGNRImmediate(SVOp),
6739 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6740 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6741 if (VT == MVT::v2f64)
6742 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6743 if (VT == MVT::v2i64)
6744 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6747 if (isPSHUFHWMask(M, VT))
6748 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6749 X86::getShufflePSHUFHWImmediate(SVOp),
6752 if (isPSHUFLWMask(M, VT))
6753 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6754 X86::getShufflePSHUFLWImmediate(SVOp),
6757 if (isSHUFPMask(M, VT))
6758 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6759 X86::getShuffleSHUFImmediate(SVOp), DAG);
6761 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6762 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6763 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6764 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6766 //===--------------------------------------------------------------------===//
6767 // Generate target specific nodes for 128 or 256-bit shuffles only
6768 // supported in the AVX instruction set.
6771 // Handle VMOVDDUPY permutations
6772 if (isMOVDDUPYMask(SVOp, Subtarget))
6773 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6775 // Handle VPERMILPS* permutations
6776 if (isVPERMILPSMask(M, VT, Subtarget))
6777 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6778 getShuffleVPERMILPSImmediate(SVOp), DAG);
6780 // Handle VPERMILPD* permutations
6781 if (isVPERMILPDMask(M, VT, Subtarget))
6782 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6783 getShuffleVPERMILPDImmediate(SVOp), DAG);
6785 // Handle VPERM2F128 permutations
6786 if (isVPERM2F128Mask(M, VT, Subtarget))
6787 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6788 getShuffleVPERM2F128Immediate(SVOp), DAG);
6790 // Handle VSHUFPSY permutations
6791 if (isVSHUFPSYMask(M, VT, Subtarget))
6792 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6793 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6795 // Handle VSHUFPDY permutations
6796 if (isVSHUFPDYMask(M, VT, Subtarget))
6797 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6798 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6800 //===--------------------------------------------------------------------===//
6801 // Since no target specific shuffle was selected for this generic one,
6802 // lower it into other known shuffles. FIXME: this isn't true yet, but
6803 // this is the plan.
6806 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6807 if (VT == MVT::v8i16) {
6808 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6809 if (NewOp.getNode())
6813 if (VT == MVT::v16i8) {
6814 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6815 if (NewOp.getNode())
6819 // Handle all 128-bit wide vectors with 4 elements, and match them with
6820 // several different shuffle types.
6821 if (NumElems == 4 && VT.getSizeInBits() == 128)
6822 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6824 // Handle general 256-bit shuffles
6825 if (VT.is256BitVector())
6826 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6832 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6833 SelectionDAG &DAG) const {
6834 EVT VT = Op.getValueType();
6835 DebugLoc dl = Op.getDebugLoc();
6837 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6840 if (VT.getSizeInBits() == 8) {
6841 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6842 Op.getOperand(0), Op.getOperand(1));
6843 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6844 DAG.getValueType(VT));
6845 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6846 } else if (VT.getSizeInBits() == 16) {
6847 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6848 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6850 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6851 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6852 DAG.getNode(ISD::BITCAST, dl,
6856 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6857 Op.getOperand(0), Op.getOperand(1));
6858 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6859 DAG.getValueType(VT));
6860 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6861 } else if (VT == MVT::f32) {
6862 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6863 // the result back to FR32 register. It's only worth matching if the
6864 // result has a single use which is a store or a bitcast to i32. And in
6865 // the case of a store, it's not worth it if the index is a constant 0,
6866 // because a MOVSSmr can be used instead, which is smaller and faster.
6867 if (!Op.hasOneUse())
6869 SDNode *User = *Op.getNode()->use_begin();
6870 if ((User->getOpcode() != ISD::STORE ||
6871 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6872 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6873 (User->getOpcode() != ISD::BITCAST ||
6874 User->getValueType(0) != MVT::i32))
6876 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6877 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6880 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6881 } else if (VT == MVT::i32) {
6882 // ExtractPS works with constant index.
6883 if (isa<ConstantSDNode>(Op.getOperand(1)))
6891 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6892 SelectionDAG &DAG) const {
6893 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6896 SDValue Vec = Op.getOperand(0);
6897 EVT VecVT = Vec.getValueType();
6899 // If this is a 256-bit vector result, first extract the 128-bit vector and
6900 // then extract the element from the 128-bit vector.
6901 if (VecVT.getSizeInBits() == 256) {
6902 DebugLoc dl = Op.getNode()->getDebugLoc();
6903 unsigned NumElems = VecVT.getVectorNumElements();
6904 SDValue Idx = Op.getOperand(1);
6905 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6907 // Get the 128-bit vector.
6908 bool Upper = IdxVal >= NumElems/2;
6909 Vec = Extract128BitVector(Vec,
6910 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6912 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6913 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6916 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6918 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6919 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6924 EVT VT = Op.getValueType();
6925 DebugLoc dl = Op.getDebugLoc();
6926 // TODO: handle v16i8.
6927 if (VT.getSizeInBits() == 16) {
6928 SDValue Vec = Op.getOperand(0);
6929 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6931 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6932 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6933 DAG.getNode(ISD::BITCAST, dl,
6936 // Transform it so it match pextrw which produces a 32-bit result.
6937 EVT EltVT = MVT::i32;
6938 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6939 Op.getOperand(0), Op.getOperand(1));
6940 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6941 DAG.getValueType(VT));
6942 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6943 } else if (VT.getSizeInBits() == 32) {
6944 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6948 // SHUFPS the element to the lowest double word, then movss.
6949 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6950 EVT VVT = Op.getOperand(0).getValueType();
6951 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6952 DAG.getUNDEF(VVT), Mask);
6953 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6954 DAG.getIntPtrConstant(0));
6955 } else if (VT.getSizeInBits() == 64) {
6956 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6957 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6958 // to match extract_elt for f64.
6959 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6963 // UNPCKHPD the element to the lowest double word, then movsd.
6964 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6965 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6966 int Mask[2] = { 1, -1 };
6967 EVT VVT = Op.getOperand(0).getValueType();
6968 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6969 DAG.getUNDEF(VVT), Mask);
6970 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6971 DAG.getIntPtrConstant(0));
6978 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6979 SelectionDAG &DAG) const {
6980 EVT VT = Op.getValueType();
6981 EVT EltVT = VT.getVectorElementType();
6982 DebugLoc dl = Op.getDebugLoc();
6984 SDValue N0 = Op.getOperand(0);
6985 SDValue N1 = Op.getOperand(1);
6986 SDValue N2 = Op.getOperand(2);
6988 if (VT.getSizeInBits() == 256)
6991 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6992 isa<ConstantSDNode>(N2)) {
6994 if (VT == MVT::v8i16)
6995 Opc = X86ISD::PINSRW;
6996 else if (VT == MVT::v16i8)
6997 Opc = X86ISD::PINSRB;
6999 Opc = X86ISD::PINSRB;
7001 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7003 if (N1.getValueType() != MVT::i32)
7004 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7005 if (N2.getValueType() != MVT::i32)
7006 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7007 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7008 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7009 // Bits [7:6] of the constant are the source select. This will always be
7010 // zero here. The DAG Combiner may combine an extract_elt index into these
7011 // bits. For example (insert (extract, 3), 2) could be matched by putting
7012 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7013 // Bits [5:4] of the constant are the destination select. This is the
7014 // value of the incoming immediate.
7015 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7016 // combine either bitwise AND or insert of float 0.0 to set these bits.
7017 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7018 // Create this as a scalar to vector..
7019 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7020 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7021 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7022 // PINSR* works with constant index.
7029 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7030 EVT VT = Op.getValueType();
7031 EVT EltVT = VT.getVectorElementType();
7033 DebugLoc dl = Op.getDebugLoc();
7034 SDValue N0 = Op.getOperand(0);
7035 SDValue N1 = Op.getOperand(1);
7036 SDValue N2 = Op.getOperand(2);
7038 // If this is a 256-bit vector result, first extract the 128-bit vector,
7039 // insert the element into the extracted half and then place it back.
7040 if (VT.getSizeInBits() == 256) {
7041 if (!isa<ConstantSDNode>(N2))
7044 // Get the desired 128-bit vector half.
7045 unsigned NumElems = VT.getVectorNumElements();
7046 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7047 bool Upper = IdxVal >= NumElems/2;
7048 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7049 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7051 // Insert the element into the desired half.
7052 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7053 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7055 // Insert the changed part back to the 256-bit vector
7056 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7059 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7060 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7062 if (EltVT == MVT::i8)
7065 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7066 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7067 // as its second argument.
7068 if (N1.getValueType() != MVT::i32)
7069 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7070 if (N2.getValueType() != MVT::i32)
7071 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7072 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7078 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7079 LLVMContext *Context = DAG.getContext();
7080 DebugLoc dl = Op.getDebugLoc();
7081 EVT OpVT = Op.getValueType();
7083 // If this is a 256-bit vector result, first insert into a 128-bit
7084 // vector and then insert into the 256-bit vector.
7085 if (OpVT.getSizeInBits() > 128) {
7086 // Insert into a 128-bit vector.
7087 EVT VT128 = EVT::getVectorVT(*Context,
7088 OpVT.getVectorElementType(),
7089 OpVT.getVectorNumElements() / 2);
7091 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7093 // Insert the 128-bit vector.
7094 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7095 DAG.getConstant(0, MVT::i32),
7099 if (Op.getValueType() == MVT::v1i64 &&
7100 Op.getOperand(0).getValueType() == MVT::i64)
7101 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7103 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7104 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7105 "Expected an SSE type!");
7106 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7107 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7110 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7111 // a simple subregister reference or explicit instructions to grab
7112 // upper bits of a vector.
7114 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7115 if (Subtarget->hasAVX()) {
7116 DebugLoc dl = Op.getNode()->getDebugLoc();
7117 SDValue Vec = Op.getNode()->getOperand(0);
7118 SDValue Idx = Op.getNode()->getOperand(1);
7120 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7121 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7122 return Extract128BitVector(Vec, Idx, DAG, dl);
7128 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7129 // simple superregister reference or explicit instructions to insert
7130 // the upper bits of a vector.
7132 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7133 if (Subtarget->hasAVX()) {
7134 DebugLoc dl = Op.getNode()->getDebugLoc();
7135 SDValue Vec = Op.getNode()->getOperand(0);
7136 SDValue SubVec = Op.getNode()->getOperand(1);
7137 SDValue Idx = Op.getNode()->getOperand(2);
7139 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7140 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7141 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7147 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7148 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7149 // one of the above mentioned nodes. It has to be wrapped because otherwise
7150 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7151 // be used to form addressing mode. These wrapped nodes will be selected
7154 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7155 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7157 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7159 unsigned char OpFlag = 0;
7160 unsigned WrapperKind = X86ISD::Wrapper;
7161 CodeModel::Model M = getTargetMachine().getCodeModel();
7163 if (Subtarget->isPICStyleRIPRel() &&
7164 (M == CodeModel::Small || M == CodeModel::Kernel))
7165 WrapperKind = X86ISD::WrapperRIP;
7166 else if (Subtarget->isPICStyleGOT())
7167 OpFlag = X86II::MO_GOTOFF;
7168 else if (Subtarget->isPICStyleStubPIC())
7169 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7171 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7173 CP->getOffset(), OpFlag);
7174 DebugLoc DL = CP->getDebugLoc();
7175 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7176 // With PIC, the address is actually $g + Offset.
7178 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7179 DAG.getNode(X86ISD::GlobalBaseReg,
7180 DebugLoc(), getPointerTy()),
7187 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7188 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7190 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7192 unsigned char OpFlag = 0;
7193 unsigned WrapperKind = X86ISD::Wrapper;
7194 CodeModel::Model M = getTargetMachine().getCodeModel();
7196 if (Subtarget->isPICStyleRIPRel() &&
7197 (M == CodeModel::Small || M == CodeModel::Kernel))
7198 WrapperKind = X86ISD::WrapperRIP;
7199 else if (Subtarget->isPICStyleGOT())
7200 OpFlag = X86II::MO_GOTOFF;
7201 else if (Subtarget->isPICStyleStubPIC())
7202 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7204 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7206 DebugLoc DL = JT->getDebugLoc();
7207 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7209 // With PIC, the address is actually $g + Offset.
7211 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7212 DAG.getNode(X86ISD::GlobalBaseReg,
7213 DebugLoc(), getPointerTy()),
7220 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7221 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7225 unsigned char OpFlag = 0;
7226 unsigned WrapperKind = X86ISD::Wrapper;
7227 CodeModel::Model M = getTargetMachine().getCodeModel();
7229 if (Subtarget->isPICStyleRIPRel() &&
7230 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7231 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7232 OpFlag = X86II::MO_GOTPCREL;
7233 WrapperKind = X86ISD::WrapperRIP;
7234 } else if (Subtarget->isPICStyleGOT()) {
7235 OpFlag = X86II::MO_GOT;
7236 } else if (Subtarget->isPICStyleStubPIC()) {
7237 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7238 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7239 OpFlag = X86II::MO_DARWIN_NONLAZY;
7242 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7244 DebugLoc DL = Op.getDebugLoc();
7245 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7248 // With PIC, the address is actually $g + Offset.
7249 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7250 !Subtarget->is64Bit()) {
7251 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7252 DAG.getNode(X86ISD::GlobalBaseReg,
7253 DebugLoc(), getPointerTy()),
7257 // For symbols that require a load from a stub to get the address, emit the
7259 if (isGlobalStubReference(OpFlag))
7260 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7261 MachinePointerInfo::getGOT(), false, false, 0);
7267 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7268 // Create the TargetBlockAddressAddress node.
7269 unsigned char OpFlags =
7270 Subtarget->ClassifyBlockAddressReference();
7271 CodeModel::Model M = getTargetMachine().getCodeModel();
7272 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7273 DebugLoc dl = Op.getDebugLoc();
7274 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7275 /*isTarget=*/true, OpFlags);
7277 if (Subtarget->isPICStyleRIPRel() &&
7278 (M == CodeModel::Small || M == CodeModel::Kernel))
7279 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7281 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7283 // With PIC, the address is actually $g + Offset.
7284 if (isGlobalRelativeToPICBase(OpFlags)) {
7285 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7286 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7294 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7296 SelectionDAG &DAG) const {
7297 // Create the TargetGlobalAddress node, folding in the constant
7298 // offset if it is legal.
7299 unsigned char OpFlags =
7300 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7301 CodeModel::Model M = getTargetMachine().getCodeModel();
7303 if (OpFlags == X86II::MO_NO_FLAG &&
7304 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7305 // A direct static reference to a global.
7306 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7309 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7312 if (Subtarget->isPICStyleRIPRel() &&
7313 (M == CodeModel::Small || M == CodeModel::Kernel))
7314 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7316 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7318 // With PIC, the address is actually $g + Offset.
7319 if (isGlobalRelativeToPICBase(OpFlags)) {
7320 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7321 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7325 // For globals that require a load from a stub to get the address, emit the
7327 if (isGlobalStubReference(OpFlags))
7328 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7329 MachinePointerInfo::getGOT(), false, false, 0);
7331 // If there was a non-zero offset that we didn't fold, create an explicit
7334 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7335 DAG.getConstant(Offset, getPointerTy()));
7341 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7342 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7343 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7344 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7348 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7349 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7350 unsigned char OperandFlags) {
7351 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7352 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7353 DebugLoc dl = GA->getDebugLoc();
7354 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7355 GA->getValueType(0),
7359 SDValue Ops[] = { Chain, TGA, *InFlag };
7360 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7362 SDValue Ops[] = { Chain, TGA };
7363 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7366 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7367 MFI->setAdjustsStack(true);
7369 SDValue Flag = Chain.getValue(1);
7370 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7373 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7375 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7378 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7379 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7380 DAG.getNode(X86ISD::GlobalBaseReg,
7381 DebugLoc(), PtrVT), InFlag);
7382 InFlag = Chain.getValue(1);
7384 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7387 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7389 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7391 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7392 X86::RAX, X86II::MO_TLSGD);
7395 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7396 // "local exec" model.
7397 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7398 const EVT PtrVT, TLSModel::Model model,
7400 DebugLoc dl = GA->getDebugLoc();
7402 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7403 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7404 is64Bit ? 257 : 256));
7406 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7407 DAG.getIntPtrConstant(0),
7408 MachinePointerInfo(Ptr), false, false, 0);
7410 unsigned char OperandFlags = 0;
7411 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7413 unsigned WrapperKind = X86ISD::Wrapper;
7414 if (model == TLSModel::LocalExec) {
7415 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7416 } else if (is64Bit) {
7417 assert(model == TLSModel::InitialExec);
7418 OperandFlags = X86II::MO_GOTTPOFF;
7419 WrapperKind = X86ISD::WrapperRIP;
7421 assert(model == TLSModel::InitialExec);
7422 OperandFlags = X86II::MO_INDNTPOFF;
7425 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7427 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7428 GA->getValueType(0),
7429 GA->getOffset(), OperandFlags);
7430 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7432 if (model == TLSModel::InitialExec)
7433 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7434 MachinePointerInfo::getGOT(), false, false, 0);
7436 // The address of the thread local variable is the add of the thread
7437 // pointer with the offset of the variable.
7438 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7442 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7444 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7445 const GlobalValue *GV = GA->getGlobal();
7447 if (Subtarget->isTargetELF()) {
7448 // TODO: implement the "local dynamic" model
7449 // TODO: implement the "initial exec"model for pic executables
7451 // If GV is an alias then use the aliasee for determining
7452 // thread-localness.
7453 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7454 GV = GA->resolveAliasedGlobal(false);
7456 TLSModel::Model model
7457 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7460 case TLSModel::GeneralDynamic:
7461 case TLSModel::LocalDynamic: // not implemented
7462 if (Subtarget->is64Bit())
7463 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7464 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7466 case TLSModel::InitialExec:
7467 case TLSModel::LocalExec:
7468 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7469 Subtarget->is64Bit());
7471 } else if (Subtarget->isTargetDarwin()) {
7472 // Darwin only has one model of TLS. Lower to that.
7473 unsigned char OpFlag = 0;
7474 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7475 X86ISD::WrapperRIP : X86ISD::Wrapper;
7477 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7479 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7480 !Subtarget->is64Bit();
7482 OpFlag = X86II::MO_TLVP_PIC_BASE;
7484 OpFlag = X86II::MO_TLVP;
7485 DebugLoc DL = Op.getDebugLoc();
7486 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7487 GA->getValueType(0),
7488 GA->getOffset(), OpFlag);
7489 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7491 // With PIC32, the address is actually $g + Offset.
7493 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494 DAG.getNode(X86ISD::GlobalBaseReg,
7495 DebugLoc(), getPointerTy()),
7498 // Lowering the machine isd will make sure everything is in the right
7500 SDValue Chain = DAG.getEntryNode();
7501 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7502 SDValue Args[] = { Chain, Offset };
7503 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7505 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7506 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7507 MFI->setAdjustsStack(true);
7509 // And our return value (tls address) is in the standard call return value
7511 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7512 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7516 "TLS not implemented for this target.");
7518 llvm_unreachable("Unreachable");
7523 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7524 /// take a 2 x i32 value to shift plus a shift amount.
7525 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7526 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7527 EVT VT = Op.getValueType();
7528 unsigned VTBits = VT.getSizeInBits();
7529 DebugLoc dl = Op.getDebugLoc();
7530 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7531 SDValue ShOpLo = Op.getOperand(0);
7532 SDValue ShOpHi = Op.getOperand(1);
7533 SDValue ShAmt = Op.getOperand(2);
7534 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7535 DAG.getConstant(VTBits - 1, MVT::i8))
7536 : DAG.getConstant(0, VT);
7539 if (Op.getOpcode() == ISD::SHL_PARTS) {
7540 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7541 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7543 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7544 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7547 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7548 DAG.getConstant(VTBits, MVT::i8));
7549 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7550 AndNode, DAG.getConstant(0, MVT::i8));
7553 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7554 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7555 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7557 if (Op.getOpcode() == ISD::SHL_PARTS) {
7558 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7559 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7561 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7562 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7565 SDValue Ops[2] = { Lo, Hi };
7566 return DAG.getMergeValues(Ops, 2, dl);
7569 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7570 SelectionDAG &DAG) const {
7571 EVT SrcVT = Op.getOperand(0).getValueType();
7573 if (SrcVT.isVector())
7576 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7577 "Unknown SINT_TO_FP to lower!");
7579 // These are really Legal; return the operand so the caller accepts it as
7581 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7583 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7584 Subtarget->is64Bit()) {
7588 DebugLoc dl = Op.getDebugLoc();
7589 unsigned Size = SrcVT.getSizeInBits()/8;
7590 MachineFunction &MF = DAG.getMachineFunction();
7591 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7592 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7593 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7595 MachinePointerInfo::getFixedStack(SSFI),
7597 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7600 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7602 SelectionDAG &DAG) const {
7604 DebugLoc DL = Op.getDebugLoc();
7606 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7608 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7610 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7612 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7614 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7615 MachineMemOperand *MMO;
7617 int SSFI = FI->getIndex();
7619 DAG.getMachineFunction()
7620 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7621 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7623 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7624 StackSlot = StackSlot.getOperand(1);
7626 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7627 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7629 Tys, Ops, array_lengthof(Ops),
7633 Chain = Result.getValue(1);
7634 SDValue InFlag = Result.getValue(2);
7636 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7637 // shouldn't be necessary except that RFP cannot be live across
7638 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7639 MachineFunction &MF = DAG.getMachineFunction();
7640 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7641 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7642 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7643 Tys = DAG.getVTList(MVT::Other);
7645 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7647 MachineMemOperand *MMO =
7648 DAG.getMachineFunction()
7649 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7650 MachineMemOperand::MOStore, SSFISize, SSFISize);
7652 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7653 Ops, array_lengthof(Ops),
7654 Op.getValueType(), MMO);
7655 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7656 MachinePointerInfo::getFixedStack(SSFI),
7663 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7664 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7665 SelectionDAG &DAG) const {
7666 // This algorithm is not obvious. Here it is in C code, more or less:
7668 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7669 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7670 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7672 // Copy ints to xmm registers.
7673 __m128i xh = _mm_cvtsi32_si128( hi );
7674 __m128i xl = _mm_cvtsi32_si128( lo );
7676 // Combine into low half of a single xmm register.
7677 __m128i x = _mm_unpacklo_epi32( xh, xl );
7681 // Merge in appropriate exponents to give the integer bits the right
7683 x = _mm_unpacklo_epi32( x, exp );
7685 // Subtract away the biases to deal with the IEEE-754 double precision
7687 d = _mm_sub_pd( (__m128d) x, bias );
7689 // All conversions up to here are exact. The correctly rounded result is
7690 // calculated using the current rounding mode using the following
7692 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7693 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7694 // store doesn't really need to be here (except
7695 // maybe to zero the other double)
7700 DebugLoc dl = Op.getDebugLoc();
7701 LLVMContext *Context = DAG.getContext();
7703 // Build some magic constants.
7704 std::vector<Constant*> CV0;
7705 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7706 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7707 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7708 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7709 Constant *C0 = ConstantVector::get(CV0);
7710 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7712 std::vector<Constant*> CV1;
7714 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7716 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7717 Constant *C1 = ConstantVector::get(CV1);
7718 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7720 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7721 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7723 DAG.getIntPtrConstant(1)));
7724 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7725 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7727 DAG.getIntPtrConstant(0)));
7728 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7729 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7730 MachinePointerInfo::getConstantPool(),
7732 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7733 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7734 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7735 MachinePointerInfo::getConstantPool(),
7737 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7739 // Add the halves; easiest way is to swap them into another reg first.
7740 int ShufMask[2] = { 1, -1 };
7741 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7742 DAG.getUNDEF(MVT::v2f64), ShufMask);
7743 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7744 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7745 DAG.getIntPtrConstant(0));
7748 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7749 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7750 SelectionDAG &DAG) const {
7751 DebugLoc dl = Op.getDebugLoc();
7752 // FP constant to bias correct the final result.
7753 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7756 // Load the 32-bit value into an XMM register.
7757 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7760 // Zero out the upper parts of the register.
7761 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG);
7763 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7764 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7765 DAG.getIntPtrConstant(0));
7767 // Or the load with the bias.
7768 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7769 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7770 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7772 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7773 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7774 MVT::v2f64, Bias)));
7775 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7776 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7777 DAG.getIntPtrConstant(0));
7779 // Subtract the bias.
7780 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7782 // Handle final rounding.
7783 EVT DestVT = Op.getValueType();
7785 if (DestVT.bitsLT(MVT::f64)) {
7786 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7787 DAG.getIntPtrConstant(0));
7788 } else if (DestVT.bitsGT(MVT::f64)) {
7789 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7792 // Handle final rounding.
7796 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7797 SelectionDAG &DAG) const {
7798 SDValue N0 = Op.getOperand(0);
7799 DebugLoc dl = Op.getDebugLoc();
7801 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7802 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7803 // the optimization here.
7804 if (DAG.SignBitIsZero(N0))
7805 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7807 EVT SrcVT = N0.getValueType();
7808 EVT DstVT = Op.getValueType();
7809 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7810 return LowerUINT_TO_FP_i64(Op, DAG);
7811 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7812 return LowerUINT_TO_FP_i32(Op, DAG);
7814 // Make a 64-bit buffer, and use it to build an FILD.
7815 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7816 if (SrcVT == MVT::i32) {
7817 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7818 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7819 getPointerTy(), StackSlot, WordOff);
7820 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7821 StackSlot, MachinePointerInfo(),
7823 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7824 OffsetSlot, MachinePointerInfo(),
7826 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7830 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7831 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7832 StackSlot, MachinePointerInfo(),
7834 // For i64 source, we need to add the appropriate power of 2 if the input
7835 // was negative. This is the same as the optimization in
7836 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7837 // we must be careful to do the computation in x87 extended precision, not
7838 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7839 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7840 MachineMemOperand *MMO =
7841 DAG.getMachineFunction()
7842 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7843 MachineMemOperand::MOLoad, 8, 8);
7845 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7846 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7847 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7850 APInt FF(32, 0x5F800000ULL);
7852 // Check whether the sign bit is set.
7853 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7854 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7857 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7858 SDValue FudgePtr = DAG.getConstantPool(
7859 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7862 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7863 SDValue Zero = DAG.getIntPtrConstant(0);
7864 SDValue Four = DAG.getIntPtrConstant(4);
7865 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7867 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7869 // Load the value out, extending it from f32 to f80.
7870 // FIXME: Avoid the extend by constructing the right constant pool?
7871 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7872 FudgePtr, MachinePointerInfo::getConstantPool(),
7873 MVT::f32, false, false, 4);
7874 // Extend everything to 80 bits to force it to be done on x87.
7875 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7876 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7879 std::pair<SDValue,SDValue> X86TargetLowering::
7880 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7881 DebugLoc DL = Op.getDebugLoc();
7883 EVT DstTy = Op.getValueType();
7886 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7890 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7891 DstTy.getSimpleVT() >= MVT::i16 &&
7892 "Unknown FP_TO_SINT to lower!");
7894 // These are really Legal.
7895 if (DstTy == MVT::i32 &&
7896 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7897 return std::make_pair(SDValue(), SDValue());
7898 if (Subtarget->is64Bit() &&
7899 DstTy == MVT::i64 &&
7900 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7901 return std::make_pair(SDValue(), SDValue());
7903 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7905 MachineFunction &MF = DAG.getMachineFunction();
7906 unsigned MemSize = DstTy.getSizeInBits()/8;
7907 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7908 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913 switch (DstTy.getSimpleVT().SimpleTy) {
7914 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7915 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7916 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7917 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7920 SDValue Chain = DAG.getEntryNode();
7921 SDValue Value = Op.getOperand(0);
7922 EVT TheVT = Op.getOperand(0).getValueType();
7923 if (isScalarFPTypeInSSEReg(TheVT)) {
7924 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7925 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7926 MachinePointerInfo::getFixedStack(SSFI),
7928 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7930 Chain, StackSlot, DAG.getValueType(TheVT)
7933 MachineMemOperand *MMO =
7934 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7935 MachineMemOperand::MOLoad, MemSize, MemSize);
7936 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7938 Chain = Value.getValue(1);
7939 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7940 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7943 MachineMemOperand *MMO =
7944 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7945 MachineMemOperand::MOStore, MemSize, MemSize);
7947 // Build the FP_TO_INT*_IN_MEM
7948 SDValue Ops[] = { Chain, Value, StackSlot };
7949 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7950 Ops, 3, DstTy, MMO);
7952 return std::make_pair(FIST, StackSlot);
7955 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7956 SelectionDAG &DAG) const {
7957 if (Op.getValueType().isVector())
7960 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7961 SDValue FIST = Vals.first, StackSlot = Vals.second;
7962 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7963 if (FIST.getNode() == 0) return Op;
7966 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7967 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7970 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7971 SelectionDAG &DAG) const {
7972 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7973 SDValue FIST = Vals.first, StackSlot = Vals.second;
7974 assert(FIST.getNode() && "Unexpected failure");
7977 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7978 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7981 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7982 SelectionDAG &DAG) const {
7983 LLVMContext *Context = DAG.getContext();
7984 DebugLoc dl = Op.getDebugLoc();
7985 EVT VT = Op.getValueType();
7988 EltVT = VT.getVectorElementType();
7989 std::vector<Constant*> CV;
7990 if (EltVT == MVT::f64) {
7991 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7995 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8001 Constant *C = ConstantVector::get(CV);
8002 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8003 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8004 MachinePointerInfo::getConstantPool(),
8006 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8009 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8010 LLVMContext *Context = DAG.getContext();
8011 DebugLoc dl = Op.getDebugLoc();
8012 EVT VT = Op.getValueType();
8015 EltVT = VT.getVectorElementType();
8016 std::vector<Constant*> CV;
8017 if (EltVT == MVT::f64) {
8018 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8022 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8028 Constant *C = ConstantVector::get(CV);
8029 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8030 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8031 MachinePointerInfo::getConstantPool(),
8033 if (VT.isVector()) {
8034 return DAG.getNode(ISD::BITCAST, dl, VT,
8035 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8036 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8038 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8040 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8044 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8045 LLVMContext *Context = DAG.getContext();
8046 SDValue Op0 = Op.getOperand(0);
8047 SDValue Op1 = Op.getOperand(1);
8048 DebugLoc dl = Op.getDebugLoc();
8049 EVT VT = Op.getValueType();
8050 EVT SrcVT = Op1.getValueType();
8052 // If second operand is smaller, extend it first.
8053 if (SrcVT.bitsLT(VT)) {
8054 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8057 // And if it is bigger, shrink it first.
8058 if (SrcVT.bitsGT(VT)) {
8059 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8063 // At this point the operands and the result should have the same
8064 // type, and that won't be f80 since that is not custom lowered.
8066 // First get the sign bit of second operand.
8067 std::vector<Constant*> CV;
8068 if (SrcVT == MVT::f64) {
8069 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8070 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8072 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8073 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8074 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8075 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8077 Constant *C = ConstantVector::get(CV);
8078 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8079 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8080 MachinePointerInfo::getConstantPool(),
8082 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8084 // Shift sign bit right or left if the two operands have different types.
8085 if (SrcVT.bitsGT(VT)) {
8086 // Op0 is MVT::f32, Op1 is MVT::f64.
8087 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8088 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8089 DAG.getConstant(32, MVT::i32));
8090 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8091 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8092 DAG.getIntPtrConstant(0));
8095 // Clear first operand sign bit.
8097 if (VT == MVT::f64) {
8098 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8099 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8101 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8102 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8103 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8104 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8106 C = ConstantVector::get(CV);
8107 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8108 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8109 MachinePointerInfo::getConstantPool(),
8111 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8113 // Or the value with the sign bit.
8114 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8117 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8118 SDValue N0 = Op.getOperand(0);
8119 DebugLoc dl = Op.getDebugLoc();
8120 EVT VT = Op.getValueType();
8122 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8123 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8124 DAG.getConstant(1, VT));
8125 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8128 /// Emit nodes that will be selected as "test Op0,Op0", or something
8130 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8131 SelectionDAG &DAG) const {
8132 DebugLoc dl = Op.getDebugLoc();
8134 // CF and OF aren't always set the way we want. Determine which
8135 // of these we need.
8136 bool NeedCF = false;
8137 bool NeedOF = false;
8140 case X86::COND_A: case X86::COND_AE:
8141 case X86::COND_B: case X86::COND_BE:
8144 case X86::COND_G: case X86::COND_GE:
8145 case X86::COND_L: case X86::COND_LE:
8146 case X86::COND_O: case X86::COND_NO:
8151 // See if we can use the EFLAGS value from the operand instead of
8152 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8153 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8154 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8155 // Emit a CMP with 0, which is the TEST pattern.
8156 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8157 DAG.getConstant(0, Op.getValueType()));
8159 unsigned Opcode = 0;
8160 unsigned NumOperands = 0;
8161 switch (Op.getNode()->getOpcode()) {
8163 // Due to an isel shortcoming, be conservative if this add is likely to be
8164 // selected as part of a load-modify-store instruction. When the root node
8165 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8166 // uses of other nodes in the match, such as the ADD in this case. This
8167 // leads to the ADD being left around and reselected, with the result being
8168 // two adds in the output. Alas, even if none our users are stores, that
8169 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8170 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8171 // climbing the DAG back to the root, and it doesn't seem to be worth the
8173 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8174 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8175 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8178 if (ConstantSDNode *C =
8179 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8180 // An add of one will be selected as an INC.
8181 if (C->getAPIntValue() == 1) {
8182 Opcode = X86ISD::INC;
8187 // An add of negative one (subtract of one) will be selected as a DEC.
8188 if (C->getAPIntValue().isAllOnesValue()) {
8189 Opcode = X86ISD::DEC;
8195 // Otherwise use a regular EFLAGS-setting add.
8196 Opcode = X86ISD::ADD;
8200 // If the primary and result isn't used, don't bother using X86ISD::AND,
8201 // because a TEST instruction will be better.
8202 bool NonFlagUse = false;
8203 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8204 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8206 unsigned UOpNo = UI.getOperandNo();
8207 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8208 // Look pass truncate.
8209 UOpNo = User->use_begin().getOperandNo();
8210 User = *User->use_begin();
8213 if (User->getOpcode() != ISD::BRCOND &&
8214 User->getOpcode() != ISD::SETCC &&
8215 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8228 // Due to the ISEL shortcoming noted above, be conservative if this op is
8229 // likely to be selected as part of a load-modify-store instruction.
8230 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8231 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8232 if (UI->getOpcode() == ISD::STORE)
8235 // Otherwise use a regular EFLAGS-setting instruction.
8236 switch (Op.getNode()->getOpcode()) {
8237 default: llvm_unreachable("unexpected operator!");
8238 case ISD::SUB: Opcode = X86ISD::SUB; break;
8239 case ISD::OR: Opcode = X86ISD::OR; break;
8240 case ISD::XOR: Opcode = X86ISD::XOR; break;
8241 case ISD::AND: Opcode = X86ISD::AND; break;
8253 return SDValue(Op.getNode(), 1);
8260 // Emit a CMP with 0, which is the TEST pattern.
8261 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8262 DAG.getConstant(0, Op.getValueType()));
8264 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8265 SmallVector<SDValue, 4> Ops;
8266 for (unsigned i = 0; i != NumOperands; ++i)
8267 Ops.push_back(Op.getOperand(i));
8269 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8270 DAG.ReplaceAllUsesWith(Op, New);
8271 return SDValue(New.getNode(), 1);
8274 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8276 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8277 SelectionDAG &DAG) const {
8278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8279 if (C->getAPIntValue() == 0)
8280 return EmitTest(Op0, X86CC, DAG);
8282 DebugLoc dl = Op0.getDebugLoc();
8283 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8286 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8287 /// if it's possible.
8288 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8289 DebugLoc dl, SelectionDAG &DAG) const {
8290 SDValue Op0 = And.getOperand(0);
8291 SDValue Op1 = And.getOperand(1);
8292 if (Op0.getOpcode() == ISD::TRUNCATE)
8293 Op0 = Op0.getOperand(0);
8294 if (Op1.getOpcode() == ISD::TRUNCATE)
8295 Op1 = Op1.getOperand(0);
8298 if (Op1.getOpcode() == ISD::SHL)
8299 std::swap(Op0, Op1);
8300 if (Op0.getOpcode() == ISD::SHL) {
8301 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8302 if (And00C->getZExtValue() == 1) {
8303 // If we looked past a truncate, check that it's only truncating away
8305 unsigned BitWidth = Op0.getValueSizeInBits();
8306 unsigned AndBitWidth = And.getValueSizeInBits();
8307 if (BitWidth > AndBitWidth) {
8308 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8309 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8310 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8314 RHS = Op0.getOperand(1);
8316 } else if (Op1.getOpcode() == ISD::Constant) {
8317 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8318 SDValue AndLHS = Op0;
8319 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8320 LHS = AndLHS.getOperand(0);
8321 RHS = AndLHS.getOperand(1);
8325 if (LHS.getNode()) {
8326 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8327 // instruction. Since the shift amount is in-range-or-undefined, we know
8328 // that doing a bittest on the i32 value is ok. We extend to i32 because
8329 // the encoding for the i16 version is larger than the i32 version.
8330 // Also promote i16 to i32 for performance / code size reason.
8331 if (LHS.getValueType() == MVT::i8 ||
8332 LHS.getValueType() == MVT::i16)
8333 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8335 // If the operand types disagree, extend the shift amount to match. Since
8336 // BT ignores high bits (like shifts) we can use anyextend.
8337 if (LHS.getValueType() != RHS.getValueType())
8338 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8340 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8341 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8342 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8343 DAG.getConstant(Cond, MVT::i8), BT);
8349 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8351 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8353 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8354 SDValue Op0 = Op.getOperand(0);
8355 SDValue Op1 = Op.getOperand(1);
8356 DebugLoc dl = Op.getDebugLoc();
8357 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8359 // Optimize to BT if possible.
8360 // Lower (X & (1 << N)) == 0 to BT(X, N).
8361 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8362 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8363 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8364 Op1.getOpcode() == ISD::Constant &&
8365 cast<ConstantSDNode>(Op1)->isNullValue() &&
8366 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8367 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8368 if (NewSetCC.getNode())
8372 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8374 if (Op1.getOpcode() == ISD::Constant &&
8375 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8376 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8377 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8379 // If the input is a setcc, then reuse the input setcc or use a new one with
8380 // the inverted condition.
8381 if (Op0.getOpcode() == X86ISD::SETCC) {
8382 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8383 bool Invert = (CC == ISD::SETNE) ^
8384 cast<ConstantSDNode>(Op1)->isNullValue();
8385 if (!Invert) return Op0;
8387 CCode = X86::GetOppositeBranchCondition(CCode);
8388 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8389 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8393 bool isFP = Op1.getValueType().isFloatingPoint();
8394 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8395 if (X86CC == X86::COND_INVALID)
8398 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8399 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8400 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8403 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8404 // ones, and then concatenate the result back.
8405 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8406 EVT VT = Op.getValueType();
8408 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8409 "Unsupported value type for operation");
8411 int NumElems = VT.getVectorNumElements();
8412 DebugLoc dl = Op.getDebugLoc();
8413 SDValue CC = Op.getOperand(2);
8414 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8415 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8417 // Extract the LHS vectors
8418 SDValue LHS = Op.getOperand(0);
8419 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8420 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8422 // Extract the RHS vectors
8423 SDValue RHS = Op.getOperand(1);
8424 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8425 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8427 // Issue the operation on the smaller types and concatenate the result back
8428 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8429 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8430 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8431 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8432 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8436 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8438 SDValue Op0 = Op.getOperand(0);
8439 SDValue Op1 = Op.getOperand(1);
8440 SDValue CC = Op.getOperand(2);
8441 EVT VT = Op.getValueType();
8442 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8443 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8444 DebugLoc dl = Op.getDebugLoc();
8448 EVT EltVT = Op0.getValueType().getVectorElementType();
8449 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8451 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8454 // SSE Condition code mapping:
8463 switch (SetCCOpcode) {
8466 case ISD::SETEQ: SSECC = 0; break;
8468 case ISD::SETGT: Swap = true; // Fallthrough
8470 case ISD::SETOLT: SSECC = 1; break;
8472 case ISD::SETGE: Swap = true; // Fallthrough
8474 case ISD::SETOLE: SSECC = 2; break;
8475 case ISD::SETUO: SSECC = 3; break;
8477 case ISD::SETNE: SSECC = 4; break;
8478 case ISD::SETULE: Swap = true;
8479 case ISD::SETUGE: SSECC = 5; break;
8480 case ISD::SETULT: Swap = true;
8481 case ISD::SETUGT: SSECC = 6; break;
8482 case ISD::SETO: SSECC = 7; break;
8485 std::swap(Op0, Op1);
8487 // In the two special cases we can't handle, emit two comparisons.
8489 if (SetCCOpcode == ISD::SETUEQ) {
8491 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8492 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8493 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8495 else if (SetCCOpcode == ISD::SETONE) {
8497 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8498 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8499 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8501 llvm_unreachable("Illegal FP comparison");
8503 // Handle all other FP comparisons here.
8504 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8507 // Break 256-bit integer vector compare into smaller ones.
8508 if (!isFP && VT.getSizeInBits() == 256)
8509 return Lower256IntVETCC(Op, DAG);
8511 // We are handling one of the integer comparisons here. Since SSE only has
8512 // GT and EQ comparisons for integer, swapping operands and multiple
8513 // operations may be required for some comparisons.
8514 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8515 bool Swap = false, Invert = false, FlipSigns = false;
8517 switch (VT.getSimpleVT().SimpleTy) {
8519 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8520 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8521 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8522 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8525 switch (SetCCOpcode) {
8527 case ISD::SETNE: Invert = true;
8528 case ISD::SETEQ: Opc = EQOpc; break;
8529 case ISD::SETLT: Swap = true;
8530 case ISD::SETGT: Opc = GTOpc; break;
8531 case ISD::SETGE: Swap = true;
8532 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8533 case ISD::SETULT: Swap = true;
8534 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8535 case ISD::SETUGE: Swap = true;
8536 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8539 std::swap(Op0, Op1);
8541 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8542 // bits of the inputs before performing those operations.
8544 EVT EltVT = VT.getVectorElementType();
8545 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8547 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8548 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8550 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8551 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8554 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8556 // If the logical-not of the result is required, perform that now.
8558 Result = DAG.getNOT(dl, Result, VT);
8563 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8564 static bool isX86LogicalCmp(SDValue Op) {
8565 unsigned Opc = Op.getNode()->getOpcode();
8566 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8568 if (Op.getResNo() == 1 &&
8569 (Opc == X86ISD::ADD ||
8570 Opc == X86ISD::SUB ||
8571 Opc == X86ISD::ADC ||
8572 Opc == X86ISD::SBB ||
8573 Opc == X86ISD::SMUL ||
8574 Opc == X86ISD::UMUL ||
8575 Opc == X86ISD::INC ||
8576 Opc == X86ISD::DEC ||
8577 Opc == X86ISD::OR ||
8578 Opc == X86ISD::XOR ||
8579 Opc == X86ISD::AND))
8582 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8588 static bool isZero(SDValue V) {
8589 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8590 return C && C->isNullValue();
8593 static bool isAllOnes(SDValue V) {
8594 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8595 return C && C->isAllOnesValue();
8598 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8599 bool addTest = true;
8600 SDValue Cond = Op.getOperand(0);
8601 SDValue Op1 = Op.getOperand(1);
8602 SDValue Op2 = Op.getOperand(2);
8603 DebugLoc DL = Op.getDebugLoc();
8606 if (Cond.getOpcode() == ISD::SETCC) {
8607 SDValue NewCond = LowerSETCC(Cond, DAG);
8608 if (NewCond.getNode())
8612 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8613 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8614 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8615 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8616 if (Cond.getOpcode() == X86ISD::SETCC &&
8617 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8618 isZero(Cond.getOperand(1).getOperand(1))) {
8619 SDValue Cmp = Cond.getOperand(1);
8621 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8623 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8624 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8625 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8627 SDValue CmpOp0 = Cmp.getOperand(0);
8628 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8629 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8631 SDValue Res = // Res = 0 or -1.
8632 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8633 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8635 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8636 Res = DAG.getNOT(DL, Res, Res.getValueType());
8638 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8639 if (N2C == 0 || !N2C->isNullValue())
8640 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8645 // Look past (and (setcc_carry (cmp ...)), 1).
8646 if (Cond.getOpcode() == ISD::AND &&
8647 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8649 if (C && C->getAPIntValue() == 1)
8650 Cond = Cond.getOperand(0);
8653 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8654 // setting operand in place of the X86ISD::SETCC.
8655 if (Cond.getOpcode() == X86ISD::SETCC ||
8656 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8657 CC = Cond.getOperand(0);
8659 SDValue Cmp = Cond.getOperand(1);
8660 unsigned Opc = Cmp.getOpcode();
8661 EVT VT = Op.getValueType();
8663 bool IllegalFPCMov = false;
8664 if (VT.isFloatingPoint() && !VT.isVector() &&
8665 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8666 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8668 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8669 Opc == X86ISD::BT) { // FIXME
8676 // Look pass the truncate.
8677 if (Cond.getOpcode() == ISD::TRUNCATE)
8678 Cond = Cond.getOperand(0);
8680 // We know the result of AND is compared against zero. Try to match
8682 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8683 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8684 if (NewSetCC.getNode()) {
8685 CC = NewSetCC.getOperand(0);
8686 Cond = NewSetCC.getOperand(1);
8693 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8694 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8697 // a < b ? -1 : 0 -> RES = ~setcc_carry
8698 // a < b ? 0 : -1 -> RES = setcc_carry
8699 // a >= b ? -1 : 0 -> RES = setcc_carry
8700 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8701 if (Cond.getOpcode() == X86ISD::CMP) {
8702 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8704 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8705 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8706 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8707 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8708 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8709 return DAG.getNOT(DL, Res, Res.getValueType());
8714 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8715 // condition is true.
8716 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8717 SDValue Ops[] = { Op2, Op1, CC, Cond };
8718 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8721 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8722 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8723 // from the AND / OR.
8724 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8725 Opc = Op.getOpcode();
8726 if (Opc != ISD::OR && Opc != ISD::AND)
8728 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8729 Op.getOperand(0).hasOneUse() &&
8730 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8731 Op.getOperand(1).hasOneUse());
8734 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8735 // 1 and that the SETCC node has a single use.
8736 static bool isXor1OfSetCC(SDValue Op) {
8737 if (Op.getOpcode() != ISD::XOR)
8739 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8740 if (N1C && N1C->getAPIntValue() == 1) {
8741 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8742 Op.getOperand(0).hasOneUse();
8747 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8748 bool addTest = true;
8749 SDValue Chain = Op.getOperand(0);
8750 SDValue Cond = Op.getOperand(1);
8751 SDValue Dest = Op.getOperand(2);
8752 DebugLoc dl = Op.getDebugLoc();
8755 if (Cond.getOpcode() == ISD::SETCC) {
8756 SDValue NewCond = LowerSETCC(Cond, DAG);
8757 if (NewCond.getNode())
8761 // FIXME: LowerXALUO doesn't handle these!!
8762 else if (Cond.getOpcode() == X86ISD::ADD ||
8763 Cond.getOpcode() == X86ISD::SUB ||
8764 Cond.getOpcode() == X86ISD::SMUL ||
8765 Cond.getOpcode() == X86ISD::UMUL)
8766 Cond = LowerXALUO(Cond, DAG);
8769 // Look pass (and (setcc_carry (cmp ...)), 1).
8770 if (Cond.getOpcode() == ISD::AND &&
8771 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8773 if (C && C->getAPIntValue() == 1)
8774 Cond = Cond.getOperand(0);
8777 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8778 // setting operand in place of the X86ISD::SETCC.
8779 if (Cond.getOpcode() == X86ISD::SETCC ||
8780 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8781 CC = Cond.getOperand(0);
8783 SDValue Cmp = Cond.getOperand(1);
8784 unsigned Opc = Cmp.getOpcode();
8785 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8786 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8790 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8794 // These can only come from an arithmetic instruction with overflow,
8795 // e.g. SADDO, UADDO.
8796 Cond = Cond.getNode()->getOperand(1);
8803 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8804 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8805 if (CondOpc == ISD::OR) {
8806 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8807 // two branches instead of an explicit OR instruction with a
8809 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8810 isX86LogicalCmp(Cmp)) {
8811 CC = Cond.getOperand(0).getOperand(0);
8812 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8813 Chain, Dest, CC, Cmp);
8814 CC = Cond.getOperand(1).getOperand(0);
8818 } else { // ISD::AND
8819 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8820 // two branches instead of an explicit AND instruction with a
8821 // separate test. However, we only do this if this block doesn't
8822 // have a fall-through edge, because this requires an explicit
8823 // jmp when the condition is false.
8824 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8825 isX86LogicalCmp(Cmp) &&
8826 Op.getNode()->hasOneUse()) {
8827 X86::CondCode CCode =
8828 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8829 CCode = X86::GetOppositeBranchCondition(CCode);
8830 CC = DAG.getConstant(CCode, MVT::i8);
8831 SDNode *User = *Op.getNode()->use_begin();
8832 // Look for an unconditional branch following this conditional branch.
8833 // We need this because we need to reverse the successors in order
8834 // to implement FCMP_OEQ.
8835 if (User->getOpcode() == ISD::BR) {
8836 SDValue FalseBB = User->getOperand(1);
8838 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8839 assert(NewBR == User);
8843 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8844 Chain, Dest, CC, Cmp);
8845 X86::CondCode CCode =
8846 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8847 CCode = X86::GetOppositeBranchCondition(CCode);
8848 CC = DAG.getConstant(CCode, MVT::i8);
8854 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8855 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8856 // It should be transformed during dag combiner except when the condition
8857 // is set by a arithmetics with overflow node.
8858 X86::CondCode CCode =
8859 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8860 CCode = X86::GetOppositeBranchCondition(CCode);
8861 CC = DAG.getConstant(CCode, MVT::i8);
8862 Cond = Cond.getOperand(0).getOperand(1);
8868 // Look pass the truncate.
8869 if (Cond.getOpcode() == ISD::TRUNCATE)
8870 Cond = Cond.getOperand(0);
8872 // We know the result of AND is compared against zero. Try to match
8874 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8875 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8876 if (NewSetCC.getNode()) {
8877 CC = NewSetCC.getOperand(0);
8878 Cond = NewSetCC.getOperand(1);
8885 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8886 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8888 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8889 Chain, Dest, CC, Cond);
8893 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8894 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8895 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8896 // that the guard pages used by the OS virtual memory manager are allocated in
8897 // correct sequence.
8899 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8900 SelectionDAG &DAG) const {
8901 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8902 EnableSegmentedStacks) &&
8903 "This should be used only on Windows targets or when segmented stacks "
8905 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8906 DebugLoc dl = Op.getDebugLoc();
8909 SDValue Chain = Op.getOperand(0);
8910 SDValue Size = Op.getOperand(1);
8911 // FIXME: Ensure alignment here
8913 bool Is64Bit = Subtarget->is64Bit();
8914 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8916 if (EnableSegmentedStacks) {
8917 MachineFunction &MF = DAG.getMachineFunction();
8918 MachineRegisterInfo &MRI = MF.getRegInfo();
8921 // The 64 bit implementation of segmented stacks needs to clobber both r10
8922 // r11. This makes it impossible to use it along with nested parameters.
8923 const Function *F = MF.getFunction();
8925 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8927 if (I->hasNestAttr())
8928 report_fatal_error("Cannot use segmented stacks with functions that "
8929 "have nested arguments.");
8932 const TargetRegisterClass *AddrRegClass =
8933 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8934 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8935 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8936 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8937 DAG.getRegister(Vreg, SPTy));
8938 SDValue Ops1[2] = { Value, Chain };
8939 return DAG.getMergeValues(Ops1, 2, dl);
8942 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8944 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8945 Flag = Chain.getValue(1);
8946 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8948 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8949 Flag = Chain.getValue(1);
8951 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8953 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8954 return DAG.getMergeValues(Ops1, 2, dl);
8958 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8959 MachineFunction &MF = DAG.getMachineFunction();
8960 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8962 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8963 DebugLoc DL = Op.getDebugLoc();
8965 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8966 // vastart just stores the address of the VarArgsFrameIndex slot into the
8967 // memory location argument.
8968 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8970 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8971 MachinePointerInfo(SV), false, false, 0);
8975 // gp_offset (0 - 6 * 8)
8976 // fp_offset (48 - 48 + 8 * 16)
8977 // overflow_arg_area (point to parameters coming in memory).
8979 SmallVector<SDValue, 8> MemOps;
8980 SDValue FIN = Op.getOperand(1);
8982 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8983 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8985 FIN, MachinePointerInfo(SV), false, false, 0);
8986 MemOps.push_back(Store);
8989 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8990 FIN, DAG.getIntPtrConstant(4));
8991 Store = DAG.getStore(Op.getOperand(0), DL,
8992 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8994 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8995 MemOps.push_back(Store);
8997 // Store ptr to overflow_arg_area
8998 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8999 FIN, DAG.getIntPtrConstant(4));
9000 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9002 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9003 MachinePointerInfo(SV, 8),
9005 MemOps.push_back(Store);
9007 // Store ptr to reg_save_area.
9008 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9009 FIN, DAG.getIntPtrConstant(8));
9010 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9012 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9013 MachinePointerInfo(SV, 16), false, false, 0);
9014 MemOps.push_back(Store);
9015 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9016 &MemOps[0], MemOps.size());
9019 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9020 assert(Subtarget->is64Bit() &&
9021 "LowerVAARG only handles 64-bit va_arg!");
9022 assert((Subtarget->isTargetLinux() ||
9023 Subtarget->isTargetDarwin()) &&
9024 "Unhandled target in LowerVAARG");
9025 assert(Op.getNode()->getNumOperands() == 4);
9026 SDValue Chain = Op.getOperand(0);
9027 SDValue SrcPtr = Op.getOperand(1);
9028 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9029 unsigned Align = Op.getConstantOperandVal(3);
9030 DebugLoc dl = Op.getDebugLoc();
9032 EVT ArgVT = Op.getNode()->getValueType(0);
9033 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9034 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9037 // Decide which area this value should be read from.
9038 // TODO: Implement the AMD64 ABI in its entirety. This simple
9039 // selection mechanism works only for the basic types.
9040 if (ArgVT == MVT::f80) {
9041 llvm_unreachable("va_arg for f80 not yet implemented");
9042 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9043 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9044 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9045 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9047 llvm_unreachable("Unhandled argument type in LowerVAARG");
9051 // Sanity Check: Make sure using fp_offset makes sense.
9052 assert(!UseSoftFloat &&
9053 !(DAG.getMachineFunction()
9054 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9055 Subtarget->hasXMM());
9058 // Insert VAARG_64 node into the DAG
9059 // VAARG_64 returns two values: Variable Argument Address, Chain
9060 SmallVector<SDValue, 11> InstOps;
9061 InstOps.push_back(Chain);
9062 InstOps.push_back(SrcPtr);
9063 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9064 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9065 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9066 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9067 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9068 VTs, &InstOps[0], InstOps.size(),
9070 MachinePointerInfo(SV),
9075 Chain = VAARG.getValue(1);
9077 // Load the next argument and return it
9078 return DAG.getLoad(ArgVT, dl,
9081 MachinePointerInfo(),
9085 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9086 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9087 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9088 SDValue Chain = Op.getOperand(0);
9089 SDValue DstPtr = Op.getOperand(1);
9090 SDValue SrcPtr = Op.getOperand(2);
9091 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9092 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9093 DebugLoc DL = Op.getDebugLoc();
9095 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9096 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9098 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9102 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9103 DebugLoc dl = Op.getDebugLoc();
9104 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9106 default: return SDValue(); // Don't custom lower most intrinsics.
9107 // Comparison intrinsics.
9108 case Intrinsic::x86_sse_comieq_ss:
9109 case Intrinsic::x86_sse_comilt_ss:
9110 case Intrinsic::x86_sse_comile_ss:
9111 case Intrinsic::x86_sse_comigt_ss:
9112 case Intrinsic::x86_sse_comige_ss:
9113 case Intrinsic::x86_sse_comineq_ss:
9114 case Intrinsic::x86_sse_ucomieq_ss:
9115 case Intrinsic::x86_sse_ucomilt_ss:
9116 case Intrinsic::x86_sse_ucomile_ss:
9117 case Intrinsic::x86_sse_ucomigt_ss:
9118 case Intrinsic::x86_sse_ucomige_ss:
9119 case Intrinsic::x86_sse_ucomineq_ss:
9120 case Intrinsic::x86_sse2_comieq_sd:
9121 case Intrinsic::x86_sse2_comilt_sd:
9122 case Intrinsic::x86_sse2_comile_sd:
9123 case Intrinsic::x86_sse2_comigt_sd:
9124 case Intrinsic::x86_sse2_comige_sd:
9125 case Intrinsic::x86_sse2_comineq_sd:
9126 case Intrinsic::x86_sse2_ucomieq_sd:
9127 case Intrinsic::x86_sse2_ucomilt_sd:
9128 case Intrinsic::x86_sse2_ucomile_sd:
9129 case Intrinsic::x86_sse2_ucomigt_sd:
9130 case Intrinsic::x86_sse2_ucomige_sd:
9131 case Intrinsic::x86_sse2_ucomineq_sd: {
9133 ISD::CondCode CC = ISD::SETCC_INVALID;
9136 case Intrinsic::x86_sse_comieq_ss:
9137 case Intrinsic::x86_sse2_comieq_sd:
9141 case Intrinsic::x86_sse_comilt_ss:
9142 case Intrinsic::x86_sse2_comilt_sd:
9146 case Intrinsic::x86_sse_comile_ss:
9147 case Intrinsic::x86_sse2_comile_sd:
9151 case Intrinsic::x86_sse_comigt_ss:
9152 case Intrinsic::x86_sse2_comigt_sd:
9156 case Intrinsic::x86_sse_comige_ss:
9157 case Intrinsic::x86_sse2_comige_sd:
9161 case Intrinsic::x86_sse_comineq_ss:
9162 case Intrinsic::x86_sse2_comineq_sd:
9166 case Intrinsic::x86_sse_ucomieq_ss:
9167 case Intrinsic::x86_sse2_ucomieq_sd:
9168 Opc = X86ISD::UCOMI;
9171 case Intrinsic::x86_sse_ucomilt_ss:
9172 case Intrinsic::x86_sse2_ucomilt_sd:
9173 Opc = X86ISD::UCOMI;
9176 case Intrinsic::x86_sse_ucomile_ss:
9177 case Intrinsic::x86_sse2_ucomile_sd:
9178 Opc = X86ISD::UCOMI;
9181 case Intrinsic::x86_sse_ucomigt_ss:
9182 case Intrinsic::x86_sse2_ucomigt_sd:
9183 Opc = X86ISD::UCOMI;
9186 case Intrinsic::x86_sse_ucomige_ss:
9187 case Intrinsic::x86_sse2_ucomige_sd:
9188 Opc = X86ISD::UCOMI;
9191 case Intrinsic::x86_sse_ucomineq_ss:
9192 case Intrinsic::x86_sse2_ucomineq_sd:
9193 Opc = X86ISD::UCOMI;
9198 SDValue LHS = Op.getOperand(1);
9199 SDValue RHS = Op.getOperand(2);
9200 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9201 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9202 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9203 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9204 DAG.getConstant(X86CC, MVT::i8), Cond);
9205 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9207 // ptest and testp intrinsics. The intrinsic these come from are designed to
9208 // return an integer value, not just an instruction so lower it to the ptest
9209 // or testp pattern and a setcc for the result.
9210 case Intrinsic::x86_sse41_ptestz:
9211 case Intrinsic::x86_sse41_ptestc:
9212 case Intrinsic::x86_sse41_ptestnzc:
9213 case Intrinsic::x86_avx_ptestz_256:
9214 case Intrinsic::x86_avx_ptestc_256:
9215 case Intrinsic::x86_avx_ptestnzc_256:
9216 case Intrinsic::x86_avx_vtestz_ps:
9217 case Intrinsic::x86_avx_vtestc_ps:
9218 case Intrinsic::x86_avx_vtestnzc_ps:
9219 case Intrinsic::x86_avx_vtestz_pd:
9220 case Intrinsic::x86_avx_vtestc_pd:
9221 case Intrinsic::x86_avx_vtestnzc_pd:
9222 case Intrinsic::x86_avx_vtestz_ps_256:
9223 case Intrinsic::x86_avx_vtestc_ps_256:
9224 case Intrinsic::x86_avx_vtestnzc_ps_256:
9225 case Intrinsic::x86_avx_vtestz_pd_256:
9226 case Intrinsic::x86_avx_vtestc_pd_256:
9227 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9228 bool IsTestPacked = false;
9231 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9232 case Intrinsic::x86_avx_vtestz_ps:
9233 case Intrinsic::x86_avx_vtestz_pd:
9234 case Intrinsic::x86_avx_vtestz_ps_256:
9235 case Intrinsic::x86_avx_vtestz_pd_256:
9236 IsTestPacked = true; // Fallthrough
9237 case Intrinsic::x86_sse41_ptestz:
9238 case Intrinsic::x86_avx_ptestz_256:
9240 X86CC = X86::COND_E;
9242 case Intrinsic::x86_avx_vtestc_ps:
9243 case Intrinsic::x86_avx_vtestc_pd:
9244 case Intrinsic::x86_avx_vtestc_ps_256:
9245 case Intrinsic::x86_avx_vtestc_pd_256:
9246 IsTestPacked = true; // Fallthrough
9247 case Intrinsic::x86_sse41_ptestc:
9248 case Intrinsic::x86_avx_ptestc_256:
9250 X86CC = X86::COND_B;
9252 case Intrinsic::x86_avx_vtestnzc_ps:
9253 case Intrinsic::x86_avx_vtestnzc_pd:
9254 case Intrinsic::x86_avx_vtestnzc_ps_256:
9255 case Intrinsic::x86_avx_vtestnzc_pd_256:
9256 IsTestPacked = true; // Fallthrough
9257 case Intrinsic::x86_sse41_ptestnzc:
9258 case Intrinsic::x86_avx_ptestnzc_256:
9260 X86CC = X86::COND_A;
9264 SDValue LHS = Op.getOperand(1);
9265 SDValue RHS = Op.getOperand(2);
9266 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9267 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9268 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9269 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9270 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9273 // Fix vector shift instructions where the last operand is a non-immediate
9275 case Intrinsic::x86_sse2_pslli_w:
9276 case Intrinsic::x86_sse2_pslli_d:
9277 case Intrinsic::x86_sse2_pslli_q:
9278 case Intrinsic::x86_sse2_psrli_w:
9279 case Intrinsic::x86_sse2_psrli_d:
9280 case Intrinsic::x86_sse2_psrli_q:
9281 case Intrinsic::x86_sse2_psrai_w:
9282 case Intrinsic::x86_sse2_psrai_d:
9283 case Intrinsic::x86_mmx_pslli_w:
9284 case Intrinsic::x86_mmx_pslli_d:
9285 case Intrinsic::x86_mmx_pslli_q:
9286 case Intrinsic::x86_mmx_psrli_w:
9287 case Intrinsic::x86_mmx_psrli_d:
9288 case Intrinsic::x86_mmx_psrli_q:
9289 case Intrinsic::x86_mmx_psrai_w:
9290 case Intrinsic::x86_mmx_psrai_d: {
9291 SDValue ShAmt = Op.getOperand(2);
9292 if (isa<ConstantSDNode>(ShAmt))
9295 unsigned NewIntNo = 0;
9296 EVT ShAmtVT = MVT::v4i32;
9298 case Intrinsic::x86_sse2_pslli_w:
9299 NewIntNo = Intrinsic::x86_sse2_psll_w;
9301 case Intrinsic::x86_sse2_pslli_d:
9302 NewIntNo = Intrinsic::x86_sse2_psll_d;
9304 case Intrinsic::x86_sse2_pslli_q:
9305 NewIntNo = Intrinsic::x86_sse2_psll_q;
9307 case Intrinsic::x86_sse2_psrli_w:
9308 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9310 case Intrinsic::x86_sse2_psrli_d:
9311 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9313 case Intrinsic::x86_sse2_psrli_q:
9314 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9316 case Intrinsic::x86_sse2_psrai_w:
9317 NewIntNo = Intrinsic::x86_sse2_psra_w;
9319 case Intrinsic::x86_sse2_psrai_d:
9320 NewIntNo = Intrinsic::x86_sse2_psra_d;
9323 ShAmtVT = MVT::v2i32;
9325 case Intrinsic::x86_mmx_pslli_w:
9326 NewIntNo = Intrinsic::x86_mmx_psll_w;
9328 case Intrinsic::x86_mmx_pslli_d:
9329 NewIntNo = Intrinsic::x86_mmx_psll_d;
9331 case Intrinsic::x86_mmx_pslli_q:
9332 NewIntNo = Intrinsic::x86_mmx_psll_q;
9334 case Intrinsic::x86_mmx_psrli_w:
9335 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9337 case Intrinsic::x86_mmx_psrli_d:
9338 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9340 case Intrinsic::x86_mmx_psrli_q:
9341 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9343 case Intrinsic::x86_mmx_psrai_w:
9344 NewIntNo = Intrinsic::x86_mmx_psra_w;
9346 case Intrinsic::x86_mmx_psrai_d:
9347 NewIntNo = Intrinsic::x86_mmx_psra_d;
9349 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9355 // The vector shift intrinsics with scalars uses 32b shift amounts but
9356 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9360 ShOps[1] = DAG.getConstant(0, MVT::i32);
9361 if (ShAmtVT == MVT::v4i32) {
9362 ShOps[2] = DAG.getUNDEF(MVT::i32);
9363 ShOps[3] = DAG.getUNDEF(MVT::i32);
9364 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9366 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9367 // FIXME this must be lowered to get rid of the invalid type.
9370 EVT VT = Op.getValueType();
9371 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9372 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9373 DAG.getConstant(NewIntNo, MVT::i32),
9374 Op.getOperand(1), ShAmt);
9379 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9380 SelectionDAG &DAG) const {
9381 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9382 MFI->setReturnAddressIsTaken(true);
9384 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9385 DebugLoc dl = Op.getDebugLoc();
9388 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9390 DAG.getConstant(TD->getPointerSize(),
9391 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9392 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9393 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9395 MachinePointerInfo(), false, false, 0);
9398 // Just load the return address.
9399 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9400 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9401 RetAddrFI, MachinePointerInfo(), false, false, 0);
9404 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9405 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9406 MFI->setFrameAddressIsTaken(true);
9408 EVT VT = Op.getValueType();
9409 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9410 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9411 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9412 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9414 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9415 MachinePointerInfo(),
9420 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9421 SelectionDAG &DAG) const {
9422 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9425 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9426 MachineFunction &MF = DAG.getMachineFunction();
9427 SDValue Chain = Op.getOperand(0);
9428 SDValue Offset = Op.getOperand(1);
9429 SDValue Handler = Op.getOperand(2);
9430 DebugLoc dl = Op.getDebugLoc();
9432 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9433 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9435 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9437 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9438 DAG.getIntPtrConstant(TD->getPointerSize()));
9439 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9440 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9442 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9443 MF.getRegInfo().addLiveOut(StoreAddrReg);
9445 return DAG.getNode(X86ISD::EH_RETURN, dl,
9447 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9450 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9451 SelectionDAG &DAG) const {
9452 return Op.getOperand(0);
9455 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9456 SelectionDAG &DAG) const {
9457 SDValue Root = Op.getOperand(0);
9458 SDValue Trmp = Op.getOperand(1); // trampoline
9459 SDValue FPtr = Op.getOperand(2); // nested function
9460 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9461 DebugLoc dl = Op.getDebugLoc();
9463 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9465 if (Subtarget->is64Bit()) {
9466 SDValue OutChains[6];
9468 // Large code-model.
9469 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9470 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9472 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9473 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9475 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9477 // Load the pointer to the nested function into R11.
9478 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9479 SDValue Addr = Trmp;
9480 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9481 Addr, MachinePointerInfo(TrmpAddr),
9484 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9485 DAG.getConstant(2, MVT::i64));
9486 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9487 MachinePointerInfo(TrmpAddr, 2),
9490 // Load the 'nest' parameter value into R10.
9491 // R10 is specified in X86CallingConv.td
9492 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9493 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9494 DAG.getConstant(10, MVT::i64));
9495 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9496 Addr, MachinePointerInfo(TrmpAddr, 10),
9499 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9500 DAG.getConstant(12, MVT::i64));
9501 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9502 MachinePointerInfo(TrmpAddr, 12),
9505 // Jump to the nested function.
9506 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9507 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9508 DAG.getConstant(20, MVT::i64));
9509 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9510 Addr, MachinePointerInfo(TrmpAddr, 20),
9513 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9514 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9515 DAG.getConstant(22, MVT::i64));
9516 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9517 MachinePointerInfo(TrmpAddr, 22),
9520 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9522 const Function *Func =
9523 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9524 CallingConv::ID CC = Func->getCallingConv();
9529 llvm_unreachable("Unsupported calling convention");
9530 case CallingConv::C:
9531 case CallingConv::X86_StdCall: {
9532 // Pass 'nest' parameter in ECX.
9533 // Must be kept in sync with X86CallingConv.td
9536 // Check that ECX wasn't needed by an 'inreg' parameter.
9537 FunctionType *FTy = Func->getFunctionType();
9538 const AttrListPtr &Attrs = Func->getAttributes();
9540 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9541 unsigned InRegCount = 0;
9544 for (FunctionType::param_iterator I = FTy->param_begin(),
9545 E = FTy->param_end(); I != E; ++I, ++Idx)
9546 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9547 // FIXME: should only count parameters that are lowered to integers.
9548 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9550 if (InRegCount > 2) {
9551 report_fatal_error("Nest register in use - reduce number of inreg"
9557 case CallingConv::X86_FastCall:
9558 case CallingConv::X86_ThisCall:
9559 case CallingConv::Fast:
9560 // Pass 'nest' parameter in EAX.
9561 // Must be kept in sync with X86CallingConv.td
9566 SDValue OutChains[4];
9569 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9570 DAG.getConstant(10, MVT::i32));
9571 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9573 // This is storing the opcode for MOV32ri.
9574 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9575 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9576 OutChains[0] = DAG.getStore(Root, dl,
9577 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9578 Trmp, MachinePointerInfo(TrmpAddr),
9581 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9582 DAG.getConstant(1, MVT::i32));
9583 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9584 MachinePointerInfo(TrmpAddr, 1),
9587 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9588 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9589 DAG.getConstant(5, MVT::i32));
9590 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9591 MachinePointerInfo(TrmpAddr, 5),
9594 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9595 DAG.getConstant(6, MVT::i32));
9596 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9597 MachinePointerInfo(TrmpAddr, 6),
9600 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9604 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9605 SelectionDAG &DAG) const {
9607 The rounding mode is in bits 11:10 of FPSR, and has the following
9614 FLT_ROUNDS, on the other hand, expects the following:
9621 To perform the conversion, we do:
9622 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9625 MachineFunction &MF = DAG.getMachineFunction();
9626 const TargetMachine &TM = MF.getTarget();
9627 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9628 unsigned StackAlignment = TFI.getStackAlignment();
9629 EVT VT = Op.getValueType();
9630 DebugLoc DL = Op.getDebugLoc();
9632 // Save FP Control Word to stack slot
9633 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9634 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9637 MachineMemOperand *MMO =
9638 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9639 MachineMemOperand::MOStore, 2, 2);
9641 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9642 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9643 DAG.getVTList(MVT::Other),
9644 Ops, 2, MVT::i16, MMO);
9646 // Load FP Control Word from stack slot
9647 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9648 MachinePointerInfo(), false, false, 0);
9650 // Transform as necessary
9652 DAG.getNode(ISD::SRL, DL, MVT::i16,
9653 DAG.getNode(ISD::AND, DL, MVT::i16,
9654 CWD, DAG.getConstant(0x800, MVT::i16)),
9655 DAG.getConstant(11, MVT::i8));
9657 DAG.getNode(ISD::SRL, DL, MVT::i16,
9658 DAG.getNode(ISD::AND, DL, MVT::i16,
9659 CWD, DAG.getConstant(0x400, MVT::i16)),
9660 DAG.getConstant(9, MVT::i8));
9663 DAG.getNode(ISD::AND, DL, MVT::i16,
9664 DAG.getNode(ISD::ADD, DL, MVT::i16,
9665 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9666 DAG.getConstant(1, MVT::i16)),
9667 DAG.getConstant(3, MVT::i16));
9670 return DAG.getNode((VT.getSizeInBits() < 16 ?
9671 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9674 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9675 EVT VT = Op.getValueType();
9677 unsigned NumBits = VT.getSizeInBits();
9678 DebugLoc dl = Op.getDebugLoc();
9680 Op = Op.getOperand(0);
9681 if (VT == MVT::i8) {
9682 // Zero extend to i32 since there is not an i8 bsr.
9684 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9687 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9688 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9689 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9691 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9694 DAG.getConstant(NumBits+NumBits-1, OpVT),
9695 DAG.getConstant(X86::COND_E, MVT::i8),
9698 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9700 // Finally xor with NumBits-1.
9701 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9704 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9708 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9709 EVT VT = Op.getValueType();
9711 unsigned NumBits = VT.getSizeInBits();
9712 DebugLoc dl = Op.getDebugLoc();
9714 Op = Op.getOperand(0);
9715 if (VT == MVT::i8) {
9717 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9720 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9721 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9722 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9724 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9727 DAG.getConstant(NumBits, OpVT),
9728 DAG.getConstant(X86::COND_E, MVT::i8),
9731 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9734 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9738 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9739 // ones, and then concatenate the result back.
9740 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9741 EVT VT = Op.getValueType();
9743 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9744 "Unsupported value type for operation");
9746 int NumElems = VT.getVectorNumElements();
9747 DebugLoc dl = Op.getDebugLoc();
9748 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9749 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9751 // Extract the LHS vectors
9752 SDValue LHS = Op.getOperand(0);
9753 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9754 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9756 // Extract the RHS vectors
9757 SDValue RHS = Op.getOperand(1);
9758 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9759 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9761 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9762 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9764 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9765 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9766 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9769 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9770 assert(Op.getValueType().getSizeInBits() == 256 &&
9771 Op.getValueType().isInteger() &&
9772 "Only handle AVX 256-bit vector integer operation");
9773 return Lower256IntArith(Op, DAG);
9776 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9777 assert(Op.getValueType().getSizeInBits() == 256 &&
9778 Op.getValueType().isInteger() &&
9779 "Only handle AVX 256-bit vector integer operation");
9780 return Lower256IntArith(Op, DAG);
9783 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9784 EVT VT = Op.getValueType();
9786 // Decompose 256-bit ops into smaller 128-bit ops.
9787 if (VT.getSizeInBits() == 256)
9788 return Lower256IntArith(Op, DAG);
9790 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9791 DebugLoc dl = Op.getDebugLoc();
9793 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9794 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9795 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9796 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9797 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9799 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9800 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9801 // return AloBlo + AloBhi + AhiBlo;
9803 SDValue A = Op.getOperand(0);
9804 SDValue B = Op.getOperand(1);
9806 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9807 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9808 A, DAG.getConstant(32, MVT::i32));
9809 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9810 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9811 B, DAG.getConstant(32, MVT::i32));
9812 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9813 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9815 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9816 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9818 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9819 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9821 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9822 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9823 AloBhi, DAG.getConstant(32, MVT::i32));
9824 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9825 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9826 AhiBlo, DAG.getConstant(32, MVT::i32));
9827 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9828 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9832 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9834 EVT VT = Op.getValueType();
9835 DebugLoc dl = Op.getDebugLoc();
9836 SDValue R = Op.getOperand(0);
9837 SDValue Amt = Op.getOperand(1);
9838 LLVMContext *Context = DAG.getContext();
9840 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9843 // Decompose 256-bit shifts into smaller 128-bit shifts.
9844 if (VT.getSizeInBits() == 256) {
9845 int NumElems = VT.getVectorNumElements();
9846 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9847 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9849 // Extract the two vectors
9850 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9851 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9854 // Recreate the shift amount vectors
9856 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9857 // Constant shift amount
9858 SmallVector<SDValue, 4> Amt1Csts;
9859 SmallVector<SDValue, 4> Amt2Csts;
9860 for (int i = 0; i < NumElems/2; ++i)
9861 Amt1Csts.push_back(Amt->getOperand(i));
9862 for (int i = NumElems/2; i < NumElems; ++i)
9863 Amt2Csts.push_back(Amt->getOperand(i));
9865 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9866 &Amt1Csts[0], NumElems/2);
9867 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9868 &Amt2Csts[0], NumElems/2);
9870 // Variable shift amount
9871 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9872 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9876 // Issue new vector shifts for the smaller types
9877 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9878 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9880 // Concatenate the result back
9881 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9884 // Optimize shl/srl/sra with constant shift amount.
9885 if (isSplatVector(Amt.getNode())) {
9886 SDValue SclrAmt = Amt->getOperand(0);
9887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9888 uint64_t ShiftAmt = C->getZExtValue();
9890 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9891 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9892 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9893 R, DAG.getConstant(ShiftAmt, MVT::i32));
9895 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9896 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9897 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9898 R, DAG.getConstant(ShiftAmt, MVT::i32));
9900 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9901 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9902 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9903 R, DAG.getConstant(ShiftAmt, MVT::i32));
9905 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9906 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9907 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9908 R, DAG.getConstant(ShiftAmt, MVT::i32));
9910 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9911 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9912 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9913 R, DAG.getConstant(ShiftAmt, MVT::i32));
9915 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9916 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9917 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9918 R, DAG.getConstant(ShiftAmt, MVT::i32));
9920 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9921 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9922 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9923 R, DAG.getConstant(ShiftAmt, MVT::i32));
9925 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9926 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9927 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9928 R, DAG.getConstant(ShiftAmt, MVT::i32));
9932 // Lower SHL with variable shift amount.
9933 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9934 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9935 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9936 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9938 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9940 std::vector<Constant*> CV(4, CI);
9941 Constant *C = ConstantVector::get(CV);
9942 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9943 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9944 MachinePointerInfo::getConstantPool(),
9947 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9948 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9949 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9950 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9952 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9954 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9955 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9956 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9958 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9959 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9961 std::vector<Constant*> CVM1(16, CM1);
9962 std::vector<Constant*> CVM2(16, CM2);
9963 Constant *C = ConstantVector::get(CVM1);
9964 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9965 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9966 MachinePointerInfo::getConstantPool(),
9969 // r = pblendv(r, psllw(r & (char16)15, 4), a);
9970 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9971 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9972 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9973 DAG.getConstant(4, MVT::i32));
9974 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9976 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9978 C = ConstantVector::get(CVM2);
9979 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9980 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9981 MachinePointerInfo::getConstantPool(),
9984 // r = pblendv(r, psllw(r & (char16)63, 2), a);
9985 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9986 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9987 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9988 DAG.getConstant(2, MVT::i32));
9989 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9991 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9993 // return pblendv(r, r+r, a);
9994 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
9995 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10001 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10002 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10003 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10004 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10005 // has only one use.
10006 SDNode *N = Op.getNode();
10007 SDValue LHS = N->getOperand(0);
10008 SDValue RHS = N->getOperand(1);
10009 unsigned BaseOp = 0;
10011 DebugLoc DL = Op.getDebugLoc();
10012 switch (Op.getOpcode()) {
10013 default: llvm_unreachable("Unknown ovf instruction!");
10015 // A subtract of one will be selected as a INC. Note that INC doesn't
10016 // set CF, so we can't do this for UADDO.
10017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10019 BaseOp = X86ISD::INC;
10020 Cond = X86::COND_O;
10023 BaseOp = X86ISD::ADD;
10024 Cond = X86::COND_O;
10027 BaseOp = X86ISD::ADD;
10028 Cond = X86::COND_B;
10031 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10032 // set CF, so we can't do this for USUBO.
10033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10035 BaseOp = X86ISD::DEC;
10036 Cond = X86::COND_O;
10039 BaseOp = X86ISD::SUB;
10040 Cond = X86::COND_O;
10043 BaseOp = X86ISD::SUB;
10044 Cond = X86::COND_B;
10047 BaseOp = X86ISD::SMUL;
10048 Cond = X86::COND_O;
10050 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10051 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10053 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10056 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10057 DAG.getConstant(X86::COND_O, MVT::i32),
10058 SDValue(Sum.getNode(), 2));
10060 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10064 // Also sets EFLAGS.
10065 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10066 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10069 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10070 DAG.getConstant(Cond, MVT::i32),
10071 SDValue(Sum.getNode(), 1));
10073 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10076 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10077 DebugLoc dl = Op.getDebugLoc();
10078 SDNode* Node = Op.getNode();
10079 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10080 EVT VT = Node->getValueType(0);
10081 if (Subtarget->hasSSE2() && VT.isVector()) {
10082 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10083 ExtraVT.getScalarType().getSizeInBits();
10084 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10086 unsigned SHLIntrinsicsID = 0;
10087 unsigned SRAIntrinsicsID = 0;
10088 switch (VT.getSimpleVT().SimpleTy) {
10092 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10093 SRAIntrinsicsID = 0;
10097 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10098 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10102 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10103 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10108 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10109 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10110 Node->getOperand(0), ShAmt);
10112 // In case of 1 bit sext, no need to shr
10113 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10115 if (SRAIntrinsicsID) {
10116 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10117 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10127 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10128 DebugLoc dl = Op.getDebugLoc();
10130 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10131 // There isn't any reason to disable it if the target processor supports it.
10132 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10133 SDValue Chain = Op.getOperand(0);
10134 SDValue Zero = DAG.getConstant(0, MVT::i32);
10136 DAG.getRegister(X86::ESP, MVT::i32), // Base
10137 DAG.getTargetConstant(1, MVT::i8), // Scale
10138 DAG.getRegister(0, MVT::i32), // Index
10139 DAG.getTargetConstant(0, MVT::i32), // Disp
10140 DAG.getRegister(0, MVT::i32), // Segment.
10145 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10146 array_lengthof(Ops));
10147 return SDValue(Res, 0);
10150 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10152 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10154 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10155 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10156 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10157 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10159 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10160 if (!Op1 && !Op2 && !Op3 && Op4)
10161 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10163 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10164 if (Op1 && !Op2 && !Op3 && !Op4)
10165 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10167 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10169 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10172 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10173 SelectionDAG &DAG) const {
10174 DebugLoc dl = Op.getDebugLoc();
10175 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10176 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10177 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10178 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10180 // The only fence that needs an instruction is a sequentially-consistent
10181 // cross-thread fence.
10182 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10183 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10184 // no-sse2). There isn't any reason to disable it if the target processor
10186 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10187 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10189 SDValue Chain = Op.getOperand(0);
10190 SDValue Zero = DAG.getConstant(0, MVT::i32);
10192 DAG.getRegister(X86::ESP, MVT::i32), // Base
10193 DAG.getTargetConstant(1, MVT::i8), // Scale
10194 DAG.getRegister(0, MVT::i32), // Index
10195 DAG.getTargetConstant(0, MVT::i32), // Disp
10196 DAG.getRegister(0, MVT::i32), // Segment.
10201 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10202 array_lengthof(Ops));
10203 return SDValue(Res, 0);
10206 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10207 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10211 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10212 EVT T = Op.getValueType();
10213 DebugLoc DL = Op.getDebugLoc();
10216 switch(T.getSimpleVT().SimpleTy) {
10218 assert(false && "Invalid value type!");
10219 case MVT::i8: Reg = X86::AL; size = 1; break;
10220 case MVT::i16: Reg = X86::AX; size = 2; break;
10221 case MVT::i32: Reg = X86::EAX; size = 4; break;
10223 assert(Subtarget->is64Bit() && "Node not type legal!");
10224 Reg = X86::RAX; size = 8;
10227 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10228 Op.getOperand(2), SDValue());
10229 SDValue Ops[] = { cpIn.getValue(0),
10232 DAG.getTargetConstant(size, MVT::i8),
10233 cpIn.getValue(1) };
10234 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10235 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10236 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10239 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10243 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10244 SelectionDAG &DAG) const {
10245 assert(Subtarget->is64Bit() && "Result not type legalized?");
10246 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10247 SDValue TheChain = Op.getOperand(0);
10248 DebugLoc dl = Op.getDebugLoc();
10249 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10250 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10251 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10253 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10254 DAG.getConstant(32, MVT::i8));
10256 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10259 return DAG.getMergeValues(Ops, 2, dl);
10262 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10263 SelectionDAG &DAG) const {
10264 EVT SrcVT = Op.getOperand(0).getValueType();
10265 EVT DstVT = Op.getValueType();
10266 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10267 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10268 assert((DstVT == MVT::i64 ||
10269 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10270 "Unexpected custom BITCAST");
10271 // i64 <=> MMX conversions are Legal.
10272 if (SrcVT==MVT::i64 && DstVT.isVector())
10274 if (DstVT==MVT::i64 && SrcVT.isVector())
10276 // MMX <=> MMX conversions are Legal.
10277 if (SrcVT.isVector() && DstVT.isVector())
10279 // All other conversions need to be expanded.
10283 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10284 SDNode *Node = Op.getNode();
10285 DebugLoc dl = Node->getDebugLoc();
10286 EVT T = Node->getValueType(0);
10287 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10288 DAG.getConstant(0, T), Node->getOperand(2));
10289 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10290 cast<AtomicSDNode>(Node)->getMemoryVT(),
10291 Node->getOperand(0),
10292 Node->getOperand(1), negOp,
10293 cast<AtomicSDNode>(Node)->getSrcValue(),
10294 cast<AtomicSDNode>(Node)->getAlignment(),
10295 cast<AtomicSDNode>(Node)->getOrdering(),
10296 cast<AtomicSDNode>(Node)->getSynchScope());
10299 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10300 SDNode *Node = Op.getNode();
10301 DebugLoc dl = Node->getDebugLoc();
10302 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10304 // Convert seq_cst store -> xchg
10305 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10306 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10307 // (The only way to get a 16-byte store is cmpxchg16b)
10308 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10309 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10310 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10311 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10312 cast<AtomicSDNode>(Node)->getMemoryVT(),
10313 Node->getOperand(0),
10314 Node->getOperand(1), Node->getOperand(2),
10315 cast<AtomicSDNode>(Node)->getMemOperand(),
10316 cast<AtomicSDNode>(Node)->getOrdering(),
10317 cast<AtomicSDNode>(Node)->getSynchScope());
10318 return Swap.getValue(1);
10320 // Other atomic stores have a simple pattern.
10324 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10325 EVT VT = Op.getNode()->getValueType(0);
10327 // Let legalize expand this if it isn't a legal type yet.
10328 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10331 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10334 bool ExtraOp = false;
10335 switch (Op.getOpcode()) {
10336 default: assert(0 && "Invalid code");
10337 case ISD::ADDC: Opc = X86ISD::ADD; break;
10338 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10339 case ISD::SUBC: Opc = X86ISD::SUB; break;
10340 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10344 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10346 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10347 Op.getOperand(1), Op.getOperand(2));
10350 /// LowerOperation - Provide custom lowering hooks for some operations.
10352 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10353 switch (Op.getOpcode()) {
10354 default: llvm_unreachable("Should not custom lower this!");
10355 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10356 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10357 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10358 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10359 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10360 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10361 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10362 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10363 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10364 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10365 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10366 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10367 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10368 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10369 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10370 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10371 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10372 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10373 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10374 case ISD::SHL_PARTS:
10375 case ISD::SRA_PARTS:
10376 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10377 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10378 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10379 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10380 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10381 case ISD::FABS: return LowerFABS(Op, DAG);
10382 case ISD::FNEG: return LowerFNEG(Op, DAG);
10383 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10384 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10385 case ISD::SETCC: return LowerSETCC(Op, DAG);
10386 case ISD::SELECT: return LowerSELECT(Op, DAG);
10387 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10388 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10389 case ISD::VASTART: return LowerVASTART(Op, DAG);
10390 case ISD::VAARG: return LowerVAARG(Op, DAG);
10391 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10392 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10393 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10394 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10395 case ISD::FRAME_TO_ARGS_OFFSET:
10396 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10397 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10398 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10399 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10400 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10401 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10402 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10403 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10404 case ISD::MUL: return LowerMUL(Op, DAG);
10407 case ISD::SHL: return LowerShift(Op, DAG);
10413 case ISD::UMULO: return LowerXALUO(Op, DAG);
10414 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10415 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10419 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10420 case ISD::ADD: return LowerADD(Op, DAG);
10421 case ISD::SUB: return LowerSUB(Op, DAG);
10425 static void ReplaceATOMIC_LOAD(SDNode *Node,
10426 SmallVectorImpl<SDValue> &Results,
10427 SelectionDAG &DAG) {
10428 DebugLoc dl = Node->getDebugLoc();
10429 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10431 // Convert wide load -> cmpxchg8b/cmpxchg16b
10432 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10433 // (The only way to get a 16-byte load is cmpxchg16b)
10434 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10435 SDValue Zero = DAG.getConstant(0, VT);
10436 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10437 Node->getOperand(0),
10438 Node->getOperand(1), Zero, Zero,
10439 cast<AtomicSDNode>(Node)->getMemOperand(),
10440 cast<AtomicSDNode>(Node)->getOrdering(),
10441 cast<AtomicSDNode>(Node)->getSynchScope());
10442 Results.push_back(Swap.getValue(0));
10443 Results.push_back(Swap.getValue(1));
10446 void X86TargetLowering::
10447 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10448 SelectionDAG &DAG, unsigned NewOp) const {
10449 EVT T = Node->getValueType(0);
10450 DebugLoc dl = Node->getDebugLoc();
10451 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10453 SDValue Chain = Node->getOperand(0);
10454 SDValue In1 = Node->getOperand(1);
10455 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10456 Node->getOperand(2), DAG.getIntPtrConstant(0));
10457 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10458 Node->getOperand(2), DAG.getIntPtrConstant(1));
10459 SDValue Ops[] = { Chain, In1, In2L, In2H };
10460 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10462 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10463 cast<MemSDNode>(Node)->getMemOperand());
10464 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10465 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10466 Results.push_back(Result.getValue(2));
10469 /// ReplaceNodeResults - Replace a node with an illegal result type
10470 /// with a new node built out of custom code.
10471 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10472 SmallVectorImpl<SDValue>&Results,
10473 SelectionDAG &DAG) const {
10474 DebugLoc dl = N->getDebugLoc();
10475 switch (N->getOpcode()) {
10477 assert(false && "Do not know how to custom type legalize this operation!");
10479 case ISD::SIGN_EXTEND_INREG:
10484 // We don't want to expand or promote these.
10486 case ISD::FP_TO_SINT: {
10487 std::pair<SDValue,SDValue> Vals =
10488 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10489 SDValue FIST = Vals.first, StackSlot = Vals.second;
10490 if (FIST.getNode() != 0) {
10491 EVT VT = N->getValueType(0);
10492 // Return a load from the stack slot.
10493 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10494 MachinePointerInfo(), false, false, 0));
10498 case ISD::READCYCLECOUNTER: {
10499 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10500 SDValue TheChain = N->getOperand(0);
10501 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10502 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10504 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10506 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10507 SDValue Ops[] = { eax, edx };
10508 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10509 Results.push_back(edx.getValue(1));
10512 case ISD::ATOMIC_CMP_SWAP: {
10513 EVT T = N->getValueType(0);
10514 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10515 bool Regs64bit = T == MVT::i128;
10516 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10517 SDValue cpInL, cpInH;
10518 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10519 DAG.getConstant(0, HalfT));
10520 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10521 DAG.getConstant(1, HalfT));
10522 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10523 Regs64bit ? X86::RAX : X86::EAX,
10525 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10526 Regs64bit ? X86::RDX : X86::EDX,
10527 cpInH, cpInL.getValue(1));
10528 SDValue swapInL, swapInH;
10529 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10530 DAG.getConstant(0, HalfT));
10531 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10532 DAG.getConstant(1, HalfT));
10533 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10534 Regs64bit ? X86::RBX : X86::EBX,
10535 swapInL, cpInH.getValue(1));
10536 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10537 Regs64bit ? X86::RCX : X86::ECX,
10538 swapInH, swapInL.getValue(1));
10539 SDValue Ops[] = { swapInH.getValue(0),
10541 swapInH.getValue(1) };
10542 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10543 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10544 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10545 X86ISD::LCMPXCHG8_DAG;
10546 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10548 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10549 Regs64bit ? X86::RAX : X86::EAX,
10550 HalfT, Result.getValue(1));
10551 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10552 Regs64bit ? X86::RDX : X86::EDX,
10553 HalfT, cpOutL.getValue(2));
10554 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10555 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10556 Results.push_back(cpOutH.getValue(1));
10559 case ISD::ATOMIC_LOAD_ADD:
10560 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10562 case ISD::ATOMIC_LOAD_AND:
10563 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10565 case ISD::ATOMIC_LOAD_NAND:
10566 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10568 case ISD::ATOMIC_LOAD_OR:
10569 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10571 case ISD::ATOMIC_LOAD_SUB:
10572 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10574 case ISD::ATOMIC_LOAD_XOR:
10575 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10577 case ISD::ATOMIC_SWAP:
10578 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10580 case ISD::ATOMIC_LOAD:
10581 ReplaceATOMIC_LOAD(N, Results, DAG);
10585 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10587 default: return NULL;
10588 case X86ISD::BSF: return "X86ISD::BSF";
10589 case X86ISD::BSR: return "X86ISD::BSR";
10590 case X86ISD::SHLD: return "X86ISD::SHLD";
10591 case X86ISD::SHRD: return "X86ISD::SHRD";
10592 case X86ISD::FAND: return "X86ISD::FAND";
10593 case X86ISD::FOR: return "X86ISD::FOR";
10594 case X86ISD::FXOR: return "X86ISD::FXOR";
10595 case X86ISD::FSRL: return "X86ISD::FSRL";
10596 case X86ISD::FILD: return "X86ISD::FILD";
10597 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10598 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10599 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10600 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10601 case X86ISD::FLD: return "X86ISD::FLD";
10602 case X86ISD::FST: return "X86ISD::FST";
10603 case X86ISD::CALL: return "X86ISD::CALL";
10604 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10605 case X86ISD::BT: return "X86ISD::BT";
10606 case X86ISD::CMP: return "X86ISD::CMP";
10607 case X86ISD::COMI: return "X86ISD::COMI";
10608 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10609 case X86ISD::SETCC: return "X86ISD::SETCC";
10610 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10611 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10612 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10613 case X86ISD::CMOV: return "X86ISD::CMOV";
10614 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10615 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10616 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10617 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10618 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10619 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10620 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10621 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10622 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10623 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10624 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10625 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10626 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10627 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10628 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10629 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10630 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10631 case X86ISD::FMAX: return "X86ISD::FMAX";
10632 case X86ISD::FMIN: return "X86ISD::FMIN";
10633 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10634 case X86ISD::FRCP: return "X86ISD::FRCP";
10635 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10636 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10637 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10638 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10639 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10640 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10641 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10642 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10643 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10644 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10645 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10646 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10647 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10648 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10649 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10650 case X86ISD::VSHL: return "X86ISD::VSHL";
10651 case X86ISD::VSRL: return "X86ISD::VSRL";
10652 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10653 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10654 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10655 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10656 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10657 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10658 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10659 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10660 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10661 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10662 case X86ISD::ADD: return "X86ISD::ADD";
10663 case X86ISD::SUB: return "X86ISD::SUB";
10664 case X86ISD::ADC: return "X86ISD::ADC";
10665 case X86ISD::SBB: return "X86ISD::SBB";
10666 case X86ISD::SMUL: return "X86ISD::SMUL";
10667 case X86ISD::UMUL: return "X86ISD::UMUL";
10668 case X86ISD::INC: return "X86ISD::INC";
10669 case X86ISD::DEC: return "X86ISD::DEC";
10670 case X86ISD::OR: return "X86ISD::OR";
10671 case X86ISD::XOR: return "X86ISD::XOR";
10672 case X86ISD::AND: return "X86ISD::AND";
10673 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10674 case X86ISD::PTEST: return "X86ISD::PTEST";
10675 case X86ISD::TESTP: return "X86ISD::TESTP";
10676 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10677 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10678 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10679 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10680 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10681 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10682 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10683 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10684 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10685 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10686 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10687 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10688 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10689 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10690 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10691 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10692 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10693 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10694 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10695 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10696 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10697 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
10698 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
10699 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
10700 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
10701 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
10702 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
10703 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
10704 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
10705 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
10706 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
10707 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
10708 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
10709 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
10710 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10711 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
10712 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
10713 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
10714 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
10715 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
10716 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10717 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10718 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10719 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10720 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
10724 // isLegalAddressingMode - Return true if the addressing mode represented
10725 // by AM is legal for this target, for a load/store of the specified type.
10726 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10728 // X86 supports extremely general addressing modes.
10729 CodeModel::Model M = getTargetMachine().getCodeModel();
10730 Reloc::Model R = getTargetMachine().getRelocationModel();
10732 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10733 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10738 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10740 // If a reference to this global requires an extra load, we can't fold it.
10741 if (isGlobalStubReference(GVFlags))
10744 // If BaseGV requires a register for the PIC base, we cannot also have a
10745 // BaseReg specified.
10746 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10749 // If lower 4G is not available, then we must use rip-relative addressing.
10750 if ((M != CodeModel::Small || R != Reloc::Static) &&
10751 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10755 switch (AM.Scale) {
10761 // These scales always work.
10766 // These scales are formed with basereg+scalereg. Only accept if there is
10771 default: // Other stuff never works.
10779 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10780 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10782 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10783 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10784 if (NumBits1 <= NumBits2)
10789 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10790 if (!VT1.isInteger() || !VT2.isInteger())
10792 unsigned NumBits1 = VT1.getSizeInBits();
10793 unsigned NumBits2 = VT2.getSizeInBits();
10794 if (NumBits1 <= NumBits2)
10799 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10800 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10801 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10804 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10805 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10806 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10809 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10810 // i16 instructions are longer (0x66 prefix) and potentially slower.
10811 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10814 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10815 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10816 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10817 /// are assumed to be legal.
10819 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10821 // Very little shuffling can be done for 64-bit vectors right now.
10822 if (VT.getSizeInBits() == 64)
10823 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10825 // FIXME: pshufb, blends, shifts.
10826 return (VT.getVectorNumElements() == 2 ||
10827 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10828 isMOVLMask(M, VT) ||
10829 isSHUFPMask(M, VT) ||
10830 isPSHUFDMask(M, VT) ||
10831 isPSHUFHWMask(M, VT) ||
10832 isPSHUFLWMask(M, VT) ||
10833 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10834 isUNPCKLMask(M, VT) ||
10835 isUNPCKHMask(M, VT) ||
10836 isUNPCKL_v_undef_Mask(M, VT) ||
10837 isUNPCKH_v_undef_Mask(M, VT));
10841 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10843 unsigned NumElts = VT.getVectorNumElements();
10844 // FIXME: This collection of masks seems suspect.
10847 if (NumElts == 4 && VT.getSizeInBits() == 128) {
10848 return (isMOVLMask(Mask, VT) ||
10849 isCommutedMOVLMask(Mask, VT, true) ||
10850 isSHUFPMask(Mask, VT) ||
10851 isCommutedSHUFPMask(Mask, VT));
10856 //===----------------------------------------------------------------------===//
10857 // X86 Scheduler Hooks
10858 //===----------------------------------------------------------------------===//
10860 // private utility function
10861 MachineBasicBlock *
10862 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10863 MachineBasicBlock *MBB,
10870 TargetRegisterClass *RC,
10871 bool invSrc) const {
10872 // For the atomic bitwise operator, we generate
10875 // ld t1 = [bitinstr.addr]
10876 // op t2 = t1, [bitinstr.val]
10878 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10880 // fallthrough -->nextMBB
10881 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10882 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10883 MachineFunction::iterator MBBIter = MBB;
10886 /// First build the CFG
10887 MachineFunction *F = MBB->getParent();
10888 MachineBasicBlock *thisMBB = MBB;
10889 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10890 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10891 F->insert(MBBIter, newMBB);
10892 F->insert(MBBIter, nextMBB);
10894 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10895 nextMBB->splice(nextMBB->begin(), thisMBB,
10896 llvm::next(MachineBasicBlock::iterator(bInstr)),
10898 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10900 // Update thisMBB to fall through to newMBB
10901 thisMBB->addSuccessor(newMBB);
10903 // newMBB jumps to itself and fall through to nextMBB
10904 newMBB->addSuccessor(nextMBB);
10905 newMBB->addSuccessor(newMBB);
10907 // Insert instructions into newMBB based on incoming instruction
10908 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10909 "unexpected number of operands");
10910 DebugLoc dl = bInstr->getDebugLoc();
10911 MachineOperand& destOper = bInstr->getOperand(0);
10912 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10913 int numArgs = bInstr->getNumOperands() - 1;
10914 for (int i=0; i < numArgs; ++i)
10915 argOpers[i] = &bInstr->getOperand(i+1);
10917 // x86 address has 4 operands: base, index, scale, and displacement
10918 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10919 int valArgIndx = lastAddrIndx + 1;
10921 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10922 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10923 for (int i=0; i <= lastAddrIndx; ++i)
10924 (*MIB).addOperand(*argOpers[i]);
10926 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10928 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10933 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10934 assert((argOpers[valArgIndx]->isReg() ||
10935 argOpers[valArgIndx]->isImm()) &&
10936 "invalid operand");
10937 if (argOpers[valArgIndx]->isReg())
10938 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10940 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10942 (*MIB).addOperand(*argOpers[valArgIndx]);
10944 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10947 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10948 for (int i=0; i <= lastAddrIndx; ++i)
10949 (*MIB).addOperand(*argOpers[i]);
10951 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10952 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10953 bInstr->memoperands_end());
10955 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10956 MIB.addReg(EAXreg);
10959 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10961 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10965 // private utility function: 64 bit atomics on 32 bit host.
10966 MachineBasicBlock *
10967 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10968 MachineBasicBlock *MBB,
10973 bool invSrc) const {
10974 // For the atomic bitwise operator, we generate
10975 // thisMBB (instructions are in pairs, except cmpxchg8b)
10976 // ld t1,t2 = [bitinstr.addr]
10978 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10979 // op t5, t6 <- out1, out2, [bitinstr.val]
10980 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
10981 // mov ECX, EBX <- t5, t6
10982 // mov EAX, EDX <- t1, t2
10983 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
10984 // mov t3, t4 <- EAX, EDX
10986 // result in out1, out2
10987 // fallthrough -->nextMBB
10989 const TargetRegisterClass *RC = X86::GR32RegisterClass;
10990 const unsigned LoadOpc = X86::MOV32rm;
10991 const unsigned NotOpc = X86::NOT32r;
10992 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10993 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10994 MachineFunction::iterator MBBIter = MBB;
10997 /// First build the CFG
10998 MachineFunction *F = MBB->getParent();
10999 MachineBasicBlock *thisMBB = MBB;
11000 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11001 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11002 F->insert(MBBIter, newMBB);
11003 F->insert(MBBIter, nextMBB);
11005 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11006 nextMBB->splice(nextMBB->begin(), thisMBB,
11007 llvm::next(MachineBasicBlock::iterator(bInstr)),
11009 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11011 // Update thisMBB to fall through to newMBB
11012 thisMBB->addSuccessor(newMBB);
11014 // newMBB jumps to itself and fall through to nextMBB
11015 newMBB->addSuccessor(nextMBB);
11016 newMBB->addSuccessor(newMBB);
11018 DebugLoc dl = bInstr->getDebugLoc();
11019 // Insert instructions into newMBB based on incoming instruction
11020 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11021 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11022 "unexpected number of operands");
11023 MachineOperand& dest1Oper = bInstr->getOperand(0);
11024 MachineOperand& dest2Oper = bInstr->getOperand(1);
11025 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11026 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11027 argOpers[i] = &bInstr->getOperand(i+2);
11029 // We use some of the operands multiple times, so conservatively just
11030 // clear any kill flags that might be present.
11031 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11032 argOpers[i]->setIsKill(false);
11035 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11036 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11038 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11039 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11040 for (int i=0; i <= lastAddrIndx; ++i)
11041 (*MIB).addOperand(*argOpers[i]);
11042 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11043 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11044 // add 4 to displacement.
11045 for (int i=0; i <= lastAddrIndx-2; ++i)
11046 (*MIB).addOperand(*argOpers[i]);
11047 MachineOperand newOp3 = *(argOpers[3]);
11048 if (newOp3.isImm())
11049 newOp3.setImm(newOp3.getImm()+4);
11051 newOp3.setOffset(newOp3.getOffset()+4);
11052 (*MIB).addOperand(newOp3);
11053 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11055 // t3/4 are defined later, at the bottom of the loop
11056 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11057 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11058 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11059 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11060 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11061 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11063 // The subsequent operations should be using the destination registers of
11064 //the PHI instructions.
11066 t1 = F->getRegInfo().createVirtualRegister(RC);
11067 t2 = F->getRegInfo().createVirtualRegister(RC);
11068 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11069 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11071 t1 = dest1Oper.getReg();
11072 t2 = dest2Oper.getReg();
11075 int valArgIndx = lastAddrIndx + 1;
11076 assert((argOpers[valArgIndx]->isReg() ||
11077 argOpers[valArgIndx]->isImm()) &&
11078 "invalid operand");
11079 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11080 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11081 if (argOpers[valArgIndx]->isReg())
11082 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11084 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11085 if (regOpcL != X86::MOV32rr)
11087 (*MIB).addOperand(*argOpers[valArgIndx]);
11088 assert(argOpers[valArgIndx + 1]->isReg() ==
11089 argOpers[valArgIndx]->isReg());
11090 assert(argOpers[valArgIndx + 1]->isImm() ==
11091 argOpers[valArgIndx]->isImm());
11092 if (argOpers[valArgIndx + 1]->isReg())
11093 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11095 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11096 if (regOpcH != X86::MOV32rr)
11098 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11100 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11102 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11105 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11107 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11110 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11111 for (int i=0; i <= lastAddrIndx; ++i)
11112 (*MIB).addOperand(*argOpers[i]);
11114 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11115 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11116 bInstr->memoperands_end());
11118 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11119 MIB.addReg(X86::EAX);
11120 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11121 MIB.addReg(X86::EDX);
11124 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11126 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11130 // private utility function
11131 MachineBasicBlock *
11132 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11133 MachineBasicBlock *MBB,
11134 unsigned cmovOpc) const {
11135 // For the atomic min/max operator, we generate
11138 // ld t1 = [min/max.addr]
11139 // mov t2 = [min/max.val]
11141 // cmov[cond] t2 = t1
11143 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11145 // fallthrough -->nextMBB
11147 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11148 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11149 MachineFunction::iterator MBBIter = MBB;
11152 /// First build the CFG
11153 MachineFunction *F = MBB->getParent();
11154 MachineBasicBlock *thisMBB = MBB;
11155 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11156 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11157 F->insert(MBBIter, newMBB);
11158 F->insert(MBBIter, nextMBB);
11160 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11161 nextMBB->splice(nextMBB->begin(), thisMBB,
11162 llvm::next(MachineBasicBlock::iterator(mInstr)),
11164 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11166 // Update thisMBB to fall through to newMBB
11167 thisMBB->addSuccessor(newMBB);
11169 // newMBB jumps to newMBB and fall through to nextMBB
11170 newMBB->addSuccessor(nextMBB);
11171 newMBB->addSuccessor(newMBB);
11173 DebugLoc dl = mInstr->getDebugLoc();
11174 // Insert instructions into newMBB based on incoming instruction
11175 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11176 "unexpected number of operands");
11177 MachineOperand& destOper = mInstr->getOperand(0);
11178 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11179 int numArgs = mInstr->getNumOperands() - 1;
11180 for (int i=0; i < numArgs; ++i)
11181 argOpers[i] = &mInstr->getOperand(i+1);
11183 // x86 address has 4 operands: base, index, scale, and displacement
11184 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11185 int valArgIndx = lastAddrIndx + 1;
11187 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11188 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11189 for (int i=0; i <= lastAddrIndx; ++i)
11190 (*MIB).addOperand(*argOpers[i]);
11192 // We only support register and immediate values
11193 assert((argOpers[valArgIndx]->isReg() ||
11194 argOpers[valArgIndx]->isImm()) &&
11195 "invalid operand");
11197 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11198 if (argOpers[valArgIndx]->isReg())
11199 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11201 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11202 (*MIB).addOperand(*argOpers[valArgIndx]);
11204 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11207 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11212 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11213 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11217 // Cmp and exchange if none has modified the memory location
11218 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11219 for (int i=0; i <= lastAddrIndx; ++i)
11220 (*MIB).addOperand(*argOpers[i]);
11222 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11223 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11224 mInstr->memoperands_end());
11226 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11227 MIB.addReg(X86::EAX);
11230 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11232 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11236 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11237 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11238 // in the .td file.
11239 MachineBasicBlock *
11240 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11241 unsigned numArgs, bool memArg) const {
11242 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11243 "Target must have SSE4.2 or AVX features enabled");
11245 DebugLoc dl = MI->getDebugLoc();
11246 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11248 if (!Subtarget->hasAVX()) {
11250 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11252 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11255 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11257 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11260 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11261 for (unsigned i = 0; i < numArgs; ++i) {
11262 MachineOperand &Op = MI->getOperand(i+1);
11263 if (!(Op.isReg() && Op.isImplicit()))
11264 MIB.addOperand(Op);
11266 BuildMI(*BB, MI, dl,
11267 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11268 MI->getOperand(0).getReg())
11269 .addReg(X86::XMM0);
11271 MI->eraseFromParent();
11275 MachineBasicBlock *
11276 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11277 DebugLoc dl = MI->getDebugLoc();
11278 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11280 // Address into RAX/EAX, other two args into ECX, EDX.
11281 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11282 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11283 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11284 for (int i = 0; i < X86::AddrNumOperands; ++i)
11285 MIB.addOperand(MI->getOperand(i));
11287 unsigned ValOps = X86::AddrNumOperands;
11288 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11289 .addReg(MI->getOperand(ValOps).getReg());
11290 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11291 .addReg(MI->getOperand(ValOps+1).getReg());
11293 // The instruction doesn't actually take any operands though.
11294 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11296 MI->eraseFromParent(); // The pseudo is gone now.
11300 MachineBasicBlock *
11301 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11302 DebugLoc dl = MI->getDebugLoc();
11303 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11305 // First arg in ECX, the second in EAX.
11306 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11307 .addReg(MI->getOperand(0).getReg());
11308 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11309 .addReg(MI->getOperand(1).getReg());
11311 // The instruction doesn't actually take any operands though.
11312 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11314 MI->eraseFromParent(); // The pseudo is gone now.
11318 MachineBasicBlock *
11319 X86TargetLowering::EmitVAARG64WithCustomInserter(
11321 MachineBasicBlock *MBB) const {
11322 // Emit va_arg instruction on X86-64.
11324 // Operands to this pseudo-instruction:
11325 // 0 ) Output : destination address (reg)
11326 // 1-5) Input : va_list address (addr, i64mem)
11327 // 6 ) ArgSize : Size (in bytes) of vararg type
11328 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11329 // 8 ) Align : Alignment of type
11330 // 9 ) EFLAGS (implicit-def)
11332 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11333 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11335 unsigned DestReg = MI->getOperand(0).getReg();
11336 MachineOperand &Base = MI->getOperand(1);
11337 MachineOperand &Scale = MI->getOperand(2);
11338 MachineOperand &Index = MI->getOperand(3);
11339 MachineOperand &Disp = MI->getOperand(4);
11340 MachineOperand &Segment = MI->getOperand(5);
11341 unsigned ArgSize = MI->getOperand(6).getImm();
11342 unsigned ArgMode = MI->getOperand(7).getImm();
11343 unsigned Align = MI->getOperand(8).getImm();
11345 // Memory Reference
11346 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11347 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11348 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11350 // Machine Information
11351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11352 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11353 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11354 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11355 DebugLoc DL = MI->getDebugLoc();
11357 // struct va_list {
11360 // i64 overflow_area (address)
11361 // i64 reg_save_area (address)
11363 // sizeof(va_list) = 24
11364 // alignment(va_list) = 8
11366 unsigned TotalNumIntRegs = 6;
11367 unsigned TotalNumXMMRegs = 8;
11368 bool UseGPOffset = (ArgMode == 1);
11369 bool UseFPOffset = (ArgMode == 2);
11370 unsigned MaxOffset = TotalNumIntRegs * 8 +
11371 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11373 /* Align ArgSize to a multiple of 8 */
11374 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11375 bool NeedsAlign = (Align > 8);
11377 MachineBasicBlock *thisMBB = MBB;
11378 MachineBasicBlock *overflowMBB;
11379 MachineBasicBlock *offsetMBB;
11380 MachineBasicBlock *endMBB;
11382 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11383 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11384 unsigned OffsetReg = 0;
11386 if (!UseGPOffset && !UseFPOffset) {
11387 // If we only pull from the overflow region, we don't create a branch.
11388 // We don't need to alter control flow.
11389 OffsetDestReg = 0; // unused
11390 OverflowDestReg = DestReg;
11393 overflowMBB = thisMBB;
11396 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11397 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11398 // If not, pull from overflow_area. (branch to overflowMBB)
11403 // offsetMBB overflowMBB
11408 // Registers for the PHI in endMBB
11409 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11410 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11412 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11413 MachineFunction *MF = MBB->getParent();
11414 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11415 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11416 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11418 MachineFunction::iterator MBBIter = MBB;
11421 // Insert the new basic blocks
11422 MF->insert(MBBIter, offsetMBB);
11423 MF->insert(MBBIter, overflowMBB);
11424 MF->insert(MBBIter, endMBB);
11426 // Transfer the remainder of MBB and its successor edges to endMBB.
11427 endMBB->splice(endMBB->begin(), thisMBB,
11428 llvm::next(MachineBasicBlock::iterator(MI)),
11430 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11432 // Make offsetMBB and overflowMBB successors of thisMBB
11433 thisMBB->addSuccessor(offsetMBB);
11434 thisMBB->addSuccessor(overflowMBB);
11436 // endMBB is a successor of both offsetMBB and overflowMBB
11437 offsetMBB->addSuccessor(endMBB);
11438 overflowMBB->addSuccessor(endMBB);
11440 // Load the offset value into a register
11441 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11442 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11446 .addDisp(Disp, UseFPOffset ? 4 : 0)
11447 .addOperand(Segment)
11448 .setMemRefs(MMOBegin, MMOEnd);
11450 // Check if there is enough room left to pull this argument.
11451 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11453 .addImm(MaxOffset + 8 - ArgSizeA8);
11455 // Branch to "overflowMBB" if offset >= max
11456 // Fall through to "offsetMBB" otherwise
11457 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11458 .addMBB(overflowMBB);
11461 // In offsetMBB, emit code to use the reg_save_area.
11463 assert(OffsetReg != 0);
11465 // Read the reg_save_area address.
11466 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11467 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11472 .addOperand(Segment)
11473 .setMemRefs(MMOBegin, MMOEnd);
11475 // Zero-extend the offset
11476 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11477 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11480 .addImm(X86::sub_32bit);
11482 // Add the offset to the reg_save_area to get the final address.
11483 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11484 .addReg(OffsetReg64)
11485 .addReg(RegSaveReg);
11487 // Compute the offset for the next argument
11488 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11489 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11491 .addImm(UseFPOffset ? 16 : 8);
11493 // Store it back into the va_list.
11494 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11498 .addDisp(Disp, UseFPOffset ? 4 : 0)
11499 .addOperand(Segment)
11500 .addReg(NextOffsetReg)
11501 .setMemRefs(MMOBegin, MMOEnd);
11504 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11509 // Emit code to use overflow area
11512 // Load the overflow_area address into a register.
11513 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11514 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11519 .addOperand(Segment)
11520 .setMemRefs(MMOBegin, MMOEnd);
11522 // If we need to align it, do so. Otherwise, just copy the address
11523 // to OverflowDestReg.
11525 // Align the overflow address
11526 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11527 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11529 // aligned_addr = (addr + (align-1)) & ~(align-1)
11530 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11531 .addReg(OverflowAddrReg)
11534 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11536 .addImm(~(uint64_t)(Align-1));
11538 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11539 .addReg(OverflowAddrReg);
11542 // Compute the next overflow address after this argument.
11543 // (the overflow address should be kept 8-byte aligned)
11544 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11545 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11546 .addReg(OverflowDestReg)
11547 .addImm(ArgSizeA8);
11549 // Store the new overflow address.
11550 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11555 .addOperand(Segment)
11556 .addReg(NextAddrReg)
11557 .setMemRefs(MMOBegin, MMOEnd);
11559 // If we branched, emit the PHI to the front of endMBB.
11561 BuildMI(*endMBB, endMBB->begin(), DL,
11562 TII->get(X86::PHI), DestReg)
11563 .addReg(OffsetDestReg).addMBB(offsetMBB)
11564 .addReg(OverflowDestReg).addMBB(overflowMBB);
11567 // Erase the pseudo instruction
11568 MI->eraseFromParent();
11573 MachineBasicBlock *
11574 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11576 MachineBasicBlock *MBB) const {
11577 // Emit code to save XMM registers to the stack. The ABI says that the
11578 // number of registers to save is given in %al, so it's theoretically
11579 // possible to do an indirect jump trick to avoid saving all of them,
11580 // however this code takes a simpler approach and just executes all
11581 // of the stores if %al is non-zero. It's less code, and it's probably
11582 // easier on the hardware branch predictor, and stores aren't all that
11583 // expensive anyway.
11585 // Create the new basic blocks. One block contains all the XMM stores,
11586 // and one block is the final destination regardless of whether any
11587 // stores were performed.
11588 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11589 MachineFunction *F = MBB->getParent();
11590 MachineFunction::iterator MBBIter = MBB;
11592 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11593 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11594 F->insert(MBBIter, XMMSaveMBB);
11595 F->insert(MBBIter, EndMBB);
11597 // Transfer the remainder of MBB and its successor edges to EndMBB.
11598 EndMBB->splice(EndMBB->begin(), MBB,
11599 llvm::next(MachineBasicBlock::iterator(MI)),
11601 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11603 // The original block will now fall through to the XMM save block.
11604 MBB->addSuccessor(XMMSaveMBB);
11605 // The XMMSaveMBB will fall through to the end block.
11606 XMMSaveMBB->addSuccessor(EndMBB);
11608 // Now add the instructions.
11609 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11610 DebugLoc DL = MI->getDebugLoc();
11612 unsigned CountReg = MI->getOperand(0).getReg();
11613 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11614 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11616 if (!Subtarget->isTargetWin64()) {
11617 // If %al is 0, branch around the XMM save block.
11618 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11619 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11620 MBB->addSuccessor(EndMBB);
11623 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11624 // In the XMM save block, save all the XMM argument registers.
11625 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11626 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11627 MachineMemOperand *MMO =
11628 F->getMachineMemOperand(
11629 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11630 MachineMemOperand::MOStore,
11631 /*Size=*/16, /*Align=*/16);
11632 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11633 .addFrameIndex(RegSaveFrameIndex)
11634 .addImm(/*Scale=*/1)
11635 .addReg(/*IndexReg=*/0)
11636 .addImm(/*Disp=*/Offset)
11637 .addReg(/*Segment=*/0)
11638 .addReg(MI->getOperand(i).getReg())
11639 .addMemOperand(MMO);
11642 MI->eraseFromParent(); // The pseudo instruction is gone now.
11647 MachineBasicBlock *
11648 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11649 MachineBasicBlock *BB) const {
11650 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11651 DebugLoc DL = MI->getDebugLoc();
11653 // To "insert" a SELECT_CC instruction, we actually have to insert the
11654 // diamond control-flow pattern. The incoming instruction knows the
11655 // destination vreg to set, the condition code register to branch on, the
11656 // true/false values to select between, and a branch opcode to use.
11657 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11658 MachineFunction::iterator It = BB;
11664 // cmpTY ccX, r1, r2
11666 // fallthrough --> copy0MBB
11667 MachineBasicBlock *thisMBB = BB;
11668 MachineFunction *F = BB->getParent();
11669 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11670 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11671 F->insert(It, copy0MBB);
11672 F->insert(It, sinkMBB);
11674 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11675 // live into the sink and copy blocks.
11676 if (!MI->killsRegister(X86::EFLAGS)) {
11677 copy0MBB->addLiveIn(X86::EFLAGS);
11678 sinkMBB->addLiveIn(X86::EFLAGS);
11681 // Transfer the remainder of BB and its successor edges to sinkMBB.
11682 sinkMBB->splice(sinkMBB->begin(), BB,
11683 llvm::next(MachineBasicBlock::iterator(MI)),
11685 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11687 // Add the true and fallthrough blocks as its successors.
11688 BB->addSuccessor(copy0MBB);
11689 BB->addSuccessor(sinkMBB);
11691 // Create the conditional branch instruction.
11693 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11694 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11697 // %FalseValue = ...
11698 // # fallthrough to sinkMBB
11699 copy0MBB->addSuccessor(sinkMBB);
11702 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11704 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11705 TII->get(X86::PHI), MI->getOperand(0).getReg())
11706 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11707 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11709 MI->eraseFromParent(); // The pseudo instruction is gone now.
11713 MachineBasicBlock *
11714 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11715 bool Is64Bit) const {
11716 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11717 DebugLoc DL = MI->getDebugLoc();
11718 MachineFunction *MF = BB->getParent();
11719 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11721 assert(EnableSegmentedStacks);
11723 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11724 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11727 // ... [Till the alloca]
11728 // If stacklet is not large enough, jump to mallocMBB
11731 // Allocate by subtracting from RSP
11732 // Jump to continueMBB
11735 // Allocate by call to runtime
11739 // [rest of original BB]
11742 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11743 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11744 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11746 MachineRegisterInfo &MRI = MF->getRegInfo();
11747 const TargetRegisterClass *AddrRegClass =
11748 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11750 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11751 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11752 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11753 sizeVReg = MI->getOperand(1).getReg(),
11754 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11756 MachineFunction::iterator MBBIter = BB;
11759 MF->insert(MBBIter, bumpMBB);
11760 MF->insert(MBBIter, mallocMBB);
11761 MF->insert(MBBIter, continueMBB);
11763 continueMBB->splice(continueMBB->begin(), BB, llvm::next
11764 (MachineBasicBlock::iterator(MI)), BB->end());
11765 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11767 // Add code to the main basic block to check if the stack limit has been hit,
11768 // and if so, jump to mallocMBB otherwise to bumpMBB.
11769 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11770 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11771 .addReg(tmpSPVReg).addReg(sizeVReg);
11772 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11773 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11774 .addReg(tmpSPVReg);
11775 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11777 // bumpMBB simply decreases the stack pointer, since we know the current
11778 // stacklet has enough space.
11779 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11780 .addReg(tmpSPVReg);
11781 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11782 .addReg(tmpSPVReg);
11783 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11785 // Calls into a routine in libgcc to allocate more space from the heap.
11787 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11789 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11790 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11792 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11794 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11795 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11796 .addExternalSymbol("__morestack_allocate_stack_space");
11800 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11803 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11804 .addReg(Is64Bit ? X86::RAX : X86::EAX);
11805 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11807 // Set up the CFG correctly.
11808 BB->addSuccessor(bumpMBB);
11809 BB->addSuccessor(mallocMBB);
11810 mallocMBB->addSuccessor(continueMBB);
11811 bumpMBB->addSuccessor(continueMBB);
11813 // Take care of the PHI nodes.
11814 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11815 MI->getOperand(0).getReg())
11816 .addReg(mallocPtrVReg).addMBB(mallocMBB)
11817 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11819 // Delete the original pseudo instruction.
11820 MI->eraseFromParent();
11823 return continueMBB;
11826 MachineBasicBlock *
11827 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11828 MachineBasicBlock *BB) const {
11829 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11830 DebugLoc DL = MI->getDebugLoc();
11832 assert(!Subtarget->isTargetEnvMacho());
11834 // The lowering is pretty easy: we're just emitting the call to _alloca. The
11835 // non-trivial part is impdef of ESP.
11837 if (Subtarget->isTargetWin64()) {
11838 if (Subtarget->isTargetCygMing()) {
11839 // ___chkstk(Mingw64):
11840 // Clobbers R10, R11, RAX and EFLAGS.
11842 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11843 .addExternalSymbol("___chkstk")
11844 .addReg(X86::RAX, RegState::Implicit)
11845 .addReg(X86::RSP, RegState::Implicit)
11846 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11847 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11848 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11850 // __chkstk(MSVCRT): does not update stack pointer.
11851 // Clobbers R10, R11 and EFLAGS.
11852 // FIXME: RAX(allocated size) might be reused and not killed.
11853 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11854 .addExternalSymbol("__chkstk")
11855 .addReg(X86::RAX, RegState::Implicit)
11856 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11857 // RAX has the offset to subtracted from RSP.
11858 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11863 const char *StackProbeSymbol =
11864 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11866 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11867 .addExternalSymbol(StackProbeSymbol)
11868 .addReg(X86::EAX, RegState::Implicit)
11869 .addReg(X86::ESP, RegState::Implicit)
11870 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11871 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11872 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11875 MI->eraseFromParent(); // The pseudo instruction is gone now.
11879 MachineBasicBlock *
11880 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11881 MachineBasicBlock *BB) const {
11882 // This is pretty easy. We're taking the value that we received from
11883 // our load from the relocation, sticking it in either RDI (x86-64)
11884 // or EAX and doing an indirect call. The return value will then
11885 // be in the normal return register.
11886 const X86InstrInfo *TII
11887 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11888 DebugLoc DL = MI->getDebugLoc();
11889 MachineFunction *F = BB->getParent();
11891 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11892 assert(MI->getOperand(3).isGlobal() && "This should be a global");
11894 if (Subtarget->is64Bit()) {
11895 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11896 TII->get(X86::MOV64rm), X86::RDI)
11898 .addImm(0).addReg(0)
11899 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11900 MI->getOperand(3).getTargetFlags())
11902 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11903 addDirectMem(MIB, X86::RDI);
11904 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11905 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11906 TII->get(X86::MOV32rm), X86::EAX)
11908 .addImm(0).addReg(0)
11909 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11910 MI->getOperand(3).getTargetFlags())
11912 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11913 addDirectMem(MIB, X86::EAX);
11915 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11916 TII->get(X86::MOV32rm), X86::EAX)
11917 .addReg(TII->getGlobalBaseReg(F))
11918 .addImm(0).addReg(0)
11919 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11920 MI->getOperand(3).getTargetFlags())
11922 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11923 addDirectMem(MIB, X86::EAX);
11926 MI->eraseFromParent(); // The pseudo instruction is gone now.
11930 MachineBasicBlock *
11931 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11932 MachineBasicBlock *BB) const {
11933 switch (MI->getOpcode()) {
11934 default: assert(false && "Unexpected instr type to insert");
11935 case X86::TAILJMPd64:
11936 case X86::TAILJMPr64:
11937 case X86::TAILJMPm64:
11938 assert(!"TAILJMP64 would not be touched here.");
11939 case X86::TCRETURNdi64:
11940 case X86::TCRETURNri64:
11941 case X86::TCRETURNmi64:
11942 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11943 // On AMD64, additional defs should be added before register allocation.
11944 if (!Subtarget->isTargetWin64()) {
11945 MI->addRegisterDefined(X86::RSI);
11946 MI->addRegisterDefined(X86::RDI);
11947 MI->addRegisterDefined(X86::XMM6);
11948 MI->addRegisterDefined(X86::XMM7);
11949 MI->addRegisterDefined(X86::XMM8);
11950 MI->addRegisterDefined(X86::XMM9);
11951 MI->addRegisterDefined(X86::XMM10);
11952 MI->addRegisterDefined(X86::XMM11);
11953 MI->addRegisterDefined(X86::XMM12);
11954 MI->addRegisterDefined(X86::XMM13);
11955 MI->addRegisterDefined(X86::XMM14);
11956 MI->addRegisterDefined(X86::XMM15);
11959 case X86::WIN_ALLOCA:
11960 return EmitLoweredWinAlloca(MI, BB);
11961 case X86::SEG_ALLOCA_32:
11962 return EmitLoweredSegAlloca(MI, BB, false);
11963 case X86::SEG_ALLOCA_64:
11964 return EmitLoweredSegAlloca(MI, BB, true);
11965 case X86::TLSCall_32:
11966 case X86::TLSCall_64:
11967 return EmitLoweredTLSCall(MI, BB);
11968 case X86::CMOV_GR8:
11969 case X86::CMOV_FR32:
11970 case X86::CMOV_FR64:
11971 case X86::CMOV_V4F32:
11972 case X86::CMOV_V2F64:
11973 case X86::CMOV_V2I64:
11974 case X86::CMOV_V8F32:
11975 case X86::CMOV_V4F64:
11976 case X86::CMOV_V4I64:
11977 case X86::CMOV_GR16:
11978 case X86::CMOV_GR32:
11979 case X86::CMOV_RFP32:
11980 case X86::CMOV_RFP64:
11981 case X86::CMOV_RFP80:
11982 return EmitLoweredSelect(MI, BB);
11984 case X86::FP32_TO_INT16_IN_MEM:
11985 case X86::FP32_TO_INT32_IN_MEM:
11986 case X86::FP32_TO_INT64_IN_MEM:
11987 case X86::FP64_TO_INT16_IN_MEM:
11988 case X86::FP64_TO_INT32_IN_MEM:
11989 case X86::FP64_TO_INT64_IN_MEM:
11990 case X86::FP80_TO_INT16_IN_MEM:
11991 case X86::FP80_TO_INT32_IN_MEM:
11992 case X86::FP80_TO_INT64_IN_MEM: {
11993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11994 DebugLoc DL = MI->getDebugLoc();
11996 // Change the floating point control register to use "round towards zero"
11997 // mode when truncating to an integer value.
11998 MachineFunction *F = BB->getParent();
11999 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12000 addFrameReference(BuildMI(*BB, MI, DL,
12001 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12003 // Load the old value of the high byte of the control word...
12005 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12006 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12009 // Set the high part to be round to zero...
12010 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12013 // Reload the modified control word now...
12014 addFrameReference(BuildMI(*BB, MI, DL,
12015 TII->get(X86::FLDCW16m)), CWFrameIdx);
12017 // Restore the memory image of control word to original value
12018 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12021 // Get the X86 opcode to use.
12023 switch (MI->getOpcode()) {
12024 default: llvm_unreachable("illegal opcode!");
12025 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12026 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12027 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12028 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12029 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12030 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12031 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12032 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12033 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12037 MachineOperand &Op = MI->getOperand(0);
12039 AM.BaseType = X86AddressMode::RegBase;
12040 AM.Base.Reg = Op.getReg();
12042 AM.BaseType = X86AddressMode::FrameIndexBase;
12043 AM.Base.FrameIndex = Op.getIndex();
12045 Op = MI->getOperand(1);
12047 AM.Scale = Op.getImm();
12048 Op = MI->getOperand(2);
12050 AM.IndexReg = Op.getImm();
12051 Op = MI->getOperand(3);
12052 if (Op.isGlobal()) {
12053 AM.GV = Op.getGlobal();
12055 AM.Disp = Op.getImm();
12057 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12058 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12060 // Reload the original control word now.
12061 addFrameReference(BuildMI(*BB, MI, DL,
12062 TII->get(X86::FLDCW16m)), CWFrameIdx);
12064 MI->eraseFromParent(); // The pseudo instruction is gone now.
12067 // String/text processing lowering.
12068 case X86::PCMPISTRM128REG:
12069 case X86::VPCMPISTRM128REG:
12070 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12071 case X86::PCMPISTRM128MEM:
12072 case X86::VPCMPISTRM128MEM:
12073 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12074 case X86::PCMPESTRM128REG:
12075 case X86::VPCMPESTRM128REG:
12076 return EmitPCMP(MI, BB, 5, false /* in mem */);
12077 case X86::PCMPESTRM128MEM:
12078 case X86::VPCMPESTRM128MEM:
12079 return EmitPCMP(MI, BB, 5, true /* in mem */);
12081 // Thread synchronization.
12083 return EmitMonitor(MI, BB);
12085 return EmitMwait(MI, BB);
12087 // Atomic Lowering.
12088 case X86::ATOMAND32:
12089 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12090 X86::AND32ri, X86::MOV32rm,
12092 X86::NOT32r, X86::EAX,
12093 X86::GR32RegisterClass);
12094 case X86::ATOMOR32:
12095 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12096 X86::OR32ri, X86::MOV32rm,
12098 X86::NOT32r, X86::EAX,
12099 X86::GR32RegisterClass);
12100 case X86::ATOMXOR32:
12101 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12102 X86::XOR32ri, X86::MOV32rm,
12104 X86::NOT32r, X86::EAX,
12105 X86::GR32RegisterClass);
12106 case X86::ATOMNAND32:
12107 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12108 X86::AND32ri, X86::MOV32rm,
12110 X86::NOT32r, X86::EAX,
12111 X86::GR32RegisterClass, true);
12112 case X86::ATOMMIN32:
12113 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12114 case X86::ATOMMAX32:
12115 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12116 case X86::ATOMUMIN32:
12117 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12118 case X86::ATOMUMAX32:
12119 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12121 case X86::ATOMAND16:
12122 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12123 X86::AND16ri, X86::MOV16rm,
12125 X86::NOT16r, X86::AX,
12126 X86::GR16RegisterClass);
12127 case X86::ATOMOR16:
12128 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12129 X86::OR16ri, X86::MOV16rm,
12131 X86::NOT16r, X86::AX,
12132 X86::GR16RegisterClass);
12133 case X86::ATOMXOR16:
12134 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12135 X86::XOR16ri, X86::MOV16rm,
12137 X86::NOT16r, X86::AX,
12138 X86::GR16RegisterClass);
12139 case X86::ATOMNAND16:
12140 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12141 X86::AND16ri, X86::MOV16rm,
12143 X86::NOT16r, X86::AX,
12144 X86::GR16RegisterClass, true);
12145 case X86::ATOMMIN16:
12146 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12147 case X86::ATOMMAX16:
12148 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12149 case X86::ATOMUMIN16:
12150 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12151 case X86::ATOMUMAX16:
12152 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12154 case X86::ATOMAND8:
12155 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12156 X86::AND8ri, X86::MOV8rm,
12158 X86::NOT8r, X86::AL,
12159 X86::GR8RegisterClass);
12161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12162 X86::OR8ri, X86::MOV8rm,
12164 X86::NOT8r, X86::AL,
12165 X86::GR8RegisterClass);
12166 case X86::ATOMXOR8:
12167 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12168 X86::XOR8ri, X86::MOV8rm,
12170 X86::NOT8r, X86::AL,
12171 X86::GR8RegisterClass);
12172 case X86::ATOMNAND8:
12173 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12174 X86::AND8ri, X86::MOV8rm,
12176 X86::NOT8r, X86::AL,
12177 X86::GR8RegisterClass, true);
12178 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12179 // This group is for 64-bit host.
12180 case X86::ATOMAND64:
12181 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12182 X86::AND64ri32, X86::MOV64rm,
12184 X86::NOT64r, X86::RAX,
12185 X86::GR64RegisterClass);
12186 case X86::ATOMOR64:
12187 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12188 X86::OR64ri32, X86::MOV64rm,
12190 X86::NOT64r, X86::RAX,
12191 X86::GR64RegisterClass);
12192 case X86::ATOMXOR64:
12193 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12194 X86::XOR64ri32, X86::MOV64rm,
12196 X86::NOT64r, X86::RAX,
12197 X86::GR64RegisterClass);
12198 case X86::ATOMNAND64:
12199 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12200 X86::AND64ri32, X86::MOV64rm,
12202 X86::NOT64r, X86::RAX,
12203 X86::GR64RegisterClass, true);
12204 case X86::ATOMMIN64:
12205 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12206 case X86::ATOMMAX64:
12207 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12208 case X86::ATOMUMIN64:
12209 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12210 case X86::ATOMUMAX64:
12211 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12213 // This group does 64-bit operations on a 32-bit host.
12214 case X86::ATOMAND6432:
12215 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12216 X86::AND32rr, X86::AND32rr,
12217 X86::AND32ri, X86::AND32ri,
12219 case X86::ATOMOR6432:
12220 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12221 X86::OR32rr, X86::OR32rr,
12222 X86::OR32ri, X86::OR32ri,
12224 case X86::ATOMXOR6432:
12225 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12226 X86::XOR32rr, X86::XOR32rr,
12227 X86::XOR32ri, X86::XOR32ri,
12229 case X86::ATOMNAND6432:
12230 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12231 X86::AND32rr, X86::AND32rr,
12232 X86::AND32ri, X86::AND32ri,
12234 case X86::ATOMADD6432:
12235 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12236 X86::ADD32rr, X86::ADC32rr,
12237 X86::ADD32ri, X86::ADC32ri,
12239 case X86::ATOMSUB6432:
12240 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12241 X86::SUB32rr, X86::SBB32rr,
12242 X86::SUB32ri, X86::SBB32ri,
12244 case X86::ATOMSWAP6432:
12245 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12246 X86::MOV32rr, X86::MOV32rr,
12247 X86::MOV32ri, X86::MOV32ri,
12249 case X86::VASTART_SAVE_XMM_REGS:
12250 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12252 case X86::VAARG_64:
12253 return EmitVAARG64WithCustomInserter(MI, BB);
12257 //===----------------------------------------------------------------------===//
12258 // X86 Optimization Hooks
12259 //===----------------------------------------------------------------------===//
12261 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12265 const SelectionDAG &DAG,
12266 unsigned Depth) const {
12267 unsigned Opc = Op.getOpcode();
12268 assert((Opc >= ISD::BUILTIN_OP_END ||
12269 Opc == ISD::INTRINSIC_WO_CHAIN ||
12270 Opc == ISD::INTRINSIC_W_CHAIN ||
12271 Opc == ISD::INTRINSIC_VOID) &&
12272 "Should use MaskedValueIsZero if you don't know whether Op"
12273 " is a target node!");
12275 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12289 // These nodes' second result is a boolean.
12290 if (Op.getResNo() == 0)
12293 case X86ISD::SETCC:
12294 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12295 Mask.getBitWidth() - 1);
12300 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12301 unsigned Depth) const {
12302 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12303 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12304 return Op.getValueType().getScalarType().getSizeInBits();
12310 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12311 /// node is a GlobalAddress + offset.
12312 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12313 const GlobalValue* &GA,
12314 int64_t &Offset) const {
12315 if (N->getOpcode() == X86ISD::Wrapper) {
12316 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12317 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12318 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12322 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12325 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12326 /// same as extracting the high 128-bit part of 256-bit vector and then
12327 /// inserting the result into the low part of a new 256-bit vector
12328 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12329 EVT VT = SVOp->getValueType(0);
12330 int NumElems = VT.getVectorNumElements();
12332 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12333 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12334 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12335 SVOp->getMaskElt(j) >= 0)
12341 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12342 /// same as extracting the low 128-bit part of 256-bit vector and then
12343 /// inserting the result into the high part of a new 256-bit vector
12344 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12345 EVT VT = SVOp->getValueType(0);
12346 int NumElems = VT.getVectorNumElements();
12348 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12349 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12350 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12351 SVOp->getMaskElt(j) >= 0)
12357 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12358 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12359 TargetLowering::DAGCombinerInfo &DCI) {
12360 DebugLoc dl = N->getDebugLoc();
12361 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12362 SDValue V1 = SVOp->getOperand(0);
12363 SDValue V2 = SVOp->getOperand(1);
12364 EVT VT = SVOp->getValueType(0);
12365 int NumElems = VT.getVectorNumElements();
12367 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12368 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12372 // V UNDEF BUILD_VECTOR UNDEF
12374 // CONCAT_VECTOR CONCAT_VECTOR
12377 // RESULT: V + zero extended
12379 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12380 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12381 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12384 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12387 // To match the shuffle mask, the first half of the mask should
12388 // be exactly the first vector, and all the rest a splat with the
12389 // first element of the second one.
12390 for (int i = 0; i < NumElems/2; ++i)
12391 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12392 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12395 // Emit a zeroed vector and insert the desired subvector on its
12397 SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
12398 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12399 DAG.getConstant(0, MVT::i32), DAG, dl);
12400 return DCI.CombineTo(N, InsV);
12403 //===--------------------------------------------------------------------===//
12404 // Combine some shuffles into subvector extracts and inserts:
12407 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12408 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12409 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12411 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12412 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12413 return DCI.CombineTo(N, InsV);
12416 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12417 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12418 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12419 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12420 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12421 return DCI.CombineTo(N, InsV);
12427 /// PerformShuffleCombine - Performs several different shuffle combines.
12428 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12429 TargetLowering::DAGCombinerInfo &DCI,
12430 const X86Subtarget *Subtarget) {
12431 DebugLoc dl = N->getDebugLoc();
12432 EVT VT = N->getValueType(0);
12434 // Don't create instructions with illegal types after legalize types has run.
12435 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12436 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12439 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12440 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12441 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12442 return PerformShuffleCombine256(N, DAG, DCI);
12444 // Only handle 128 wide vector from here on.
12445 if (VT.getSizeInBits() != 128)
12448 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12449 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12450 // consecutive, non-overlapping, and in the right order.
12451 SmallVector<SDValue, 16> Elts;
12452 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12453 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12455 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12458 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12459 /// generation and convert it from being a bunch of shuffles and extracts
12460 /// to a simple store and scalar loads to extract the elements.
12461 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12462 const TargetLowering &TLI) {
12463 SDValue InputVector = N->getOperand(0);
12465 // Only operate on vectors of 4 elements, where the alternative shuffling
12466 // gets to be more expensive.
12467 if (InputVector.getValueType() != MVT::v4i32)
12470 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12471 // single use which is a sign-extend or zero-extend, and all elements are
12473 SmallVector<SDNode *, 4> Uses;
12474 unsigned ExtractedElements = 0;
12475 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12476 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12477 if (UI.getUse().getResNo() != InputVector.getResNo())
12480 SDNode *Extract = *UI;
12481 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12484 if (Extract->getValueType(0) != MVT::i32)
12486 if (!Extract->hasOneUse())
12488 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12489 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12491 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12494 // Record which element was extracted.
12495 ExtractedElements |=
12496 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12498 Uses.push_back(Extract);
12501 // If not all the elements were used, this may not be worthwhile.
12502 if (ExtractedElements != 15)
12505 // Ok, we've now decided to do the transformation.
12506 DebugLoc dl = InputVector.getDebugLoc();
12508 // Store the value to a temporary stack slot.
12509 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12510 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12511 MachinePointerInfo(), false, false, 0);
12513 // Replace each use (extract) with a load of the appropriate element.
12514 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12515 UE = Uses.end(); UI != UE; ++UI) {
12516 SDNode *Extract = *UI;
12518 // cOMpute the element's address.
12519 SDValue Idx = Extract->getOperand(1);
12521 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12522 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12523 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12525 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12526 StackPtr, OffsetVal);
12528 // Load the scalar.
12529 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12530 ScalarAddr, MachinePointerInfo(),
12533 // Replace the exact with the load.
12534 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12537 // The replacement was made in place; don't return anything.
12541 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12542 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12543 const X86Subtarget *Subtarget) {
12544 DebugLoc DL = N->getDebugLoc();
12545 SDValue Cond = N->getOperand(0);
12546 // Get the LHS/RHS of the select.
12547 SDValue LHS = N->getOperand(1);
12548 SDValue RHS = N->getOperand(2);
12550 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12551 // instructions match the semantics of the common C idiom x<y?x:y but not
12552 // x<=y?x:y, because of how they handle negative zero (which can be
12553 // ignored in unsafe-math mode).
12554 if (Subtarget->hasSSE2() &&
12555 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12556 Cond.getOpcode() == ISD::SETCC) {
12557 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12559 unsigned Opcode = 0;
12560 // Check for x CC y ? x : y.
12561 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12562 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12566 // Converting this to a min would handle NaNs incorrectly, and swapping
12567 // the operands would cause it to handle comparisons between positive
12568 // and negative zero incorrectly.
12569 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12570 if (!UnsafeFPMath &&
12571 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12573 std::swap(LHS, RHS);
12575 Opcode = X86ISD::FMIN;
12578 // Converting this to a min would handle comparisons between positive
12579 // and negative zero incorrectly.
12580 if (!UnsafeFPMath &&
12581 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12583 Opcode = X86ISD::FMIN;
12586 // Converting this to a min would handle both negative zeros and NaNs
12587 // incorrectly, but we can swap the operands to fix both.
12588 std::swap(LHS, RHS);
12592 Opcode = X86ISD::FMIN;
12596 // Converting this to a max would handle comparisons between positive
12597 // and negative zero incorrectly.
12598 if (!UnsafeFPMath &&
12599 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12601 Opcode = X86ISD::FMAX;
12604 // Converting this to a max would handle NaNs incorrectly, and swapping
12605 // the operands would cause it to handle comparisons between positive
12606 // and negative zero incorrectly.
12607 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12608 if (!UnsafeFPMath &&
12609 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12611 std::swap(LHS, RHS);
12613 Opcode = X86ISD::FMAX;
12616 // Converting this to a max would handle both negative zeros and NaNs
12617 // incorrectly, but we can swap the operands to fix both.
12618 std::swap(LHS, RHS);
12622 Opcode = X86ISD::FMAX;
12625 // Check for x CC y ? y : x -- a min/max with reversed arms.
12626 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12627 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12631 // Converting this to a min would handle comparisons between positive
12632 // and negative zero incorrectly, and swapping the operands would
12633 // cause it to handle NaNs incorrectly.
12634 if (!UnsafeFPMath &&
12635 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12636 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12638 std::swap(LHS, RHS);
12640 Opcode = X86ISD::FMIN;
12643 // Converting this to a min would handle NaNs incorrectly.
12644 if (!UnsafeFPMath &&
12645 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12647 Opcode = X86ISD::FMIN;
12650 // Converting this to a min would handle both negative zeros and NaNs
12651 // incorrectly, but we can swap the operands to fix both.
12652 std::swap(LHS, RHS);
12656 Opcode = X86ISD::FMIN;
12660 // Converting this to a max would handle NaNs incorrectly.
12661 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12663 Opcode = X86ISD::FMAX;
12666 // Converting this to a max would handle comparisons between positive
12667 // and negative zero incorrectly, and swapping the operands would
12668 // cause it to handle NaNs incorrectly.
12669 if (!UnsafeFPMath &&
12670 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12671 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12673 std::swap(LHS, RHS);
12675 Opcode = X86ISD::FMAX;
12678 // Converting this to a max would handle both negative zeros and NaNs
12679 // incorrectly, but we can swap the operands to fix both.
12680 std::swap(LHS, RHS);
12684 Opcode = X86ISD::FMAX;
12690 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12693 // If this is a select between two integer constants, try to do some
12695 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12696 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12697 // Don't do this for crazy integer types.
12698 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12699 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12700 // so that TrueC (the true value) is larger than FalseC.
12701 bool NeedsCondInvert = false;
12703 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12704 // Efficiently invertible.
12705 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12706 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12707 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12708 NeedsCondInvert = true;
12709 std::swap(TrueC, FalseC);
12712 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
12713 if (FalseC->getAPIntValue() == 0 &&
12714 TrueC->getAPIntValue().isPowerOf2()) {
12715 if (NeedsCondInvert) // Invert the condition if needed.
12716 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12717 DAG.getConstant(1, Cond.getValueType()));
12719 // Zero extend the condition if needed.
12720 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12722 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12723 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12724 DAG.getConstant(ShAmt, MVT::i8));
12727 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12728 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12729 if (NeedsCondInvert) // Invert the condition if needed.
12730 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12731 DAG.getConstant(1, Cond.getValueType()));
12733 // Zero extend the condition if needed.
12734 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12735 FalseC->getValueType(0), Cond);
12736 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12737 SDValue(FalseC, 0));
12740 // Optimize cases that will turn into an LEA instruction. This requires
12741 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12742 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12743 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12744 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12746 bool isFastMultiplier = false;
12748 switch ((unsigned char)Diff) {
12750 case 1: // result = add base, cond
12751 case 2: // result = lea base( , cond*2)
12752 case 3: // result = lea base(cond, cond*2)
12753 case 4: // result = lea base( , cond*4)
12754 case 5: // result = lea base(cond, cond*4)
12755 case 8: // result = lea base( , cond*8)
12756 case 9: // result = lea base(cond, cond*8)
12757 isFastMultiplier = true;
12762 if (isFastMultiplier) {
12763 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12764 if (NeedsCondInvert) // Invert the condition if needed.
12765 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12766 DAG.getConstant(1, Cond.getValueType()));
12768 // Zero extend the condition if needed.
12769 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12771 // Scale the condition by the difference.
12773 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12774 DAG.getConstant(Diff, Cond.getValueType()));
12776 // Add the base if non-zero.
12777 if (FalseC->getAPIntValue() != 0)
12778 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12779 SDValue(FalseC, 0));
12789 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12790 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12791 TargetLowering::DAGCombinerInfo &DCI) {
12792 DebugLoc DL = N->getDebugLoc();
12794 // If the flag operand isn't dead, don't touch this CMOV.
12795 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12798 SDValue FalseOp = N->getOperand(0);
12799 SDValue TrueOp = N->getOperand(1);
12800 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12801 SDValue Cond = N->getOperand(3);
12802 if (CC == X86::COND_E || CC == X86::COND_NE) {
12803 switch (Cond.getOpcode()) {
12807 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12808 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12809 return (CC == X86::COND_E) ? FalseOp : TrueOp;
12813 // If this is a select between two integer constants, try to do some
12814 // optimizations. Note that the operands are ordered the opposite of SELECT
12816 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12817 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12818 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12819 // larger than FalseC (the false value).
12820 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12821 CC = X86::GetOppositeBranchCondition(CC);
12822 std::swap(TrueC, FalseC);
12825 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
12826 // This is efficient for any integer data type (including i8/i16) and
12828 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12829 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12830 DAG.getConstant(CC, MVT::i8), Cond);
12832 // Zero extend the condition if needed.
12833 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12835 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12836 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12837 DAG.getConstant(ShAmt, MVT::i8));
12838 if (N->getNumValues() == 2) // Dead flag value?
12839 return DCI.CombineTo(N, Cond, SDValue());
12843 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
12844 // for any integer data type, including i8/i16.
12845 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12846 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12847 DAG.getConstant(CC, MVT::i8), Cond);
12849 // Zero extend the condition if needed.
12850 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12851 FalseC->getValueType(0), Cond);
12852 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12853 SDValue(FalseC, 0));
12855 if (N->getNumValues() == 2) // Dead flag value?
12856 return DCI.CombineTo(N, Cond, SDValue());
12860 // Optimize cases that will turn into an LEA instruction. This requires
12861 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12862 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12863 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12864 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12866 bool isFastMultiplier = false;
12868 switch ((unsigned char)Diff) {
12870 case 1: // result = add base, cond
12871 case 2: // result = lea base( , cond*2)
12872 case 3: // result = lea base(cond, cond*2)
12873 case 4: // result = lea base( , cond*4)
12874 case 5: // result = lea base(cond, cond*4)
12875 case 8: // result = lea base( , cond*8)
12876 case 9: // result = lea base(cond, cond*8)
12877 isFastMultiplier = true;
12882 if (isFastMultiplier) {
12883 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12884 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12885 DAG.getConstant(CC, MVT::i8), Cond);
12886 // Zero extend the condition if needed.
12887 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12889 // Scale the condition by the difference.
12891 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12892 DAG.getConstant(Diff, Cond.getValueType()));
12894 // Add the base if non-zero.
12895 if (FalseC->getAPIntValue() != 0)
12896 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12897 SDValue(FalseC, 0));
12898 if (N->getNumValues() == 2) // Dead flag value?
12899 return DCI.CombineTo(N, Cond, SDValue());
12909 /// PerformMulCombine - Optimize a single multiply with constant into two
12910 /// in order to implement it with two cheaper instructions, e.g.
12911 /// LEA + SHL, LEA + LEA.
12912 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12913 TargetLowering::DAGCombinerInfo &DCI) {
12914 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12917 EVT VT = N->getValueType(0);
12918 if (VT != MVT::i64)
12921 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12924 uint64_t MulAmt = C->getZExtValue();
12925 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12928 uint64_t MulAmt1 = 0;
12929 uint64_t MulAmt2 = 0;
12930 if ((MulAmt % 9) == 0) {
12932 MulAmt2 = MulAmt / 9;
12933 } else if ((MulAmt % 5) == 0) {
12935 MulAmt2 = MulAmt / 5;
12936 } else if ((MulAmt % 3) == 0) {
12938 MulAmt2 = MulAmt / 3;
12941 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12942 DebugLoc DL = N->getDebugLoc();
12944 if (isPowerOf2_64(MulAmt2) &&
12945 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12946 // If second multiplifer is pow2, issue it first. We want the multiply by
12947 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12949 std::swap(MulAmt1, MulAmt2);
12952 if (isPowerOf2_64(MulAmt1))
12953 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12954 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12956 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12957 DAG.getConstant(MulAmt1, VT));
12959 if (isPowerOf2_64(MulAmt2))
12960 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12961 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12963 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12964 DAG.getConstant(MulAmt2, VT));
12966 // Do not add new nodes to DAG combiner worklist.
12967 DCI.CombineTo(N, NewMul, false);
12972 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12973 SDValue N0 = N->getOperand(0);
12974 SDValue N1 = N->getOperand(1);
12975 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12976 EVT VT = N0.getValueType();
12978 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12979 // since the result of setcc_c is all zero's or all ones.
12980 if (N1C && N0.getOpcode() == ISD::AND &&
12981 N0.getOperand(1).getOpcode() == ISD::Constant) {
12982 SDValue N00 = N0.getOperand(0);
12983 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12984 ((N00.getOpcode() == ISD::ANY_EXTEND ||
12985 N00.getOpcode() == ISD::ZERO_EXTEND) &&
12986 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12987 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12988 APInt ShAmt = N1C->getAPIntValue();
12989 Mask = Mask.shl(ShAmt);
12991 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12992 N00, DAG.getConstant(Mask, VT));
12999 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13001 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13002 const X86Subtarget *Subtarget) {
13003 EVT VT = N->getValueType(0);
13004 if (!VT.isVector() && VT.isInteger() &&
13005 N->getOpcode() == ISD::SHL)
13006 return PerformSHLCombine(N, DAG);
13008 // On X86 with SSE2 support, we can transform this to a vector shift if
13009 // all elements are shifted by the same amount. We can't do this in legalize
13010 // because the a constant vector is typically transformed to a constant pool
13011 // so we have no knowledge of the shift amount.
13012 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
13015 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13018 SDValue ShAmtOp = N->getOperand(1);
13019 EVT EltVT = VT.getVectorElementType();
13020 DebugLoc DL = N->getDebugLoc();
13021 SDValue BaseShAmt = SDValue();
13022 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13023 unsigned NumElts = VT.getVectorNumElements();
13025 for (; i != NumElts; ++i) {
13026 SDValue Arg = ShAmtOp.getOperand(i);
13027 if (Arg.getOpcode() == ISD::UNDEF) continue;
13031 for (; i != NumElts; ++i) {
13032 SDValue Arg = ShAmtOp.getOperand(i);
13033 if (Arg.getOpcode() == ISD::UNDEF) continue;
13034 if (Arg != BaseShAmt) {
13038 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13039 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13040 SDValue InVec = ShAmtOp.getOperand(0);
13041 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13042 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13044 for (; i != NumElts; ++i) {
13045 SDValue Arg = InVec.getOperand(i);
13046 if (Arg.getOpcode() == ISD::UNDEF) continue;
13050 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13052 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13053 if (C->getZExtValue() == SplatIdx)
13054 BaseShAmt = InVec.getOperand(1);
13057 if (BaseShAmt.getNode() == 0)
13058 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13059 DAG.getIntPtrConstant(0));
13063 // The shift amount is an i32.
13064 if (EltVT.bitsGT(MVT::i32))
13065 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13066 else if (EltVT.bitsLT(MVT::i32))
13067 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13069 // The shift amount is identical so we can do a vector shift.
13070 SDValue ValOp = N->getOperand(0);
13071 switch (N->getOpcode()) {
13073 llvm_unreachable("Unknown shift opcode!");
13076 if (VT == MVT::v2i64)
13077 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13078 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13080 if (VT == MVT::v4i32)
13081 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13082 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13084 if (VT == MVT::v8i16)
13085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13086 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13090 if (VT == MVT::v4i32)
13091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13092 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13094 if (VT == MVT::v8i16)
13095 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13096 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13100 if (VT == MVT::v2i64)
13101 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13102 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13104 if (VT == MVT::v4i32)
13105 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13106 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13108 if (VT == MVT::v8i16)
13109 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13110 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13118 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13119 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13120 // and friends. Likewise for OR -> CMPNEQSS.
13121 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13122 TargetLowering::DAGCombinerInfo &DCI,
13123 const X86Subtarget *Subtarget) {
13126 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13127 // we're requiring SSE2 for both.
13128 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13129 SDValue N0 = N->getOperand(0);
13130 SDValue N1 = N->getOperand(1);
13131 SDValue CMP0 = N0->getOperand(1);
13132 SDValue CMP1 = N1->getOperand(1);
13133 DebugLoc DL = N->getDebugLoc();
13135 // The SETCCs should both refer to the same CMP.
13136 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13139 SDValue CMP00 = CMP0->getOperand(0);
13140 SDValue CMP01 = CMP0->getOperand(1);
13141 EVT VT = CMP00.getValueType();
13143 if (VT == MVT::f32 || VT == MVT::f64) {
13144 bool ExpectingFlags = false;
13145 // Check for any users that want flags:
13146 for (SDNode::use_iterator UI = N->use_begin(),
13148 !ExpectingFlags && UI != UE; ++UI)
13149 switch (UI->getOpcode()) {
13154 ExpectingFlags = true;
13156 case ISD::CopyToReg:
13157 case ISD::SIGN_EXTEND:
13158 case ISD::ZERO_EXTEND:
13159 case ISD::ANY_EXTEND:
13163 if (!ExpectingFlags) {
13164 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13165 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13167 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13168 X86::CondCode tmp = cc0;
13173 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13174 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13175 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13176 X86ISD::NodeType NTOperator = is64BitFP ?
13177 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13178 // FIXME: need symbolic constants for these magic numbers.
13179 // See X86ATTInstPrinter.cpp:printSSECC().
13180 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13181 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13182 DAG.getConstant(x86cc, MVT::i8));
13183 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13185 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13186 DAG.getConstant(1, MVT::i32));
13187 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13188 return OneBitOfTruth;
13196 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13197 /// so it can be folded inside ANDNP.
13198 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13199 EVT VT = N->getValueType(0);
13201 // Match direct AllOnes for 128 and 256-bit vectors
13202 if (ISD::isBuildVectorAllOnes(N))
13205 // Look through a bit convert.
13206 if (N->getOpcode() == ISD::BITCAST)
13207 N = N->getOperand(0).getNode();
13209 // Sometimes the operand may come from a insert_subvector building a 256-bit
13211 if (VT.getSizeInBits() == 256 &&
13212 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13213 SDValue V1 = N->getOperand(0);
13214 SDValue V2 = N->getOperand(1);
13216 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13217 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13218 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13219 ISD::isBuildVectorAllOnes(V2.getNode()))
13226 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13227 TargetLowering::DAGCombinerInfo &DCI,
13228 const X86Subtarget *Subtarget) {
13229 if (DCI.isBeforeLegalizeOps())
13232 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13236 // Want to form ANDNP nodes:
13237 // 1) In the hopes of then easily combining them with OR and AND nodes
13238 // to form PBLEND/PSIGN.
13239 // 2) To match ANDN packed intrinsics
13240 EVT VT = N->getValueType(0);
13241 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13244 SDValue N0 = N->getOperand(0);
13245 SDValue N1 = N->getOperand(1);
13246 DebugLoc DL = N->getDebugLoc();
13248 // Check LHS for vnot
13249 if (N0.getOpcode() == ISD::XOR &&
13250 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13251 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13252 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13254 // Check RHS for vnot
13255 if (N1.getOpcode() == ISD::XOR &&
13256 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13257 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13258 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13263 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13264 TargetLowering::DAGCombinerInfo &DCI,
13265 const X86Subtarget *Subtarget) {
13266 if (DCI.isBeforeLegalizeOps())
13269 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13273 EVT VT = N->getValueType(0);
13274 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13277 SDValue N0 = N->getOperand(0);
13278 SDValue N1 = N->getOperand(1);
13280 // look for psign/blend
13281 if (Subtarget->hasSSSE3()) {
13282 if (VT == MVT::v2i64) {
13283 // Canonicalize pandn to RHS
13284 if (N0.getOpcode() == X86ISD::ANDNP)
13286 // or (and (m, x), (pandn m, y))
13287 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13288 SDValue Mask = N1.getOperand(0);
13289 SDValue X = N1.getOperand(1);
13291 if (N0.getOperand(0) == Mask)
13292 Y = N0.getOperand(1);
13293 if (N0.getOperand(1) == Mask)
13294 Y = N0.getOperand(0);
13296 // Check to see if the mask appeared in both the AND and ANDNP and
13300 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13301 if (Mask.getOpcode() != ISD::BITCAST ||
13302 X.getOpcode() != ISD::BITCAST ||
13303 Y.getOpcode() != ISD::BITCAST)
13306 // Look through mask bitcast.
13307 Mask = Mask.getOperand(0);
13308 EVT MaskVT = Mask.getValueType();
13310 // Validate that the Mask operand is a vector sra node. The sra node
13311 // will be an intrinsic.
13312 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13315 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13316 // there is no psrai.b
13317 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13318 case Intrinsic::x86_sse2_psrai_w:
13319 case Intrinsic::x86_sse2_psrai_d:
13321 default: return SDValue();
13324 // Check that the SRA is all signbits.
13325 SDValue SraC = Mask.getOperand(2);
13326 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13327 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13328 if ((SraAmt + 1) != EltBits)
13331 DebugLoc DL = N->getDebugLoc();
13333 // Now we know we at least have a plendvb with the mask val. See if
13334 // we can form a psignb/w/d.
13335 // psign = x.type == y.type == mask.type && y = sub(0, x);
13336 X = X.getOperand(0);
13337 Y = Y.getOperand(0);
13338 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13339 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13340 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13343 case 8: Opc = X86ISD::PSIGNB; break;
13344 case 16: Opc = X86ISD::PSIGNW; break;
13345 case 32: Opc = X86ISD::PSIGND; break;
13349 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13350 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13353 // PBLENDVB only available on SSE 4.1
13354 if (!Subtarget->hasSSE41())
13357 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13358 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13359 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13360 Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13361 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13366 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13367 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13369 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13371 if (!N0.hasOneUse() || !N1.hasOneUse())
13374 SDValue ShAmt0 = N0.getOperand(1);
13375 if (ShAmt0.getValueType() != MVT::i8)
13377 SDValue ShAmt1 = N1.getOperand(1);
13378 if (ShAmt1.getValueType() != MVT::i8)
13380 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13381 ShAmt0 = ShAmt0.getOperand(0);
13382 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13383 ShAmt1 = ShAmt1.getOperand(0);
13385 DebugLoc DL = N->getDebugLoc();
13386 unsigned Opc = X86ISD::SHLD;
13387 SDValue Op0 = N0.getOperand(0);
13388 SDValue Op1 = N1.getOperand(0);
13389 if (ShAmt0.getOpcode() == ISD::SUB) {
13390 Opc = X86ISD::SHRD;
13391 std::swap(Op0, Op1);
13392 std::swap(ShAmt0, ShAmt1);
13395 unsigned Bits = VT.getSizeInBits();
13396 if (ShAmt1.getOpcode() == ISD::SUB) {
13397 SDValue Sum = ShAmt1.getOperand(0);
13398 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13399 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13400 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13401 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13402 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13403 return DAG.getNode(Opc, DL, VT,
13405 DAG.getNode(ISD::TRUNCATE, DL,
13408 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13409 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13411 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13412 return DAG.getNode(Opc, DL, VT,
13413 N0.getOperand(0), N1.getOperand(0),
13414 DAG.getNode(ISD::TRUNCATE, DL,
13421 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13422 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13423 const X86Subtarget *Subtarget) {
13424 StoreSDNode *St = cast<StoreSDNode>(N);
13425 EVT VT = St->getValue().getValueType();
13426 EVT StVT = St->getMemoryVT();
13427 DebugLoc dl = St->getDebugLoc();
13428 SDValue StoredVal = St->getOperand(1);
13429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13431 // If we are saving a concatination of two XMM registers, perform two stores.
13432 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13433 // 128-bit ones. If in the future the cost becomes only one memory access the
13434 // first version would be better.
13435 if (VT.getSizeInBits() == 256 &&
13436 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13437 StoredVal.getNumOperands() == 2) {
13439 SDValue Value0 = StoredVal.getOperand(0);
13440 SDValue Value1 = StoredVal.getOperand(1);
13442 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13443 SDValue Ptr0 = St->getBasePtr();
13444 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13446 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13447 St->getPointerInfo(), St->isVolatile(),
13448 St->isNonTemporal(), St->getAlignment());
13449 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13450 St->getPointerInfo(), St->isVolatile(),
13451 St->isNonTemporal(), St->getAlignment());
13452 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13455 // Optimize trunc store (of multiple scalars) to shuffle and store.
13456 // First, pack all of the elements in one place. Next, store to memory
13457 // in fewer chunks.
13458 if (St->isTruncatingStore() && VT.isVector()) {
13459 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13460 unsigned NumElems = VT.getVectorNumElements();
13461 assert(StVT != VT && "Cannot truncate to the same type");
13462 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13463 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13465 // From, To sizes and ElemCount must be pow of two
13466 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13467 // We are going to use the original vector elt for storing.
13468 // accumulated smaller vector elements must be a multiple of bigger size.
13469 if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13470 unsigned SizeRatio = FromSz / ToSz;
13472 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13474 // Create a type on which we perform the shuffle
13475 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13476 StVT.getScalarType(), NumElems*SizeRatio);
13478 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13480 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13481 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13482 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13484 // Can't shuffle using an illegal type
13485 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13487 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13488 DAG.getUNDEF(WideVec.getValueType()),
13489 ShuffleVec.data());
13490 // At this point all of the data is stored at the bottom of the
13491 // register. We now need to save it to mem.
13493 // Find the largest store unit
13494 MVT StoreType = MVT::i8;
13495 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13496 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13497 MVT Tp = (MVT::SimpleValueType)tp;
13498 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13502 // Bitcast the original vector into a vector of store-size units
13503 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13504 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13505 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13506 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13507 SmallVector<SDValue, 8> Chains;
13508 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13509 TLI.getPointerTy());
13510 SDValue Ptr = St->getBasePtr();
13512 // Perform one or more big stores into memory.
13513 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13514 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13515 StoreType, ShuffWide,
13516 DAG.getIntPtrConstant(i));
13517 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13518 St->getPointerInfo(), St->isVolatile(),
13519 St->isNonTemporal(), St->getAlignment());
13520 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13521 Chains.push_back(Ch);
13524 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13529 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
13530 // the FP state in cases where an emms may be missing.
13531 // A preferable solution to the general problem is to figure out the right
13532 // places to insert EMMS. This qualifies as a quick hack.
13534 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13535 if (VT.getSizeInBits() != 64)
13538 const Function *F = DAG.getMachineFunction().getFunction();
13539 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13540 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13541 && Subtarget->hasSSE2();
13542 if ((VT.isVector() ||
13543 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13544 isa<LoadSDNode>(St->getValue()) &&
13545 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13546 St->getChain().hasOneUse() && !St->isVolatile()) {
13547 SDNode* LdVal = St->getValue().getNode();
13548 LoadSDNode *Ld = 0;
13549 int TokenFactorIndex = -1;
13550 SmallVector<SDValue, 8> Ops;
13551 SDNode* ChainVal = St->getChain().getNode();
13552 // Must be a store of a load. We currently handle two cases: the load
13553 // is a direct child, and it's under an intervening TokenFactor. It is
13554 // possible to dig deeper under nested TokenFactors.
13555 if (ChainVal == LdVal)
13556 Ld = cast<LoadSDNode>(St->getChain());
13557 else if (St->getValue().hasOneUse() &&
13558 ChainVal->getOpcode() == ISD::TokenFactor) {
13559 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13560 if (ChainVal->getOperand(i).getNode() == LdVal) {
13561 TokenFactorIndex = i;
13562 Ld = cast<LoadSDNode>(St->getValue());
13564 Ops.push_back(ChainVal->getOperand(i));
13568 if (!Ld || !ISD::isNormalLoad(Ld))
13571 // If this is not the MMX case, i.e. we are just turning i64 load/store
13572 // into f64 load/store, avoid the transformation if there are multiple
13573 // uses of the loaded value.
13574 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13577 DebugLoc LdDL = Ld->getDebugLoc();
13578 DebugLoc StDL = N->getDebugLoc();
13579 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13580 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13582 if (Subtarget->is64Bit() || F64IsLegal) {
13583 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13584 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13585 Ld->getPointerInfo(), Ld->isVolatile(),
13586 Ld->isNonTemporal(), Ld->getAlignment());
13587 SDValue NewChain = NewLd.getValue(1);
13588 if (TokenFactorIndex != -1) {
13589 Ops.push_back(NewChain);
13590 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13593 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13594 St->getPointerInfo(),
13595 St->isVolatile(), St->isNonTemporal(),
13596 St->getAlignment());
13599 // Otherwise, lower to two pairs of 32-bit loads / stores.
13600 SDValue LoAddr = Ld->getBasePtr();
13601 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13602 DAG.getConstant(4, MVT::i32));
13604 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13605 Ld->getPointerInfo(),
13606 Ld->isVolatile(), Ld->isNonTemporal(),
13607 Ld->getAlignment());
13608 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13609 Ld->getPointerInfo().getWithOffset(4),
13610 Ld->isVolatile(), Ld->isNonTemporal(),
13611 MinAlign(Ld->getAlignment(), 4));
13613 SDValue NewChain = LoLd.getValue(1);
13614 if (TokenFactorIndex != -1) {
13615 Ops.push_back(LoLd);
13616 Ops.push_back(HiLd);
13617 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13621 LoAddr = St->getBasePtr();
13622 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13623 DAG.getConstant(4, MVT::i32));
13625 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13626 St->getPointerInfo(),
13627 St->isVolatile(), St->isNonTemporal(),
13628 St->getAlignment());
13629 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13630 St->getPointerInfo().getWithOffset(4),
13632 St->isNonTemporal(),
13633 MinAlign(St->getAlignment(), 4));
13634 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13639 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13640 /// X86ISD::FXOR nodes.
13641 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13642 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13643 // F[X]OR(0.0, x) -> x
13644 // F[X]OR(x, 0.0) -> x
13645 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13646 if (C->getValueAPF().isPosZero())
13647 return N->getOperand(1);
13648 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13649 if (C->getValueAPF().isPosZero())
13650 return N->getOperand(0);
13654 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13655 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13656 // FAND(0.0, x) -> 0.0
13657 // FAND(x, 0.0) -> 0.0
13658 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13659 if (C->getValueAPF().isPosZero())
13660 return N->getOperand(0);
13661 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13662 if (C->getValueAPF().isPosZero())
13663 return N->getOperand(1);
13667 static SDValue PerformBTCombine(SDNode *N,
13669 TargetLowering::DAGCombinerInfo &DCI) {
13670 // BT ignores high bits in the bit index operand.
13671 SDValue Op1 = N->getOperand(1);
13672 if (Op1.hasOneUse()) {
13673 unsigned BitWidth = Op1.getValueSizeInBits();
13674 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13675 APInt KnownZero, KnownOne;
13676 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13677 !DCI.isBeforeLegalizeOps());
13678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13679 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13680 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13681 DCI.CommitTargetLoweringOpt(TLO);
13686 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13687 SDValue Op = N->getOperand(0);
13688 if (Op.getOpcode() == ISD::BITCAST)
13689 Op = Op.getOperand(0);
13690 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13691 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13692 VT.getVectorElementType().getSizeInBits() ==
13693 OpVT.getVectorElementType().getSizeInBits()) {
13694 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13699 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13700 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
13701 // (and (i32 x86isd::setcc_carry), 1)
13702 // This eliminates the zext. This transformation is necessary because
13703 // ISD::SETCC is always legalized to i8.
13704 DebugLoc dl = N->getDebugLoc();
13705 SDValue N0 = N->getOperand(0);
13706 EVT VT = N->getValueType(0);
13707 if (N0.getOpcode() == ISD::AND &&
13709 N0.getOperand(0).hasOneUse()) {
13710 SDValue N00 = N0.getOperand(0);
13711 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13713 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13714 if (!C || C->getZExtValue() != 1)
13716 return DAG.getNode(ISD::AND, dl, VT,
13717 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13718 N00.getOperand(0), N00.getOperand(1)),
13719 DAG.getConstant(1, VT));
13725 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13726 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13727 unsigned X86CC = N->getConstantOperandVal(0);
13728 SDValue EFLAG = N->getOperand(1);
13729 DebugLoc DL = N->getDebugLoc();
13731 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13732 // a zext and produces an all-ones bit which is more useful than 0/1 in some
13734 if (X86CC == X86::COND_B)
13735 return DAG.getNode(ISD::AND, DL, MVT::i8,
13736 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13737 DAG.getConstant(X86CC, MVT::i8), EFLAG),
13738 DAG.getConstant(1, MVT::i8));
13743 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13744 const X86TargetLowering *XTLI) {
13745 SDValue Op0 = N->getOperand(0);
13746 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13747 // a 32-bit target where SSE doesn't support i64->FP operations.
13748 if (Op0.getOpcode() == ISD::LOAD) {
13749 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13750 EVT VT = Ld->getValueType(0);
13751 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13752 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13753 !XTLI->getSubtarget()->is64Bit() &&
13754 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13755 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13756 Ld->getChain(), Op0, DAG);
13757 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13764 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13765 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13766 X86TargetLowering::DAGCombinerInfo &DCI) {
13767 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13768 // the result is either zero or one (depending on the input carry bit).
13769 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13770 if (X86::isZeroNode(N->getOperand(0)) &&
13771 X86::isZeroNode(N->getOperand(1)) &&
13772 // We don't have a good way to replace an EFLAGS use, so only do this when
13774 SDValue(N, 1).use_empty()) {
13775 DebugLoc DL = N->getDebugLoc();
13776 EVT VT = N->getValueType(0);
13777 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13778 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13779 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13780 DAG.getConstant(X86::COND_B,MVT::i8),
13782 DAG.getConstant(1, VT));
13783 return DCI.CombineTo(N, Res1, CarryOut);
13789 // fold (add Y, (sete X, 0)) -> adc 0, Y
13790 // (add Y, (setne X, 0)) -> sbb -1, Y
13791 // (sub (sete X, 0), Y) -> sbb 0, Y
13792 // (sub (setne X, 0), Y) -> adc -1, Y
13793 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13794 DebugLoc DL = N->getDebugLoc();
13796 // Look through ZExts.
13797 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13798 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13801 SDValue SetCC = Ext.getOperand(0);
13802 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13805 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13806 if (CC != X86::COND_E && CC != X86::COND_NE)
13809 SDValue Cmp = SetCC.getOperand(1);
13810 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13811 !X86::isZeroNode(Cmp.getOperand(1)) ||
13812 !Cmp.getOperand(0).getValueType().isInteger())
13815 SDValue CmpOp0 = Cmp.getOperand(0);
13816 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13817 DAG.getConstant(1, CmpOp0.getValueType()));
13819 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13820 if (CC == X86::COND_NE)
13821 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13822 DL, OtherVal.getValueType(), OtherVal,
13823 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13824 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13825 DL, OtherVal.getValueType(), OtherVal,
13826 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13829 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13830 SDValue Op0 = N->getOperand(0);
13831 SDValue Op1 = N->getOperand(1);
13833 // X86 can't encode an immediate LHS of a sub. See if we can push the
13834 // negation into a preceding instruction.
13835 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13836 // If the RHS of the sub is a XOR with one use and a constant, invert the
13837 // immediate. Then add one to the LHS of the sub so we can turn
13838 // X-Y -> X+~Y+1, saving one register.
13839 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13840 isa<ConstantSDNode>(Op1.getOperand(1))) {
13841 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13842 EVT VT = Op0.getValueType();
13843 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13845 DAG.getConstant(~XorC, VT));
13846 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13847 DAG.getConstant(C->getAPIntValue()+1, VT));
13851 return OptimizeConditionalInDecrement(N, DAG);
13854 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13855 DAGCombinerInfo &DCI) const {
13856 SelectionDAG &DAG = DCI.DAG;
13857 switch (N->getOpcode()) {
13859 case ISD::EXTRACT_VECTOR_ELT:
13860 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13861 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
13862 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
13863 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
13864 case ISD::SUB: return PerformSubCombine(N, DAG);
13865 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
13866 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
13869 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
13870 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
13871 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
13872 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
13873 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
13875 case X86ISD::FOR: return PerformFORCombine(N, DAG);
13876 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
13877 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
13878 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
13879 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
13880 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
13881 case X86ISD::SHUFPS: // Handle all target specific shuffles
13882 case X86ISD::SHUFPD:
13883 case X86ISD::PALIGN:
13884 case X86ISD::PUNPCKHBW:
13885 case X86ISD::PUNPCKHWD:
13886 case X86ISD::PUNPCKHDQ:
13887 case X86ISD::PUNPCKHQDQ:
13888 case X86ISD::UNPCKHPS:
13889 case X86ISD::UNPCKHPD:
13890 case X86ISD::VUNPCKHPSY:
13891 case X86ISD::VUNPCKHPDY:
13892 case X86ISD::PUNPCKLBW:
13893 case X86ISD::PUNPCKLWD:
13894 case X86ISD::PUNPCKLDQ:
13895 case X86ISD::PUNPCKLQDQ:
13896 case X86ISD::UNPCKLPS:
13897 case X86ISD::UNPCKLPD:
13898 case X86ISD::VUNPCKLPSY:
13899 case X86ISD::VUNPCKLPDY:
13900 case X86ISD::MOVHLPS:
13901 case X86ISD::MOVLHPS:
13902 case X86ISD::PSHUFD:
13903 case X86ISD::PSHUFHW:
13904 case X86ISD::PSHUFLW:
13905 case X86ISD::MOVSS:
13906 case X86ISD::MOVSD:
13907 case X86ISD::VPERMILPS:
13908 case X86ISD::VPERMILPSY:
13909 case X86ISD::VPERMILPD:
13910 case X86ISD::VPERMILPDY:
13911 case X86ISD::VPERM2F128:
13912 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13918 /// isTypeDesirableForOp - Return true if the target has native support for
13919 /// the specified value type and it is 'desirable' to use the type for the
13920 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13921 /// instruction encodings are longer and some i16 instructions are slow.
13922 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13923 if (!isTypeLegal(VT))
13925 if (VT != MVT::i16)
13932 case ISD::SIGN_EXTEND:
13933 case ISD::ZERO_EXTEND:
13934 case ISD::ANY_EXTEND:
13947 /// IsDesirableToPromoteOp - This method query the target whether it is
13948 /// beneficial for dag combiner to promote the specified node. If true, it
13949 /// should return the desired promotion type by reference.
13950 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13951 EVT VT = Op.getValueType();
13952 if (VT != MVT::i16)
13955 bool Promote = false;
13956 bool Commute = false;
13957 switch (Op.getOpcode()) {
13960 LoadSDNode *LD = cast<LoadSDNode>(Op);
13961 // If the non-extending load has a single use and it's not live out, then it
13962 // might be folded.
13963 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13964 Op.hasOneUse()*/) {
13965 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13966 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13967 // The only case where we'd want to promote LOAD (rather then it being
13968 // promoted as an operand is when it's only use is liveout.
13969 if (UI->getOpcode() != ISD::CopyToReg)
13976 case ISD::SIGN_EXTEND:
13977 case ISD::ZERO_EXTEND:
13978 case ISD::ANY_EXTEND:
13983 SDValue N0 = Op.getOperand(0);
13984 // Look out for (store (shl (load), x)).
13985 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13998 SDValue N0 = Op.getOperand(0);
13999 SDValue N1 = Op.getOperand(1);
14000 if (!Commute && MayFoldLoad(N1))
14002 // Avoid disabling potential load folding opportunities.
14003 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14005 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14015 //===----------------------------------------------------------------------===//
14016 // X86 Inline Assembly Support
14017 //===----------------------------------------------------------------------===//
14019 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14020 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14022 std::string AsmStr = IA->getAsmString();
14024 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14025 SmallVector<StringRef, 4> AsmPieces;
14026 SplitString(AsmStr, AsmPieces, ";\n");
14028 switch (AsmPieces.size()) {
14029 default: return false;
14031 AsmStr = AsmPieces[0];
14033 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14035 // FIXME: this should verify that we are targeting a 486 or better. If not,
14036 // we will turn this bswap into something that will be lowered to logical ops
14037 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14038 // so don't worry about this.
14040 if (AsmPieces.size() == 2 &&
14041 (AsmPieces[0] == "bswap" ||
14042 AsmPieces[0] == "bswapq" ||
14043 AsmPieces[0] == "bswapl") &&
14044 (AsmPieces[1] == "$0" ||
14045 AsmPieces[1] == "${0:q}")) {
14046 // No need to check constraints, nothing other than the equivalent of
14047 // "=r,0" would be valid here.
14048 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14049 if (!Ty || Ty->getBitWidth() % 16 != 0)
14051 return IntrinsicLowering::LowerToByteSwap(CI);
14053 // rorw $$8, ${0:w} --> llvm.bswap.i16
14054 if (CI->getType()->isIntegerTy(16) &&
14055 AsmPieces.size() == 3 &&
14056 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14057 AsmPieces[1] == "$$8," &&
14058 AsmPieces[2] == "${0:w}" &&
14059 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14061 const std::string &ConstraintsStr = IA->getConstraintString();
14062 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14063 std::sort(AsmPieces.begin(), AsmPieces.end());
14064 if (AsmPieces.size() == 4 &&
14065 AsmPieces[0] == "~{cc}" &&
14066 AsmPieces[1] == "~{dirflag}" &&
14067 AsmPieces[2] == "~{flags}" &&
14068 AsmPieces[3] == "~{fpsr}") {
14069 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14070 if (!Ty || Ty->getBitWidth() % 16 != 0)
14072 return IntrinsicLowering::LowerToByteSwap(CI);
14077 if (CI->getType()->isIntegerTy(32) &&
14078 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14079 SmallVector<StringRef, 4> Words;
14080 SplitString(AsmPieces[0], Words, " \t,");
14081 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14082 Words[2] == "${0:w}") {
14084 SplitString(AsmPieces[1], Words, " \t,");
14085 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14086 Words[2] == "$0") {
14088 SplitString(AsmPieces[2], Words, " \t,");
14089 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14090 Words[2] == "${0:w}") {
14092 const std::string &ConstraintsStr = IA->getConstraintString();
14093 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14094 std::sort(AsmPieces.begin(), AsmPieces.end());
14095 if (AsmPieces.size() == 4 &&
14096 AsmPieces[0] == "~{cc}" &&
14097 AsmPieces[1] == "~{dirflag}" &&
14098 AsmPieces[2] == "~{flags}" &&
14099 AsmPieces[3] == "~{fpsr}") {
14100 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14101 if (!Ty || Ty->getBitWidth() % 16 != 0)
14103 return IntrinsicLowering::LowerToByteSwap(CI);
14110 if (CI->getType()->isIntegerTy(64)) {
14111 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14112 if (Constraints.size() >= 2 &&
14113 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14114 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14115 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14116 SmallVector<StringRef, 4> Words;
14117 SplitString(AsmPieces[0], Words, " \t");
14118 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14120 SplitString(AsmPieces[1], Words, " \t");
14121 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14123 SplitString(AsmPieces[2], Words, " \t,");
14124 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14125 Words[2] == "%edx") {
14126 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14127 if (!Ty || Ty->getBitWidth() % 16 != 0)
14129 return IntrinsicLowering::LowerToByteSwap(CI);
14142 /// getConstraintType - Given a constraint letter, return the type of
14143 /// constraint it is for this target.
14144 X86TargetLowering::ConstraintType
14145 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14146 if (Constraint.size() == 1) {
14147 switch (Constraint[0]) {
14158 return C_RegisterClass;
14182 return TargetLowering::getConstraintType(Constraint);
14185 /// Examine constraint type and operand type and determine a weight value.
14186 /// This object must already have been set up with the operand type
14187 /// and the current alternative constraint selected.
14188 TargetLowering::ConstraintWeight
14189 X86TargetLowering::getSingleConstraintMatchWeight(
14190 AsmOperandInfo &info, const char *constraint) const {
14191 ConstraintWeight weight = CW_Invalid;
14192 Value *CallOperandVal = info.CallOperandVal;
14193 // If we don't have a value, we can't do a match,
14194 // but allow it at the lowest weight.
14195 if (CallOperandVal == NULL)
14197 Type *type = CallOperandVal->getType();
14198 // Look at the constraint type.
14199 switch (*constraint) {
14201 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14212 if (CallOperandVal->getType()->isIntegerTy())
14213 weight = CW_SpecificReg;
14218 if (type->isFloatingPointTy())
14219 weight = CW_SpecificReg;
14222 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14223 weight = CW_SpecificReg;
14227 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14228 weight = CW_Register;
14231 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14232 if (C->getZExtValue() <= 31)
14233 weight = CW_Constant;
14237 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14238 if (C->getZExtValue() <= 63)
14239 weight = CW_Constant;
14243 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14244 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14245 weight = CW_Constant;
14249 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14250 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14251 weight = CW_Constant;
14255 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14256 if (C->getZExtValue() <= 3)
14257 weight = CW_Constant;
14261 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14262 if (C->getZExtValue() <= 0xff)
14263 weight = CW_Constant;
14268 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14269 weight = CW_Constant;
14273 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14274 if ((C->getSExtValue() >= -0x80000000LL) &&
14275 (C->getSExtValue() <= 0x7fffffffLL))
14276 weight = CW_Constant;
14280 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14281 if (C->getZExtValue() <= 0xffffffff)
14282 weight = CW_Constant;
14289 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14290 /// with another that has more specific requirements based on the type of the
14291 /// corresponding operand.
14292 const char *X86TargetLowering::
14293 LowerXConstraint(EVT ConstraintVT) const {
14294 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14295 // 'f' like normal targets.
14296 if (ConstraintVT.isFloatingPoint()) {
14297 if (Subtarget->hasXMMInt())
14299 if (Subtarget->hasXMM())
14303 return TargetLowering::LowerXConstraint(ConstraintVT);
14306 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14307 /// vector. If it is invalid, don't add anything to Ops.
14308 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14309 std::string &Constraint,
14310 std::vector<SDValue>&Ops,
14311 SelectionDAG &DAG) const {
14312 SDValue Result(0, 0);
14314 // Only support length 1 constraints for now.
14315 if (Constraint.length() > 1) return;
14317 char ConstraintLetter = Constraint[0];
14318 switch (ConstraintLetter) {
14321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14322 if (C->getZExtValue() <= 31) {
14323 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14330 if (C->getZExtValue() <= 63) {
14331 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14338 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14339 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14345 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14346 if (C->getZExtValue() <= 255) {
14347 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14353 // 32-bit signed value
14354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14355 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14356 C->getSExtValue())) {
14357 // Widen to 64 bits here to get it sign extended.
14358 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14361 // FIXME gcc accepts some relocatable values here too, but only in certain
14362 // memory models; it's complicated.
14367 // 32-bit unsigned value
14368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14369 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14370 C->getZExtValue())) {
14371 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14375 // FIXME gcc accepts some relocatable values here too, but only in certain
14376 // memory models; it's complicated.
14380 // Literal immediates are always ok.
14381 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14382 // Widen to 64 bits here to get it sign extended.
14383 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14387 // In any sort of PIC mode addresses need to be computed at runtime by
14388 // adding in a register or some sort of table lookup. These can't
14389 // be used as immediates.
14390 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14393 // If we are in non-pic codegen mode, we allow the address of a global (with
14394 // an optional displacement) to be used with 'i'.
14395 GlobalAddressSDNode *GA = 0;
14396 int64_t Offset = 0;
14398 // Match either (GA), (GA+C), (GA+C1+C2), etc.
14400 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14401 Offset += GA->getOffset();
14403 } else if (Op.getOpcode() == ISD::ADD) {
14404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14405 Offset += C->getZExtValue();
14406 Op = Op.getOperand(0);
14409 } else if (Op.getOpcode() == ISD::SUB) {
14410 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14411 Offset += -C->getZExtValue();
14412 Op = Op.getOperand(0);
14417 // Otherwise, this isn't something we can handle, reject it.
14421 const GlobalValue *GV = GA->getGlobal();
14422 // If we require an extra load to get this address, as in PIC mode, we
14423 // can't accept it.
14424 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14425 getTargetMachine())))
14428 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14429 GA->getValueType(0), Offset);
14434 if (Result.getNode()) {
14435 Ops.push_back(Result);
14438 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14441 std::pair<unsigned, const TargetRegisterClass*>
14442 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14444 // First, see if this is a constraint that directly corresponds to an LLVM
14446 if (Constraint.size() == 1) {
14447 // GCC Constraint Letters
14448 switch (Constraint[0]) {
14450 // TODO: Slight differences here in allocation order and leaving
14451 // RIP in the class. Do they matter any more here than they do
14452 // in the normal allocation?
14453 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14454 if (Subtarget->is64Bit()) {
14455 if (VT == MVT::i32 || VT == MVT::f32)
14456 return std::make_pair(0U, X86::GR32RegisterClass);
14457 else if (VT == MVT::i16)
14458 return std::make_pair(0U, X86::GR16RegisterClass);
14459 else if (VT == MVT::i8 || VT == MVT::i1)
14460 return std::make_pair(0U, X86::GR8RegisterClass);
14461 else if (VT == MVT::i64 || VT == MVT::f64)
14462 return std::make_pair(0U, X86::GR64RegisterClass);
14465 // 32-bit fallthrough
14466 case 'Q': // Q_REGS
14467 if (VT == MVT::i32 || VT == MVT::f32)
14468 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14469 else if (VT == MVT::i16)
14470 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14471 else if (VT == MVT::i8 || VT == MVT::i1)
14472 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14473 else if (VT == MVT::i64)
14474 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14476 case 'r': // GENERAL_REGS
14477 case 'l': // INDEX_REGS
14478 if (VT == MVT::i8 || VT == MVT::i1)
14479 return std::make_pair(0U, X86::GR8RegisterClass);
14480 if (VT == MVT::i16)
14481 return std::make_pair(0U, X86::GR16RegisterClass);
14482 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14483 return std::make_pair(0U, X86::GR32RegisterClass);
14484 return std::make_pair(0U, X86::GR64RegisterClass);
14485 case 'R': // LEGACY_REGS
14486 if (VT == MVT::i8 || VT == MVT::i1)
14487 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14488 if (VT == MVT::i16)
14489 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14490 if (VT == MVT::i32 || !Subtarget->is64Bit())
14491 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14492 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14493 case 'f': // FP Stack registers.
14494 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14495 // value to the correct fpstack register class.
14496 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14497 return std::make_pair(0U, X86::RFP32RegisterClass);
14498 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14499 return std::make_pair(0U, X86::RFP64RegisterClass);
14500 return std::make_pair(0U, X86::RFP80RegisterClass);
14501 case 'y': // MMX_REGS if MMX allowed.
14502 if (!Subtarget->hasMMX()) break;
14503 return std::make_pair(0U, X86::VR64RegisterClass);
14504 case 'Y': // SSE_REGS if SSE2 allowed
14505 if (!Subtarget->hasXMMInt()) break;
14507 case 'x': // SSE_REGS if SSE1 allowed
14508 if (!Subtarget->hasXMM()) break;
14510 switch (VT.getSimpleVT().SimpleTy) {
14512 // Scalar SSE types.
14515 return std::make_pair(0U, X86::FR32RegisterClass);
14518 return std::make_pair(0U, X86::FR64RegisterClass);
14526 return std::make_pair(0U, X86::VR128RegisterClass);
14532 // Use the default implementation in TargetLowering to convert the register
14533 // constraint into a member of a register class.
14534 std::pair<unsigned, const TargetRegisterClass*> Res;
14535 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14537 // Not found as a standard register?
14538 if (Res.second == 0) {
14539 // Map st(0) -> st(7) -> ST0
14540 if (Constraint.size() == 7 && Constraint[0] == '{' &&
14541 tolower(Constraint[1]) == 's' &&
14542 tolower(Constraint[2]) == 't' &&
14543 Constraint[3] == '(' &&
14544 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14545 Constraint[5] == ')' &&
14546 Constraint[6] == '}') {
14548 Res.first = X86::ST0+Constraint[4]-'0';
14549 Res.second = X86::RFP80RegisterClass;
14553 // GCC allows "st(0)" to be called just plain "st".
14554 if (StringRef("{st}").equals_lower(Constraint)) {
14555 Res.first = X86::ST0;
14556 Res.second = X86::RFP80RegisterClass;
14561 if (StringRef("{flags}").equals_lower(Constraint)) {
14562 Res.first = X86::EFLAGS;
14563 Res.second = X86::CCRRegisterClass;
14567 // 'A' means EAX + EDX.
14568 if (Constraint == "A") {
14569 Res.first = X86::EAX;
14570 Res.second = X86::GR32_ADRegisterClass;
14576 // Otherwise, check to see if this is a register class of the wrong value
14577 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14578 // turn into {ax},{dx}.
14579 if (Res.second->hasType(VT))
14580 return Res; // Correct type already, nothing to do.
14582 // All of the single-register GCC register classes map their values onto
14583 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
14584 // really want an 8-bit or 32-bit register, map to the appropriate register
14585 // class and return the appropriate register.
14586 if (Res.second == X86::GR16RegisterClass) {
14587 if (VT == MVT::i8) {
14588 unsigned DestReg = 0;
14589 switch (Res.first) {
14591 case X86::AX: DestReg = X86::AL; break;
14592 case X86::DX: DestReg = X86::DL; break;
14593 case X86::CX: DestReg = X86::CL; break;
14594 case X86::BX: DestReg = X86::BL; break;
14597 Res.first = DestReg;
14598 Res.second = X86::GR8RegisterClass;
14600 } else if (VT == MVT::i32) {
14601 unsigned DestReg = 0;
14602 switch (Res.first) {
14604 case X86::AX: DestReg = X86::EAX; break;
14605 case X86::DX: DestReg = X86::EDX; break;
14606 case X86::CX: DestReg = X86::ECX; break;
14607 case X86::BX: DestReg = X86::EBX; break;
14608 case X86::SI: DestReg = X86::ESI; break;
14609 case X86::DI: DestReg = X86::EDI; break;
14610 case X86::BP: DestReg = X86::EBP; break;
14611 case X86::SP: DestReg = X86::ESP; break;
14614 Res.first = DestReg;
14615 Res.second = X86::GR32RegisterClass;
14617 } else if (VT == MVT::i64) {
14618 unsigned DestReg = 0;
14619 switch (Res.first) {
14621 case X86::AX: DestReg = X86::RAX; break;
14622 case X86::DX: DestReg = X86::RDX; break;
14623 case X86::CX: DestReg = X86::RCX; break;
14624 case X86::BX: DestReg = X86::RBX; break;
14625 case X86::SI: DestReg = X86::RSI; break;
14626 case X86::DI: DestReg = X86::RDI; break;
14627 case X86::BP: DestReg = X86::RBP; break;
14628 case X86::SP: DestReg = X86::RSP; break;
14631 Res.first = DestReg;
14632 Res.second = X86::GR64RegisterClass;
14635 } else if (Res.second == X86::FR32RegisterClass ||
14636 Res.second == X86::FR64RegisterClass ||
14637 Res.second == X86::VR128RegisterClass) {
14638 // Handle references to XMM physical registers that got mapped into the
14639 // wrong class. This can happen with constraints like {xmm0} where the
14640 // target independent register mapper will just pick the first match it can
14641 // find, ignoring the required type.
14642 if (VT == MVT::f32)
14643 Res.second = X86::FR32RegisterClass;
14644 else if (VT == MVT::f64)
14645 Res.second = X86::FR64RegisterClass;
14646 else if (X86::VR128RegisterClass->hasType(VT))
14647 Res.second = X86::VR128RegisterClass;