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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.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/CommandLine.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"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
64 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
65 bool is64Bit = Subtarget->is64Bit();
67 if (Subtarget->isTargetEnvMacho()) {
69 return new X8664_MachoTargetObjectFile();
70 return new TargetLoweringObjectFileMachO();
73 if (Subtarget->isTargetELF()) {
75 return new X8664_ELFTargetObjectFile(TM);
76 return new X8632_ELFTargetObjectFile(TM);
78 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
79 return new TargetLoweringObjectFileCOFF();
80 llvm_unreachable("unknown subtarget type");
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84 : TargetLowering(TM, createTLOF(TM)) {
85 Subtarget = &TM.getSubtarget<X86Subtarget>();
86 X86ScalarSSEf64 = Subtarget->hasXMMInt();
87 X86ScalarSSEf32 = Subtarget->hasXMM();
88 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
90 RegInfo = TM.getRegisterInfo();
93 // Set up the TargetLowering object.
94 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
96 // X86 is weird, it always uses i8 for shift amounts and setcc results.
97 setShiftAmountType(MVT::i8);
98 setBooleanContents(ZeroOrOneBooleanContent);
99 setSchedulingPreference(Sched::RegPressure);
100 setStackPointerRegisterToSaveRestore(X86StackPtr);
102 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
103 // Setup Windows compiler runtime calls.
104 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
105 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
106 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
107 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
108 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
109 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
110 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
111 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
114 if (Subtarget->isTargetDarwin()) {
115 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
116 setUseUnderscoreSetJmp(false);
117 setUseUnderscoreLongJmp(false);
118 } else if (Subtarget->isTargetMingw()) {
119 // MS runtime is weird: it exports _setjmp, but longjmp!
120 setUseUnderscoreSetJmp(true);
121 setUseUnderscoreLongJmp(false);
123 setUseUnderscoreSetJmp(true);
124 setUseUnderscoreLongJmp(true);
127 // Set up the register classes.
128 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
129 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
130 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
131 if (Subtarget->is64Bit())
132 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
136 // We don't accept any truncstore of integer registers.
137 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
138 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
139 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
140 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
141 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
142 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
144 // SETOEQ and SETUNE require checking two conditions.
145 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
146 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
147 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
148 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
149 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
150 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
152 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
154 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
155 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
156 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
158 if (Subtarget->is64Bit()) {
159 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
160 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
161 } else if (!UseSoftFloat) {
162 // We have an algorithm for SSE2->double, and we turn this into a
163 // 64-bit FILD followed by conditional FADD for other targets.
164 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
165 // We have an algorithm for SSE2, and we turn this into a 64-bit
166 // FILD for other targets.
167 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
170 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
172 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
176 // SSE has no i16 to fp conversion, only i32
177 if (X86ScalarSSEf32) {
178 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
179 // f32 and f64 cases are Legal, f80 case is not
180 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
182 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
183 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
187 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
190 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
191 // are Legal, f80 is custom lowered.
192 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
193 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
195 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
197 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
198 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
200 if (X86ScalarSSEf32) {
201 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
202 // f32 and f64 cases are Legal, f80 case is not
203 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
205 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
209 // Handle FP_TO_UINT by promoting the destination to a larger signed
211 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
212 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
213 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
215 if (Subtarget->is64Bit()) {
216 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
217 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
218 } else if (!UseSoftFloat) {
219 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
220 // Expand FP_TO_UINT into a select.
221 // FIXME: We would like to use a Custom expander here eventually to do
222 // the optimal thing for SSE vs. the default expansion in the legalizer.
223 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
225 // With SSE3 we can use fisttpll to convert to a signed i64; without
226 // SSE, we're stuck with a fistpll.
227 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
230 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
231 if (!X86ScalarSSEf64) {
232 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
233 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
234 if (Subtarget->is64Bit()) {
235 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
236 // Without SSE, i64->f64 goes through memory.
237 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
241 // Scalar integer divide and remainder are lowered to use operations that
242 // produce two results, to match the available instructions. This exposes
243 // the two-result form to trivial CSE, which is able to combine x/y and x%y
244 // into a single instruction.
246 // Scalar integer multiply-high is also lowered to use two-result
247 // operations, to match the available instructions. However, plain multiply
248 // (low) operations are left as Legal, as there are single-result
249 // instructions for this in x86. Using the two-result multiply instructions
250 // when both high and low results are needed must be arranged by dagcombine.
251 for (unsigned i = 0, e = 4; i != e; ++i) {
253 setOperationAction(ISD::MULHS, VT, Expand);
254 setOperationAction(ISD::MULHU, VT, Expand);
255 setOperationAction(ISD::SDIV, VT, Expand);
256 setOperationAction(ISD::UDIV, VT, Expand);
257 setOperationAction(ISD::SREM, VT, Expand);
258 setOperationAction(ISD::UREM, VT, Expand);
260 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
261 setOperationAction(ISD::ADDC, VT, Custom);
262 setOperationAction(ISD::ADDE, VT, Custom);
263 setOperationAction(ISD::SUBC, VT, Custom);
264 setOperationAction(ISD::SUBE, VT, Custom);
267 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
268 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
269 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
270 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
271 if (Subtarget->is64Bit())
272 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
273 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
274 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
275 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
276 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
277 setOperationAction(ISD::FREM , MVT::f32 , Expand);
278 setOperationAction(ISD::FREM , MVT::f64 , Expand);
279 setOperationAction(ISD::FREM , MVT::f80 , Expand);
280 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
282 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
283 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
284 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
285 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
286 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
287 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
288 if (Subtarget->is64Bit()) {
289 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
293 if (Subtarget->hasPOPCNT()) {
294 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
296 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
297 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
298 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
299 if (Subtarget->is64Bit())
300 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
303 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
304 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
306 // These should be promoted to a larger select which is supported.
307 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
308 // X86 wants to expand cmov itself.
309 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
310 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
311 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
312 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
313 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
314 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
315 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
316 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
317 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
318 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
319 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
320 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
325 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
328 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
329 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
330 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
331 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
335 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
338 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
339 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
340 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
341 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
343 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
349 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
350 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
353 if (Subtarget->hasXMM())
354 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
356 // We may not have a libcall for MEMBARRIER so we should lower this.
357 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
359 // On X86 and X86-64, atomic operations are lowered to locked instructions.
360 // Locked instructions, in turn, have implicit fence semantics (all memory
361 // operations are flushed before issuing the locked instruction, and they
362 // are not buffered), so we can fold away the common pattern of
363 // fence-atomic-fence.
364 setShouldFoldAtomicFences(true);
366 // Expand certain atomics
367 for (unsigned i = 0, e = 4; i != e; ++i) {
369 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
373 if (!Subtarget->is64Bit()) {
374 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
377 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
378 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
380 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
383 // FIXME - use subtarget debug flags
384 if (!Subtarget->isTargetDarwin() &&
385 !Subtarget->isTargetELF() &&
386 !Subtarget->isTargetCygMing()) {
387 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
390 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
391 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
392 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
393 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
394 if (Subtarget->is64Bit()) {
395 setExceptionPointerRegister(X86::RAX);
396 setExceptionSelectorRegister(X86::RDX);
398 setExceptionPointerRegister(X86::EAX);
399 setExceptionSelectorRegister(X86::EDX);
401 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
402 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
404 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
406 setOperationAction(ISD::TRAP, MVT::Other, Legal);
408 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
409 setOperationAction(ISD::VASTART , MVT::Other, Custom);
410 setOperationAction(ISD::VAEND , MVT::Other, Expand);
411 if (Subtarget->is64Bit()) {
412 setOperationAction(ISD::VAARG , MVT::Other, Custom);
413 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
415 setOperationAction(ISD::VAARG , MVT::Other, Expand);
416 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
419 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
420 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
421 if (Subtarget->is64Bit())
422 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
423 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
424 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
428 if (!UseSoftFloat && X86ScalarSSEf64) {
429 // f32 and f64 use SSE.
430 // Set up the FP register classes.
431 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
432 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
434 // Use ANDPD to simulate FABS.
435 setOperationAction(ISD::FABS , MVT::f64, Custom);
436 setOperationAction(ISD::FABS , MVT::f32, Custom);
438 // Use XORP to simulate FNEG.
439 setOperationAction(ISD::FNEG , MVT::f64, Custom);
440 setOperationAction(ISD::FNEG , MVT::f32, Custom);
442 // Use ANDPD and ORPD to simulate FCOPYSIGN.
443 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
444 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
446 // We don't support sin/cos/fmod
447 setOperationAction(ISD::FSIN , MVT::f64, Expand);
448 setOperationAction(ISD::FCOS , MVT::f64, Expand);
449 setOperationAction(ISD::FSIN , MVT::f32, Expand);
450 setOperationAction(ISD::FCOS , MVT::f32, Expand);
452 // Expand FP immediates into loads from the stack, except for the special
454 addLegalFPImmediate(APFloat(+0.0)); // xorpd
455 addLegalFPImmediate(APFloat(+0.0f)); // xorps
456 } else if (!UseSoftFloat && X86ScalarSSEf32) {
457 // Use SSE for f32, x87 for f64.
458 // Set up the FP register classes.
459 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
460 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
462 // Use ANDPS to simulate FABS.
463 setOperationAction(ISD::FABS , MVT::f32, Custom);
465 // Use XORP to simulate FNEG.
466 setOperationAction(ISD::FNEG , MVT::f32, Custom);
468 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
470 // Use ANDPS and ORPS to simulate FCOPYSIGN.
471 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
472 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
474 // We don't support sin/cos/fmod
475 setOperationAction(ISD::FSIN , MVT::f32, Expand);
476 setOperationAction(ISD::FCOS , MVT::f32, Expand);
478 // Special cases we handle for FP constants.
479 addLegalFPImmediate(APFloat(+0.0f)); // xorps
480 addLegalFPImmediate(APFloat(+0.0)); // FLD0
481 addLegalFPImmediate(APFloat(+1.0)); // FLD1
482 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
483 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
486 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
487 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
489 } else if (!UseSoftFloat) {
490 // f32 and f64 in x87.
491 // Set up the FP register classes.
492 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
493 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
495 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
496 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
497 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
498 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
501 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
502 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
504 addLegalFPImmediate(APFloat(+0.0)); // FLD0
505 addLegalFPImmediate(APFloat(+1.0)); // FLD1
506 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
507 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
508 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
509 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
510 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
511 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
514 // Long double always uses X87.
516 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
517 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
518 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
520 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
521 addLegalFPImmediate(TmpFlt); // FLD0
523 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
526 APFloat TmpFlt2(+1.0);
527 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
529 addLegalFPImmediate(TmpFlt2); // FLD1
530 TmpFlt2.changeSign();
531 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
535 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
536 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
540 // Always use a library call for pow.
541 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
542 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
543 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
545 setOperationAction(ISD::FLOG, MVT::f80, Expand);
546 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
547 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
548 setOperationAction(ISD::FEXP, MVT::f80, Expand);
549 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
551 // First set operation action for all vector types to either promote
552 // (for widening) or expand (for scalarization). Then we will selectively
553 // turn on ones that can be effectively codegen'd.
554 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
555 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
556 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
571 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
573 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
574 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
606 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
610 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
611 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
612 setTruncStoreAction((MVT::SimpleValueType)VT,
613 (MVT::SimpleValueType)InnerVT, Expand);
614 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
615 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
616 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
619 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
620 // with -msoft-float, disable use of MMX as well.
621 if (!UseSoftFloat && Subtarget->hasMMX()) {
622 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
623 // No operations on x86mmx supported, everything uses intrinsics.
626 // MMX-sized vectors (other than x86mmx) are expected to be expanded
627 // into smaller operations.
628 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
629 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
630 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
631 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
632 setOperationAction(ISD::AND, MVT::v8i8, Expand);
633 setOperationAction(ISD::AND, MVT::v4i16, Expand);
634 setOperationAction(ISD::AND, MVT::v2i32, Expand);
635 setOperationAction(ISD::AND, MVT::v1i64, Expand);
636 setOperationAction(ISD::OR, MVT::v8i8, Expand);
637 setOperationAction(ISD::OR, MVT::v4i16, Expand);
638 setOperationAction(ISD::OR, MVT::v2i32, Expand);
639 setOperationAction(ISD::OR, MVT::v1i64, Expand);
640 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
641 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
642 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
643 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
644 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
645 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
646 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
647 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
648 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
649 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
650 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
651 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
652 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
653 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
654 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
655 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
656 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
658 if (!UseSoftFloat && Subtarget->hasXMM()) {
659 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
661 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
662 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
663 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
664 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
665 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
666 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
667 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
668 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
669 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
671 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
672 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
675 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
676 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
678 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
679 // registers cannot be used even for integer operations.
680 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
681 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
682 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
683 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
685 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
686 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
687 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
688 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
689 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
690 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
691 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
692 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
693 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
694 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
695 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
696 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
697 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
698 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
699 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
700 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
702 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
703 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
704 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
705 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
707 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
708 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
709 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
710 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
713 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
715 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
716 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
717 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
719 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
720 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
721 EVT VT = (MVT::SimpleValueType)i;
722 // Do not attempt to custom lower non-power-of-2 vectors
723 if (!isPowerOf2_32(VT.getVectorNumElements()))
725 // Do not attempt to custom lower non-128-bit vectors
726 if (!VT.is128BitVector())
728 setOperationAction(ISD::BUILD_VECTOR,
729 VT.getSimpleVT().SimpleTy, Custom);
730 setOperationAction(ISD::VECTOR_SHUFFLE,
731 VT.getSimpleVT().SimpleTy, Custom);
732 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
733 VT.getSimpleVT().SimpleTy, Custom);
736 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
737 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
738 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
740 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
741 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
743 if (Subtarget->is64Bit()) {
744 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
748 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
749 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
750 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
753 // Do not attempt to promote non-128-bit vectors
754 if (!VT.is128BitVector())
757 setOperationAction(ISD::AND, SVT, Promote);
758 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
759 setOperationAction(ISD::OR, SVT, Promote);
760 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
761 setOperationAction(ISD::XOR, SVT, Promote);
762 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
763 setOperationAction(ISD::LOAD, SVT, Promote);
764 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
765 setOperationAction(ISD::SELECT, SVT, Promote);
766 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
769 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
771 // Custom lower v2i64 and v2f64 selects.
772 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
773 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
774 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
775 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
777 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
778 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
781 if (Subtarget->hasSSE41()) {
782 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
783 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
784 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
785 setOperationAction(ISD::FRINT, MVT::f32, Legal);
786 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
787 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
788 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
789 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
790 setOperationAction(ISD::FRINT, MVT::f64, Legal);
791 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
793 // FIXME: Do we need to handle scalar-to-vector here?
794 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
796 // Can turn SHL into an integer multiply.
797 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
798 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
800 // i8 and i16 vectors are custom , because the source register and source
801 // source memory operand types are not the same width. f32 vectors are
802 // custom since the immediate controlling the insert encodes additional
804 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
805 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
806 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
807 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
814 if (Subtarget->is64Bit()) {
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
820 if (Subtarget->hasSSE42())
821 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
823 if (!UseSoftFloat && Subtarget->hasAVX()) {
824 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
825 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
826 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
827 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
828 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
830 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
831 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
832 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
833 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
835 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
836 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
837 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
838 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
839 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
840 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
842 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
843 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
844 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
845 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
846 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
847 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
849 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
850 // insert_vector_elt extract_subvector and extract_vector_elt for
852 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
853 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
855 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
856 // Do not attempt to custom lower non-256-bit vectors
857 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
858 || (MVT(VT).getSizeInBits() < 256))
860 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
866 // Custom-lower insert_subvector and extract_subvector based on
868 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
869 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
871 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
872 // Do not attempt to custom lower non-256-bit vectors
873 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
876 if (MVT(VT).getSizeInBits() == 128) {
877 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
879 else if (MVT(VT).getSizeInBits() == 256) {
880 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
884 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
885 // Don't promote loads because we need them for VPERM vector index versions.
887 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
888 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
890 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
891 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
893 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
894 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
895 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
896 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
897 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
898 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
899 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
900 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
901 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
902 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
906 // We want to custom lower some of our intrinsics.
907 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
910 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
911 // handle type legalization for these operations here.
913 // FIXME: We really should do custom legalization for addition and
914 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
915 // than generic legalization for 64-bit multiplication-with-overflow, though.
916 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
917 // Add/Sub/Mul with overflow operations are custom lowered.
919 setOperationAction(ISD::SADDO, VT, Custom);
920 setOperationAction(ISD::UADDO, VT, Custom);
921 setOperationAction(ISD::SSUBO, VT, Custom);
922 setOperationAction(ISD::USUBO, VT, Custom);
923 setOperationAction(ISD::SMULO, VT, Custom);
924 setOperationAction(ISD::UMULO, VT, Custom);
927 // There are no 8-bit 3-address imul/mul instructions
928 setOperationAction(ISD::SMULO, MVT::i8, Expand);
929 setOperationAction(ISD::UMULO, MVT::i8, Expand);
931 if (!Subtarget->is64Bit()) {
932 // These libcalls are not available in 32-bit.
933 setLibcallName(RTLIB::SHL_I128, 0);
934 setLibcallName(RTLIB::SRL_I128, 0);
935 setLibcallName(RTLIB::SRA_I128, 0);
938 // We have target-specific dag combine patterns for the following nodes:
939 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
940 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
941 setTargetDAGCombine(ISD::BUILD_VECTOR);
942 setTargetDAGCombine(ISD::SELECT);
943 setTargetDAGCombine(ISD::SHL);
944 setTargetDAGCombine(ISD::SRA);
945 setTargetDAGCombine(ISD::SRL);
946 setTargetDAGCombine(ISD::OR);
947 setTargetDAGCombine(ISD::AND);
948 setTargetDAGCombine(ISD::ADD);
949 setTargetDAGCombine(ISD::SUB);
950 setTargetDAGCombine(ISD::STORE);
951 setTargetDAGCombine(ISD::ZERO_EXTEND);
952 if (Subtarget->is64Bit())
953 setTargetDAGCombine(ISD::MUL);
955 computeRegisterProperties();
957 // On Darwin, -Os means optimize for size without hurting performance,
958 // do not reduce the limit.
959 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
960 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
961 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
962 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
963 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
964 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
965 setPrefLoopAlignment(16);
966 benefitFromCodePlacementOpt = true;
970 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
975 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
976 /// the desired ByVal argument alignment.
977 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
980 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
981 if (VTy->getBitWidth() == 128)
983 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
984 unsigned EltAlign = 0;
985 getMaxByValAlign(ATy->getElementType(), EltAlign);
986 if (EltAlign > MaxAlign)
988 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
989 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
990 unsigned EltAlign = 0;
991 getMaxByValAlign(STy->getElementType(i), EltAlign);
992 if (EltAlign > MaxAlign)
1001 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1002 /// function arguments in the caller parameter area. For X86, aggregates
1003 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1004 /// are at 4-byte boundaries.
1005 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1006 if (Subtarget->is64Bit()) {
1007 // Max of 8 and alignment of type.
1008 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1015 if (Subtarget->hasXMM())
1016 getMaxByValAlign(Ty, Align);
1020 /// getOptimalMemOpType - Returns the target specific optimal type for load
1021 /// and store operations as a result of memset, memcpy, and memmove
1022 /// lowering. If DstAlign is zero that means it's safe to destination
1023 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1024 /// means there isn't a need to check it against alignment requirement,
1025 /// probably because the source does not need to be loaded. If
1026 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1027 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1028 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1029 /// constant so it does not need to be loaded.
1030 /// It returns EVT::Other if the type should be determined using generic
1031 /// target-independent logic.
1033 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1034 unsigned DstAlign, unsigned SrcAlign,
1035 bool NonScalarIntSafe,
1037 MachineFunction &MF) const {
1038 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1039 // linux. This is because the stack realignment code can't handle certain
1040 // cases like PR2962. This should be removed when PR2962 is fixed.
1041 const Function *F = MF.getFunction();
1042 if (NonScalarIntSafe &&
1043 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1045 (Subtarget->isUnalignedMemAccessFast() ||
1046 ((DstAlign == 0 || DstAlign >= 16) &&
1047 (SrcAlign == 0 || SrcAlign >= 16))) &&
1048 Subtarget->getStackAlignment() >= 16) {
1049 if (Subtarget->hasSSE2())
1051 if (Subtarget->hasSSE1())
1053 } else if (!MemcpyStrSrc && Size >= 8 &&
1054 !Subtarget->is64Bit() &&
1055 Subtarget->getStackAlignment() >= 8 &&
1056 Subtarget->hasXMMInt()) {
1057 // Do not use f64 to lower memcpy if source is string constant. It's
1058 // better to use i32 to avoid the loads.
1062 if (Subtarget->is64Bit() && Size >= 8)
1067 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1068 /// current function. The returned value is a member of the
1069 /// MachineJumpTableInfo::JTEntryKind enum.
1070 unsigned X86TargetLowering::getJumpTableEncoding() const {
1071 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1073 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1074 Subtarget->isPICStyleGOT())
1075 return MachineJumpTableInfo::EK_Custom32;
1077 // Otherwise, use the normal jump table encoding heuristics.
1078 return TargetLowering::getJumpTableEncoding();
1082 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1083 const MachineBasicBlock *MBB,
1084 unsigned uid,MCContext &Ctx) const{
1085 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1086 Subtarget->isPICStyleGOT());
1087 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1089 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1090 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1093 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1095 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1096 SelectionDAG &DAG) const {
1097 if (!Subtarget->is64Bit())
1098 // This doesn't have DebugLoc associated with it, but is not really the
1099 // same as a Register.
1100 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1104 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1105 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1107 const MCExpr *X86TargetLowering::
1108 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1109 MCContext &Ctx) const {
1110 // X86-64 uses RIP relative addressing based on the jump table label.
1111 if (Subtarget->isPICStyleRIPRel())
1112 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1114 // Otherwise, the reference is relative to the PIC base.
1115 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1118 /// getFunctionAlignment - Return the Log2 alignment of this function.
1119 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1120 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1123 // FIXME: Why this routine is here? Move to RegInfo!
1124 std::pair<const TargetRegisterClass*, uint8_t>
1125 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1126 const TargetRegisterClass *RRC = 0;
1128 switch (VT.getSimpleVT().SimpleTy) {
1130 return TargetLowering::findRepresentativeClass(VT);
1131 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1132 RRC = (Subtarget->is64Bit()
1133 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1136 RRC = X86::VR64RegisterClass;
1138 case MVT::f32: case MVT::f64:
1139 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1140 case MVT::v4f32: case MVT::v2f64:
1141 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1143 RRC = X86::VR128RegisterClass;
1146 return std::make_pair(RRC, Cost);
1149 // FIXME: Why this routine is here? Move to RegInfo!
1151 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1152 MachineFunction &MF) const {
1153 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1155 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1156 switch (RC->getID()) {
1159 case X86::GR32RegClassID:
1161 case X86::GR64RegClassID:
1163 case X86::VR128RegClassID:
1164 return Subtarget->is64Bit() ? 10 : 4;
1165 case X86::VR64RegClassID:
1170 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1171 unsigned &Offset) const {
1172 if (!Subtarget->isTargetLinux())
1175 if (Subtarget->is64Bit()) {
1176 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1178 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1191 //===----------------------------------------------------------------------===//
1192 // Return Value Calling Convention Implementation
1193 //===----------------------------------------------------------------------===//
1195 #include "X86GenCallingConv.inc"
1198 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1199 const SmallVectorImpl<ISD::OutputArg> &Outs,
1200 LLVMContext &Context) const {
1201 SmallVector<CCValAssign, 16> RVLocs;
1202 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1204 return CCInfo.CheckReturn(Outs, RetCC_X86);
1208 X86TargetLowering::LowerReturn(SDValue Chain,
1209 CallingConv::ID CallConv, bool isVarArg,
1210 const SmallVectorImpl<ISD::OutputArg> &Outs,
1211 const SmallVectorImpl<SDValue> &OutVals,
1212 DebugLoc dl, SelectionDAG &DAG) const {
1213 MachineFunction &MF = DAG.getMachineFunction();
1214 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1216 SmallVector<CCValAssign, 16> RVLocs;
1217 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1218 RVLocs, *DAG.getContext());
1219 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1221 // Add the regs to the liveout set for the function.
1222 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1223 for (unsigned i = 0; i != RVLocs.size(); ++i)
1224 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1225 MRI.addLiveOut(RVLocs[i].getLocReg());
1229 SmallVector<SDValue, 6> RetOps;
1230 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1231 // Operand #1 = Bytes To Pop
1232 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1235 // Copy the result values into the output registers.
1236 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1237 CCValAssign &VA = RVLocs[i];
1238 assert(VA.isRegLoc() && "Can only return in registers!");
1239 SDValue ValToCopy = OutVals[i];
1240 EVT ValVT = ValToCopy.getValueType();
1242 // If this is x86-64, and we disabled SSE, we can't return FP values,
1243 // or SSE or MMX vectors.
1244 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1245 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1246 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1247 report_fatal_error("SSE register return with SSE disabled");
1249 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1250 // llvm-gcc has never done it right and no one has noticed, so this
1251 // should be OK for now.
1252 if (ValVT == MVT::f64 &&
1253 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1254 report_fatal_error("SSE2 register return with SSE2 disabled");
1256 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1257 // the RET instruction and handled by the FP Stackifier.
1258 if (VA.getLocReg() == X86::ST0 ||
1259 VA.getLocReg() == X86::ST1) {
1260 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1261 // change the value to the FP stack register class.
1262 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1263 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1264 RetOps.push_back(ValToCopy);
1265 // Don't emit a copytoreg.
1269 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1270 // which is returned in RAX / RDX.
1271 if (Subtarget->is64Bit()) {
1272 if (ValVT == MVT::x86mmx) {
1273 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1274 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1275 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1277 // If we don't have SSE2 available, convert to v4f32 so the generated
1278 // register is legal.
1279 if (!Subtarget->hasSSE2())
1280 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1285 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1286 Flag = Chain.getValue(1);
1289 // The x86-64 ABI for returning structs by value requires that we copy
1290 // the sret argument into %rax for the return. We saved the argument into
1291 // a virtual register in the entry block, so now we copy the value out
1293 if (Subtarget->is64Bit() &&
1294 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1297 unsigned Reg = FuncInfo->getSRetReturnReg();
1299 "SRetReturnReg should have been set in LowerFormalArguments().");
1300 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1302 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1303 Flag = Chain.getValue(1);
1305 // RAX now acts like a return value.
1306 MRI.addLiveOut(X86::RAX);
1309 RetOps[0] = Chain; // Update chain.
1311 // Add the flag if we have it.
1313 RetOps.push_back(Flag);
1315 return DAG.getNode(X86ISD::RET_FLAG, dl,
1316 MVT::Other, &RetOps[0], RetOps.size());
1319 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1320 if (N->getNumValues() != 1)
1322 if (!N->hasNUsesOfValue(1, 0))
1325 SDNode *Copy = *N->use_begin();
1326 if (Copy->getOpcode() != ISD::CopyToReg &&
1327 Copy->getOpcode() != ISD::FP_EXTEND)
1330 bool HasRet = false;
1331 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1333 if (UI->getOpcode() != X86ISD::RET_FLAG)
1341 /// LowerCallResult - Lower the result values of a call into the
1342 /// appropriate copies out of appropriate physical registers.
1345 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1346 CallingConv::ID CallConv, bool isVarArg,
1347 const SmallVectorImpl<ISD::InputArg> &Ins,
1348 DebugLoc dl, SelectionDAG &DAG,
1349 SmallVectorImpl<SDValue> &InVals) const {
1351 // Assign locations to each value returned by this call.
1352 SmallVector<CCValAssign, 16> RVLocs;
1353 bool Is64Bit = Subtarget->is64Bit();
1354 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1355 RVLocs, *DAG.getContext());
1356 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1358 // Copy all of the result registers out of their specified physreg.
1359 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1360 CCValAssign &VA = RVLocs[i];
1361 EVT CopyVT = VA.getValVT();
1363 // If this is x86-64, and we disabled SSE, we can't return FP values
1364 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1365 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1366 report_fatal_error("SSE register return with SSE disabled");
1371 // If this is a call to a function that returns an fp value on the floating
1372 // point stack, we must guarantee the the value is popped from the stack, so
1373 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1374 // if the return value is not used. We use the FpGET_ST0 instructions
1376 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1377 // If we prefer to use the value in xmm registers, copy it out as f80 and
1378 // use a truncate to move it from fp stack reg to xmm reg.
1379 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1380 bool isST0 = VA.getLocReg() == X86::ST0;
1382 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1383 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1384 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1385 SDValue Ops[] = { Chain, InFlag };
1386 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1388 Val = Chain.getValue(0);
1390 // Round the f80 to the right size, which also moves it to the appropriate
1392 if (CopyVT != VA.getValVT())
1393 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1394 // This truncation won't change the value.
1395 DAG.getIntPtrConstant(1));
1396 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1397 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1398 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1399 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1400 MVT::v2i64, InFlag).getValue(1);
1401 Val = Chain.getValue(0);
1402 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1403 Val, DAG.getConstant(0, MVT::i64));
1405 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1406 MVT::i64, InFlag).getValue(1);
1407 Val = Chain.getValue(0);
1409 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1411 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1412 CopyVT, InFlag).getValue(1);
1413 Val = Chain.getValue(0);
1415 InFlag = Chain.getValue(2);
1416 InVals.push_back(Val);
1423 //===----------------------------------------------------------------------===//
1424 // C & StdCall & Fast Calling Convention implementation
1425 //===----------------------------------------------------------------------===//
1426 // StdCall calling convention seems to be standard for many Windows' API
1427 // routines and around. It differs from C calling convention just a little:
1428 // callee should clean up the stack, not caller. Symbols should be also
1429 // decorated in some fancy way :) It doesn't support any vector arguments.
1430 // For info on fast calling convention see Fast Calling Convention (tail call)
1431 // implementation LowerX86_32FastCCCallTo.
1433 /// CallIsStructReturn - Determines whether a call uses struct return
1435 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1439 return Outs[0].Flags.isSRet();
1442 /// ArgsAreStructReturn - Determines whether a function uses struct
1443 /// return semantics.
1445 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1449 return Ins[0].Flags.isSRet();
1452 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1453 /// by "Src" to address "Dst" with size and alignment information specified by
1454 /// the specific parameter attribute. The copy will be passed as a byval
1455 /// function parameter.
1457 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1458 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1460 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1462 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1463 /*isVolatile*/false, /*AlwaysInline=*/true,
1464 MachinePointerInfo(), MachinePointerInfo());
1467 /// IsTailCallConvention - Return true if the calling convention is one that
1468 /// supports tail call optimization.
1469 static bool IsTailCallConvention(CallingConv::ID CC) {
1470 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1473 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1474 /// a tailcall target by changing its ABI.
1475 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1476 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1480 X86TargetLowering::LowerMemArgument(SDValue Chain,
1481 CallingConv::ID CallConv,
1482 const SmallVectorImpl<ISD::InputArg> &Ins,
1483 DebugLoc dl, SelectionDAG &DAG,
1484 const CCValAssign &VA,
1485 MachineFrameInfo *MFI,
1487 // Create the nodes corresponding to a load from this parameter slot.
1488 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1489 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1490 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1493 // If value is passed by pointer we have address passed instead of the value
1495 if (VA.getLocInfo() == CCValAssign::Indirect)
1496 ValVT = VA.getLocVT();
1498 ValVT = VA.getValVT();
1500 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1501 // changed with more analysis.
1502 // In case of tail call optimization mark all arguments mutable. Since they
1503 // could be overwritten by lowering of arguments in case of a tail call.
1504 if (Flags.isByVal()) {
1505 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1506 VA.getLocMemOffset(), isImmutable);
1507 return DAG.getFrameIndex(FI, getPointerTy());
1509 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1510 VA.getLocMemOffset(), isImmutable);
1511 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1512 return DAG.getLoad(ValVT, dl, Chain, FIN,
1513 MachinePointerInfo::getFixedStack(FI),
1519 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1520 CallingConv::ID CallConv,
1522 const SmallVectorImpl<ISD::InputArg> &Ins,
1525 SmallVectorImpl<SDValue> &InVals)
1527 MachineFunction &MF = DAG.getMachineFunction();
1528 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1530 const Function* Fn = MF.getFunction();
1531 if (Fn->hasExternalLinkage() &&
1532 Subtarget->isTargetCygMing() &&
1533 Fn->getName() == "main")
1534 FuncInfo->setForceFramePointer(true);
1536 MachineFrameInfo *MFI = MF.getFrameInfo();
1537 bool Is64Bit = Subtarget->is64Bit();
1538 bool IsWin64 = Subtarget->isTargetWin64();
1540 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1541 "Var args not supported with calling convention fastcc or ghc");
1543 // Assign locations to all of the incoming arguments.
1544 SmallVector<CCValAssign, 16> ArgLocs;
1545 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1546 ArgLocs, *DAG.getContext());
1547 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1549 unsigned LastVal = ~0U;
1551 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1552 CCValAssign &VA = ArgLocs[i];
1553 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1555 assert(VA.getValNo() != LastVal &&
1556 "Don't support value assigned to multiple locs yet");
1557 LastVal = VA.getValNo();
1559 if (VA.isRegLoc()) {
1560 EVT RegVT = VA.getLocVT();
1561 TargetRegisterClass *RC = NULL;
1562 if (RegVT == MVT::i32)
1563 RC = X86::GR32RegisterClass;
1564 else if (Is64Bit && RegVT == MVT::i64)
1565 RC = X86::GR64RegisterClass;
1566 else if (RegVT == MVT::f32)
1567 RC = X86::FR32RegisterClass;
1568 else if (RegVT == MVT::f64)
1569 RC = X86::FR64RegisterClass;
1570 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1571 RC = X86::VR256RegisterClass;
1572 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1573 RC = X86::VR128RegisterClass;
1574 else if (RegVT == MVT::x86mmx)
1575 RC = X86::VR64RegisterClass;
1577 llvm_unreachable("Unknown argument type!");
1579 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC, dl);
1580 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1582 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1583 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1585 if (VA.getLocInfo() == CCValAssign::SExt)
1586 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1587 DAG.getValueType(VA.getValVT()));
1588 else if (VA.getLocInfo() == CCValAssign::ZExt)
1589 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1590 DAG.getValueType(VA.getValVT()));
1591 else if (VA.getLocInfo() == CCValAssign::BCvt)
1592 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1594 if (VA.isExtInLoc()) {
1595 // Handle MMX values passed in XMM regs.
1596 if (RegVT.isVector()) {
1597 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1600 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1603 assert(VA.isMemLoc());
1604 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1607 // If value is passed via pointer - do a load.
1608 if (VA.getLocInfo() == CCValAssign::Indirect)
1609 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1610 MachinePointerInfo(), false, false, 0);
1612 InVals.push_back(ArgValue);
1615 // The x86-64 ABI for returning structs by value requires that we copy
1616 // the sret argument into %rax for the return. Save the argument into
1617 // a virtual register so that we can access it from the return points.
1618 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1619 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1620 unsigned Reg = FuncInfo->getSRetReturnReg();
1622 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1623 FuncInfo->setSRetReturnReg(Reg);
1625 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1626 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1629 unsigned StackSize = CCInfo.getNextStackOffset();
1630 // Align stack specially for tail calls.
1631 if (FuncIsMadeTailCallSafe(CallConv))
1632 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1634 // If the function takes variable number of arguments, make a frame index for
1635 // the start of the first vararg value... for expansion of llvm.va_start.
1637 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1638 CallConv != CallingConv::X86_ThisCall))) {
1639 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1642 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1644 // FIXME: We should really autogenerate these arrays
1645 static const unsigned GPR64ArgRegsWin64[] = {
1646 X86::RCX, X86::RDX, X86::R8, X86::R9
1648 static const unsigned GPR64ArgRegs64Bit[] = {
1649 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1651 static const unsigned XMMArgRegs64Bit[] = {
1652 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1653 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1655 const unsigned *GPR64ArgRegs;
1656 unsigned NumXMMRegs = 0;
1659 // The XMM registers which might contain var arg parameters are shadowed
1660 // in their paired GPR. So we only need to save the GPR to their home
1662 TotalNumIntRegs = 4;
1663 GPR64ArgRegs = GPR64ArgRegsWin64;
1665 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1666 GPR64ArgRegs = GPR64ArgRegs64Bit;
1668 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1670 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1673 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1674 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1675 "SSE register cannot be used when SSE is disabled!");
1676 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1677 "SSE register cannot be used when SSE is disabled!");
1678 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1679 // Kernel mode asks for SSE to be disabled, so don't push them
1681 TotalNumXMMRegs = 0;
1684 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1685 // Get to the caller-allocated home save location. Add 8 to account
1686 // for the return address.
1687 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1688 FuncInfo->setRegSaveFrameIndex(
1689 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1690 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1692 // For X86-64, if there are vararg parameters that are passed via
1693 // registers, then we must store them to their spots on the stack so they
1694 // may be loaded by deferencing the result of va_next.
1695 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1696 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1697 FuncInfo->setRegSaveFrameIndex(
1698 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1702 // Store the integer parameter registers.
1703 SmallVector<SDValue, 8> MemOps;
1704 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1706 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1707 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1708 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1709 DAG.getIntPtrConstant(Offset));
1710 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1711 X86::GR64RegisterClass, dl);
1712 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1714 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1715 MachinePointerInfo::getFixedStack(
1716 FuncInfo->getRegSaveFrameIndex(), Offset),
1718 MemOps.push_back(Store);
1722 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1723 // Now store the XMM (fp + vector) parameter registers.
1724 SmallVector<SDValue, 11> SaveXMMOps;
1725 SaveXMMOps.push_back(Chain);
1727 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass, dl);
1728 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1729 SaveXMMOps.push_back(ALVal);
1731 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1732 FuncInfo->getRegSaveFrameIndex()));
1733 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1734 FuncInfo->getVarArgsFPOffset()));
1736 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1737 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1738 X86::VR128RegisterClass, dl);
1739 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1740 SaveXMMOps.push_back(Val);
1742 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1744 &SaveXMMOps[0], SaveXMMOps.size()));
1747 if (!MemOps.empty())
1748 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1749 &MemOps[0], MemOps.size());
1753 // Some CCs need callee pop.
1754 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1755 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1757 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1758 // If this is an sret function, the return should pop the hidden pointer.
1759 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1760 FuncInfo->setBytesToPopOnReturn(4);
1764 // RegSaveFrameIndex is X86-64 only.
1765 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1766 if (CallConv == CallingConv::X86_FastCall ||
1767 CallConv == CallingConv::X86_ThisCall)
1768 // fastcc functions can't have varargs.
1769 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1776 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1777 SDValue StackPtr, SDValue Arg,
1778 DebugLoc dl, SelectionDAG &DAG,
1779 const CCValAssign &VA,
1780 ISD::ArgFlagsTy Flags) const {
1781 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1782 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1783 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1784 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1785 if (Flags.isByVal())
1786 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1788 return DAG.getStore(Chain, dl, Arg, PtrOff,
1789 MachinePointerInfo::getStack(LocMemOffset),
1793 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1794 /// optimization is performed and it is required.
1796 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1797 SDValue &OutRetAddr, SDValue Chain,
1798 bool IsTailCall, bool Is64Bit,
1799 int FPDiff, DebugLoc dl) const {
1800 // Adjust the Return address stack slot.
1801 EVT VT = getPointerTy();
1802 OutRetAddr = getReturnAddressFrameIndex(DAG);
1804 // Load the "old" Return address.
1805 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1807 return SDValue(OutRetAddr.getNode(), 1);
1810 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1811 /// optimization is performed and it is required (FPDiff!=0).
1813 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1814 SDValue Chain, SDValue RetAddrFrIdx,
1815 bool Is64Bit, int FPDiff, DebugLoc dl) {
1816 // Store the return address to the appropriate stack slot.
1817 if (!FPDiff) return Chain;
1818 // Calculate the new stack slot for the return address.
1819 int SlotSize = Is64Bit ? 8 : 4;
1820 int NewReturnAddrFI =
1821 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1822 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1823 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1824 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1825 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1831 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1832 CallingConv::ID CallConv, bool isVarArg,
1834 const SmallVectorImpl<ISD::OutputArg> &Outs,
1835 const SmallVectorImpl<SDValue> &OutVals,
1836 const SmallVectorImpl<ISD::InputArg> &Ins,
1837 DebugLoc dl, SelectionDAG &DAG,
1838 SmallVectorImpl<SDValue> &InVals) const {
1839 MachineFunction &MF = DAG.getMachineFunction();
1840 bool Is64Bit = Subtarget->is64Bit();
1841 bool IsStructRet = CallIsStructReturn(Outs);
1842 bool IsSibcall = false;
1845 // Check if it's really possible to do a tail call.
1846 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1847 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1848 Outs, OutVals, Ins, DAG);
1850 // Sibcalls are automatically detected tailcalls which do not require
1852 if (!GuaranteedTailCallOpt && isTailCall)
1859 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1860 "Var args not supported with calling convention fastcc or ghc");
1862 // Analyze operands of the call, assigning locations to each operand.
1863 SmallVector<CCValAssign, 16> ArgLocs;
1864 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1865 ArgLocs, *DAG.getContext());
1866 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1868 // Get a count of how many bytes are to be pushed on the stack.
1869 unsigned NumBytes = CCInfo.getNextStackOffset();
1871 // This is a sibcall. The memory operands are available in caller's
1872 // own caller's stack.
1874 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1875 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1878 if (isTailCall && !IsSibcall) {
1879 // Lower arguments at fp - stackoffset + fpdiff.
1880 unsigned NumBytesCallerPushed =
1881 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1882 FPDiff = NumBytesCallerPushed - NumBytes;
1884 // Set the delta of movement of the returnaddr stackslot.
1885 // But only set if delta is greater than previous delta.
1886 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1887 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1891 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1893 SDValue RetAddrFrIdx;
1894 // Load return adress for tail calls.
1895 if (isTailCall && FPDiff)
1896 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1897 Is64Bit, FPDiff, dl);
1899 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1900 SmallVector<SDValue, 8> MemOpChains;
1903 // Walk the register/memloc assignments, inserting copies/loads. In the case
1904 // of tail call optimization arguments are handle later.
1905 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1906 CCValAssign &VA = ArgLocs[i];
1907 EVT RegVT = VA.getLocVT();
1908 SDValue Arg = OutVals[i];
1909 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1910 bool isByVal = Flags.isByVal();
1912 // Promote the value if needed.
1913 switch (VA.getLocInfo()) {
1914 default: llvm_unreachable("Unknown loc info!");
1915 case CCValAssign::Full: break;
1916 case CCValAssign::SExt:
1917 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1919 case CCValAssign::ZExt:
1920 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1922 case CCValAssign::AExt:
1923 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1924 // Special case: passing MMX values in XMM registers.
1925 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1926 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1927 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1929 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1931 case CCValAssign::BCvt:
1932 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1934 case CCValAssign::Indirect: {
1935 // Store the argument.
1936 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1937 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1938 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1939 MachinePointerInfo::getFixedStack(FI),
1946 if (VA.isRegLoc()) {
1947 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1948 if (isVarArg && Subtarget->isTargetWin64()) {
1949 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1950 // shadow reg if callee is a varargs function.
1951 unsigned ShadowReg = 0;
1952 switch (VA.getLocReg()) {
1953 case X86::XMM0: ShadowReg = X86::RCX; break;
1954 case X86::XMM1: ShadowReg = X86::RDX; break;
1955 case X86::XMM2: ShadowReg = X86::R8; break;
1956 case X86::XMM3: ShadowReg = X86::R9; break;
1959 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1961 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1962 assert(VA.isMemLoc());
1963 if (StackPtr.getNode() == 0)
1964 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1965 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1966 dl, DAG, VA, Flags));
1970 if (!MemOpChains.empty())
1971 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1972 &MemOpChains[0], MemOpChains.size());
1974 // Build a sequence of copy-to-reg nodes chained together with token chain
1975 // and flag operands which copy the outgoing args into registers.
1977 // Tail call byval lowering might overwrite argument registers so in case of
1978 // tail call optimization the copies to registers are lowered later.
1980 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1981 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1982 RegsToPass[i].second, InFlag);
1983 InFlag = Chain.getValue(1);
1986 if (Subtarget->isPICStyleGOT()) {
1987 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1990 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1991 DAG.getNode(X86ISD::GlobalBaseReg,
1992 DebugLoc(), getPointerTy()),
1994 InFlag = Chain.getValue(1);
1996 // If we are tail calling and generating PIC/GOT style code load the
1997 // address of the callee into ECX. The value in ecx is used as target of
1998 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1999 // for tail calls on PIC/GOT architectures. Normally we would just put the
2000 // address of GOT into ebx and then call target@PLT. But for tail calls
2001 // ebx would be restored (since ebx is callee saved) before jumping to the
2004 // Note: The actual moving to ECX is done further down.
2005 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2006 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2007 !G->getGlobal()->hasProtectedVisibility())
2008 Callee = LowerGlobalAddress(Callee, DAG);
2009 else if (isa<ExternalSymbolSDNode>(Callee))
2010 Callee = LowerExternalSymbol(Callee, DAG);
2014 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2015 // From AMD64 ABI document:
2016 // For calls that may call functions that use varargs or stdargs
2017 // (prototype-less calls or calls to functions containing ellipsis (...) in
2018 // the declaration) %al is used as hidden argument to specify the number
2019 // of SSE registers used. The contents of %al do not need to match exactly
2020 // the number of registers, but must be an ubound on the number of SSE
2021 // registers used and is in the range 0 - 8 inclusive.
2023 // Count the number of XMM registers allocated.
2024 static const unsigned XMMArgRegs[] = {
2025 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2026 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2028 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2029 assert((Subtarget->hasXMM() || !NumXMMRegs)
2030 && "SSE registers cannot be used when SSE is disabled");
2032 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2033 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2034 InFlag = Chain.getValue(1);
2038 // For tail calls lower the arguments to the 'real' stack slot.
2040 // Force all the incoming stack arguments to be loaded from the stack
2041 // before any new outgoing arguments are stored to the stack, because the
2042 // outgoing stack slots may alias the incoming argument stack slots, and
2043 // the alias isn't otherwise explicit. This is slightly more conservative
2044 // than necessary, because it means that each store effectively depends
2045 // on every argument instead of just those arguments it would clobber.
2046 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2048 SmallVector<SDValue, 8> MemOpChains2;
2051 // Do not flag preceeding copytoreg stuff together with the following stuff.
2053 if (GuaranteedTailCallOpt) {
2054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2055 CCValAssign &VA = ArgLocs[i];
2058 assert(VA.isMemLoc());
2059 SDValue Arg = OutVals[i];
2060 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2061 // Create frame index.
2062 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2063 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2064 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2065 FIN = DAG.getFrameIndex(FI, getPointerTy());
2067 if (Flags.isByVal()) {
2068 // Copy relative to framepointer.
2069 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2070 if (StackPtr.getNode() == 0)
2071 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2073 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2075 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2079 // Store relative to framepointer.
2080 MemOpChains2.push_back(
2081 DAG.getStore(ArgChain, dl, Arg, FIN,
2082 MachinePointerInfo::getFixedStack(FI),
2088 if (!MemOpChains2.empty())
2089 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2090 &MemOpChains2[0], MemOpChains2.size());
2092 // Copy arguments to their registers.
2093 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2094 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2095 RegsToPass[i].second, InFlag);
2096 InFlag = Chain.getValue(1);
2100 // Store the return address to the appropriate stack slot.
2101 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2105 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2106 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2107 // In the 64-bit large code model, we have to make all calls
2108 // through a register, since the call instruction's 32-bit
2109 // pc-relative offset may not be large enough to hold the whole
2111 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2112 // If the callee is a GlobalAddress node (quite common, every direct call
2113 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2116 // We should use extra load for direct calls to dllimported functions in
2118 const GlobalValue *GV = G->getGlobal();
2119 if (!GV->hasDLLImportLinkage()) {
2120 unsigned char OpFlags = 0;
2122 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2123 // external symbols most go through the PLT in PIC mode. If the symbol
2124 // has hidden or protected visibility, or if it is static or local, then
2125 // we don't need to use the PLT - we can directly call it.
2126 if (Subtarget->isTargetELF() &&
2127 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2128 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2129 OpFlags = X86II::MO_PLT;
2130 } else if (Subtarget->isPICStyleStubAny() &&
2131 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2132 Subtarget->getDarwinVers() < 9) {
2133 // PC-relative references to external symbols should go through $stub,
2134 // unless we're building with the leopard linker or later, which
2135 // automatically synthesizes these stubs.
2136 OpFlags = X86II::MO_DARWIN_STUB;
2139 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2140 G->getOffset(), OpFlags);
2142 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2143 unsigned char OpFlags = 0;
2145 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2146 // external symbols should go through the PLT.
2147 if (Subtarget->isTargetELF() &&
2148 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2149 OpFlags = X86II::MO_PLT;
2150 } else if (Subtarget->isPICStyleStubAny() &&
2151 Subtarget->getDarwinVers() < 9) {
2152 // PC-relative references to external symbols should go through $stub,
2153 // unless we're building with the leopard linker or later, which
2154 // automatically synthesizes these stubs.
2155 OpFlags = X86II::MO_DARWIN_STUB;
2158 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2162 // Returns a chain & a flag for retval copy to use.
2163 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2164 SmallVector<SDValue, 8> Ops;
2166 if (!IsSibcall && isTailCall) {
2167 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2168 DAG.getIntPtrConstant(0, true), InFlag);
2169 InFlag = Chain.getValue(1);
2172 Ops.push_back(Chain);
2173 Ops.push_back(Callee);
2176 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2178 // Add argument registers to the end of the list so that they are known live
2180 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2181 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2182 RegsToPass[i].second.getValueType()));
2184 // Add an implicit use GOT pointer in EBX.
2185 if (!isTailCall && Subtarget->isPICStyleGOT())
2186 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2188 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2189 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2190 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2192 if (InFlag.getNode())
2193 Ops.push_back(InFlag);
2197 //// If this is the first return lowered for this function, add the regs
2198 //// to the liveout set for the function.
2199 // This isn't right, although it's probably harmless on x86; liveouts
2200 // should be computed from returns not tail calls. Consider a void
2201 // function making a tail call to a function returning int.
2202 return DAG.getNode(X86ISD::TC_RETURN, dl,
2203 NodeTys, &Ops[0], Ops.size());
2206 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2207 InFlag = Chain.getValue(1);
2209 // Create the CALLSEQ_END node.
2210 unsigned NumBytesForCalleeToPush;
2211 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2212 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2213 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2214 // If this is a call to a struct-return function, the callee
2215 // pops the hidden struct pointer, so we have to push it back.
2216 // This is common for Darwin/X86, Linux & Mingw32 targets.
2217 NumBytesForCalleeToPush = 4;
2219 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2221 // Returns a flag for retval copy to use.
2223 Chain = DAG.getCALLSEQ_END(Chain,
2224 DAG.getIntPtrConstant(NumBytes, true),
2225 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2228 InFlag = Chain.getValue(1);
2231 // Handle result values, copying them out of physregs into vregs that we
2233 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2234 Ins, dl, DAG, InVals);
2238 //===----------------------------------------------------------------------===//
2239 // Fast Calling Convention (tail call) implementation
2240 //===----------------------------------------------------------------------===//
2242 // Like std call, callee cleans arguments, convention except that ECX is
2243 // reserved for storing the tail called function address. Only 2 registers are
2244 // free for argument passing (inreg). Tail call optimization is performed
2246 // * tailcallopt is enabled
2247 // * caller/callee are fastcc
2248 // On X86_64 architecture with GOT-style position independent code only local
2249 // (within module) calls are supported at the moment.
2250 // To keep the stack aligned according to platform abi the function
2251 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2252 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2253 // If a tail called function callee has more arguments than the caller the
2254 // caller needs to make sure that there is room to move the RETADDR to. This is
2255 // achieved by reserving an area the size of the argument delta right after the
2256 // original REtADDR, but before the saved framepointer or the spilled registers
2257 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2269 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2270 /// for a 16 byte align requirement.
2272 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2273 SelectionDAG& DAG) const {
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 const TargetMachine &TM = MF.getTarget();
2276 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2277 unsigned StackAlignment = TFI.getStackAlignment();
2278 uint64_t AlignMask = StackAlignment - 1;
2279 int64_t Offset = StackSize;
2280 uint64_t SlotSize = TD->getPointerSize();
2281 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2282 // Number smaller than 12 so just add the difference.
2283 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2285 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2286 Offset = ((~AlignMask) & Offset) + StackAlignment +
2287 (StackAlignment-SlotSize);
2292 /// MatchingStackOffset - Return true if the given stack call argument is
2293 /// already available in the same position (relatively) of the caller's
2294 /// incoming argument stack.
2296 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2297 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2298 const X86InstrInfo *TII) {
2299 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2301 if (Arg.getOpcode() == ISD::CopyFromReg) {
2302 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2303 if (!TargetRegisterInfo::isVirtualRegister(VR))
2305 MachineInstr *Def = MRI->getVRegDef(VR);
2308 if (!Flags.isByVal()) {
2309 if (!TII->isLoadFromStackSlot(Def, FI))
2312 unsigned Opcode = Def->getOpcode();
2313 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2314 Def->getOperand(1).isFI()) {
2315 FI = Def->getOperand(1).getIndex();
2316 Bytes = Flags.getByValSize();
2320 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2321 if (Flags.isByVal())
2322 // ByVal argument is passed in as a pointer but it's now being
2323 // dereferenced. e.g.
2324 // define @foo(%struct.X* %A) {
2325 // tail call @bar(%struct.X* byval %A)
2328 SDValue Ptr = Ld->getBasePtr();
2329 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2332 FI = FINode->getIndex();
2336 assert(FI != INT_MAX);
2337 if (!MFI->isFixedObjectIndex(FI))
2339 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2342 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2343 /// for tail call optimization. Targets which want to do tail call
2344 /// optimization should implement this function.
2346 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2347 CallingConv::ID CalleeCC,
2349 bool isCalleeStructRet,
2350 bool isCallerStructRet,
2351 const SmallVectorImpl<ISD::OutputArg> &Outs,
2352 const SmallVectorImpl<SDValue> &OutVals,
2353 const SmallVectorImpl<ISD::InputArg> &Ins,
2354 SelectionDAG& DAG) const {
2355 if (!IsTailCallConvention(CalleeCC) &&
2356 CalleeCC != CallingConv::C)
2359 // If -tailcallopt is specified, make fastcc functions tail-callable.
2360 const MachineFunction &MF = DAG.getMachineFunction();
2361 const Function *CallerF = DAG.getMachineFunction().getFunction();
2362 CallingConv::ID CallerCC = CallerF->getCallingConv();
2363 bool CCMatch = CallerCC == CalleeCC;
2365 if (GuaranteedTailCallOpt) {
2366 if (IsTailCallConvention(CalleeCC) && CCMatch)
2371 // Look for obvious safe cases to perform tail call optimization that do not
2372 // require ABI changes. This is what gcc calls sibcall.
2374 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2375 // emit a special epilogue.
2376 if (RegInfo->needsStackRealignment(MF))
2379 // Do not sibcall optimize vararg calls unless the call site is not passing
2381 if (isVarArg && !Outs.empty())
2384 // Also avoid sibcall optimization if either caller or callee uses struct
2385 // return semantics.
2386 if (isCalleeStructRet || isCallerStructRet)
2389 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2390 // Therefore if it's not used by the call it is not safe to optimize this into
2392 bool Unused = false;
2393 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2400 SmallVector<CCValAssign, 16> RVLocs;
2401 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2402 RVLocs, *DAG.getContext());
2403 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2404 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2405 CCValAssign &VA = RVLocs[i];
2406 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2411 // If the calling conventions do not match, then we'd better make sure the
2412 // results are returned in the same way as what the caller expects.
2414 SmallVector<CCValAssign, 16> RVLocs1;
2415 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2416 RVLocs1, *DAG.getContext());
2417 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2419 SmallVector<CCValAssign, 16> RVLocs2;
2420 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2421 RVLocs2, *DAG.getContext());
2422 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2424 if (RVLocs1.size() != RVLocs2.size())
2426 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2427 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2429 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2431 if (RVLocs1[i].isRegLoc()) {
2432 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2435 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2441 // If the callee takes no arguments then go on to check the results of the
2443 if (!Outs.empty()) {
2444 // Check if stack adjustment is needed. For now, do not do this if any
2445 // argument is passed on the stack.
2446 SmallVector<CCValAssign, 16> ArgLocs;
2447 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2448 ArgLocs, *DAG.getContext());
2449 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2450 if (CCInfo.getNextStackOffset()) {
2451 MachineFunction &MF = DAG.getMachineFunction();
2452 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2455 // Check if the arguments are already laid out in the right way as
2456 // the caller's fixed stack objects.
2457 MachineFrameInfo *MFI = MF.getFrameInfo();
2458 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2459 const X86InstrInfo *TII =
2460 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2461 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2462 CCValAssign &VA = ArgLocs[i];
2463 SDValue Arg = OutVals[i];
2464 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2465 if (VA.getLocInfo() == CCValAssign::Indirect)
2467 if (!VA.isRegLoc()) {
2468 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2475 // If the tailcall address may be in a register, then make sure it's
2476 // possible to register allocate for it. In 32-bit, the call address can
2477 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2478 // callee-saved registers are restored. These happen to be the same
2479 // registers used to pass 'inreg' arguments so watch out for those.
2480 if (!Subtarget->is64Bit() &&
2481 !isa<GlobalAddressSDNode>(Callee) &&
2482 !isa<ExternalSymbolSDNode>(Callee)) {
2483 unsigned NumInRegs = 0;
2484 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2485 CCValAssign &VA = ArgLocs[i];
2488 unsigned Reg = VA.getLocReg();
2491 case X86::EAX: case X86::EDX: case X86::ECX:
2492 if (++NumInRegs == 3)
2500 // An stdcall caller is expected to clean up its arguments; the callee
2501 // isn't going to do that.
2502 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2509 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2510 return X86::createFastISel(funcInfo);
2514 //===----------------------------------------------------------------------===//
2515 // Other Lowering Hooks
2516 //===----------------------------------------------------------------------===//
2518 static bool MayFoldLoad(SDValue Op) {
2519 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2522 static bool MayFoldIntoStore(SDValue Op) {
2523 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2526 static bool isTargetShuffle(unsigned Opcode) {
2528 default: return false;
2529 case X86ISD::PSHUFD:
2530 case X86ISD::PSHUFHW:
2531 case X86ISD::PSHUFLW:
2532 case X86ISD::SHUFPD:
2533 case X86ISD::PALIGN:
2534 case X86ISD::SHUFPS:
2535 case X86ISD::MOVLHPS:
2536 case X86ISD::MOVLHPD:
2537 case X86ISD::MOVHLPS:
2538 case X86ISD::MOVLPS:
2539 case X86ISD::MOVLPD:
2540 case X86ISD::MOVSHDUP:
2541 case X86ISD::MOVSLDUP:
2542 case X86ISD::MOVDDUP:
2545 case X86ISD::UNPCKLPS:
2546 case X86ISD::UNPCKLPD:
2547 case X86ISD::PUNPCKLWD:
2548 case X86ISD::PUNPCKLBW:
2549 case X86ISD::PUNPCKLDQ:
2550 case X86ISD::PUNPCKLQDQ:
2551 case X86ISD::UNPCKHPS:
2552 case X86ISD::UNPCKHPD:
2553 case X86ISD::PUNPCKHWD:
2554 case X86ISD::PUNPCKHBW:
2555 case X86ISD::PUNPCKHDQ:
2556 case X86ISD::PUNPCKHQDQ:
2562 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2563 SDValue V1, SelectionDAG &DAG) {
2565 default: llvm_unreachable("Unknown x86 shuffle node");
2566 case X86ISD::MOVSHDUP:
2567 case X86ISD::MOVSLDUP:
2568 case X86ISD::MOVDDUP:
2569 return DAG.getNode(Opc, dl, VT, V1);
2575 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2576 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2578 default: llvm_unreachable("Unknown x86 shuffle node");
2579 case X86ISD::PSHUFD:
2580 case X86ISD::PSHUFHW:
2581 case X86ISD::PSHUFLW:
2582 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2588 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2589 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2591 default: llvm_unreachable("Unknown x86 shuffle node");
2592 case X86ISD::PALIGN:
2593 case X86ISD::SHUFPD:
2594 case X86ISD::SHUFPS:
2595 return DAG.getNode(Opc, dl, VT, V1, V2,
2596 DAG.getConstant(TargetMask, MVT::i8));
2601 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2602 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2604 default: llvm_unreachable("Unknown x86 shuffle node");
2605 case X86ISD::MOVLHPS:
2606 case X86ISD::MOVLHPD:
2607 case X86ISD::MOVHLPS:
2608 case X86ISD::MOVLPS:
2609 case X86ISD::MOVLPD:
2612 case X86ISD::UNPCKLPS:
2613 case X86ISD::UNPCKLPD:
2614 case X86ISD::PUNPCKLWD:
2615 case X86ISD::PUNPCKLBW:
2616 case X86ISD::PUNPCKLDQ:
2617 case X86ISD::PUNPCKLQDQ:
2618 case X86ISD::UNPCKHPS:
2619 case X86ISD::UNPCKHPD:
2620 case X86ISD::PUNPCKHWD:
2621 case X86ISD::PUNPCKHBW:
2622 case X86ISD::PUNPCKHDQ:
2623 case X86ISD::PUNPCKHQDQ:
2624 return DAG.getNode(Opc, dl, VT, V1, V2);
2629 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2630 MachineFunction &MF = DAG.getMachineFunction();
2631 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2632 int ReturnAddrIndex = FuncInfo->getRAIndex();
2634 if (ReturnAddrIndex == 0) {
2635 // Set up a frame object for the return address.
2636 uint64_t SlotSize = TD->getPointerSize();
2637 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2639 FuncInfo->setRAIndex(ReturnAddrIndex);
2642 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2646 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2647 bool hasSymbolicDisplacement) {
2648 // Offset should fit into 32 bit immediate field.
2649 if (!isInt<32>(Offset))
2652 // If we don't have a symbolic displacement - we don't have any extra
2654 if (!hasSymbolicDisplacement)
2657 // FIXME: Some tweaks might be needed for medium code model.
2658 if (M != CodeModel::Small && M != CodeModel::Kernel)
2661 // For small code model we assume that latest object is 16MB before end of 31
2662 // bits boundary. We may also accept pretty large negative constants knowing
2663 // that all objects are in the positive half of address space.
2664 if (M == CodeModel::Small && Offset < 16*1024*1024)
2667 // For kernel code model we know that all object resist in the negative half
2668 // of 32bits address space. We may not accept negative offsets, since they may
2669 // be just off and we may accept pretty large positive ones.
2670 if (M == CodeModel::Kernel && Offset > 0)
2676 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2677 /// specific condition code, returning the condition code and the LHS/RHS of the
2678 /// comparison to make.
2679 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2680 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2682 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2683 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2684 // X > -1 -> X == 0, jump !sign.
2685 RHS = DAG.getConstant(0, RHS.getValueType());
2686 return X86::COND_NS;
2687 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2688 // X < 0 -> X == 0, jump on sign.
2690 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2692 RHS = DAG.getConstant(0, RHS.getValueType());
2693 return X86::COND_LE;
2697 switch (SetCCOpcode) {
2698 default: llvm_unreachable("Invalid integer condition!");
2699 case ISD::SETEQ: return X86::COND_E;
2700 case ISD::SETGT: return X86::COND_G;
2701 case ISD::SETGE: return X86::COND_GE;
2702 case ISD::SETLT: return X86::COND_L;
2703 case ISD::SETLE: return X86::COND_LE;
2704 case ISD::SETNE: return X86::COND_NE;
2705 case ISD::SETULT: return X86::COND_B;
2706 case ISD::SETUGT: return X86::COND_A;
2707 case ISD::SETULE: return X86::COND_BE;
2708 case ISD::SETUGE: return X86::COND_AE;
2712 // First determine if it is required or is profitable to flip the operands.
2714 // If LHS is a foldable load, but RHS is not, flip the condition.
2715 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2716 !ISD::isNON_EXTLoad(RHS.getNode())) {
2717 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2718 std::swap(LHS, RHS);
2721 switch (SetCCOpcode) {
2727 std::swap(LHS, RHS);
2731 // On a floating point condition, the flags are set as follows:
2733 // 0 | 0 | 0 | X > Y
2734 // 0 | 0 | 1 | X < Y
2735 // 1 | 0 | 0 | X == Y
2736 // 1 | 1 | 1 | unordered
2737 switch (SetCCOpcode) {
2738 default: llvm_unreachable("Condcode should be pre-legalized away");
2740 case ISD::SETEQ: return X86::COND_E;
2741 case ISD::SETOLT: // flipped
2743 case ISD::SETGT: return X86::COND_A;
2744 case ISD::SETOLE: // flipped
2746 case ISD::SETGE: return X86::COND_AE;
2747 case ISD::SETUGT: // flipped
2749 case ISD::SETLT: return X86::COND_B;
2750 case ISD::SETUGE: // flipped
2752 case ISD::SETLE: return X86::COND_BE;
2754 case ISD::SETNE: return X86::COND_NE;
2755 case ISD::SETUO: return X86::COND_P;
2756 case ISD::SETO: return X86::COND_NP;
2758 case ISD::SETUNE: return X86::COND_INVALID;
2762 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2763 /// code. Current x86 isa includes the following FP cmov instructions:
2764 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2765 static bool hasFPCMov(unsigned X86CC) {
2781 /// isFPImmLegal - Returns true if the target can instruction select the
2782 /// specified FP immediate natively. If false, the legalizer will
2783 /// materialize the FP immediate as a load from a constant pool.
2784 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2785 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2786 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2792 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2793 /// the specified range (L, H].
2794 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2795 return (Val < 0) || (Val >= Low && Val < Hi);
2798 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2799 /// specified value.
2800 static bool isUndefOrEqual(int Val, int CmpVal) {
2801 if (Val < 0 || Val == CmpVal)
2806 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2807 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2808 /// the second operand.
2809 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2810 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2811 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2812 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2813 return (Mask[0] < 2 && Mask[1] < 2);
2817 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2818 SmallVector<int, 8> M;
2820 return ::isPSHUFDMask(M, N->getValueType(0));
2823 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2824 /// is suitable for input to PSHUFHW.
2825 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2826 if (VT != MVT::v8i16)
2829 // Lower quadword copied in order or undef.
2830 for (int i = 0; i != 4; ++i)
2831 if (Mask[i] >= 0 && Mask[i] != i)
2834 // Upper quadword shuffled.
2835 for (int i = 4; i != 8; ++i)
2836 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2842 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2843 SmallVector<int, 8> M;
2845 return ::isPSHUFHWMask(M, N->getValueType(0));
2848 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2849 /// is suitable for input to PSHUFLW.
2850 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2851 if (VT != MVT::v8i16)
2854 // Upper quadword copied in order.
2855 for (int i = 4; i != 8; ++i)
2856 if (Mask[i] >= 0 && Mask[i] != i)
2859 // Lower quadword shuffled.
2860 for (int i = 0; i != 4; ++i)
2867 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2868 SmallVector<int, 8> M;
2870 return ::isPSHUFLWMask(M, N->getValueType(0));
2873 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2874 /// is suitable for input to PALIGNR.
2875 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2877 int i, e = VT.getVectorNumElements();
2879 // Do not handle v2i64 / v2f64 shuffles with palignr.
2880 if (e < 4 || !hasSSSE3)
2883 for (i = 0; i != e; ++i)
2887 // All undef, not a palignr.
2891 // Determine if it's ok to perform a palignr with only the LHS, since we
2892 // don't have access to the actual shuffle elements to see if RHS is undef.
2893 bool Unary = Mask[i] < (int)e;
2894 bool NeedsUnary = false;
2896 int s = Mask[i] - i;
2898 // Check the rest of the elements to see if they are consecutive.
2899 for (++i; i != e; ++i) {
2904 Unary = Unary && (m < (int)e);
2905 NeedsUnary = NeedsUnary || (m < s);
2907 if (NeedsUnary && !Unary)
2909 if (Unary && m != ((s+i) & (e-1)))
2911 if (!Unary && m != (s+i))
2917 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2918 SmallVector<int, 8> M;
2920 return ::isPALIGNRMask(M, N->getValueType(0), true);
2923 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2924 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2925 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2926 int NumElems = VT.getVectorNumElements();
2927 if (NumElems != 2 && NumElems != 4)
2930 int Half = NumElems / 2;
2931 for (int i = 0; i < Half; ++i)
2932 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2934 for (int i = Half; i < NumElems; ++i)
2935 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2941 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2942 SmallVector<int, 8> M;
2944 return ::isSHUFPMask(M, N->getValueType(0));
2947 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2948 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2949 /// half elements to come from vector 1 (which would equal the dest.) and
2950 /// the upper half to come from vector 2.
2951 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2952 int NumElems = VT.getVectorNumElements();
2954 if (NumElems != 2 && NumElems != 4)
2957 int Half = NumElems / 2;
2958 for (int i = 0; i < Half; ++i)
2959 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2961 for (int i = Half; i < NumElems; ++i)
2962 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2967 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2968 SmallVector<int, 8> M;
2970 return isCommutedSHUFPMask(M, N->getValueType(0));
2973 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2974 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2975 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2976 if (N->getValueType(0).getVectorNumElements() != 4)
2979 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2980 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2981 isUndefOrEqual(N->getMaskElt(1), 7) &&
2982 isUndefOrEqual(N->getMaskElt(2), 2) &&
2983 isUndefOrEqual(N->getMaskElt(3), 3);
2986 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2987 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2989 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2990 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2995 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2996 isUndefOrEqual(N->getMaskElt(1), 3) &&
2997 isUndefOrEqual(N->getMaskElt(2), 2) &&
2998 isUndefOrEqual(N->getMaskElt(3), 3);
3001 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3002 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3003 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3004 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3006 if (NumElems != 2 && NumElems != 4)
3009 for (unsigned i = 0; i < NumElems/2; ++i)
3010 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3013 for (unsigned i = NumElems/2; i < NumElems; ++i)
3014 if (!isUndefOrEqual(N->getMaskElt(i), i))
3020 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3021 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3022 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3023 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3025 if (NumElems != 2 && NumElems != 4)
3028 for (unsigned i = 0; i < NumElems/2; ++i)
3029 if (!isUndefOrEqual(N->getMaskElt(i), i))
3032 for (unsigned i = 0; i < NumElems/2; ++i)
3033 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3039 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3040 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3041 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3042 bool V2IsSplat = false) {
3043 int NumElts = VT.getVectorNumElements();
3044 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3047 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3049 int BitI1 = Mask[i+1];
3050 if (!isUndefOrEqual(BitI, j))
3053 if (!isUndefOrEqual(BitI1, NumElts))
3056 if (!isUndefOrEqual(BitI1, j + NumElts))
3063 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3064 SmallVector<int, 8> M;
3066 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3069 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3070 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3071 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3072 bool V2IsSplat = false) {
3073 int NumElts = VT.getVectorNumElements();
3074 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3077 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3079 int BitI1 = Mask[i+1];
3080 if (!isUndefOrEqual(BitI, j + NumElts/2))
3083 if (isUndefOrEqual(BitI1, NumElts))
3086 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3093 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3094 SmallVector<int, 8> M;
3096 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3099 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3100 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3102 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3103 int NumElems = VT.getVectorNumElements();
3104 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3107 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3109 int BitI1 = Mask[i+1];
3110 if (!isUndefOrEqual(BitI, j))
3112 if (!isUndefOrEqual(BitI1, j))
3118 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3119 SmallVector<int, 8> M;
3121 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3124 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3125 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3127 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3128 int NumElems = VT.getVectorNumElements();
3129 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3132 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3134 int BitI1 = Mask[i+1];
3135 if (!isUndefOrEqual(BitI, j))
3137 if (!isUndefOrEqual(BitI1, j))
3143 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3144 SmallVector<int, 8> M;
3146 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3149 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3150 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3151 /// MOVSD, and MOVD, i.e. setting the lowest element.
3152 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3153 if (VT.getVectorElementType().getSizeInBits() < 32)
3156 int NumElts = VT.getVectorNumElements();
3158 if (!isUndefOrEqual(Mask[0], NumElts))
3161 for (int i = 1; i < NumElts; ++i)
3162 if (!isUndefOrEqual(Mask[i], i))
3168 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3169 SmallVector<int, 8> M;
3171 return ::isMOVLMask(M, N->getValueType(0));
3174 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3175 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3176 /// element of vector 2 and the other elements to come from vector 1 in order.
3177 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3178 bool V2IsSplat = false, bool V2IsUndef = false) {
3179 int NumOps = VT.getVectorNumElements();
3180 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3183 if (!isUndefOrEqual(Mask[0], 0))
3186 for (int i = 1; i < NumOps; ++i)
3187 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3188 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3189 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3195 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3196 bool V2IsUndef = false) {
3197 SmallVector<int, 8> M;
3199 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3202 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3203 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3204 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3205 if (N->getValueType(0).getVectorNumElements() != 4)
3208 // Expect 1, 1, 3, 3
3209 for (unsigned i = 0; i < 2; ++i) {
3210 int Elt = N->getMaskElt(i);
3211 if (Elt >= 0 && Elt != 1)
3216 for (unsigned i = 2; i < 4; ++i) {
3217 int Elt = N->getMaskElt(i);
3218 if (Elt >= 0 && Elt != 3)
3223 // Don't use movshdup if it can be done with a shufps.
3224 // FIXME: verify that matching u, u, 3, 3 is what we want.
3228 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3229 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3230 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3231 if (N->getValueType(0).getVectorNumElements() != 4)
3234 // Expect 0, 0, 2, 2
3235 for (unsigned i = 0; i < 2; ++i)
3236 if (N->getMaskElt(i) > 0)
3240 for (unsigned i = 2; i < 4; ++i) {
3241 int Elt = N->getMaskElt(i);
3242 if (Elt >= 0 && Elt != 2)
3247 // Don't use movsldup if it can be done with a shufps.
3251 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3252 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3253 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3254 int e = N->getValueType(0).getVectorNumElements() / 2;
3256 for (int i = 0; i < e; ++i)
3257 if (!isUndefOrEqual(N->getMaskElt(i), i))
3259 for (int i = 0; i < e; ++i)
3260 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3265 /// isVEXTRACTF128Index - Return true if the specified
3266 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3267 /// suitable for input to VEXTRACTF128.
3268 bool X86::isVEXTRACTF128Index(SDNode *N) {
3269 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3272 // The index should be aligned on a 128-bit boundary.
3274 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3276 unsigned VL = N->getValueType(0).getVectorNumElements();
3277 unsigned VBits = N->getValueType(0).getSizeInBits();
3278 unsigned ElSize = VBits / VL;
3279 bool Result = (Index * ElSize) % 128 == 0;
3284 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3285 /// operand specifies a subvector insert that is suitable for input to
3287 bool X86::isVINSERTF128Index(SDNode *N) {
3288 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3291 // The index should be aligned on a 128-bit boundary.
3293 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3295 unsigned VL = N->getValueType(0).getVectorNumElements();
3296 unsigned VBits = N->getValueType(0).getSizeInBits();
3297 unsigned ElSize = VBits / VL;
3298 bool Result = (Index * ElSize) % 128 == 0;
3303 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3304 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3305 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3306 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3307 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3309 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3311 for (int i = 0; i < NumOperands; ++i) {
3312 int Val = SVOp->getMaskElt(NumOperands-i-1);
3313 if (Val < 0) Val = 0;
3314 if (Val >= NumOperands) Val -= NumOperands;
3316 if (i != NumOperands - 1)
3322 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3323 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3324 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3325 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3327 // 8 nodes, but we only care about the last 4.
3328 for (unsigned i = 7; i >= 4; --i) {
3329 int Val = SVOp->getMaskElt(i);
3338 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3339 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3340 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3341 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3343 // 8 nodes, but we only care about the first 4.
3344 for (int i = 3; i >= 0; --i) {
3345 int Val = SVOp->getMaskElt(i);
3354 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3355 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3356 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3357 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3358 EVT VVT = N->getValueType(0);
3359 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3363 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3364 Val = SVOp->getMaskElt(i);
3368 return (Val - i) * EltSize;
3371 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3372 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3374 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3375 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3376 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3379 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3381 EVT VecVT = N->getOperand(0).getValueType();
3382 EVT ElVT = VecVT.getVectorElementType();
3384 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3386 return Index / NumElemsPerChunk;
3389 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3390 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3392 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3393 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3394 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3397 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3399 EVT VecVT = N->getValueType(0);
3400 EVT ElVT = VecVT.getVectorElementType();
3402 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3404 return Index / NumElemsPerChunk;
3407 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3409 bool X86::isZeroNode(SDValue Elt) {
3410 return ((isa<ConstantSDNode>(Elt) &&
3411 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3412 (isa<ConstantFPSDNode>(Elt) &&
3413 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3416 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3417 /// their permute mask.
3418 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3419 SelectionDAG &DAG) {
3420 EVT VT = SVOp->getValueType(0);
3421 unsigned NumElems = VT.getVectorNumElements();
3422 SmallVector<int, 8> MaskVec;
3424 for (unsigned i = 0; i != NumElems; ++i) {
3425 int idx = SVOp->getMaskElt(i);
3427 MaskVec.push_back(idx);
3428 else if (idx < (int)NumElems)
3429 MaskVec.push_back(idx + NumElems);
3431 MaskVec.push_back(idx - NumElems);
3433 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3434 SVOp->getOperand(0), &MaskVec[0]);
3437 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3438 /// the two vector operands have swapped position.
3439 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3440 unsigned NumElems = VT.getVectorNumElements();
3441 for (unsigned i = 0; i != NumElems; ++i) {
3445 else if (idx < (int)NumElems)
3446 Mask[i] = idx + NumElems;
3448 Mask[i] = idx - NumElems;
3452 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3453 /// match movhlps. The lower half elements should come from upper half of
3454 /// V1 (and in order), and the upper half elements should come from the upper
3455 /// half of V2 (and in order).
3456 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3457 if (Op->getValueType(0).getVectorNumElements() != 4)
3459 for (unsigned i = 0, e = 2; i != e; ++i)
3460 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3462 for (unsigned i = 2; i != 4; ++i)
3463 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3468 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3469 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3471 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3472 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3474 N = N->getOperand(0).getNode();
3475 if (!ISD::isNON_EXTLoad(N))
3478 *LD = cast<LoadSDNode>(N);
3482 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3483 /// match movlp{s|d}. The lower half elements should come from lower half of
3484 /// V1 (and in order), and the upper half elements should come from the upper
3485 /// half of V2 (and in order). And since V1 will become the source of the
3486 /// MOVLP, it must be either a vector load or a scalar load to vector.
3487 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3488 ShuffleVectorSDNode *Op) {
3489 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3491 // Is V2 is a vector load, don't do this transformation. We will try to use
3492 // load folding shufps op.
3493 if (ISD::isNON_EXTLoad(V2))
3496 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3498 if (NumElems != 2 && NumElems != 4)
3500 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3501 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3503 for (unsigned i = NumElems/2; i != NumElems; ++i)
3504 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3509 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3511 static bool isSplatVector(SDNode *N) {
3512 if (N->getOpcode() != ISD::BUILD_VECTOR)
3515 SDValue SplatValue = N->getOperand(0);
3516 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3517 if (N->getOperand(i) != SplatValue)
3522 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3523 /// to an zero vector.
3524 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3525 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3526 SDValue V1 = N->getOperand(0);
3527 SDValue V2 = N->getOperand(1);
3528 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3529 for (unsigned i = 0; i != NumElems; ++i) {
3530 int Idx = N->getMaskElt(i);
3531 if (Idx >= (int)NumElems) {
3532 unsigned Opc = V2.getOpcode();
3533 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3535 if (Opc != ISD::BUILD_VECTOR ||
3536 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3538 } else if (Idx >= 0) {
3539 unsigned Opc = V1.getOpcode();
3540 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3542 if (Opc != ISD::BUILD_VECTOR ||
3543 !X86::isZeroNode(V1.getOperand(Idx)))
3550 /// getZeroVector - Returns a vector of specified type with all zero elements.
3552 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3554 assert(VT.isVector() && "Expected a vector type");
3556 // Always build SSE zero vectors as <4 x i32> bitcasted
3557 // to their dest type. This ensures they get CSE'd.
3559 if (VT.getSizeInBits() == 128) { // SSE
3560 if (HasSSE2) { // SSE2
3561 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3562 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3564 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3565 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3567 } else if (VT.getSizeInBits() == 256) { // AVX
3568 // 256-bit logic and arithmetic instructions in AVX are
3569 // all floating-point, no support for integer ops. Default
3570 // to emitting fp zeroed vectors then.
3571 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3572 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3573 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3575 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3578 /// getOnesVector - Returns a vector of specified type with all bits set.
3580 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3581 assert(VT.isVector() && "Expected a vector type");
3583 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3584 // type. This ensures they get CSE'd.
3585 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3587 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3588 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3592 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3593 /// that point to V2 points to its first element.
3594 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3595 EVT VT = SVOp->getValueType(0);
3596 unsigned NumElems = VT.getVectorNumElements();
3598 bool Changed = false;
3599 SmallVector<int, 8> MaskVec;
3600 SVOp->getMask(MaskVec);
3602 for (unsigned i = 0; i != NumElems; ++i) {
3603 if (MaskVec[i] > (int)NumElems) {
3604 MaskVec[i] = NumElems;
3609 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3610 SVOp->getOperand(1), &MaskVec[0]);
3611 return SDValue(SVOp, 0);
3614 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3615 /// operation of specified width.
3616 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3618 unsigned NumElems = VT.getVectorNumElements();
3619 SmallVector<int, 8> Mask;
3620 Mask.push_back(NumElems);
3621 for (unsigned i = 1; i != NumElems; ++i)
3623 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3626 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3627 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3629 unsigned NumElems = VT.getVectorNumElements();
3630 SmallVector<int, 8> Mask;
3631 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3633 Mask.push_back(i + NumElems);
3635 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3638 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3639 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3641 unsigned NumElems = VT.getVectorNumElements();
3642 unsigned Half = NumElems/2;
3643 SmallVector<int, 8> Mask;
3644 for (unsigned i = 0; i != Half; ++i) {
3645 Mask.push_back(i + Half);
3646 Mask.push_back(i + NumElems + Half);
3648 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3651 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3652 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3653 EVT PVT = MVT::v4f32;
3654 EVT VT = SV->getValueType(0);
3655 DebugLoc dl = SV->getDebugLoc();
3656 SDValue V1 = SV->getOperand(0);
3657 int NumElems = VT.getVectorNumElements();
3658 int EltNo = SV->getSplatIndex();
3660 // unpack elements to the correct location
3661 while (NumElems > 4) {
3662 if (EltNo < NumElems/2) {
3663 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3665 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3666 EltNo -= NumElems/2;
3671 // Perform the splat.
3672 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3673 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3674 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3675 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3678 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3679 /// vector of zero or undef vector. This produces a shuffle where the low
3680 /// element of V2 is swizzled into the zero/undef vector, landing at element
3681 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3682 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3683 bool isZero, bool HasSSE2,
3684 SelectionDAG &DAG) {
3685 EVT VT = V2.getValueType();
3687 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3688 unsigned NumElems = VT.getVectorNumElements();
3689 SmallVector<int, 16> MaskVec;
3690 for (unsigned i = 0; i != NumElems; ++i)
3691 // If this is the insertion idx, put the low elt of V2 here.
3692 MaskVec.push_back(i == Idx ? NumElems : i);
3693 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3696 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3697 /// element of the result of the vector shuffle.
3698 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3701 return SDValue(); // Limit search depth.
3703 SDValue V = SDValue(N, 0);
3704 EVT VT = V.getValueType();
3705 unsigned Opcode = V.getOpcode();
3707 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3708 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3709 Index = SV->getMaskElt(Index);
3712 return DAG.getUNDEF(VT.getVectorElementType());
3714 int NumElems = VT.getVectorNumElements();
3715 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3716 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3719 // Recurse into target specific vector shuffles to find scalars.
3720 if (isTargetShuffle(Opcode)) {
3721 int NumElems = VT.getVectorNumElements();
3722 SmallVector<unsigned, 16> ShuffleMask;
3726 case X86ISD::SHUFPS:
3727 case X86ISD::SHUFPD:
3728 ImmN = N->getOperand(N->getNumOperands()-1);
3729 DecodeSHUFPSMask(NumElems,
3730 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3733 case X86ISD::PUNPCKHBW:
3734 case X86ISD::PUNPCKHWD:
3735 case X86ISD::PUNPCKHDQ:
3736 case X86ISD::PUNPCKHQDQ:
3737 DecodePUNPCKHMask(NumElems, ShuffleMask);
3739 case X86ISD::UNPCKHPS:
3740 case X86ISD::UNPCKHPD:
3741 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3743 case X86ISD::PUNPCKLBW:
3744 case X86ISD::PUNPCKLWD:
3745 case X86ISD::PUNPCKLDQ:
3746 case X86ISD::PUNPCKLQDQ:
3747 DecodePUNPCKLMask(NumElems, ShuffleMask);
3749 case X86ISD::UNPCKLPS:
3750 case X86ISD::UNPCKLPD:
3751 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3753 case X86ISD::MOVHLPS:
3754 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3756 case X86ISD::MOVLHPS:
3757 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3759 case X86ISD::PSHUFD:
3760 ImmN = N->getOperand(N->getNumOperands()-1);
3761 DecodePSHUFMask(NumElems,
3762 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3765 case X86ISD::PSHUFHW:
3766 ImmN = N->getOperand(N->getNumOperands()-1);
3767 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3770 case X86ISD::PSHUFLW:
3771 ImmN = N->getOperand(N->getNumOperands()-1);
3772 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3776 case X86ISD::MOVSD: {
3777 // The index 0 always comes from the first element of the second source,
3778 // this is why MOVSS and MOVSD are used in the first place. The other
3779 // elements come from the other positions of the first source vector.
3780 unsigned OpNum = (Index == 0) ? 1 : 0;
3781 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3785 assert("not implemented for target shuffle node");
3789 Index = ShuffleMask[Index];
3791 return DAG.getUNDEF(VT.getVectorElementType());
3793 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3794 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3798 // Actual nodes that may contain scalar elements
3799 if (Opcode == ISD::BITCAST) {
3800 V = V.getOperand(0);
3801 EVT SrcVT = V.getValueType();
3802 unsigned NumElems = VT.getVectorNumElements();
3804 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3808 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3809 return (Index == 0) ? V.getOperand(0)
3810 : DAG.getUNDEF(VT.getVectorElementType());
3812 if (V.getOpcode() == ISD::BUILD_VECTOR)
3813 return V.getOperand(Index);
3818 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3819 /// shuffle operation which come from a consecutively from a zero. The
3820 /// search can start in two diferent directions, from left or right.
3822 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3823 bool ZerosFromLeft, SelectionDAG &DAG) {
3826 while (i < NumElems) {
3827 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3828 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3829 if (!(Elt.getNode() &&
3830 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3838 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3839 /// MaskE correspond consecutively to elements from one of the vector operands,
3840 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3842 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3843 int OpIdx, int NumElems, unsigned &OpNum) {
3844 bool SeenV1 = false;
3845 bool SeenV2 = false;
3847 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3848 int Idx = SVOp->getMaskElt(i);
3849 // Ignore undef indicies
3858 // Only accept consecutive elements from the same vector
3859 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3863 OpNum = SeenV1 ? 0 : 1;
3867 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3868 /// logical left shift of a vector.
3869 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3870 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3871 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3872 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3873 false /* check zeros from right */, DAG);
3879 // Considering the elements in the mask that are not consecutive zeros,
3880 // check if they consecutively come from only one of the source vectors.
3882 // V1 = {X, A, B, C} 0
3884 // vector_shuffle V1, V2 <1, 2, 3, X>
3886 if (!isShuffleMaskConsecutive(SVOp,
3887 0, // Mask Start Index
3888 NumElems-NumZeros-1, // Mask End Index
3889 NumZeros, // Where to start looking in the src vector
3890 NumElems, // Number of elements in vector
3891 OpSrc)) // Which source operand ?
3896 ShVal = SVOp->getOperand(OpSrc);
3900 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3901 /// logical left shift of a vector.
3902 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3903 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3904 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3905 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3906 true /* check zeros from left */, DAG);
3912 // Considering the elements in the mask that are not consecutive zeros,
3913 // check if they consecutively come from only one of the source vectors.
3915 // 0 { A, B, X, X } = V2
3917 // vector_shuffle V1, V2 <X, X, 4, 5>
3919 if (!isShuffleMaskConsecutive(SVOp,
3920 NumZeros, // Mask Start Index
3921 NumElems-1, // Mask End Index
3922 0, // Where to start looking in the src vector
3923 NumElems, // Number of elements in vector
3924 OpSrc)) // Which source operand ?
3929 ShVal = SVOp->getOperand(OpSrc);
3933 /// isVectorShift - Returns true if the shuffle can be implemented as a
3934 /// logical left or right shift of a vector.
3935 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3936 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3937 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3938 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3944 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3946 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3947 unsigned NumNonZero, unsigned NumZero,
3949 const TargetLowering &TLI) {
3953 DebugLoc dl = Op.getDebugLoc();
3956 for (unsigned i = 0; i < 16; ++i) {
3957 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3958 if (ThisIsNonZero && First) {
3960 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3962 V = DAG.getUNDEF(MVT::v8i16);
3967 SDValue ThisElt(0, 0), LastElt(0, 0);
3968 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3969 if (LastIsNonZero) {
3970 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3971 MVT::i16, Op.getOperand(i-1));
3973 if (ThisIsNonZero) {
3974 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3975 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3976 ThisElt, DAG.getConstant(8, MVT::i8));
3978 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3982 if (ThisElt.getNode())
3983 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3984 DAG.getIntPtrConstant(i/2));
3988 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3991 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3993 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3994 unsigned NumNonZero, unsigned NumZero,
3996 const TargetLowering &TLI) {
4000 DebugLoc dl = Op.getDebugLoc();
4003 for (unsigned i = 0; i < 8; ++i) {
4004 bool isNonZero = (NonZeros & (1 << i)) != 0;
4008 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4010 V = DAG.getUNDEF(MVT::v8i16);
4013 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4014 MVT::v8i16, V, Op.getOperand(i),
4015 DAG.getIntPtrConstant(i));
4022 /// getVShift - Return a vector logical shift node.
4024 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4025 unsigned NumBits, SelectionDAG &DAG,
4026 const TargetLowering &TLI, DebugLoc dl) {
4027 EVT ShVT = MVT::v2i64;
4028 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4029 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4030 return DAG.getNode(ISD::BITCAST, dl, VT,
4031 DAG.getNode(Opc, dl, ShVT, SrcOp,
4032 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4036 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4037 SelectionDAG &DAG) const {
4039 // Check if the scalar load can be widened into a vector load. And if
4040 // the address is "base + cst" see if the cst can be "absorbed" into
4041 // the shuffle mask.
4042 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4043 SDValue Ptr = LD->getBasePtr();
4044 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4046 EVT PVT = LD->getValueType(0);
4047 if (PVT != MVT::i32 && PVT != MVT::f32)
4052 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4053 FI = FINode->getIndex();
4055 } else if (Ptr.getOpcode() == ISD::ADD &&
4056 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4057 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4058 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4059 Offset = Ptr.getConstantOperandVal(1);
4060 Ptr = Ptr.getOperand(0);
4065 SDValue Chain = LD->getChain();
4066 // Make sure the stack object alignment is at least 16.
4067 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4068 if (DAG.InferPtrAlignment(Ptr) < 16) {
4069 if (MFI->isFixedObjectIndex(FI)) {
4070 // Can't change the alignment. FIXME: It's possible to compute
4071 // the exact stack offset and reference FI + adjust offset instead.
4072 // If someone *really* cares about this. That's the way to implement it.
4075 MFI->setObjectAlignment(FI, 16);
4079 // (Offset % 16) must be multiple of 4. Then address is then
4080 // Ptr + (Offset & ~15).
4083 if ((Offset % 16) & 3)
4085 int64_t StartOffset = Offset & ~15;
4087 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4088 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4090 int EltNo = (Offset - StartOffset) >> 2;
4091 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4092 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4093 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4094 LD->getPointerInfo().getWithOffset(StartOffset),
4096 // Canonicalize it to a v4i32 shuffle.
4097 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4098 return DAG.getNode(ISD::BITCAST, dl, VT,
4099 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4100 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4106 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4107 /// vector of type 'VT', see if the elements can be replaced by a single large
4108 /// load which has the same value as a build_vector whose operands are 'elts'.
4110 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4112 /// FIXME: we'd also like to handle the case where the last elements are zero
4113 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4114 /// There's even a handy isZeroNode for that purpose.
4115 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4116 DebugLoc &DL, SelectionDAG &DAG) {
4117 EVT EltVT = VT.getVectorElementType();
4118 unsigned NumElems = Elts.size();
4120 LoadSDNode *LDBase = NULL;
4121 unsigned LastLoadedElt = -1U;
4123 // For each element in the initializer, see if we've found a load or an undef.
4124 // If we don't find an initial load element, or later load elements are
4125 // non-consecutive, bail out.
4126 for (unsigned i = 0; i < NumElems; ++i) {
4127 SDValue Elt = Elts[i];
4129 if (!Elt.getNode() ||
4130 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4133 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4135 LDBase = cast<LoadSDNode>(Elt.getNode());
4139 if (Elt.getOpcode() == ISD::UNDEF)
4142 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4143 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4148 // If we have found an entire vector of loads and undefs, then return a large
4149 // load of the entire vector width starting at the base pointer. If we found
4150 // consecutive loads for the low half, generate a vzext_load node.
4151 if (LastLoadedElt == NumElems - 1) {
4152 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4153 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4154 LDBase->getPointerInfo(),
4155 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4156 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4157 LDBase->getPointerInfo(),
4158 LDBase->isVolatile(), LDBase->isNonTemporal(),
4159 LDBase->getAlignment());
4160 } else if (NumElems == 4 && LastLoadedElt == 1) {
4161 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4162 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4163 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4165 LDBase->getMemOperand());
4166 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4172 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4173 DebugLoc dl = Op.getDebugLoc();
4174 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4175 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4176 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4177 // is present, so AllOnes is ignored.
4178 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4179 (Op.getValueType().getSizeInBits() != 256 &&
4180 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4181 // Canonicalize this to <4 x i32> (SSE) to
4182 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4183 // eliminated on x86-32 hosts.
4184 if (Op.getValueType() == MVT::v4i32)
4187 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4188 return getOnesVector(Op.getValueType(), DAG, dl);
4189 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4192 EVT VT = Op.getValueType();
4193 EVT ExtVT = VT.getVectorElementType();
4194 unsigned EVTBits = ExtVT.getSizeInBits();
4196 unsigned NumElems = Op.getNumOperands();
4197 unsigned NumZero = 0;
4198 unsigned NumNonZero = 0;
4199 unsigned NonZeros = 0;
4200 bool IsAllConstants = true;
4201 SmallSet<SDValue, 8> Values;
4202 for (unsigned i = 0; i < NumElems; ++i) {
4203 SDValue Elt = Op.getOperand(i);
4204 if (Elt.getOpcode() == ISD::UNDEF)
4207 if (Elt.getOpcode() != ISD::Constant &&
4208 Elt.getOpcode() != ISD::ConstantFP)
4209 IsAllConstants = false;
4210 if (X86::isZeroNode(Elt))
4213 NonZeros |= (1 << i);
4218 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4219 if (NumNonZero == 0)
4220 return DAG.getUNDEF(VT);
4222 // Special case for single non-zero, non-undef, element.
4223 if (NumNonZero == 1) {
4224 unsigned Idx = CountTrailingZeros_32(NonZeros);
4225 SDValue Item = Op.getOperand(Idx);
4227 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4228 // the value are obviously zero, truncate the value to i32 and do the
4229 // insertion that way. Only do this if the value is non-constant or if the
4230 // value is a constant being inserted into element 0. It is cheaper to do
4231 // a constant pool load than it is to do a movd + shuffle.
4232 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4233 (!IsAllConstants || Idx == 0)) {
4234 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4236 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4237 EVT VecVT = MVT::v4i32;
4238 unsigned VecElts = 4;
4240 // Truncate the value (which may itself be a constant) to i32, and
4241 // convert it to a vector with movd (S2V+shuffle to zero extend).
4242 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4243 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4244 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4245 Subtarget->hasSSE2(), DAG);
4247 // Now we have our 32-bit value zero extended in the low element of
4248 // a vector. If Idx != 0, swizzle it into place.
4250 SmallVector<int, 4> Mask;
4251 Mask.push_back(Idx);
4252 for (unsigned i = 1; i != VecElts; ++i)
4254 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4255 DAG.getUNDEF(Item.getValueType()),
4258 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4262 // If we have a constant or non-constant insertion into the low element of
4263 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4264 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4265 // depending on what the source datatype is.
4268 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4269 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4270 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4271 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4272 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4273 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4275 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4276 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4277 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4278 EVT MiddleVT = MVT::v4i32;
4279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4280 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4281 Subtarget->hasSSE2(), DAG);
4282 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4286 // Is it a vector logical left shift?
4287 if (NumElems == 2 && Idx == 1 &&
4288 X86::isZeroNode(Op.getOperand(0)) &&
4289 !X86::isZeroNode(Op.getOperand(1))) {
4290 unsigned NumBits = VT.getSizeInBits();
4291 return getVShift(true, VT,
4292 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4293 VT, Op.getOperand(1)),
4294 NumBits/2, DAG, *this, dl);
4297 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4300 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4301 // is a non-constant being inserted into an element other than the low one,
4302 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4303 // movd/movss) to move this into the low element, then shuffle it into
4305 if (EVTBits == 32) {
4306 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4308 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4309 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4310 Subtarget->hasSSE2(), DAG);
4311 SmallVector<int, 8> MaskVec;
4312 for (unsigned i = 0; i < NumElems; i++)
4313 MaskVec.push_back(i == Idx ? 0 : 1);
4314 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4318 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4319 if (Values.size() == 1) {
4320 if (EVTBits == 32) {
4321 // Instead of a shuffle like this:
4322 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4323 // Check if it's possible to issue this instead.
4324 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4325 unsigned Idx = CountTrailingZeros_32(NonZeros);
4326 SDValue Item = Op.getOperand(Idx);
4327 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4328 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4333 // A vector full of immediates; various special cases are already
4334 // handled, so this is best done with a single constant-pool load.
4338 // Let legalizer expand 2-wide build_vectors.
4339 if (EVTBits == 64) {
4340 if (NumNonZero == 1) {
4341 // One half is zero or undef.
4342 unsigned Idx = CountTrailingZeros_32(NonZeros);
4343 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4344 Op.getOperand(Idx));
4345 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4346 Subtarget->hasSSE2(), DAG);
4351 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4352 if (EVTBits == 8 && NumElems == 16) {
4353 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4355 if (V.getNode()) return V;
4358 if (EVTBits == 16 && NumElems == 8) {
4359 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4361 if (V.getNode()) return V;
4364 // If element VT is == 32 bits, turn it into a number of shuffles.
4365 SmallVector<SDValue, 8> V;
4367 if (NumElems == 4 && NumZero > 0) {
4368 for (unsigned i = 0; i < 4; ++i) {
4369 bool isZero = !(NonZeros & (1 << i));
4371 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4373 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4376 for (unsigned i = 0; i < 2; ++i) {
4377 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4380 V[i] = V[i*2]; // Must be a zero vector.
4383 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4386 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4389 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4394 SmallVector<int, 8> MaskVec;
4395 bool Reverse = (NonZeros & 0x3) == 2;
4396 for (unsigned i = 0; i < 2; ++i)
4397 MaskVec.push_back(Reverse ? 1-i : i);
4398 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4399 for (unsigned i = 0; i < 2; ++i)
4400 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4401 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4404 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4405 // Check for a build vector of consecutive loads.
4406 for (unsigned i = 0; i < NumElems; ++i)
4407 V[i] = Op.getOperand(i);
4409 // Check for elements which are consecutive loads.
4410 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4414 // For SSE 4.1, use insertps to put the high elements into the low element.
4415 if (getSubtarget()->hasSSE41()) {
4417 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4418 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4420 Result = DAG.getUNDEF(VT);
4422 for (unsigned i = 1; i < NumElems; ++i) {
4423 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4424 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4425 Op.getOperand(i), DAG.getIntPtrConstant(i));
4430 // Otherwise, expand into a number of unpckl*, start by extending each of
4431 // our (non-undef) elements to the full vector width with the element in the
4432 // bottom slot of the vector (which generates no code for SSE).
4433 for (unsigned i = 0; i < NumElems; ++i) {
4434 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4435 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4437 V[i] = DAG.getUNDEF(VT);
4440 // Next, we iteratively mix elements, e.g. for v4f32:
4441 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4442 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4443 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4444 unsigned EltStride = NumElems >> 1;
4445 while (EltStride != 0) {
4446 for (unsigned i = 0; i < EltStride; ++i) {
4447 // If V[i+EltStride] is undef and this is the first round of mixing,
4448 // then it is safe to just drop this shuffle: V[i] is already in the
4449 // right place, the one element (since it's the first round) being
4450 // inserted as undef can be dropped. This isn't safe for successive
4451 // rounds because they will permute elements within both vectors.
4452 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4453 EltStride == NumElems/2)
4456 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4466 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4467 // We support concatenate two MMX registers and place them in a MMX
4468 // register. This is better than doing a stack convert.
4469 DebugLoc dl = Op.getDebugLoc();
4470 EVT ResVT = Op.getValueType();
4471 assert(Op.getNumOperands() == 2);
4472 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4473 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4475 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4476 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4477 InVec = Op.getOperand(1);
4478 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4479 unsigned NumElts = ResVT.getVectorNumElements();
4480 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4481 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4482 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4484 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4485 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4486 Mask[0] = 0; Mask[1] = 2;
4487 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4489 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4492 // v8i16 shuffles - Prefer shuffles in the following order:
4493 // 1. [all] pshuflw, pshufhw, optional move
4494 // 2. [ssse3] 1 x pshufb
4495 // 3. [ssse3] 2 x pshufb + 1 x por
4496 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4498 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4499 SelectionDAG &DAG) const {
4500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4501 SDValue V1 = SVOp->getOperand(0);
4502 SDValue V2 = SVOp->getOperand(1);
4503 DebugLoc dl = SVOp->getDebugLoc();
4504 SmallVector<int, 8> MaskVals;
4506 // Determine if more than 1 of the words in each of the low and high quadwords
4507 // of the result come from the same quadword of one of the two inputs. Undef
4508 // mask values count as coming from any quadword, for better codegen.
4509 SmallVector<unsigned, 4> LoQuad(4);
4510 SmallVector<unsigned, 4> HiQuad(4);
4511 BitVector InputQuads(4);
4512 for (unsigned i = 0; i < 8; ++i) {
4513 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4514 int EltIdx = SVOp->getMaskElt(i);
4515 MaskVals.push_back(EltIdx);
4524 InputQuads.set(EltIdx / 4);
4527 int BestLoQuad = -1;
4528 unsigned MaxQuad = 1;
4529 for (unsigned i = 0; i < 4; ++i) {
4530 if (LoQuad[i] > MaxQuad) {
4532 MaxQuad = LoQuad[i];
4536 int BestHiQuad = -1;
4538 for (unsigned i = 0; i < 4; ++i) {
4539 if (HiQuad[i] > MaxQuad) {
4541 MaxQuad = HiQuad[i];
4545 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4546 // of the two input vectors, shuffle them into one input vector so only a
4547 // single pshufb instruction is necessary. If There are more than 2 input
4548 // quads, disable the next transformation since it does not help SSSE3.
4549 bool V1Used = InputQuads[0] || InputQuads[1];
4550 bool V2Used = InputQuads[2] || InputQuads[3];
4551 if (Subtarget->hasSSSE3()) {
4552 if (InputQuads.count() == 2 && V1Used && V2Used) {
4553 BestLoQuad = InputQuads.find_first();
4554 BestHiQuad = InputQuads.find_next(BestLoQuad);
4556 if (InputQuads.count() > 2) {
4562 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4563 // the shuffle mask. If a quad is scored as -1, that means that it contains
4564 // words from all 4 input quadwords.
4566 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4567 SmallVector<int, 8> MaskV;
4568 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4569 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4570 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4571 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4572 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4573 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4575 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4576 // source words for the shuffle, to aid later transformations.
4577 bool AllWordsInNewV = true;
4578 bool InOrder[2] = { true, true };
4579 for (unsigned i = 0; i != 8; ++i) {
4580 int idx = MaskVals[i];
4582 InOrder[i/4] = false;
4583 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4585 AllWordsInNewV = false;
4589 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4590 if (AllWordsInNewV) {
4591 for (int i = 0; i != 8; ++i) {
4592 int idx = MaskVals[i];
4595 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4596 if ((idx != i) && idx < 4)
4598 if ((idx != i) && idx > 3)
4607 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4608 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4609 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4610 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4611 unsigned TargetMask = 0;
4612 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4613 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4614 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4615 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4616 V1 = NewV.getOperand(0);
4617 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4621 // If we have SSSE3, and all words of the result are from 1 input vector,
4622 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4623 // is present, fall back to case 4.
4624 if (Subtarget->hasSSSE3()) {
4625 SmallVector<SDValue,16> pshufbMask;
4627 // If we have elements from both input vectors, set the high bit of the
4628 // shuffle mask element to zero out elements that come from V2 in the V1
4629 // mask, and elements that come from V1 in the V2 mask, so that the two
4630 // results can be OR'd together.
4631 bool TwoInputs = V1Used && V2Used;
4632 for (unsigned i = 0; i != 8; ++i) {
4633 int EltIdx = MaskVals[i] * 2;
4634 if (TwoInputs && (EltIdx >= 16)) {
4635 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4636 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4639 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4640 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4642 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4643 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4644 DAG.getNode(ISD::BUILD_VECTOR, dl,
4645 MVT::v16i8, &pshufbMask[0], 16));
4647 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4649 // Calculate the shuffle mask for the second input, shuffle it, and
4650 // OR it with the first shuffled input.
4652 for (unsigned i = 0; i != 8; ++i) {
4653 int EltIdx = MaskVals[i] * 2;
4655 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4656 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4659 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4660 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4662 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4663 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4664 DAG.getNode(ISD::BUILD_VECTOR, dl,
4665 MVT::v16i8, &pshufbMask[0], 16));
4666 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4667 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4670 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4671 // and update MaskVals with new element order.
4672 BitVector InOrder(8);
4673 if (BestLoQuad >= 0) {
4674 SmallVector<int, 8> MaskV;
4675 for (int i = 0; i != 4; ++i) {
4676 int idx = MaskVals[i];
4678 MaskV.push_back(-1);
4680 } else if ((idx / 4) == BestLoQuad) {
4681 MaskV.push_back(idx & 3);
4684 MaskV.push_back(-1);
4687 for (unsigned i = 4; i != 8; ++i)
4689 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4692 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4693 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4695 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4699 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4700 // and update MaskVals with the new element order.
4701 if (BestHiQuad >= 0) {
4702 SmallVector<int, 8> MaskV;
4703 for (unsigned i = 0; i != 4; ++i)
4705 for (unsigned i = 4; i != 8; ++i) {
4706 int idx = MaskVals[i];
4708 MaskV.push_back(-1);
4710 } else if ((idx / 4) == BestHiQuad) {
4711 MaskV.push_back((idx & 3) + 4);
4714 MaskV.push_back(-1);
4717 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4720 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4721 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4723 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4727 // In case BestHi & BestLo were both -1, which means each quadword has a word
4728 // from each of the four input quadwords, calculate the InOrder bitvector now
4729 // before falling through to the insert/extract cleanup.
4730 if (BestLoQuad == -1 && BestHiQuad == -1) {
4732 for (int i = 0; i != 8; ++i)
4733 if (MaskVals[i] < 0 || MaskVals[i] == i)
4737 // The other elements are put in the right place using pextrw and pinsrw.
4738 for (unsigned i = 0; i != 8; ++i) {
4741 int EltIdx = MaskVals[i];
4744 SDValue ExtOp = (EltIdx < 8)
4745 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4746 DAG.getIntPtrConstant(EltIdx))
4747 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4748 DAG.getIntPtrConstant(EltIdx - 8));
4749 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4750 DAG.getIntPtrConstant(i));
4755 // v16i8 shuffles - Prefer shuffles in the following order:
4756 // 1. [ssse3] 1 x pshufb
4757 // 2. [ssse3] 2 x pshufb + 1 x por
4758 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4760 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4762 const X86TargetLowering &TLI) {
4763 SDValue V1 = SVOp->getOperand(0);
4764 SDValue V2 = SVOp->getOperand(1);
4765 DebugLoc dl = SVOp->getDebugLoc();
4766 SmallVector<int, 16> MaskVals;
4767 SVOp->getMask(MaskVals);
4769 // If we have SSSE3, case 1 is generated when all result bytes come from
4770 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4771 // present, fall back to case 3.
4772 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4775 for (unsigned i = 0; i < 16; ++i) {
4776 int EltIdx = MaskVals[i];
4785 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4786 if (TLI.getSubtarget()->hasSSSE3()) {
4787 SmallVector<SDValue,16> pshufbMask;
4789 // If all result elements are from one input vector, then only translate
4790 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4792 // Otherwise, we have elements from both input vectors, and must zero out
4793 // elements that come from V2 in the first mask, and V1 in the second mask
4794 // so that we can OR them together.
4795 bool TwoInputs = !(V1Only || V2Only);
4796 for (unsigned i = 0; i != 16; ++i) {
4797 int EltIdx = MaskVals[i];
4798 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4799 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4802 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4804 // If all the elements are from V2, assign it to V1 and return after
4805 // building the first pshufb.
4808 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4809 DAG.getNode(ISD::BUILD_VECTOR, dl,
4810 MVT::v16i8, &pshufbMask[0], 16));
4814 // Calculate the shuffle mask for the second input, shuffle it, and
4815 // OR it with the first shuffled input.
4817 for (unsigned i = 0; i != 16; ++i) {
4818 int EltIdx = MaskVals[i];
4820 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4823 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4825 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4826 DAG.getNode(ISD::BUILD_VECTOR, dl,
4827 MVT::v16i8, &pshufbMask[0], 16));
4828 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4831 // No SSSE3 - Calculate in place words and then fix all out of place words
4832 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4833 // the 16 different words that comprise the two doublequadword input vectors.
4834 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4835 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4836 SDValue NewV = V2Only ? V2 : V1;
4837 for (int i = 0; i != 8; ++i) {
4838 int Elt0 = MaskVals[i*2];
4839 int Elt1 = MaskVals[i*2+1];
4841 // This word of the result is all undef, skip it.
4842 if (Elt0 < 0 && Elt1 < 0)
4845 // This word of the result is already in the correct place, skip it.
4846 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4848 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4851 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4852 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4855 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4856 // using a single extract together, load it and store it.
4857 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4858 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4859 DAG.getIntPtrConstant(Elt1 / 2));
4860 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4861 DAG.getIntPtrConstant(i));
4865 // If Elt1 is defined, extract it from the appropriate source. If the
4866 // source byte is not also odd, shift the extracted word left 8 bits
4867 // otherwise clear the bottom 8 bits if we need to do an or.
4869 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4870 DAG.getIntPtrConstant(Elt1 / 2));
4871 if ((Elt1 & 1) == 0)
4872 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4873 DAG.getConstant(8, TLI.getShiftAmountTy()));
4875 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4876 DAG.getConstant(0xFF00, MVT::i16));
4878 // If Elt0 is defined, extract it from the appropriate source. If the
4879 // source byte is not also even, shift the extracted word right 8 bits. If
4880 // Elt1 was also defined, OR the extracted values together before
4881 // inserting them in the result.
4883 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4884 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4885 if ((Elt0 & 1) != 0)
4886 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4887 DAG.getConstant(8, TLI.getShiftAmountTy()));
4889 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4890 DAG.getConstant(0x00FF, MVT::i16));
4891 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4894 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4895 DAG.getIntPtrConstant(i));
4897 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4900 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4901 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4902 /// done when every pair / quad of shuffle mask elements point to elements in
4903 /// the right sequence. e.g.
4904 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4906 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4907 SelectionDAG &DAG, DebugLoc dl) {
4908 EVT VT = SVOp->getValueType(0);
4909 SDValue V1 = SVOp->getOperand(0);
4910 SDValue V2 = SVOp->getOperand(1);
4911 unsigned NumElems = VT.getVectorNumElements();
4912 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4914 switch (VT.getSimpleVT().SimpleTy) {
4915 default: assert(false && "Unexpected!");
4916 case MVT::v4f32: NewVT = MVT::v2f64; break;
4917 case MVT::v4i32: NewVT = MVT::v2i64; break;
4918 case MVT::v8i16: NewVT = MVT::v4i32; break;
4919 case MVT::v16i8: NewVT = MVT::v4i32; break;
4922 int Scale = NumElems / NewWidth;
4923 SmallVector<int, 8> MaskVec;
4924 for (unsigned i = 0; i < NumElems; i += Scale) {
4926 for (int j = 0; j < Scale; ++j) {
4927 int EltIdx = SVOp->getMaskElt(i+j);
4931 StartIdx = EltIdx - (EltIdx % Scale);
4932 if (EltIdx != StartIdx + j)
4936 MaskVec.push_back(-1);
4938 MaskVec.push_back(StartIdx / Scale);
4941 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4942 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4943 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4946 /// getVZextMovL - Return a zero-extending vector move low node.
4948 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4949 SDValue SrcOp, SelectionDAG &DAG,
4950 const X86Subtarget *Subtarget, DebugLoc dl) {
4951 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4952 LoadSDNode *LD = NULL;
4953 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4954 LD = dyn_cast<LoadSDNode>(SrcOp);
4956 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4958 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4959 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4960 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4961 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4962 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4964 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4965 return DAG.getNode(ISD::BITCAST, dl, VT,
4966 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4967 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4975 return DAG.getNode(ISD::BITCAST, dl, VT,
4976 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4977 DAG.getNode(ISD::BITCAST, dl,
4981 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4984 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4985 SDValue V1 = SVOp->getOperand(0);
4986 SDValue V2 = SVOp->getOperand(1);
4987 DebugLoc dl = SVOp->getDebugLoc();
4988 EVT VT = SVOp->getValueType(0);
4990 SmallVector<std::pair<int, int>, 8> Locs;
4992 SmallVector<int, 8> Mask1(4U, -1);
4993 SmallVector<int, 8> PermMask;
4994 SVOp->getMask(PermMask);
4998 for (unsigned i = 0; i != 4; ++i) {
4999 int Idx = PermMask[i];
5001 Locs[i] = std::make_pair(-1, -1);
5003 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5005 Locs[i] = std::make_pair(0, NumLo);
5009 Locs[i] = std::make_pair(1, NumHi);
5011 Mask1[2+NumHi] = Idx;
5017 if (NumLo <= 2 && NumHi <= 2) {
5018 // If no more than two elements come from either vector. This can be
5019 // implemented with two shuffles. First shuffle gather the elements.
5020 // The second shuffle, which takes the first shuffle as both of its
5021 // vector operands, put the elements into the right order.
5022 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5024 SmallVector<int, 8> Mask2(4U, -1);
5026 for (unsigned i = 0; i != 4; ++i) {
5027 if (Locs[i].first == -1)
5030 unsigned Idx = (i < 2) ? 0 : 4;
5031 Idx += Locs[i].first * 2 + Locs[i].second;
5036 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5037 } else if (NumLo == 3 || NumHi == 3) {
5038 // Otherwise, we must have three elements from one vector, call it X, and
5039 // one element from the other, call it Y. First, use a shufps to build an
5040 // intermediate vector with the one element from Y and the element from X
5041 // that will be in the same half in the final destination (the indexes don't
5042 // matter). Then, use a shufps to build the final vector, taking the half
5043 // containing the element from Y from the intermediate, and the other half
5046 // Normalize it so the 3 elements come from V1.
5047 CommuteVectorShuffleMask(PermMask, VT);
5051 // Find the element from V2.
5053 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5054 int Val = PermMask[HiIndex];
5061 Mask1[0] = PermMask[HiIndex];
5063 Mask1[2] = PermMask[HiIndex^1];
5065 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5068 Mask1[0] = PermMask[0];
5069 Mask1[1] = PermMask[1];
5070 Mask1[2] = HiIndex & 1 ? 6 : 4;
5071 Mask1[3] = HiIndex & 1 ? 4 : 6;
5072 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5074 Mask1[0] = HiIndex & 1 ? 2 : 0;
5075 Mask1[1] = HiIndex & 1 ? 0 : 2;
5076 Mask1[2] = PermMask[2];
5077 Mask1[3] = PermMask[3];
5082 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5086 // Break it into (shuffle shuffle_hi, shuffle_lo).
5088 SmallVector<int,8> LoMask(4U, -1);
5089 SmallVector<int,8> HiMask(4U, -1);
5091 SmallVector<int,8> *MaskPtr = &LoMask;
5092 unsigned MaskIdx = 0;
5095 for (unsigned i = 0; i != 4; ++i) {
5102 int Idx = PermMask[i];
5104 Locs[i] = std::make_pair(-1, -1);
5105 } else if (Idx < 4) {
5106 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5107 (*MaskPtr)[LoIdx] = Idx;
5110 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5111 (*MaskPtr)[HiIdx] = Idx;
5116 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5117 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5118 SmallVector<int, 8> MaskOps;
5119 for (unsigned i = 0; i != 4; ++i) {
5120 if (Locs[i].first == -1) {
5121 MaskOps.push_back(-1);
5123 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5124 MaskOps.push_back(Idx);
5127 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5130 static bool MayFoldVectorLoad(SDValue V) {
5131 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5132 V = V.getOperand(0);
5133 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5134 V = V.getOperand(0);
5140 // FIXME: the version above should always be used. Since there's
5141 // a bug where several vector shuffles can't be folded because the
5142 // DAG is not updated during lowering and a node claims to have two
5143 // uses while it only has one, use this version, and let isel match
5144 // another instruction if the load really happens to have more than
5145 // one use. Remove this version after this bug get fixed.
5146 // rdar://8434668, PR8156
5147 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5148 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5149 V = V.getOperand(0);
5150 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5151 V = V.getOperand(0);
5152 if (ISD::isNormalLoad(V.getNode()))
5157 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5158 /// a vector extract, and if both can be later optimized into a single load.
5159 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5160 /// here because otherwise a target specific shuffle node is going to be
5161 /// emitted for this shuffle, and the optimization not done.
5162 /// FIXME: This is probably not the best approach, but fix the problem
5163 /// until the right path is decided.
5165 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5166 const TargetLowering &TLI) {
5167 EVT VT = V.getValueType();
5168 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5170 // Be sure that the vector shuffle is present in a pattern like this:
5171 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5175 SDNode *N = *V.getNode()->use_begin();
5176 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5179 SDValue EltNo = N->getOperand(1);
5180 if (!isa<ConstantSDNode>(EltNo))
5183 // If the bit convert changed the number of elements, it is unsafe
5184 // to examine the mask.
5185 bool HasShuffleIntoBitcast = false;
5186 if (V.getOpcode() == ISD::BITCAST) {
5187 EVT SrcVT = V.getOperand(0).getValueType();
5188 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5190 V = V.getOperand(0);
5191 HasShuffleIntoBitcast = true;
5194 // Select the input vector, guarding against out of range extract vector.
5195 unsigned NumElems = VT.getVectorNumElements();
5196 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5197 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5198 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5200 // Skip one more bit_convert if necessary
5201 if (V.getOpcode() == ISD::BITCAST)
5202 V = V.getOperand(0);
5204 if (ISD::isNormalLoad(V.getNode())) {
5205 // Is the original load suitable?
5206 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5208 // FIXME: avoid the multi-use bug that is preventing lots of
5209 // of foldings to be detected, this is still wrong of course, but
5210 // give the temporary desired behavior, and if it happens that
5211 // the load has real more uses, during isel it will not fold, and
5212 // will generate poor code.
5213 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5216 if (!HasShuffleIntoBitcast)
5219 // If there's a bitcast before the shuffle, check if the load type and
5220 // alignment is valid.
5221 unsigned Align = LN0->getAlignment();
5223 TLI.getTargetData()->getABITypeAlignment(
5224 VT.getTypeForEVT(*DAG.getContext()));
5226 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5234 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5235 EVT VT = Op.getValueType();
5237 // Canonizalize to v2f64.
5238 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5239 return DAG.getNode(ISD::BITCAST, dl, VT,
5240 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5245 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5247 SDValue V1 = Op.getOperand(0);
5248 SDValue V2 = Op.getOperand(1);
5249 EVT VT = Op.getValueType();
5251 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5253 if (HasSSE2 && VT == MVT::v2f64)
5254 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5257 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5261 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5262 SDValue V1 = Op.getOperand(0);
5263 SDValue V2 = Op.getOperand(1);
5264 EVT VT = Op.getValueType();
5266 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5267 "unsupported shuffle type");
5269 if (V2.getOpcode() == ISD::UNDEF)
5273 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5277 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5278 SDValue V1 = Op.getOperand(0);
5279 SDValue V2 = Op.getOperand(1);
5280 EVT VT = Op.getValueType();
5281 unsigned NumElems = VT.getVectorNumElements();
5283 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5284 // operand of these instructions is only memory, so check if there's a
5285 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5287 bool CanFoldLoad = false;
5289 // Trivial case, when V2 comes from a load.
5290 if (MayFoldVectorLoad(V2))
5293 // When V1 is a load, it can be folded later into a store in isel, example:
5294 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5296 // (MOVLPSmr addr:$src1, VR128:$src2)
5297 // So, recognize this potential and also use MOVLPS or MOVLPD
5298 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5302 if (HasSSE2 && NumElems == 2)
5303 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5306 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5309 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5310 // movl and movlp will both match v2i64, but v2i64 is never matched by
5311 // movl earlier because we make it strict to avoid messing with the movlp load
5312 // folding logic (see the code above getMOVLP call). Match it here then,
5313 // this is horrible, but will stay like this until we move all shuffle
5314 // matching to x86 specific nodes. Note that for the 1st condition all
5315 // types are matched with movsd.
5316 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5317 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5319 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5322 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5324 // Invert the operand order and use SHUFPS to match it.
5325 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5326 X86::getShuffleSHUFImmediate(SVOp), DAG);
5329 static inline unsigned getUNPCKLOpcode(EVT VT) {
5330 switch(VT.getSimpleVT().SimpleTy) {
5331 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5332 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5333 case MVT::v4f32: return X86ISD::UNPCKLPS;
5334 case MVT::v2f64: return X86ISD::UNPCKLPD;
5335 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5336 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5338 llvm_unreachable("Unknow type for unpckl");
5343 static inline unsigned getUNPCKHOpcode(EVT VT) {
5344 switch(VT.getSimpleVT().SimpleTy) {
5345 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5346 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5347 case MVT::v4f32: return X86ISD::UNPCKHPS;
5348 case MVT::v2f64: return X86ISD::UNPCKHPD;
5349 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5350 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5352 llvm_unreachable("Unknow type for unpckh");
5358 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5359 const TargetLowering &TLI,
5360 const X86Subtarget *Subtarget) {
5361 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5362 EVT VT = Op.getValueType();
5363 DebugLoc dl = Op.getDebugLoc();
5364 SDValue V1 = Op.getOperand(0);
5365 SDValue V2 = Op.getOperand(1);
5367 if (isZeroShuffle(SVOp))
5368 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5370 // Handle splat operations
5371 if (SVOp->isSplat()) {
5372 // Special case, this is the only place now where it's
5373 // allowed to return a vector_shuffle operation without
5374 // using a target specific node, because *hopefully* it
5375 // will be optimized away by the dag combiner.
5376 if (VT.getVectorNumElements() <= 4 &&
5377 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5380 // Handle splats by matching through known masks
5381 if (VT.getVectorNumElements() <= 4)
5384 // Canonicalize all of the remaining to v4f32.
5385 return PromoteSplat(SVOp, DAG);
5388 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5390 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5391 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5392 if (NewOp.getNode())
5393 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5394 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5395 // FIXME: Figure out a cleaner way to do this.
5396 // Try to make use of movq to zero out the top part.
5397 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5398 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5399 if (NewOp.getNode()) {
5400 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5401 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5402 DAG, Subtarget, dl);
5404 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5405 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5406 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5407 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5408 DAG, Subtarget, dl);
5415 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5416 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5417 SDValue V1 = Op.getOperand(0);
5418 SDValue V2 = Op.getOperand(1);
5419 EVT VT = Op.getValueType();
5420 DebugLoc dl = Op.getDebugLoc();
5421 unsigned NumElems = VT.getVectorNumElements();
5422 bool isMMX = VT.getSizeInBits() == 64;
5423 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5424 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5425 bool V1IsSplat = false;
5426 bool V2IsSplat = false;
5427 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5428 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5429 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5430 MachineFunction &MF = DAG.getMachineFunction();
5431 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5433 // Shuffle operations on MMX not supported.
5437 // Vector shuffle lowering takes 3 steps:
5439 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5440 // narrowing and commutation of operands should be handled.
5441 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5443 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5444 // so the shuffle can be broken into other shuffles and the legalizer can
5445 // try the lowering again.
5447 // The general ideia is that no vector_shuffle operation should be left to
5448 // be matched during isel, all of them must be converted to a target specific
5451 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5452 // narrowing and commutation of operands should be handled. The actual code
5453 // doesn't include all of those, work in progress...
5454 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5455 if (NewOp.getNode())
5458 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5459 // unpckh_undef). Only use pshufd if speed is more important than size.
5460 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5461 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5462 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5463 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5464 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5465 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5467 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5468 RelaxedMayFoldVectorLoad(V1))
5469 return getMOVDDup(Op, dl, V1, DAG);
5471 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5472 return getMOVHighToLow(Op, dl, DAG);
5474 // Use to match splats
5475 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5476 (VT == MVT::v2f64 || VT == MVT::v2i64))
5477 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5479 if (X86::isPSHUFDMask(SVOp)) {
5480 // The actual implementation will match the mask in the if above and then
5481 // during isel it can match several different instructions, not only pshufd
5482 // as its name says, sad but true, emulate the behavior for now...
5483 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5484 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5486 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5488 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5489 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5491 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5492 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5495 if (VT == MVT::v4f32)
5496 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5500 // Check if this can be converted into a logical shift.
5501 bool isLeft = false;
5504 bool isShift = getSubtarget()->hasSSE2() &&
5505 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5506 if (isShift && ShVal.hasOneUse()) {
5507 // If the shifted value has multiple uses, it may be cheaper to use
5508 // v_set0 + movlhps or movhlps, etc.
5509 EVT EltVT = VT.getVectorElementType();
5510 ShAmt *= EltVT.getSizeInBits();
5511 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5514 if (X86::isMOVLMask(SVOp)) {
5517 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5518 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5519 if (!X86::isMOVLPMask(SVOp)) {
5520 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5521 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5523 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5524 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5528 // FIXME: fold these into legal mask.
5529 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5530 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5532 if (X86::isMOVHLPSMask(SVOp))
5533 return getMOVHighToLow(Op, dl, DAG);
5535 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5536 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5538 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5539 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5541 if (X86::isMOVLPMask(SVOp))
5542 return getMOVLP(Op, dl, DAG, HasSSE2);
5544 if (ShouldXformToMOVHLPS(SVOp) ||
5545 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5546 return CommuteVectorShuffle(SVOp, DAG);
5549 // No better options. Use a vshl / vsrl.
5550 EVT EltVT = VT.getVectorElementType();
5551 ShAmt *= EltVT.getSizeInBits();
5552 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5555 bool Commuted = false;
5556 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5557 // 1,1,1,1 -> v8i16 though.
5558 V1IsSplat = isSplatVector(V1.getNode());
5559 V2IsSplat = isSplatVector(V2.getNode());
5561 // Canonicalize the splat or undef, if present, to be on the RHS.
5562 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5563 Op = CommuteVectorShuffle(SVOp, DAG);
5564 SVOp = cast<ShuffleVectorSDNode>(Op);
5565 V1 = SVOp->getOperand(0);
5566 V2 = SVOp->getOperand(1);
5567 std::swap(V1IsSplat, V2IsSplat);
5568 std::swap(V1IsUndef, V2IsUndef);
5572 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5573 // Shuffling low element of v1 into undef, just return v1.
5576 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5577 // the instruction selector will not match, so get a canonical MOVL with
5578 // swapped operands to undo the commute.
5579 return getMOVL(DAG, dl, VT, V2, V1);
5582 if (X86::isUNPCKLMask(SVOp))
5583 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5585 if (X86::isUNPCKHMask(SVOp))
5586 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5589 // Normalize mask so all entries that point to V2 points to its first
5590 // element then try to match unpck{h|l} again. If match, return a
5591 // new vector_shuffle with the corrected mask.
5592 SDValue NewMask = NormalizeMask(SVOp, DAG);
5593 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5594 if (NSVOp != SVOp) {
5595 if (X86::isUNPCKLMask(NSVOp, true)) {
5597 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5604 // Commute is back and try unpck* again.
5605 // FIXME: this seems wrong.
5606 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5607 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5609 if (X86::isUNPCKLMask(NewSVOp))
5610 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5612 if (X86::isUNPCKHMask(NewSVOp))
5613 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5616 // Normalize the node to match x86 shuffle ops if needed
5617 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5618 return CommuteVectorShuffle(SVOp, DAG);
5620 // The checks below are all present in isShuffleMaskLegal, but they are
5621 // inlined here right now to enable us to directly emit target specific
5622 // nodes, and remove one by one until they don't return Op anymore.
5623 SmallVector<int, 16> M;
5626 if (isPALIGNRMask(M, VT, HasSSSE3))
5627 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5628 X86::getShufflePALIGNRImmediate(SVOp),
5631 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5632 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5633 if (VT == MVT::v2f64)
5634 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5635 if (VT == MVT::v2i64)
5636 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5639 if (isPSHUFHWMask(M, VT))
5640 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5641 X86::getShufflePSHUFHWImmediate(SVOp),
5644 if (isPSHUFLWMask(M, VT))
5645 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5646 X86::getShufflePSHUFLWImmediate(SVOp),
5649 if (isSHUFPMask(M, VT)) {
5650 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5651 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5652 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5654 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5655 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5659 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5660 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5661 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5662 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5663 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5664 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5666 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5667 if (VT == MVT::v8i16) {
5668 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5669 if (NewOp.getNode())
5673 if (VT == MVT::v16i8) {
5674 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5675 if (NewOp.getNode())
5679 // Handle all 4 wide cases with a number of shuffles.
5681 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5687 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5688 SelectionDAG &DAG) const {
5689 EVT VT = Op.getValueType();
5690 DebugLoc dl = Op.getDebugLoc();
5691 if (VT.getSizeInBits() == 8) {
5692 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5693 Op.getOperand(0), Op.getOperand(1));
5694 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5695 DAG.getValueType(VT));
5696 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5697 } else if (VT.getSizeInBits() == 16) {
5698 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5699 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5701 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5702 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5703 DAG.getNode(ISD::BITCAST, dl,
5707 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5708 Op.getOperand(0), Op.getOperand(1));
5709 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5710 DAG.getValueType(VT));
5711 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5712 } else if (VT == MVT::f32) {
5713 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5714 // the result back to FR32 register. It's only worth matching if the
5715 // result has a single use which is a store or a bitcast to i32. And in
5716 // the case of a store, it's not worth it if the index is a constant 0,
5717 // because a MOVSSmr can be used instead, which is smaller and faster.
5718 if (!Op.hasOneUse())
5720 SDNode *User = *Op.getNode()->use_begin();
5721 if ((User->getOpcode() != ISD::STORE ||
5722 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5723 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5724 (User->getOpcode() != ISD::BITCAST ||
5725 User->getValueType(0) != MVT::i32))
5727 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5728 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5731 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5732 } else if (VT == MVT::i32) {
5733 // ExtractPS works with constant index.
5734 if (isa<ConstantSDNode>(Op.getOperand(1)))
5742 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5743 SelectionDAG &DAG) const {
5744 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5747 if (Subtarget->hasSSE41()) {
5748 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5753 EVT VT = Op.getValueType();
5754 DebugLoc dl = Op.getDebugLoc();
5755 // TODO: handle v16i8.
5756 if (VT.getSizeInBits() == 16) {
5757 SDValue Vec = Op.getOperand(0);
5758 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5760 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5761 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5762 DAG.getNode(ISD::BITCAST, dl,
5765 // Transform it so it match pextrw which produces a 32-bit result.
5766 EVT EltVT = MVT::i32;
5767 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5768 Op.getOperand(0), Op.getOperand(1));
5769 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5770 DAG.getValueType(VT));
5771 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5772 } else if (VT.getSizeInBits() == 32) {
5773 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5777 // SHUFPS the element to the lowest double word, then movss.
5778 int Mask[4] = { Idx, -1, -1, -1 };
5779 EVT VVT = Op.getOperand(0).getValueType();
5780 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5781 DAG.getUNDEF(VVT), Mask);
5782 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5783 DAG.getIntPtrConstant(0));
5784 } else if (VT.getSizeInBits() == 64) {
5785 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5786 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5787 // to match extract_elt for f64.
5788 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5792 // UNPCKHPD the element to the lowest double word, then movsd.
5793 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5794 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5795 int Mask[2] = { 1, -1 };
5796 EVT VVT = Op.getOperand(0).getValueType();
5797 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5798 DAG.getUNDEF(VVT), Mask);
5799 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5800 DAG.getIntPtrConstant(0));
5807 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5808 SelectionDAG &DAG) const {
5809 EVT VT = Op.getValueType();
5810 EVT EltVT = VT.getVectorElementType();
5811 DebugLoc dl = Op.getDebugLoc();
5813 SDValue N0 = Op.getOperand(0);
5814 SDValue N1 = Op.getOperand(1);
5815 SDValue N2 = Op.getOperand(2);
5817 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5818 isa<ConstantSDNode>(N2)) {
5820 if (VT == MVT::v8i16)
5821 Opc = X86ISD::PINSRW;
5822 else if (VT == MVT::v16i8)
5823 Opc = X86ISD::PINSRB;
5825 Opc = X86ISD::PINSRB;
5827 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5829 if (N1.getValueType() != MVT::i32)
5830 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5831 if (N2.getValueType() != MVT::i32)
5832 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5833 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5834 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5835 // Bits [7:6] of the constant are the source select. This will always be
5836 // zero here. The DAG Combiner may combine an extract_elt index into these
5837 // bits. For example (insert (extract, 3), 2) could be matched by putting
5838 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5839 // Bits [5:4] of the constant are the destination select. This is the
5840 // value of the incoming immediate.
5841 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5842 // combine either bitwise AND or insert of float 0.0 to set these bits.
5843 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5844 // Create this as a scalar to vector..
5845 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5846 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5847 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5848 // PINSR* works with constant index.
5855 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5856 EVT VT = Op.getValueType();
5857 EVT EltVT = VT.getVectorElementType();
5859 if (Subtarget->hasSSE41())
5860 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5862 if (EltVT == MVT::i8)
5865 DebugLoc dl = Op.getDebugLoc();
5866 SDValue N0 = Op.getOperand(0);
5867 SDValue N1 = Op.getOperand(1);
5868 SDValue N2 = Op.getOperand(2);
5870 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5871 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5872 // as its second argument.
5873 if (N1.getValueType() != MVT::i32)
5874 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5875 if (N2.getValueType() != MVT::i32)
5876 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5877 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5883 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5884 DebugLoc dl = Op.getDebugLoc();
5886 if (Op.getValueType() == MVT::v1i64 &&
5887 Op.getOperand(0).getValueType() == MVT::i64)
5888 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5890 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5891 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5892 "Expected an SSE type!");
5893 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5894 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5897 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
5898 // a simple subregister reference or explicit instructions to grab
5899 // upper bits of a vector.
5901 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
5902 if (Subtarget->hasAVX()) {
5908 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
5909 // simple superregister reference or explicit instructions to insert
5910 // the upper bits of a vector.
5912 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
5913 if (Subtarget->hasAVX()) {
5914 DebugLoc dl = Op.getNode()->getDebugLoc();
5915 SDValue Vec = Op.getNode()->getOperand(0);
5916 SDValue SubVec = Op.getNode()->getOperand(1);
5917 SDValue Idx = Op.getNode()->getOperand(2);
5919 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
5920 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
5927 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5928 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5929 // one of the above mentioned nodes. It has to be wrapped because otherwise
5930 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5931 // be used to form addressing mode. These wrapped nodes will be selected
5934 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5935 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5937 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5939 unsigned char OpFlag = 0;
5940 unsigned WrapperKind = X86ISD::Wrapper;
5941 CodeModel::Model M = getTargetMachine().getCodeModel();
5943 if (Subtarget->isPICStyleRIPRel() &&
5944 (M == CodeModel::Small || M == CodeModel::Kernel))
5945 WrapperKind = X86ISD::WrapperRIP;
5946 else if (Subtarget->isPICStyleGOT())
5947 OpFlag = X86II::MO_GOTOFF;
5948 else if (Subtarget->isPICStyleStubPIC())
5949 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5951 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5953 CP->getOffset(), OpFlag);
5954 DebugLoc DL = CP->getDebugLoc();
5955 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5956 // With PIC, the address is actually $g + Offset.
5958 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5959 DAG.getNode(X86ISD::GlobalBaseReg,
5960 DebugLoc(), getPointerTy()),
5967 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5968 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5970 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5972 unsigned char OpFlag = 0;
5973 unsigned WrapperKind = X86ISD::Wrapper;
5974 CodeModel::Model M = getTargetMachine().getCodeModel();
5976 if (Subtarget->isPICStyleRIPRel() &&
5977 (M == CodeModel::Small || M == CodeModel::Kernel))
5978 WrapperKind = X86ISD::WrapperRIP;
5979 else if (Subtarget->isPICStyleGOT())
5980 OpFlag = X86II::MO_GOTOFF;
5981 else if (Subtarget->isPICStyleStubPIC())
5982 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5984 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5986 DebugLoc DL = JT->getDebugLoc();
5987 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5989 // With PIC, the address is actually $g + Offset.
5991 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5992 DAG.getNode(X86ISD::GlobalBaseReg,
5993 DebugLoc(), getPointerTy()),
6000 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6001 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6003 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6005 unsigned char OpFlag = 0;
6006 unsigned WrapperKind = X86ISD::Wrapper;
6007 CodeModel::Model M = getTargetMachine().getCodeModel();
6009 if (Subtarget->isPICStyleRIPRel() &&
6010 (M == CodeModel::Small || M == CodeModel::Kernel))
6011 WrapperKind = X86ISD::WrapperRIP;
6012 else if (Subtarget->isPICStyleGOT())
6013 OpFlag = X86II::MO_GOTOFF;
6014 else if (Subtarget->isPICStyleStubPIC())
6015 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6017 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6019 DebugLoc DL = Op.getDebugLoc();
6020 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6023 // With PIC, the address is actually $g + Offset.
6024 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6025 !Subtarget->is64Bit()) {
6026 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6027 DAG.getNode(X86ISD::GlobalBaseReg,
6028 DebugLoc(), getPointerTy()),
6036 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6037 // Create the TargetBlockAddressAddress node.
6038 unsigned char OpFlags =
6039 Subtarget->ClassifyBlockAddressReference();
6040 CodeModel::Model M = getTargetMachine().getCodeModel();
6041 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6042 DebugLoc dl = Op.getDebugLoc();
6043 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6044 /*isTarget=*/true, OpFlags);
6046 if (Subtarget->isPICStyleRIPRel() &&
6047 (M == CodeModel::Small || M == CodeModel::Kernel))
6048 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6050 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6052 // With PIC, the address is actually $g + Offset.
6053 if (isGlobalRelativeToPICBase(OpFlags)) {
6054 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6055 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6063 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6065 SelectionDAG &DAG) const {
6066 // Create the TargetGlobalAddress node, folding in the constant
6067 // offset if it is legal.
6068 unsigned char OpFlags =
6069 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6070 CodeModel::Model M = getTargetMachine().getCodeModel();
6072 if (OpFlags == X86II::MO_NO_FLAG &&
6073 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6074 // A direct static reference to a global.
6075 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6078 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6081 if (Subtarget->isPICStyleRIPRel() &&
6082 (M == CodeModel::Small || M == CodeModel::Kernel))
6083 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6085 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6087 // With PIC, the address is actually $g + Offset.
6088 if (isGlobalRelativeToPICBase(OpFlags)) {
6089 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6090 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6094 // For globals that require a load from a stub to get the address, emit the
6096 if (isGlobalStubReference(OpFlags))
6097 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6098 MachinePointerInfo::getGOT(), false, false, 0);
6100 // If there was a non-zero offset that we didn't fold, create an explicit
6103 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6104 DAG.getConstant(Offset, getPointerTy()));
6110 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6111 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6112 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6113 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6117 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6118 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6119 unsigned char OperandFlags) {
6120 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6121 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6122 DebugLoc dl = GA->getDebugLoc();
6123 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6124 GA->getValueType(0),
6128 SDValue Ops[] = { Chain, TGA, *InFlag };
6129 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6131 SDValue Ops[] = { Chain, TGA };
6132 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6135 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6136 MFI->setAdjustsStack(true);
6138 SDValue Flag = Chain.getValue(1);
6139 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6142 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6144 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6147 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6148 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6149 DAG.getNode(X86ISD::GlobalBaseReg,
6150 DebugLoc(), PtrVT), InFlag);
6151 InFlag = Chain.getValue(1);
6153 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6156 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6158 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6160 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6161 X86::RAX, X86II::MO_TLSGD);
6164 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6165 // "local exec" model.
6166 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6167 const EVT PtrVT, TLSModel::Model model,
6169 DebugLoc dl = GA->getDebugLoc();
6171 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6172 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6173 is64Bit ? 257 : 256));
6175 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6176 DAG.getIntPtrConstant(0),
6177 MachinePointerInfo(Ptr), false, false, 0);
6179 unsigned char OperandFlags = 0;
6180 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6182 unsigned WrapperKind = X86ISD::Wrapper;
6183 if (model == TLSModel::LocalExec) {
6184 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6185 } else if (is64Bit) {
6186 assert(model == TLSModel::InitialExec);
6187 OperandFlags = X86II::MO_GOTTPOFF;
6188 WrapperKind = X86ISD::WrapperRIP;
6190 assert(model == TLSModel::InitialExec);
6191 OperandFlags = X86II::MO_INDNTPOFF;
6194 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6196 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6197 GA->getValueType(0),
6198 GA->getOffset(), OperandFlags);
6199 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6201 if (model == TLSModel::InitialExec)
6202 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6203 MachinePointerInfo::getGOT(), false, false, 0);
6205 // The address of the thread local variable is the add of the thread
6206 // pointer with the offset of the variable.
6207 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6211 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6213 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6214 const GlobalValue *GV = GA->getGlobal();
6216 if (Subtarget->isTargetELF()) {
6217 // TODO: implement the "local dynamic" model
6218 // TODO: implement the "initial exec"model for pic executables
6220 // If GV is an alias then use the aliasee for determining
6221 // thread-localness.
6222 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6223 GV = GA->resolveAliasedGlobal(false);
6225 TLSModel::Model model
6226 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6229 case TLSModel::GeneralDynamic:
6230 case TLSModel::LocalDynamic: // not implemented
6231 if (Subtarget->is64Bit())
6232 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6233 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6235 case TLSModel::InitialExec:
6236 case TLSModel::LocalExec:
6237 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6238 Subtarget->is64Bit());
6240 } else if (Subtarget->isTargetDarwin()) {
6241 // Darwin only has one model of TLS. Lower to that.
6242 unsigned char OpFlag = 0;
6243 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6244 X86ISD::WrapperRIP : X86ISD::Wrapper;
6246 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6248 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6249 !Subtarget->is64Bit();
6251 OpFlag = X86II::MO_TLVP_PIC_BASE;
6253 OpFlag = X86II::MO_TLVP;
6254 DebugLoc DL = Op.getDebugLoc();
6255 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6256 GA->getValueType(0),
6257 GA->getOffset(), OpFlag);
6258 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6260 // With PIC32, the address is actually $g + Offset.
6262 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6263 DAG.getNode(X86ISD::GlobalBaseReg,
6264 DebugLoc(), getPointerTy()),
6267 // Lowering the machine isd will make sure everything is in the right
6269 SDValue Chain = DAG.getEntryNode();
6270 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6271 SDValue Args[] = { Chain, Offset };
6272 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6274 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6275 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6276 MFI->setAdjustsStack(true);
6278 // And our return value (tls address) is in the standard call return value
6280 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6281 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6285 "TLS not implemented for this target.");
6287 llvm_unreachable("Unreachable");
6292 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6293 /// take a 2 x i32 value to shift plus a shift amount.
6294 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6295 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6296 EVT VT = Op.getValueType();
6297 unsigned VTBits = VT.getSizeInBits();
6298 DebugLoc dl = Op.getDebugLoc();
6299 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6300 SDValue ShOpLo = Op.getOperand(0);
6301 SDValue ShOpHi = Op.getOperand(1);
6302 SDValue ShAmt = Op.getOperand(2);
6303 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6304 DAG.getConstant(VTBits - 1, MVT::i8))
6305 : DAG.getConstant(0, VT);
6308 if (Op.getOpcode() == ISD::SHL_PARTS) {
6309 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6310 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6312 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6313 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6316 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6317 DAG.getConstant(VTBits, MVT::i8));
6318 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6319 AndNode, DAG.getConstant(0, MVT::i8));
6322 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6323 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6324 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6326 if (Op.getOpcode() == ISD::SHL_PARTS) {
6327 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6328 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6330 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6331 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6334 SDValue Ops[2] = { Lo, Hi };
6335 return DAG.getMergeValues(Ops, 2, dl);
6338 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6339 SelectionDAG &DAG) const {
6340 EVT SrcVT = Op.getOperand(0).getValueType();
6342 if (SrcVT.isVector())
6345 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6346 "Unknown SINT_TO_FP to lower!");
6348 // These are really Legal; return the operand so the caller accepts it as
6350 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6352 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6353 Subtarget->is64Bit()) {
6357 DebugLoc dl = Op.getDebugLoc();
6358 unsigned Size = SrcVT.getSizeInBits()/8;
6359 MachineFunction &MF = DAG.getMachineFunction();
6360 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6361 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6362 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6364 MachinePointerInfo::getFixedStack(SSFI),
6366 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6369 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6371 SelectionDAG &DAG) const {
6373 DebugLoc DL = Op.getDebugLoc();
6375 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6377 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6379 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6381 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6383 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6384 MachineMemOperand *MMO =
6385 DAG.getMachineFunction()
6386 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6387 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6389 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6390 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6392 Tys, Ops, array_lengthof(Ops),
6396 Chain = Result.getValue(1);
6397 SDValue InFlag = Result.getValue(2);
6399 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6400 // shouldn't be necessary except that RFP cannot be live across
6401 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6402 MachineFunction &MF = DAG.getMachineFunction();
6403 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6404 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6405 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6406 Tys = DAG.getVTList(MVT::Other);
6408 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6410 MachineMemOperand *MMO =
6411 DAG.getMachineFunction()
6412 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6413 MachineMemOperand::MOStore, SSFISize, SSFISize);
6415 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6416 Ops, array_lengthof(Ops),
6417 Op.getValueType(), MMO);
6418 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6419 MachinePointerInfo::getFixedStack(SSFI),
6426 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6427 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6428 SelectionDAG &DAG) const {
6429 // This algorithm is not obvious. Here it is in C code, more or less:
6431 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6432 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6433 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6435 // Copy ints to xmm registers.
6436 __m128i xh = _mm_cvtsi32_si128( hi );
6437 __m128i xl = _mm_cvtsi32_si128( lo );
6439 // Combine into low half of a single xmm register.
6440 __m128i x = _mm_unpacklo_epi32( xh, xl );
6444 // Merge in appropriate exponents to give the integer bits the right
6446 x = _mm_unpacklo_epi32( x, exp );
6448 // Subtract away the biases to deal with the IEEE-754 double precision
6450 d = _mm_sub_pd( (__m128d) x, bias );
6452 // All conversions up to here are exact. The correctly rounded result is
6453 // calculated using the current rounding mode using the following
6455 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6456 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6457 // store doesn't really need to be here (except
6458 // maybe to zero the other double)
6463 DebugLoc dl = Op.getDebugLoc();
6464 LLVMContext *Context = DAG.getContext();
6466 // Build some magic constants.
6467 std::vector<Constant*> CV0;
6468 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6469 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6470 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6471 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6472 Constant *C0 = ConstantVector::get(CV0);
6473 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6475 std::vector<Constant*> CV1;
6477 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6479 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6480 Constant *C1 = ConstantVector::get(CV1);
6481 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6483 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6484 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6486 DAG.getIntPtrConstant(1)));
6487 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6488 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6490 DAG.getIntPtrConstant(0)));
6491 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6492 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6493 MachinePointerInfo::getConstantPool(),
6495 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6496 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6497 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6498 MachinePointerInfo::getConstantPool(),
6500 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6502 // Add the halves; easiest way is to swap them into another reg first.
6503 int ShufMask[2] = { 1, -1 };
6504 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6505 DAG.getUNDEF(MVT::v2f64), ShufMask);
6506 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6507 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6508 DAG.getIntPtrConstant(0));
6511 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6512 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6513 SelectionDAG &DAG) const {
6514 DebugLoc dl = Op.getDebugLoc();
6515 // FP constant to bias correct the final result.
6516 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6519 // Load the 32-bit value into an XMM register.
6520 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6521 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6523 DAG.getIntPtrConstant(0)));
6525 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6526 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6527 DAG.getIntPtrConstant(0));
6529 // Or the load with the bias.
6530 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6531 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6532 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6534 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6535 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6536 MVT::v2f64, Bias)));
6537 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6538 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6539 DAG.getIntPtrConstant(0));
6541 // Subtract the bias.
6542 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6544 // Handle final rounding.
6545 EVT DestVT = Op.getValueType();
6547 if (DestVT.bitsLT(MVT::f64)) {
6548 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6549 DAG.getIntPtrConstant(0));
6550 } else if (DestVT.bitsGT(MVT::f64)) {
6551 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6554 // Handle final rounding.
6558 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6559 SelectionDAG &DAG) const {
6560 SDValue N0 = Op.getOperand(0);
6561 DebugLoc dl = Op.getDebugLoc();
6563 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6564 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6565 // the optimization here.
6566 if (DAG.SignBitIsZero(N0))
6567 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6569 EVT SrcVT = N0.getValueType();
6570 EVT DstVT = Op.getValueType();
6571 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6572 return LowerUINT_TO_FP_i64(Op, DAG);
6573 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6574 return LowerUINT_TO_FP_i32(Op, DAG);
6576 // Make a 64-bit buffer, and use it to build an FILD.
6577 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6578 if (SrcVT == MVT::i32) {
6579 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6580 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6581 getPointerTy(), StackSlot, WordOff);
6582 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6583 StackSlot, MachinePointerInfo(),
6585 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6586 OffsetSlot, MachinePointerInfo(),
6588 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6592 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6593 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6594 StackSlot, MachinePointerInfo(),
6596 // For i64 source, we need to add the appropriate power of 2 if the input
6597 // was negative. This is the same as the optimization in
6598 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6599 // we must be careful to do the computation in x87 extended precision, not
6600 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6601 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6602 MachineMemOperand *MMO =
6603 DAG.getMachineFunction()
6604 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6605 MachineMemOperand::MOLoad, 8, 8);
6607 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6608 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6609 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6612 APInt FF(32, 0x5F800000ULL);
6614 // Check whether the sign bit is set.
6615 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6616 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6619 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6620 SDValue FudgePtr = DAG.getConstantPool(
6621 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6624 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6625 SDValue Zero = DAG.getIntPtrConstant(0);
6626 SDValue Four = DAG.getIntPtrConstant(4);
6627 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6629 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6631 // Load the value out, extending it from f32 to f80.
6632 // FIXME: Avoid the extend by constructing the right constant pool?
6633 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6634 FudgePtr, MachinePointerInfo::getConstantPool(),
6635 MVT::f32, false, false, 4);
6636 // Extend everything to 80 bits to force it to be done on x87.
6637 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6638 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6641 std::pair<SDValue,SDValue> X86TargetLowering::
6642 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6643 DebugLoc DL = Op.getDebugLoc();
6645 EVT DstTy = Op.getValueType();
6648 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6652 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6653 DstTy.getSimpleVT() >= MVT::i16 &&
6654 "Unknown FP_TO_SINT to lower!");
6656 // These are really Legal.
6657 if (DstTy == MVT::i32 &&
6658 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6659 return std::make_pair(SDValue(), SDValue());
6660 if (Subtarget->is64Bit() &&
6661 DstTy == MVT::i64 &&
6662 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6663 return std::make_pair(SDValue(), SDValue());
6665 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6667 MachineFunction &MF = DAG.getMachineFunction();
6668 unsigned MemSize = DstTy.getSizeInBits()/8;
6669 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6670 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6675 switch (DstTy.getSimpleVT().SimpleTy) {
6676 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6677 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6678 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6679 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6682 SDValue Chain = DAG.getEntryNode();
6683 SDValue Value = Op.getOperand(0);
6684 EVT TheVT = Op.getOperand(0).getValueType();
6685 if (isScalarFPTypeInSSEReg(TheVT)) {
6686 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6687 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6688 MachinePointerInfo::getFixedStack(SSFI),
6690 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6692 Chain, StackSlot, DAG.getValueType(TheVT)
6695 MachineMemOperand *MMO =
6696 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6697 MachineMemOperand::MOLoad, MemSize, MemSize);
6698 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6700 Chain = Value.getValue(1);
6701 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6702 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6705 MachineMemOperand *MMO =
6706 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6707 MachineMemOperand::MOStore, MemSize, MemSize);
6709 // Build the FP_TO_INT*_IN_MEM
6710 SDValue Ops[] = { Chain, Value, StackSlot };
6711 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6712 Ops, 3, DstTy, MMO);
6714 return std::make_pair(FIST, StackSlot);
6717 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6718 SelectionDAG &DAG) const {
6719 if (Op.getValueType().isVector())
6722 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6723 SDValue FIST = Vals.first, StackSlot = Vals.second;
6724 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6725 if (FIST.getNode() == 0) return Op;
6728 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6729 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6732 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6733 SelectionDAG &DAG) const {
6734 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6735 SDValue FIST = Vals.first, StackSlot = Vals.second;
6736 assert(FIST.getNode() && "Unexpected failure");
6739 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6740 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6743 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6744 SelectionDAG &DAG) const {
6745 LLVMContext *Context = DAG.getContext();
6746 DebugLoc dl = Op.getDebugLoc();
6747 EVT VT = Op.getValueType();
6750 EltVT = VT.getVectorElementType();
6751 std::vector<Constant*> CV;
6752 if (EltVT == MVT::f64) {
6753 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6757 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6763 Constant *C = ConstantVector::get(CV);
6764 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6765 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6766 MachinePointerInfo::getConstantPool(),
6768 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6771 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6772 LLVMContext *Context = DAG.getContext();
6773 DebugLoc dl = Op.getDebugLoc();
6774 EVT VT = Op.getValueType();
6777 EltVT = VT.getVectorElementType();
6778 std::vector<Constant*> CV;
6779 if (EltVT == MVT::f64) {
6780 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6784 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6790 Constant *C = ConstantVector::get(CV);
6791 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6792 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6793 MachinePointerInfo::getConstantPool(),
6795 if (VT.isVector()) {
6796 return DAG.getNode(ISD::BITCAST, dl, VT,
6797 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6798 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6800 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6802 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6806 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6807 LLVMContext *Context = DAG.getContext();
6808 SDValue Op0 = Op.getOperand(0);
6809 SDValue Op1 = Op.getOperand(1);
6810 DebugLoc dl = Op.getDebugLoc();
6811 EVT VT = Op.getValueType();
6812 EVT SrcVT = Op1.getValueType();
6814 // If second operand is smaller, extend it first.
6815 if (SrcVT.bitsLT(VT)) {
6816 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6819 // And if it is bigger, shrink it first.
6820 if (SrcVT.bitsGT(VT)) {
6821 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6825 // At this point the operands and the result should have the same
6826 // type, and that won't be f80 since that is not custom lowered.
6828 // First get the sign bit of second operand.
6829 std::vector<Constant*> CV;
6830 if (SrcVT == MVT::f64) {
6831 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6832 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6834 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6835 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6836 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6837 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6839 Constant *C = ConstantVector::get(CV);
6840 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6841 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6842 MachinePointerInfo::getConstantPool(),
6844 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6846 // Shift sign bit right or left if the two operands have different types.
6847 if (SrcVT.bitsGT(VT)) {
6848 // Op0 is MVT::f32, Op1 is MVT::f64.
6849 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6850 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6851 DAG.getConstant(32, MVT::i32));
6852 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6853 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6854 DAG.getIntPtrConstant(0));
6857 // Clear first operand sign bit.
6859 if (VT == MVT::f64) {
6860 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6861 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6863 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6864 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6865 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6866 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6868 C = ConstantVector::get(CV);
6869 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6870 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6871 MachinePointerInfo::getConstantPool(),
6873 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6875 // Or the value with the sign bit.
6876 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6879 /// Emit nodes that will be selected as "test Op0,Op0", or something
6881 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6882 SelectionDAG &DAG) const {
6883 DebugLoc dl = Op.getDebugLoc();
6885 // CF and OF aren't always set the way we want. Determine which
6886 // of these we need.
6887 bool NeedCF = false;
6888 bool NeedOF = false;
6891 case X86::COND_A: case X86::COND_AE:
6892 case X86::COND_B: case X86::COND_BE:
6895 case X86::COND_G: case X86::COND_GE:
6896 case X86::COND_L: case X86::COND_LE:
6897 case X86::COND_O: case X86::COND_NO:
6902 // See if we can use the EFLAGS value from the operand instead of
6903 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6904 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6905 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6906 // Emit a CMP with 0, which is the TEST pattern.
6907 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6908 DAG.getConstant(0, Op.getValueType()));
6910 unsigned Opcode = 0;
6911 unsigned NumOperands = 0;
6912 switch (Op.getNode()->getOpcode()) {
6914 // Due to an isel shortcoming, be conservative if this add is likely to be
6915 // selected as part of a load-modify-store instruction. When the root node
6916 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6917 // uses of other nodes in the match, such as the ADD in this case. This
6918 // leads to the ADD being left around and reselected, with the result being
6919 // two adds in the output. Alas, even if none our users are stores, that
6920 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6921 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6922 // climbing the DAG back to the root, and it doesn't seem to be worth the
6924 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6925 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6926 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6929 if (ConstantSDNode *C =
6930 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6931 // An add of one will be selected as an INC.
6932 if (C->getAPIntValue() == 1) {
6933 Opcode = X86ISD::INC;
6938 // An add of negative one (subtract of one) will be selected as a DEC.
6939 if (C->getAPIntValue().isAllOnesValue()) {
6940 Opcode = X86ISD::DEC;
6946 // Otherwise use a regular EFLAGS-setting add.
6947 Opcode = X86ISD::ADD;
6951 // If the primary and result isn't used, don't bother using X86ISD::AND,
6952 // because a TEST instruction will be better.
6953 bool NonFlagUse = false;
6954 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6955 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6957 unsigned UOpNo = UI.getOperandNo();
6958 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6959 // Look pass truncate.
6960 UOpNo = User->use_begin().getOperandNo();
6961 User = *User->use_begin();
6964 if (User->getOpcode() != ISD::BRCOND &&
6965 User->getOpcode() != ISD::SETCC &&
6966 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6979 // Due to the ISEL shortcoming noted above, be conservative if this op is
6980 // likely to be selected as part of a load-modify-store instruction.
6981 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6982 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6983 if (UI->getOpcode() == ISD::STORE)
6986 // Otherwise use a regular EFLAGS-setting instruction.
6987 switch (Op.getNode()->getOpcode()) {
6988 default: llvm_unreachable("unexpected operator!");
6989 case ISD::SUB: Opcode = X86ISD::SUB; break;
6990 case ISD::OR: Opcode = X86ISD::OR; break;
6991 case ISD::XOR: Opcode = X86ISD::XOR; break;
6992 case ISD::AND: Opcode = X86ISD::AND; break;
7004 return SDValue(Op.getNode(), 1);
7011 // Emit a CMP with 0, which is the TEST pattern.
7012 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7013 DAG.getConstant(0, Op.getValueType()));
7015 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7016 SmallVector<SDValue, 4> Ops;
7017 for (unsigned i = 0; i != NumOperands; ++i)
7018 Ops.push_back(Op.getOperand(i));
7020 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7021 DAG.ReplaceAllUsesWith(Op, New);
7022 return SDValue(New.getNode(), 1);
7025 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7027 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7028 SelectionDAG &DAG) const {
7029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7030 if (C->getAPIntValue() == 0)
7031 return EmitTest(Op0, X86CC, DAG);
7033 DebugLoc dl = Op0.getDebugLoc();
7034 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7037 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7038 /// if it's possible.
7039 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7040 DebugLoc dl, SelectionDAG &DAG) const {
7041 SDValue Op0 = And.getOperand(0);
7042 SDValue Op1 = And.getOperand(1);
7043 if (Op0.getOpcode() == ISD::TRUNCATE)
7044 Op0 = Op0.getOperand(0);
7045 if (Op1.getOpcode() == ISD::TRUNCATE)
7046 Op1 = Op1.getOperand(0);
7049 if (Op1.getOpcode() == ISD::SHL)
7050 std::swap(Op0, Op1);
7051 if (Op0.getOpcode() == ISD::SHL) {
7052 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7053 if (And00C->getZExtValue() == 1) {
7054 // If we looked past a truncate, check that it's only truncating away
7056 unsigned BitWidth = Op0.getValueSizeInBits();
7057 unsigned AndBitWidth = And.getValueSizeInBits();
7058 if (BitWidth > AndBitWidth) {
7059 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7060 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7061 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7065 RHS = Op0.getOperand(1);
7067 } else if (Op1.getOpcode() == ISD::Constant) {
7068 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7069 SDValue AndLHS = Op0;
7070 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7071 LHS = AndLHS.getOperand(0);
7072 RHS = AndLHS.getOperand(1);
7076 if (LHS.getNode()) {
7077 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7078 // instruction. Since the shift amount is in-range-or-undefined, we know
7079 // that doing a bittest on the i32 value is ok. We extend to i32 because
7080 // the encoding for the i16 version is larger than the i32 version.
7081 // Also promote i16 to i32 for performance / code size reason.
7082 if (LHS.getValueType() == MVT::i8 ||
7083 LHS.getValueType() == MVT::i16)
7084 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7086 // If the operand types disagree, extend the shift amount to match. Since
7087 // BT ignores high bits (like shifts) we can use anyextend.
7088 if (LHS.getValueType() != RHS.getValueType())
7089 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7091 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7092 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7093 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7094 DAG.getConstant(Cond, MVT::i8), BT);
7100 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7101 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7102 SDValue Op0 = Op.getOperand(0);
7103 SDValue Op1 = Op.getOperand(1);
7104 DebugLoc dl = Op.getDebugLoc();
7105 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7107 // Optimize to BT if possible.
7108 // Lower (X & (1 << N)) == 0 to BT(X, N).
7109 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7110 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7111 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7112 Op1.getOpcode() == ISD::Constant &&
7113 cast<ConstantSDNode>(Op1)->isNullValue() &&
7114 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7115 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7116 if (NewSetCC.getNode())
7120 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7122 if (Op1.getOpcode() == ISD::Constant &&
7123 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7124 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7125 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7127 // If the input is a setcc, then reuse the input setcc or use a new one with
7128 // the inverted condition.
7129 if (Op0.getOpcode() == X86ISD::SETCC) {
7130 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7131 bool Invert = (CC == ISD::SETNE) ^
7132 cast<ConstantSDNode>(Op1)->isNullValue();
7133 if (!Invert) return Op0;
7135 CCode = X86::GetOppositeBranchCondition(CCode);
7136 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7137 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7141 bool isFP = Op1.getValueType().isFloatingPoint();
7142 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7143 if (X86CC == X86::COND_INVALID)
7146 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7147 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7148 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7151 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7153 SDValue Op0 = Op.getOperand(0);
7154 SDValue Op1 = Op.getOperand(1);
7155 SDValue CC = Op.getOperand(2);
7156 EVT VT = Op.getValueType();
7157 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7158 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7159 DebugLoc dl = Op.getDebugLoc();
7163 EVT VT0 = Op0.getValueType();
7164 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7165 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7168 switch (SetCCOpcode) {
7171 case ISD::SETEQ: SSECC = 0; break;
7173 case ISD::SETGT: Swap = true; // Fallthrough
7175 case ISD::SETOLT: SSECC = 1; break;
7177 case ISD::SETGE: Swap = true; // Fallthrough
7179 case ISD::SETOLE: SSECC = 2; break;
7180 case ISD::SETUO: SSECC = 3; break;
7182 case ISD::SETNE: SSECC = 4; break;
7183 case ISD::SETULE: Swap = true;
7184 case ISD::SETUGE: SSECC = 5; break;
7185 case ISD::SETULT: Swap = true;
7186 case ISD::SETUGT: SSECC = 6; break;
7187 case ISD::SETO: SSECC = 7; break;
7190 std::swap(Op0, Op1);
7192 // In the two special cases we can't handle, emit two comparisons.
7194 if (SetCCOpcode == ISD::SETUEQ) {
7196 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7197 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7198 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7200 else if (SetCCOpcode == ISD::SETONE) {
7202 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7203 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7204 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7206 llvm_unreachable("Illegal FP comparison");
7208 // Handle all other FP comparisons here.
7209 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7212 // We are handling one of the integer comparisons here. Since SSE only has
7213 // GT and EQ comparisons for integer, swapping operands and multiple
7214 // operations may be required for some comparisons.
7215 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7216 bool Swap = false, Invert = false, FlipSigns = false;
7218 switch (VT.getSimpleVT().SimpleTy) {
7220 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7221 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7222 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7223 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7226 switch (SetCCOpcode) {
7228 case ISD::SETNE: Invert = true;
7229 case ISD::SETEQ: Opc = EQOpc; break;
7230 case ISD::SETLT: Swap = true;
7231 case ISD::SETGT: Opc = GTOpc; break;
7232 case ISD::SETGE: Swap = true;
7233 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7234 case ISD::SETULT: Swap = true;
7235 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7236 case ISD::SETUGE: Swap = true;
7237 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7240 std::swap(Op0, Op1);
7242 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7243 // bits of the inputs before performing those operations.
7245 EVT EltVT = VT.getVectorElementType();
7246 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7248 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7249 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7251 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7252 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7255 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7257 // If the logical-not of the result is required, perform that now.
7259 Result = DAG.getNOT(dl, Result, VT);
7264 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7265 static bool isX86LogicalCmp(SDValue Op) {
7266 unsigned Opc = Op.getNode()->getOpcode();
7267 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7269 if (Op.getResNo() == 1 &&
7270 (Opc == X86ISD::ADD ||
7271 Opc == X86ISD::SUB ||
7272 Opc == X86ISD::ADC ||
7273 Opc == X86ISD::SBB ||
7274 Opc == X86ISD::SMUL ||
7275 Opc == X86ISD::UMUL ||
7276 Opc == X86ISD::INC ||
7277 Opc == X86ISD::DEC ||
7278 Opc == X86ISD::OR ||
7279 Opc == X86ISD::XOR ||
7280 Opc == X86ISD::AND))
7283 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7289 static bool isZero(SDValue V) {
7290 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7291 return C && C->isNullValue();
7294 static bool isAllOnes(SDValue V) {
7295 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7296 return C && C->isAllOnesValue();
7299 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7300 bool addTest = true;
7301 SDValue Cond = Op.getOperand(0);
7302 SDValue Op1 = Op.getOperand(1);
7303 SDValue Op2 = Op.getOperand(2);
7304 DebugLoc DL = Op.getDebugLoc();
7307 if (Cond.getOpcode() == ISD::SETCC) {
7308 SDValue NewCond = LowerSETCC(Cond, DAG);
7309 if (NewCond.getNode())
7313 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7314 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7315 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7316 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7317 if (Cond.getOpcode() == X86ISD::SETCC &&
7318 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7319 isZero(Cond.getOperand(1).getOperand(1))) {
7320 SDValue Cmp = Cond.getOperand(1);
7322 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7324 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7325 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7326 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7328 SDValue CmpOp0 = Cmp.getOperand(0);
7329 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7330 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7332 SDValue Res = // Res = 0 or -1.
7333 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7334 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7336 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7337 Res = DAG.getNOT(DL, Res, Res.getValueType());
7339 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7340 if (N2C == 0 || !N2C->isNullValue())
7341 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7346 // Look past (and (setcc_carry (cmp ...)), 1).
7347 if (Cond.getOpcode() == ISD::AND &&
7348 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7349 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7350 if (C && C->getAPIntValue() == 1)
7351 Cond = Cond.getOperand(0);
7354 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7355 // setting operand in place of the X86ISD::SETCC.
7356 if (Cond.getOpcode() == X86ISD::SETCC ||
7357 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7358 CC = Cond.getOperand(0);
7360 SDValue Cmp = Cond.getOperand(1);
7361 unsigned Opc = Cmp.getOpcode();
7362 EVT VT = Op.getValueType();
7364 bool IllegalFPCMov = false;
7365 if (VT.isFloatingPoint() && !VT.isVector() &&
7366 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7367 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7369 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7370 Opc == X86ISD::BT) { // FIXME
7377 // Look pass the truncate.
7378 if (Cond.getOpcode() == ISD::TRUNCATE)
7379 Cond = Cond.getOperand(0);
7381 // We know the result of AND is compared against zero. Try to match
7383 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7384 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7385 if (NewSetCC.getNode()) {
7386 CC = NewSetCC.getOperand(0);
7387 Cond = NewSetCC.getOperand(1);
7394 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7395 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7398 // a < b ? -1 : 0 -> RES = ~setcc_carry
7399 // a < b ? 0 : -1 -> RES = setcc_carry
7400 // a >= b ? -1 : 0 -> RES = setcc_carry
7401 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7402 if (Cond.getOpcode() == X86ISD::CMP) {
7403 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7405 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7406 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7407 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7408 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7409 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7410 return DAG.getNOT(DL, Res, Res.getValueType());
7415 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7416 // condition is true.
7417 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7418 SDValue Ops[] = { Op2, Op1, CC, Cond };
7419 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7422 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7423 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7424 // from the AND / OR.
7425 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7426 Opc = Op.getOpcode();
7427 if (Opc != ISD::OR && Opc != ISD::AND)
7429 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7430 Op.getOperand(0).hasOneUse() &&
7431 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7432 Op.getOperand(1).hasOneUse());
7435 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7436 // 1 and that the SETCC node has a single use.
7437 static bool isXor1OfSetCC(SDValue Op) {
7438 if (Op.getOpcode() != ISD::XOR)
7440 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7441 if (N1C && N1C->getAPIntValue() == 1) {
7442 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7443 Op.getOperand(0).hasOneUse();
7448 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7449 bool addTest = true;
7450 SDValue Chain = Op.getOperand(0);
7451 SDValue Cond = Op.getOperand(1);
7452 SDValue Dest = Op.getOperand(2);
7453 DebugLoc dl = Op.getDebugLoc();
7456 if (Cond.getOpcode() == ISD::SETCC) {
7457 SDValue NewCond = LowerSETCC(Cond, DAG);
7458 if (NewCond.getNode())
7462 // FIXME: LowerXALUO doesn't handle these!!
7463 else if (Cond.getOpcode() == X86ISD::ADD ||
7464 Cond.getOpcode() == X86ISD::SUB ||
7465 Cond.getOpcode() == X86ISD::SMUL ||
7466 Cond.getOpcode() == X86ISD::UMUL)
7467 Cond = LowerXALUO(Cond, DAG);
7470 // Look pass (and (setcc_carry (cmp ...)), 1).
7471 if (Cond.getOpcode() == ISD::AND &&
7472 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7473 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7474 if (C && C->getAPIntValue() == 1)
7475 Cond = Cond.getOperand(0);
7478 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7479 // setting operand in place of the X86ISD::SETCC.
7480 if (Cond.getOpcode() == X86ISD::SETCC ||
7481 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7482 CC = Cond.getOperand(0);
7484 SDValue Cmp = Cond.getOperand(1);
7485 unsigned Opc = Cmp.getOpcode();
7486 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7487 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7491 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7495 // These can only come from an arithmetic instruction with overflow,
7496 // e.g. SADDO, UADDO.
7497 Cond = Cond.getNode()->getOperand(1);
7504 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7505 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7506 if (CondOpc == ISD::OR) {
7507 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7508 // two branches instead of an explicit OR instruction with a
7510 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7511 isX86LogicalCmp(Cmp)) {
7512 CC = Cond.getOperand(0).getOperand(0);
7513 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7514 Chain, Dest, CC, Cmp);
7515 CC = Cond.getOperand(1).getOperand(0);
7519 } else { // ISD::AND
7520 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7521 // two branches instead of an explicit AND instruction with a
7522 // separate test. However, we only do this if this block doesn't
7523 // have a fall-through edge, because this requires an explicit
7524 // jmp when the condition is false.
7525 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7526 isX86LogicalCmp(Cmp) &&
7527 Op.getNode()->hasOneUse()) {
7528 X86::CondCode CCode =
7529 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7530 CCode = X86::GetOppositeBranchCondition(CCode);
7531 CC = DAG.getConstant(CCode, MVT::i8);
7532 SDNode *User = *Op.getNode()->use_begin();
7533 // Look for an unconditional branch following this conditional branch.
7534 // We need this because we need to reverse the successors in order
7535 // to implement FCMP_OEQ.
7536 if (User->getOpcode() == ISD::BR) {
7537 SDValue FalseBB = User->getOperand(1);
7539 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7540 assert(NewBR == User);
7544 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7545 Chain, Dest, CC, Cmp);
7546 X86::CondCode CCode =
7547 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7548 CCode = X86::GetOppositeBranchCondition(CCode);
7549 CC = DAG.getConstant(CCode, MVT::i8);
7555 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7556 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7557 // It should be transformed during dag combiner except when the condition
7558 // is set by a arithmetics with overflow node.
7559 X86::CondCode CCode =
7560 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7561 CCode = X86::GetOppositeBranchCondition(CCode);
7562 CC = DAG.getConstant(CCode, MVT::i8);
7563 Cond = Cond.getOperand(0).getOperand(1);
7569 // Look pass the truncate.
7570 if (Cond.getOpcode() == ISD::TRUNCATE)
7571 Cond = Cond.getOperand(0);
7573 // We know the result of AND is compared against zero. Try to match
7575 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7576 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7577 if (NewSetCC.getNode()) {
7578 CC = NewSetCC.getOperand(0);
7579 Cond = NewSetCC.getOperand(1);
7586 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7587 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7589 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7590 Chain, Dest, CC, Cond);
7594 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7595 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7596 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7597 // that the guard pages used by the OS virtual memory manager are allocated in
7598 // correct sequence.
7600 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7601 SelectionDAG &DAG) const {
7602 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7603 "This should be used only on Windows targets");
7604 DebugLoc dl = Op.getDebugLoc();
7607 SDValue Chain = Op.getOperand(0);
7608 SDValue Size = Op.getOperand(1);
7609 // FIXME: Ensure alignment here
7613 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7615 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7616 Flag = Chain.getValue(1);
7618 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7620 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7621 Flag = Chain.getValue(1);
7623 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7625 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7626 return DAG.getMergeValues(Ops1, 2, dl);
7629 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7630 MachineFunction &MF = DAG.getMachineFunction();
7631 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7633 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7634 DebugLoc DL = Op.getDebugLoc();
7636 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7637 // vastart just stores the address of the VarArgsFrameIndex slot into the
7638 // memory location argument.
7639 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7641 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7642 MachinePointerInfo(SV), false, false, 0);
7646 // gp_offset (0 - 6 * 8)
7647 // fp_offset (48 - 48 + 8 * 16)
7648 // overflow_arg_area (point to parameters coming in memory).
7650 SmallVector<SDValue, 8> MemOps;
7651 SDValue FIN = Op.getOperand(1);
7653 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7654 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7656 FIN, MachinePointerInfo(SV), false, false, 0);
7657 MemOps.push_back(Store);
7660 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7661 FIN, DAG.getIntPtrConstant(4));
7662 Store = DAG.getStore(Op.getOperand(0), DL,
7663 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7665 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7666 MemOps.push_back(Store);
7668 // Store ptr to overflow_arg_area
7669 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7670 FIN, DAG.getIntPtrConstant(4));
7671 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7673 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7674 MachinePointerInfo(SV, 8),
7676 MemOps.push_back(Store);
7678 // Store ptr to reg_save_area.
7679 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7680 FIN, DAG.getIntPtrConstant(8));
7681 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7683 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7684 MachinePointerInfo(SV, 16), false, false, 0);
7685 MemOps.push_back(Store);
7686 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7687 &MemOps[0], MemOps.size());
7690 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7691 assert(Subtarget->is64Bit() &&
7692 "LowerVAARG only handles 64-bit va_arg!");
7693 assert((Subtarget->isTargetLinux() ||
7694 Subtarget->isTargetDarwin()) &&
7695 "Unhandled target in LowerVAARG");
7696 assert(Op.getNode()->getNumOperands() == 4);
7697 SDValue Chain = Op.getOperand(0);
7698 SDValue SrcPtr = Op.getOperand(1);
7699 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7700 unsigned Align = Op.getConstantOperandVal(3);
7701 DebugLoc dl = Op.getDebugLoc();
7703 EVT ArgVT = Op.getNode()->getValueType(0);
7704 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7705 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7708 // Decide which area this value should be read from.
7709 // TODO: Implement the AMD64 ABI in its entirety. This simple
7710 // selection mechanism works only for the basic types.
7711 if (ArgVT == MVT::f80) {
7712 llvm_unreachable("va_arg for f80 not yet implemented");
7713 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7714 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7715 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7716 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7718 llvm_unreachable("Unhandled argument type in LowerVAARG");
7722 // Sanity Check: Make sure using fp_offset makes sense.
7723 assert(!UseSoftFloat &&
7724 !(DAG.getMachineFunction()
7725 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7726 Subtarget->hasXMM());
7729 // Insert VAARG_64 node into the DAG
7730 // VAARG_64 returns two values: Variable Argument Address, Chain
7731 SmallVector<SDValue, 11> InstOps;
7732 InstOps.push_back(Chain);
7733 InstOps.push_back(SrcPtr);
7734 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7735 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7736 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7737 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7738 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7739 VTs, &InstOps[0], InstOps.size(),
7741 MachinePointerInfo(SV),
7746 Chain = VAARG.getValue(1);
7748 // Load the next argument and return it
7749 return DAG.getLoad(ArgVT, dl,
7752 MachinePointerInfo(),
7756 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7757 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7758 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7759 SDValue Chain = Op.getOperand(0);
7760 SDValue DstPtr = Op.getOperand(1);
7761 SDValue SrcPtr = Op.getOperand(2);
7762 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7763 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7764 DebugLoc DL = Op.getDebugLoc();
7766 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7767 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7769 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7773 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7774 DebugLoc dl = Op.getDebugLoc();
7775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7777 default: return SDValue(); // Don't custom lower most intrinsics.
7778 // Comparison intrinsics.
7779 case Intrinsic::x86_sse_comieq_ss:
7780 case Intrinsic::x86_sse_comilt_ss:
7781 case Intrinsic::x86_sse_comile_ss:
7782 case Intrinsic::x86_sse_comigt_ss:
7783 case Intrinsic::x86_sse_comige_ss:
7784 case Intrinsic::x86_sse_comineq_ss:
7785 case Intrinsic::x86_sse_ucomieq_ss:
7786 case Intrinsic::x86_sse_ucomilt_ss:
7787 case Intrinsic::x86_sse_ucomile_ss:
7788 case Intrinsic::x86_sse_ucomigt_ss:
7789 case Intrinsic::x86_sse_ucomige_ss:
7790 case Intrinsic::x86_sse_ucomineq_ss:
7791 case Intrinsic::x86_sse2_comieq_sd:
7792 case Intrinsic::x86_sse2_comilt_sd:
7793 case Intrinsic::x86_sse2_comile_sd:
7794 case Intrinsic::x86_sse2_comigt_sd:
7795 case Intrinsic::x86_sse2_comige_sd:
7796 case Intrinsic::x86_sse2_comineq_sd:
7797 case Intrinsic::x86_sse2_ucomieq_sd:
7798 case Intrinsic::x86_sse2_ucomilt_sd:
7799 case Intrinsic::x86_sse2_ucomile_sd:
7800 case Intrinsic::x86_sse2_ucomigt_sd:
7801 case Intrinsic::x86_sse2_ucomige_sd:
7802 case Intrinsic::x86_sse2_ucomineq_sd: {
7804 ISD::CondCode CC = ISD::SETCC_INVALID;
7807 case Intrinsic::x86_sse_comieq_ss:
7808 case Intrinsic::x86_sse2_comieq_sd:
7812 case Intrinsic::x86_sse_comilt_ss:
7813 case Intrinsic::x86_sse2_comilt_sd:
7817 case Intrinsic::x86_sse_comile_ss:
7818 case Intrinsic::x86_sse2_comile_sd:
7822 case Intrinsic::x86_sse_comigt_ss:
7823 case Intrinsic::x86_sse2_comigt_sd:
7827 case Intrinsic::x86_sse_comige_ss:
7828 case Intrinsic::x86_sse2_comige_sd:
7832 case Intrinsic::x86_sse_comineq_ss:
7833 case Intrinsic::x86_sse2_comineq_sd:
7837 case Intrinsic::x86_sse_ucomieq_ss:
7838 case Intrinsic::x86_sse2_ucomieq_sd:
7839 Opc = X86ISD::UCOMI;
7842 case Intrinsic::x86_sse_ucomilt_ss:
7843 case Intrinsic::x86_sse2_ucomilt_sd:
7844 Opc = X86ISD::UCOMI;
7847 case Intrinsic::x86_sse_ucomile_ss:
7848 case Intrinsic::x86_sse2_ucomile_sd:
7849 Opc = X86ISD::UCOMI;
7852 case Intrinsic::x86_sse_ucomigt_ss:
7853 case Intrinsic::x86_sse2_ucomigt_sd:
7854 Opc = X86ISD::UCOMI;
7857 case Intrinsic::x86_sse_ucomige_ss:
7858 case Intrinsic::x86_sse2_ucomige_sd:
7859 Opc = X86ISD::UCOMI;
7862 case Intrinsic::x86_sse_ucomineq_ss:
7863 case Intrinsic::x86_sse2_ucomineq_sd:
7864 Opc = X86ISD::UCOMI;
7869 SDValue LHS = Op.getOperand(1);
7870 SDValue RHS = Op.getOperand(2);
7871 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7872 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7873 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7874 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7875 DAG.getConstant(X86CC, MVT::i8), Cond);
7876 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7878 // ptest and testp intrinsics. The intrinsic these come from are designed to
7879 // return an integer value, not just an instruction so lower it to the ptest
7880 // or testp pattern and a setcc for the result.
7881 case Intrinsic::x86_sse41_ptestz:
7882 case Intrinsic::x86_sse41_ptestc:
7883 case Intrinsic::x86_sse41_ptestnzc:
7884 case Intrinsic::x86_avx_ptestz_256:
7885 case Intrinsic::x86_avx_ptestc_256:
7886 case Intrinsic::x86_avx_ptestnzc_256:
7887 case Intrinsic::x86_avx_vtestz_ps:
7888 case Intrinsic::x86_avx_vtestc_ps:
7889 case Intrinsic::x86_avx_vtestnzc_ps:
7890 case Intrinsic::x86_avx_vtestz_pd:
7891 case Intrinsic::x86_avx_vtestc_pd:
7892 case Intrinsic::x86_avx_vtestnzc_pd:
7893 case Intrinsic::x86_avx_vtestz_ps_256:
7894 case Intrinsic::x86_avx_vtestc_ps_256:
7895 case Intrinsic::x86_avx_vtestnzc_ps_256:
7896 case Intrinsic::x86_avx_vtestz_pd_256:
7897 case Intrinsic::x86_avx_vtestc_pd_256:
7898 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7899 bool IsTestPacked = false;
7902 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7903 case Intrinsic::x86_avx_vtestz_ps:
7904 case Intrinsic::x86_avx_vtestz_pd:
7905 case Intrinsic::x86_avx_vtestz_ps_256:
7906 case Intrinsic::x86_avx_vtestz_pd_256:
7907 IsTestPacked = true; // Fallthrough
7908 case Intrinsic::x86_sse41_ptestz:
7909 case Intrinsic::x86_avx_ptestz_256:
7911 X86CC = X86::COND_E;
7913 case Intrinsic::x86_avx_vtestc_ps:
7914 case Intrinsic::x86_avx_vtestc_pd:
7915 case Intrinsic::x86_avx_vtestc_ps_256:
7916 case Intrinsic::x86_avx_vtestc_pd_256:
7917 IsTestPacked = true; // Fallthrough
7918 case Intrinsic::x86_sse41_ptestc:
7919 case Intrinsic::x86_avx_ptestc_256:
7921 X86CC = X86::COND_B;
7923 case Intrinsic::x86_avx_vtestnzc_ps:
7924 case Intrinsic::x86_avx_vtestnzc_pd:
7925 case Intrinsic::x86_avx_vtestnzc_ps_256:
7926 case Intrinsic::x86_avx_vtestnzc_pd_256:
7927 IsTestPacked = true; // Fallthrough
7928 case Intrinsic::x86_sse41_ptestnzc:
7929 case Intrinsic::x86_avx_ptestnzc_256:
7931 X86CC = X86::COND_A;
7935 SDValue LHS = Op.getOperand(1);
7936 SDValue RHS = Op.getOperand(2);
7937 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7938 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7939 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7940 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7941 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7944 // Fix vector shift instructions where the last operand is a non-immediate
7946 case Intrinsic::x86_sse2_pslli_w:
7947 case Intrinsic::x86_sse2_pslli_d:
7948 case Intrinsic::x86_sse2_pslli_q:
7949 case Intrinsic::x86_sse2_psrli_w:
7950 case Intrinsic::x86_sse2_psrli_d:
7951 case Intrinsic::x86_sse2_psrli_q:
7952 case Intrinsic::x86_sse2_psrai_w:
7953 case Intrinsic::x86_sse2_psrai_d:
7954 case Intrinsic::x86_mmx_pslli_w:
7955 case Intrinsic::x86_mmx_pslli_d:
7956 case Intrinsic::x86_mmx_pslli_q:
7957 case Intrinsic::x86_mmx_psrli_w:
7958 case Intrinsic::x86_mmx_psrli_d:
7959 case Intrinsic::x86_mmx_psrli_q:
7960 case Intrinsic::x86_mmx_psrai_w:
7961 case Intrinsic::x86_mmx_psrai_d: {
7962 SDValue ShAmt = Op.getOperand(2);
7963 if (isa<ConstantSDNode>(ShAmt))
7966 unsigned NewIntNo = 0;
7967 EVT ShAmtVT = MVT::v4i32;
7969 case Intrinsic::x86_sse2_pslli_w:
7970 NewIntNo = Intrinsic::x86_sse2_psll_w;
7972 case Intrinsic::x86_sse2_pslli_d:
7973 NewIntNo = Intrinsic::x86_sse2_psll_d;
7975 case Intrinsic::x86_sse2_pslli_q:
7976 NewIntNo = Intrinsic::x86_sse2_psll_q;
7978 case Intrinsic::x86_sse2_psrli_w:
7979 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7981 case Intrinsic::x86_sse2_psrli_d:
7982 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7984 case Intrinsic::x86_sse2_psrli_q:
7985 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7987 case Intrinsic::x86_sse2_psrai_w:
7988 NewIntNo = Intrinsic::x86_sse2_psra_w;
7990 case Intrinsic::x86_sse2_psrai_d:
7991 NewIntNo = Intrinsic::x86_sse2_psra_d;
7994 ShAmtVT = MVT::v2i32;
7996 case Intrinsic::x86_mmx_pslli_w:
7997 NewIntNo = Intrinsic::x86_mmx_psll_w;
7999 case Intrinsic::x86_mmx_pslli_d:
8000 NewIntNo = Intrinsic::x86_mmx_psll_d;
8002 case Intrinsic::x86_mmx_pslli_q:
8003 NewIntNo = Intrinsic::x86_mmx_psll_q;
8005 case Intrinsic::x86_mmx_psrli_w:
8006 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8008 case Intrinsic::x86_mmx_psrli_d:
8009 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8011 case Intrinsic::x86_mmx_psrli_q:
8012 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8014 case Intrinsic::x86_mmx_psrai_w:
8015 NewIntNo = Intrinsic::x86_mmx_psra_w;
8017 case Intrinsic::x86_mmx_psrai_d:
8018 NewIntNo = Intrinsic::x86_mmx_psra_d;
8020 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8026 // The vector shift intrinsics with scalars uses 32b shift amounts but
8027 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8031 ShOps[1] = DAG.getConstant(0, MVT::i32);
8032 if (ShAmtVT == MVT::v4i32) {
8033 ShOps[2] = DAG.getUNDEF(MVT::i32);
8034 ShOps[3] = DAG.getUNDEF(MVT::i32);
8035 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8037 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8038 // FIXME this must be lowered to get rid of the invalid type.
8041 EVT VT = Op.getValueType();
8042 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8043 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8044 DAG.getConstant(NewIntNo, MVT::i32),
8045 Op.getOperand(1), ShAmt);
8050 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8051 SelectionDAG &DAG) const {
8052 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8053 MFI->setReturnAddressIsTaken(true);
8055 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8056 DebugLoc dl = Op.getDebugLoc();
8059 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8061 DAG.getConstant(TD->getPointerSize(),
8062 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8063 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8064 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8066 MachinePointerInfo(), false, false, 0);
8069 // Just load the return address.
8070 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8071 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8072 RetAddrFI, MachinePointerInfo(), false, false, 0);
8075 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8077 MFI->setFrameAddressIsTaken(true);
8079 EVT VT = Op.getValueType();
8080 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8081 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8082 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8083 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8085 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8086 MachinePointerInfo(),
8091 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8092 SelectionDAG &DAG) const {
8093 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8096 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8097 MachineFunction &MF = DAG.getMachineFunction();
8098 SDValue Chain = Op.getOperand(0);
8099 SDValue Offset = Op.getOperand(1);
8100 SDValue Handler = Op.getOperand(2);
8101 DebugLoc dl = Op.getDebugLoc();
8103 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8104 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8106 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8108 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8109 DAG.getIntPtrConstant(TD->getPointerSize()));
8110 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8111 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8113 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8114 MF.getRegInfo().addLiveOut(StoreAddrReg);
8116 return DAG.getNode(X86ISD::EH_RETURN, dl,
8118 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8121 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8122 SelectionDAG &DAG) const {
8123 SDValue Root = Op.getOperand(0);
8124 SDValue Trmp = Op.getOperand(1); // trampoline
8125 SDValue FPtr = Op.getOperand(2); // nested function
8126 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8127 DebugLoc dl = Op.getDebugLoc();
8129 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8131 if (Subtarget->is64Bit()) {
8132 SDValue OutChains[6];
8134 // Large code-model.
8135 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8136 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8138 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8139 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8141 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8143 // Load the pointer to the nested function into R11.
8144 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8145 SDValue Addr = Trmp;
8146 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8147 Addr, MachinePointerInfo(TrmpAddr),
8150 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8151 DAG.getConstant(2, MVT::i64));
8152 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8153 MachinePointerInfo(TrmpAddr, 2),
8156 // Load the 'nest' parameter value into R10.
8157 // R10 is specified in X86CallingConv.td
8158 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8159 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8160 DAG.getConstant(10, MVT::i64));
8161 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8162 Addr, MachinePointerInfo(TrmpAddr, 10),
8165 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8166 DAG.getConstant(12, MVT::i64));
8167 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8168 MachinePointerInfo(TrmpAddr, 12),
8171 // Jump to the nested function.
8172 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8173 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8174 DAG.getConstant(20, MVT::i64));
8175 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8176 Addr, MachinePointerInfo(TrmpAddr, 20),
8179 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8180 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8181 DAG.getConstant(22, MVT::i64));
8182 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8183 MachinePointerInfo(TrmpAddr, 22),
8187 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8188 return DAG.getMergeValues(Ops, 2, dl);
8190 const Function *Func =
8191 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8192 CallingConv::ID CC = Func->getCallingConv();
8197 llvm_unreachable("Unsupported calling convention");
8198 case CallingConv::C:
8199 case CallingConv::X86_StdCall: {
8200 // Pass 'nest' parameter in ECX.
8201 // Must be kept in sync with X86CallingConv.td
8204 // Check that ECX wasn't needed by an 'inreg' parameter.
8205 const FunctionType *FTy = Func->getFunctionType();
8206 const AttrListPtr &Attrs = Func->getAttributes();
8208 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8209 unsigned InRegCount = 0;
8212 for (FunctionType::param_iterator I = FTy->param_begin(),
8213 E = FTy->param_end(); I != E; ++I, ++Idx)
8214 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8215 // FIXME: should only count parameters that are lowered to integers.
8216 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8218 if (InRegCount > 2) {
8219 report_fatal_error("Nest register in use - reduce number of inreg"
8225 case CallingConv::X86_FastCall:
8226 case CallingConv::X86_ThisCall:
8227 case CallingConv::Fast:
8228 // Pass 'nest' parameter in EAX.
8229 // Must be kept in sync with X86CallingConv.td
8234 SDValue OutChains[4];
8237 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8238 DAG.getConstant(10, MVT::i32));
8239 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8241 // This is storing the opcode for MOV32ri.
8242 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8243 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8244 OutChains[0] = DAG.getStore(Root, dl,
8245 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8246 Trmp, MachinePointerInfo(TrmpAddr),
8249 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8250 DAG.getConstant(1, MVT::i32));
8251 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8252 MachinePointerInfo(TrmpAddr, 1),
8255 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8256 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8257 DAG.getConstant(5, MVT::i32));
8258 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8259 MachinePointerInfo(TrmpAddr, 5),
8262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8263 DAG.getConstant(6, MVT::i32));
8264 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8265 MachinePointerInfo(TrmpAddr, 6),
8269 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8270 return DAG.getMergeValues(Ops, 2, dl);
8274 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8275 SelectionDAG &DAG) const {
8277 The rounding mode is in bits 11:10 of FPSR, and has the following
8284 FLT_ROUNDS, on the other hand, expects the following:
8291 To perform the conversion, we do:
8292 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8295 MachineFunction &MF = DAG.getMachineFunction();
8296 const TargetMachine &TM = MF.getTarget();
8297 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8298 unsigned StackAlignment = TFI.getStackAlignment();
8299 EVT VT = Op.getValueType();
8300 DebugLoc DL = Op.getDebugLoc();
8302 // Save FP Control Word to stack slot
8303 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8304 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8307 MachineMemOperand *MMO =
8308 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8309 MachineMemOperand::MOStore, 2, 2);
8311 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8312 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8313 DAG.getVTList(MVT::Other),
8314 Ops, 2, MVT::i16, MMO);
8316 // Load FP Control Word from stack slot
8317 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8318 MachinePointerInfo(), false, false, 0);
8320 // Transform as necessary
8322 DAG.getNode(ISD::SRL, DL, MVT::i16,
8323 DAG.getNode(ISD::AND, DL, MVT::i16,
8324 CWD, DAG.getConstant(0x800, MVT::i16)),
8325 DAG.getConstant(11, MVT::i8));
8327 DAG.getNode(ISD::SRL, DL, MVT::i16,
8328 DAG.getNode(ISD::AND, DL, MVT::i16,
8329 CWD, DAG.getConstant(0x400, MVT::i16)),
8330 DAG.getConstant(9, MVT::i8));
8333 DAG.getNode(ISD::AND, DL, MVT::i16,
8334 DAG.getNode(ISD::ADD, DL, MVT::i16,
8335 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8336 DAG.getConstant(1, MVT::i16)),
8337 DAG.getConstant(3, MVT::i16));
8340 return DAG.getNode((VT.getSizeInBits() < 16 ?
8341 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8344 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8345 EVT VT = Op.getValueType();
8347 unsigned NumBits = VT.getSizeInBits();
8348 DebugLoc dl = Op.getDebugLoc();
8350 Op = Op.getOperand(0);
8351 if (VT == MVT::i8) {
8352 // Zero extend to i32 since there is not an i8 bsr.
8354 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8357 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8358 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8359 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8361 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8364 DAG.getConstant(NumBits+NumBits-1, OpVT),
8365 DAG.getConstant(X86::COND_E, MVT::i8),
8368 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8370 // Finally xor with NumBits-1.
8371 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8374 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8378 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8379 EVT VT = Op.getValueType();
8381 unsigned NumBits = VT.getSizeInBits();
8382 DebugLoc dl = Op.getDebugLoc();
8384 Op = Op.getOperand(0);
8385 if (VT == MVT::i8) {
8387 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8390 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8391 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8392 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8394 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8397 DAG.getConstant(NumBits, OpVT),
8398 DAG.getConstant(X86::COND_E, MVT::i8),
8401 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8404 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8408 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8409 EVT VT = Op.getValueType();
8410 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8411 DebugLoc dl = Op.getDebugLoc();
8413 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8414 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8415 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8416 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8417 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8419 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8420 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8421 // return AloBlo + AloBhi + AhiBlo;
8423 SDValue A = Op.getOperand(0);
8424 SDValue B = Op.getOperand(1);
8426 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8427 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8428 A, DAG.getConstant(32, MVT::i32));
8429 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8430 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8431 B, DAG.getConstant(32, MVT::i32));
8432 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8433 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8435 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8436 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8438 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8439 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8441 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8442 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8443 AloBhi, DAG.getConstant(32, MVT::i32));
8444 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8445 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8446 AhiBlo, DAG.getConstant(32, MVT::i32));
8447 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8448 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8452 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8453 EVT VT = Op.getValueType();
8454 DebugLoc dl = Op.getDebugLoc();
8455 SDValue R = Op.getOperand(0);
8457 LLVMContext *Context = DAG.getContext();
8459 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8461 if (VT == MVT::v4i32) {
8462 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8463 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8464 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8466 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8468 std::vector<Constant*> CV(4, CI);
8469 Constant *C = ConstantVector::get(CV);
8470 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8471 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8472 MachinePointerInfo::getConstantPool(),
8475 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8476 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8477 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8478 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8480 if (VT == MVT::v16i8) {
8482 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8483 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8484 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8486 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8487 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8489 std::vector<Constant*> CVM1(16, CM1);
8490 std::vector<Constant*> CVM2(16, CM2);
8491 Constant *C = ConstantVector::get(CVM1);
8492 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8493 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8494 MachinePointerInfo::getConstantPool(),
8497 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8498 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8499 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8500 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8501 DAG.getConstant(4, MVT::i32));
8502 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8504 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8506 C = ConstantVector::get(CVM2);
8507 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8508 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8509 MachinePointerInfo::getConstantPool(),
8512 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8513 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8514 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8515 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8516 DAG.getConstant(2, MVT::i32));
8517 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8519 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8521 // return pblendv(r, r+r, a);
8522 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8523 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8529 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8530 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8531 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8532 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8533 // has only one use.
8534 SDNode *N = Op.getNode();
8535 SDValue LHS = N->getOperand(0);
8536 SDValue RHS = N->getOperand(1);
8537 unsigned BaseOp = 0;
8539 DebugLoc DL = Op.getDebugLoc();
8540 switch (Op.getOpcode()) {
8541 default: llvm_unreachable("Unknown ovf instruction!");
8543 // A subtract of one will be selected as a INC. Note that INC doesn't
8544 // set CF, so we can't do this for UADDO.
8545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8546 if (C->getAPIntValue() == 1) {
8547 BaseOp = X86ISD::INC;
8551 BaseOp = X86ISD::ADD;
8555 BaseOp = X86ISD::ADD;
8559 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8560 // set CF, so we can't do this for USUBO.
8561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8562 if (C->getAPIntValue() == 1) {
8563 BaseOp = X86ISD::DEC;
8567 BaseOp = X86ISD::SUB;
8571 BaseOp = X86ISD::SUB;
8575 BaseOp = X86ISD::SMUL;
8578 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8579 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8581 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8584 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8585 DAG.getConstant(X86::COND_O, MVT::i32),
8586 SDValue(Sum.getNode(), 2));
8588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8593 // Also sets EFLAGS.
8594 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8595 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8598 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8599 DAG.getConstant(Cond, MVT::i32),
8600 SDValue(Sum.getNode(), 1));
8602 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8606 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8607 DebugLoc dl = Op.getDebugLoc();
8609 if (!Subtarget->hasSSE2()) {
8610 SDValue Chain = Op.getOperand(0);
8611 SDValue Zero = DAG.getConstant(0,
8612 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8614 DAG.getRegister(X86::ESP, MVT::i32), // Base
8615 DAG.getTargetConstant(1, MVT::i8), // Scale
8616 DAG.getRegister(0, MVT::i32), // Index
8617 DAG.getTargetConstant(0, MVT::i32), // Disp
8618 DAG.getRegister(0, MVT::i32), // Segment.
8623 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8624 array_lengthof(Ops));
8625 return SDValue(Res, 0);
8628 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8630 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8632 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8633 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8634 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8635 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8637 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8638 if (!Op1 && !Op2 && !Op3 && Op4)
8639 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8641 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8642 if (Op1 && !Op2 && !Op3 && !Op4)
8643 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8645 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8647 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8650 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8651 EVT T = Op.getValueType();
8652 DebugLoc DL = Op.getDebugLoc();
8655 switch(T.getSimpleVT().SimpleTy) {
8657 assert(false && "Invalid value type!");
8658 case MVT::i8: Reg = X86::AL; size = 1; break;
8659 case MVT::i16: Reg = X86::AX; size = 2; break;
8660 case MVT::i32: Reg = X86::EAX; size = 4; break;
8662 assert(Subtarget->is64Bit() && "Node not type legal!");
8663 Reg = X86::RAX; size = 8;
8666 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8667 Op.getOperand(2), SDValue());
8668 SDValue Ops[] = { cpIn.getValue(0),
8671 DAG.getTargetConstant(size, MVT::i8),
8673 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8674 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8675 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8678 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8682 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8683 SelectionDAG &DAG) const {
8684 assert(Subtarget->is64Bit() && "Result not type legalized?");
8685 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8686 SDValue TheChain = Op.getOperand(0);
8687 DebugLoc dl = Op.getDebugLoc();
8688 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8689 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8690 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8692 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8693 DAG.getConstant(32, MVT::i8));
8695 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8698 return DAG.getMergeValues(Ops, 2, dl);
8701 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8702 SelectionDAG &DAG) const {
8703 EVT SrcVT = Op.getOperand(0).getValueType();
8704 EVT DstVT = Op.getValueType();
8705 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8706 Subtarget->hasMMX() && "Unexpected custom BITCAST");
8707 assert((DstVT == MVT::i64 ||
8708 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8709 "Unexpected custom BITCAST");
8710 // i64 <=> MMX conversions are Legal.
8711 if (SrcVT==MVT::i64 && DstVT.isVector())
8713 if (DstVT==MVT::i64 && SrcVT.isVector())
8715 // MMX <=> MMX conversions are Legal.
8716 if (SrcVT.isVector() && DstVT.isVector())
8718 // All other conversions need to be expanded.
8722 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8723 SDNode *Node = Op.getNode();
8724 DebugLoc dl = Node->getDebugLoc();
8725 EVT T = Node->getValueType(0);
8726 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8727 DAG.getConstant(0, T), Node->getOperand(2));
8728 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8729 cast<AtomicSDNode>(Node)->getMemoryVT(),
8730 Node->getOperand(0),
8731 Node->getOperand(1), negOp,
8732 cast<AtomicSDNode>(Node)->getSrcValue(),
8733 cast<AtomicSDNode>(Node)->getAlignment());
8736 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8737 EVT VT = Op.getNode()->getValueType(0);
8739 // Let legalize expand this if it isn't a legal type yet.
8740 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8743 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8746 bool ExtraOp = false;
8747 switch (Op.getOpcode()) {
8748 default: assert(0 && "Invalid code");
8749 case ISD::ADDC: Opc = X86ISD::ADD; break;
8750 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8751 case ISD::SUBC: Opc = X86ISD::SUB; break;
8752 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8756 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8758 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8759 Op.getOperand(1), Op.getOperand(2));
8762 /// LowerOperation - Provide custom lowering hooks for some operations.
8764 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8765 switch (Op.getOpcode()) {
8766 default: llvm_unreachable("Should not custom lower this!");
8767 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8768 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8769 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8770 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8771 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8772 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8773 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8774 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8775 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
8776 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
8777 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8778 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8779 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8780 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8781 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8782 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8783 case ISD::SHL_PARTS:
8784 case ISD::SRA_PARTS:
8785 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8786 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8787 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8788 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8789 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8790 case ISD::FABS: return LowerFABS(Op, DAG);
8791 case ISD::FNEG: return LowerFNEG(Op, DAG);
8792 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8793 case ISD::SETCC: return LowerSETCC(Op, DAG);
8794 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8795 case ISD::SELECT: return LowerSELECT(Op, DAG);
8796 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8797 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8798 case ISD::VASTART: return LowerVASTART(Op, DAG);
8799 case ISD::VAARG: return LowerVAARG(Op, DAG);
8800 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8801 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8802 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8803 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8804 case ISD::FRAME_TO_ARGS_OFFSET:
8805 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8806 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8807 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8808 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8809 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8810 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8811 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8812 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8813 case ISD::SHL: return LowerSHL(Op, DAG);
8819 case ISD::UMULO: return LowerXALUO(Op, DAG);
8820 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8821 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
8825 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8829 void X86TargetLowering::
8830 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8831 SelectionDAG &DAG, unsigned NewOp) const {
8832 EVT T = Node->getValueType(0);
8833 DebugLoc dl = Node->getDebugLoc();
8834 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8836 SDValue Chain = Node->getOperand(0);
8837 SDValue In1 = Node->getOperand(1);
8838 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8839 Node->getOperand(2), DAG.getIntPtrConstant(0));
8840 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8841 Node->getOperand(2), DAG.getIntPtrConstant(1));
8842 SDValue Ops[] = { Chain, In1, In2L, In2H };
8843 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8845 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8846 cast<MemSDNode>(Node)->getMemOperand());
8847 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8848 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8849 Results.push_back(Result.getValue(2));
8852 /// ReplaceNodeResults - Replace a node with an illegal result type
8853 /// with a new node built out of custom code.
8854 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8855 SmallVectorImpl<SDValue>&Results,
8856 SelectionDAG &DAG) const {
8857 DebugLoc dl = N->getDebugLoc();
8858 switch (N->getOpcode()) {
8860 assert(false && "Do not know how to custom type legalize this operation!");
8866 // We don't want to expand or promote these.
8868 case ISD::FP_TO_SINT: {
8869 std::pair<SDValue,SDValue> Vals =
8870 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8871 SDValue FIST = Vals.first, StackSlot = Vals.second;
8872 if (FIST.getNode() != 0) {
8873 EVT VT = N->getValueType(0);
8874 // Return a load from the stack slot.
8875 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8876 MachinePointerInfo(), false, false, 0));
8880 case ISD::READCYCLECOUNTER: {
8881 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8882 SDValue TheChain = N->getOperand(0);
8883 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8884 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8886 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8888 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8889 SDValue Ops[] = { eax, edx };
8890 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8891 Results.push_back(edx.getValue(1));
8894 case ISD::ATOMIC_CMP_SWAP: {
8895 EVT T = N->getValueType(0);
8896 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8897 SDValue cpInL, cpInH;
8898 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8899 DAG.getConstant(0, MVT::i32));
8900 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8901 DAG.getConstant(1, MVT::i32));
8902 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8903 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8905 SDValue swapInL, swapInH;
8906 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8907 DAG.getConstant(0, MVT::i32));
8908 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8909 DAG.getConstant(1, MVT::i32));
8910 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8912 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8913 swapInL.getValue(1));
8914 SDValue Ops[] = { swapInH.getValue(0),
8916 swapInH.getValue(1) };
8917 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8918 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8919 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8921 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8922 MVT::i32, Result.getValue(1));
8923 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8924 MVT::i32, cpOutL.getValue(2));
8925 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8926 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8927 Results.push_back(cpOutH.getValue(1));
8930 case ISD::ATOMIC_LOAD_ADD:
8931 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8933 case ISD::ATOMIC_LOAD_AND:
8934 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8936 case ISD::ATOMIC_LOAD_NAND:
8937 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8939 case ISD::ATOMIC_LOAD_OR:
8940 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8942 case ISD::ATOMIC_LOAD_SUB:
8943 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8945 case ISD::ATOMIC_LOAD_XOR:
8946 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8948 case ISD::ATOMIC_SWAP:
8949 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8954 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8956 default: return NULL;
8957 case X86ISD::BSF: return "X86ISD::BSF";
8958 case X86ISD::BSR: return "X86ISD::BSR";
8959 case X86ISD::SHLD: return "X86ISD::SHLD";
8960 case X86ISD::SHRD: return "X86ISD::SHRD";
8961 case X86ISD::FAND: return "X86ISD::FAND";
8962 case X86ISD::FOR: return "X86ISD::FOR";
8963 case X86ISD::FXOR: return "X86ISD::FXOR";
8964 case X86ISD::FSRL: return "X86ISD::FSRL";
8965 case X86ISD::FILD: return "X86ISD::FILD";
8966 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8967 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8968 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8969 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8970 case X86ISD::FLD: return "X86ISD::FLD";
8971 case X86ISD::FST: return "X86ISD::FST";
8972 case X86ISD::CALL: return "X86ISD::CALL";
8973 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8974 case X86ISD::BT: return "X86ISD::BT";
8975 case X86ISD::CMP: return "X86ISD::CMP";
8976 case X86ISD::COMI: return "X86ISD::COMI";
8977 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8978 case X86ISD::SETCC: return "X86ISD::SETCC";
8979 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8980 case X86ISD::CMOV: return "X86ISD::CMOV";
8981 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8982 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8983 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8984 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8985 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8986 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8987 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8988 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8989 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8990 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8991 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8992 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8993 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8994 case X86ISD::PANDN: return "X86ISD::PANDN";
8995 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
8996 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
8997 case X86ISD::PSIGND: return "X86ISD::PSIGND";
8998 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
8999 case X86ISD::FMAX: return "X86ISD::FMAX";
9000 case X86ISD::FMIN: return "X86ISD::FMIN";
9001 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9002 case X86ISD::FRCP: return "X86ISD::FRCP";
9003 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9004 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9005 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9006 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9007 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9008 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9009 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9010 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9011 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9012 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9013 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9014 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9015 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9016 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9017 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9018 case X86ISD::VSHL: return "X86ISD::VSHL";
9019 case X86ISD::VSRL: return "X86ISD::VSRL";
9020 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9021 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9022 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9023 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9024 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9025 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9026 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9027 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9028 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9029 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9030 case X86ISD::ADD: return "X86ISD::ADD";
9031 case X86ISD::SUB: return "X86ISD::SUB";
9032 case X86ISD::ADC: return "X86ISD::ADC";
9033 case X86ISD::SBB: return "X86ISD::SBB";
9034 case X86ISD::SMUL: return "X86ISD::SMUL";
9035 case X86ISD::UMUL: return "X86ISD::UMUL";
9036 case X86ISD::INC: return "X86ISD::INC";
9037 case X86ISD::DEC: return "X86ISD::DEC";
9038 case X86ISD::OR: return "X86ISD::OR";
9039 case X86ISD::XOR: return "X86ISD::XOR";
9040 case X86ISD::AND: return "X86ISD::AND";
9041 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9042 case X86ISD::PTEST: return "X86ISD::PTEST";
9043 case X86ISD::TESTP: return "X86ISD::TESTP";
9044 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9045 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9046 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9047 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9048 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9049 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9050 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9051 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9052 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9053 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9054 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9055 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9056 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9057 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9058 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9059 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9060 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9061 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9062 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9063 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9064 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9065 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9066 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9067 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9068 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9069 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9070 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9071 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9072 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9073 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9074 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9075 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9076 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9077 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9078 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9079 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9083 // isLegalAddressingMode - Return true if the addressing mode represented
9084 // by AM is legal for this target, for a load/store of the specified type.
9085 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9086 const Type *Ty) const {
9087 // X86 supports extremely general addressing modes.
9088 CodeModel::Model M = getTargetMachine().getCodeModel();
9089 Reloc::Model R = getTargetMachine().getRelocationModel();
9091 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9092 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9097 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9099 // If a reference to this global requires an extra load, we can't fold it.
9100 if (isGlobalStubReference(GVFlags))
9103 // If BaseGV requires a register for the PIC base, we cannot also have a
9104 // BaseReg specified.
9105 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9108 // If lower 4G is not available, then we must use rip-relative addressing.
9109 if ((M != CodeModel::Small || R != Reloc::Static) &&
9110 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9120 // These scales always work.
9125 // These scales are formed with basereg+scalereg. Only accept if there is
9130 default: // Other stuff never works.
9138 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9139 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9141 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9142 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9143 if (NumBits1 <= NumBits2)
9148 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9149 if (!VT1.isInteger() || !VT2.isInteger())
9151 unsigned NumBits1 = VT1.getSizeInBits();
9152 unsigned NumBits2 = VT2.getSizeInBits();
9153 if (NumBits1 <= NumBits2)
9158 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9159 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9160 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9163 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9164 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9165 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9168 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9169 // i16 instructions are longer (0x66 prefix) and potentially slower.
9170 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9173 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9174 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9175 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9176 /// are assumed to be legal.
9178 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9180 // Very little shuffling can be done for 64-bit vectors right now.
9181 if (VT.getSizeInBits() == 64)
9182 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9184 // FIXME: pshufb, blends, shifts.
9185 return (VT.getVectorNumElements() == 2 ||
9186 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9187 isMOVLMask(M, VT) ||
9188 isSHUFPMask(M, VT) ||
9189 isPSHUFDMask(M, VT) ||
9190 isPSHUFHWMask(M, VT) ||
9191 isPSHUFLWMask(M, VT) ||
9192 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9193 isUNPCKLMask(M, VT) ||
9194 isUNPCKHMask(M, VT) ||
9195 isUNPCKL_v_undef_Mask(M, VT) ||
9196 isUNPCKH_v_undef_Mask(M, VT));
9200 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9202 unsigned NumElts = VT.getVectorNumElements();
9203 // FIXME: This collection of masks seems suspect.
9206 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9207 return (isMOVLMask(Mask, VT) ||
9208 isCommutedMOVLMask(Mask, VT, true) ||
9209 isSHUFPMask(Mask, VT) ||
9210 isCommutedSHUFPMask(Mask, VT));
9215 //===----------------------------------------------------------------------===//
9216 // X86 Scheduler Hooks
9217 //===----------------------------------------------------------------------===//
9219 // private utility function
9221 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9222 MachineBasicBlock *MBB,
9229 TargetRegisterClass *RC,
9230 bool invSrc) const {
9231 // For the atomic bitwise operator, we generate
9234 // ld t1 = [bitinstr.addr]
9235 // op t2 = t1, [bitinstr.val]
9237 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9239 // fallthrough -->nextMBB
9240 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9241 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9242 MachineFunction::iterator MBBIter = MBB;
9245 /// First build the CFG
9246 MachineFunction *F = MBB->getParent();
9247 MachineBasicBlock *thisMBB = MBB;
9248 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9249 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9250 F->insert(MBBIter, newMBB);
9251 F->insert(MBBIter, nextMBB);
9253 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9254 nextMBB->splice(nextMBB->begin(), thisMBB,
9255 llvm::next(MachineBasicBlock::iterator(bInstr)),
9257 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9259 // Update thisMBB to fall through to newMBB
9260 thisMBB->addSuccessor(newMBB);
9262 // newMBB jumps to itself and fall through to nextMBB
9263 newMBB->addSuccessor(nextMBB);
9264 newMBB->addSuccessor(newMBB);
9266 // Insert instructions into newMBB based on incoming instruction
9267 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9268 "unexpected number of operands");
9269 DebugLoc dl = bInstr->getDebugLoc();
9270 MachineOperand& destOper = bInstr->getOperand(0);
9271 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9272 int numArgs = bInstr->getNumOperands() - 1;
9273 for (int i=0; i < numArgs; ++i)
9274 argOpers[i] = &bInstr->getOperand(i+1);
9276 // x86 address has 4 operands: base, index, scale, and displacement
9277 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9278 int valArgIndx = lastAddrIndx + 1;
9280 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9281 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9282 for (int i=0; i <= lastAddrIndx; ++i)
9283 (*MIB).addOperand(*argOpers[i]);
9285 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9287 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9292 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9293 assert((argOpers[valArgIndx]->isReg() ||
9294 argOpers[valArgIndx]->isImm()) &&
9296 if (argOpers[valArgIndx]->isReg())
9297 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9299 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9301 (*MIB).addOperand(*argOpers[valArgIndx]);
9303 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9306 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9307 for (int i=0; i <= lastAddrIndx; ++i)
9308 (*MIB).addOperand(*argOpers[i]);
9310 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9311 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9312 bInstr->memoperands_end());
9314 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9318 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9320 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9324 // private utility function: 64 bit atomics on 32 bit host.
9326 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9327 MachineBasicBlock *MBB,
9332 bool invSrc) const {
9333 // For the atomic bitwise operator, we generate
9334 // thisMBB (instructions are in pairs, except cmpxchg8b)
9335 // ld t1,t2 = [bitinstr.addr]
9337 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9338 // op t5, t6 <- out1, out2, [bitinstr.val]
9339 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9340 // mov ECX, EBX <- t5, t6
9341 // mov EAX, EDX <- t1, t2
9342 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9343 // mov t3, t4 <- EAX, EDX
9345 // result in out1, out2
9346 // fallthrough -->nextMBB
9348 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9349 const unsigned LoadOpc = X86::MOV32rm;
9350 const unsigned NotOpc = X86::NOT32r;
9351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9352 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9353 MachineFunction::iterator MBBIter = MBB;
9356 /// First build the CFG
9357 MachineFunction *F = MBB->getParent();
9358 MachineBasicBlock *thisMBB = MBB;
9359 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9360 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9361 F->insert(MBBIter, newMBB);
9362 F->insert(MBBIter, nextMBB);
9364 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9365 nextMBB->splice(nextMBB->begin(), thisMBB,
9366 llvm::next(MachineBasicBlock::iterator(bInstr)),
9368 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9370 // Update thisMBB to fall through to newMBB
9371 thisMBB->addSuccessor(newMBB);
9373 // newMBB jumps to itself and fall through to nextMBB
9374 newMBB->addSuccessor(nextMBB);
9375 newMBB->addSuccessor(newMBB);
9377 DebugLoc dl = bInstr->getDebugLoc();
9378 // Insert instructions into newMBB based on incoming instruction
9379 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9380 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9381 "unexpected number of operands");
9382 MachineOperand& dest1Oper = bInstr->getOperand(0);
9383 MachineOperand& dest2Oper = bInstr->getOperand(1);
9384 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9385 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9386 argOpers[i] = &bInstr->getOperand(i+2);
9388 // We use some of the operands multiple times, so conservatively just
9389 // clear any kill flags that might be present.
9390 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9391 argOpers[i]->setIsKill(false);
9394 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9395 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9397 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9398 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9399 for (int i=0; i <= lastAddrIndx; ++i)
9400 (*MIB).addOperand(*argOpers[i]);
9401 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9402 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9403 // add 4 to displacement.
9404 for (int i=0; i <= lastAddrIndx-2; ++i)
9405 (*MIB).addOperand(*argOpers[i]);
9406 MachineOperand newOp3 = *(argOpers[3]);
9408 newOp3.setImm(newOp3.getImm()+4);
9410 newOp3.setOffset(newOp3.getOffset()+4);
9411 (*MIB).addOperand(newOp3);
9412 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9414 // t3/4 are defined later, at the bottom of the loop
9415 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9416 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9417 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9418 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9419 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9420 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9422 // The subsequent operations should be using the destination registers of
9423 //the PHI instructions.
9425 t1 = F->getRegInfo().createVirtualRegister(RC);
9426 t2 = F->getRegInfo().createVirtualRegister(RC);
9427 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9428 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9430 t1 = dest1Oper.getReg();
9431 t2 = dest2Oper.getReg();
9434 int valArgIndx = lastAddrIndx + 1;
9435 assert((argOpers[valArgIndx]->isReg() ||
9436 argOpers[valArgIndx]->isImm()) &&
9438 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9439 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9440 if (argOpers[valArgIndx]->isReg())
9441 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9443 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9444 if (regOpcL != X86::MOV32rr)
9446 (*MIB).addOperand(*argOpers[valArgIndx]);
9447 assert(argOpers[valArgIndx + 1]->isReg() ==
9448 argOpers[valArgIndx]->isReg());
9449 assert(argOpers[valArgIndx + 1]->isImm() ==
9450 argOpers[valArgIndx]->isImm());
9451 if (argOpers[valArgIndx + 1]->isReg())
9452 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9454 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9455 if (regOpcH != X86::MOV32rr)
9457 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9459 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9461 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9464 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9466 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9469 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9470 for (int i=0; i <= lastAddrIndx; ++i)
9471 (*MIB).addOperand(*argOpers[i]);
9473 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9474 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9475 bInstr->memoperands_end());
9477 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9478 MIB.addReg(X86::EAX);
9479 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9480 MIB.addReg(X86::EDX);
9483 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9485 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9489 // private utility function
9491 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9492 MachineBasicBlock *MBB,
9493 unsigned cmovOpc) const {
9494 // For the atomic min/max operator, we generate
9497 // ld t1 = [min/max.addr]
9498 // mov t2 = [min/max.val]
9500 // cmov[cond] t2 = t1
9502 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9504 // fallthrough -->nextMBB
9506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9507 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9508 MachineFunction::iterator MBBIter = MBB;
9511 /// First build the CFG
9512 MachineFunction *F = MBB->getParent();
9513 MachineBasicBlock *thisMBB = MBB;
9514 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9515 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9516 F->insert(MBBIter, newMBB);
9517 F->insert(MBBIter, nextMBB);
9519 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9520 nextMBB->splice(nextMBB->begin(), thisMBB,
9521 llvm::next(MachineBasicBlock::iterator(mInstr)),
9523 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9525 // Update thisMBB to fall through to newMBB
9526 thisMBB->addSuccessor(newMBB);
9528 // newMBB jumps to newMBB and fall through to nextMBB
9529 newMBB->addSuccessor(nextMBB);
9530 newMBB->addSuccessor(newMBB);
9532 DebugLoc dl = mInstr->getDebugLoc();
9533 // Insert instructions into newMBB based on incoming instruction
9534 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9535 "unexpected number of operands");
9536 MachineOperand& destOper = mInstr->getOperand(0);
9537 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9538 int numArgs = mInstr->getNumOperands() - 1;
9539 for (int i=0; i < numArgs; ++i)
9540 argOpers[i] = &mInstr->getOperand(i+1);
9542 // x86 address has 4 operands: base, index, scale, and displacement
9543 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9544 int valArgIndx = lastAddrIndx + 1;
9546 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9547 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9548 for (int i=0; i <= lastAddrIndx; ++i)
9549 (*MIB).addOperand(*argOpers[i]);
9551 // We only support register and immediate values
9552 assert((argOpers[valArgIndx]->isReg() ||
9553 argOpers[valArgIndx]->isImm()) &&
9556 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9557 if (argOpers[valArgIndx]->isReg())
9558 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9560 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9561 (*MIB).addOperand(*argOpers[valArgIndx]);
9563 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9566 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9571 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9572 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9576 // Cmp and exchange if none has modified the memory location
9577 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9578 for (int i=0; i <= lastAddrIndx; ++i)
9579 (*MIB).addOperand(*argOpers[i]);
9581 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9582 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9583 mInstr->memoperands_end());
9585 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9586 MIB.addReg(X86::EAX);
9589 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9591 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9595 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9596 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9599 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9600 unsigned numArgs, bool memArg) const {
9601 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9602 "Target must have SSE4.2 or AVX features enabled");
9604 DebugLoc dl = MI->getDebugLoc();
9605 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9607 if (!Subtarget->hasAVX()) {
9609 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9611 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9614 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9616 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9619 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9620 for (unsigned i = 0; i < numArgs; ++i) {
9621 MachineOperand &Op = MI->getOperand(i+1);
9622 if (!(Op.isReg() && Op.isImplicit()))
9625 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9628 MI->eraseFromParent();
9633 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9634 DebugLoc dl = MI->getDebugLoc();
9635 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9637 // Address into RAX/EAX, other two args into ECX, EDX.
9638 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9639 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9640 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9641 for (int i = 0; i < X86::AddrNumOperands; ++i)
9642 MIB.addOperand(MI->getOperand(i));
9644 unsigned ValOps = X86::AddrNumOperands;
9645 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9646 .addReg(MI->getOperand(ValOps).getReg());
9647 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9648 .addReg(MI->getOperand(ValOps+1).getReg());
9650 // The instruction doesn't actually take any operands though.
9651 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9653 MI->eraseFromParent(); // The pseudo is gone now.
9658 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9659 DebugLoc dl = MI->getDebugLoc();
9660 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9662 // First arg in ECX, the second in EAX.
9663 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9664 .addReg(MI->getOperand(0).getReg());
9665 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9666 .addReg(MI->getOperand(1).getReg());
9668 // The instruction doesn't actually take any operands though.
9669 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9671 MI->eraseFromParent(); // The pseudo is gone now.
9676 X86TargetLowering::EmitVAARG64WithCustomInserter(
9678 MachineBasicBlock *MBB) const {
9679 // Emit va_arg instruction on X86-64.
9681 // Operands to this pseudo-instruction:
9682 // 0 ) Output : destination address (reg)
9683 // 1-5) Input : va_list address (addr, i64mem)
9684 // 6 ) ArgSize : Size (in bytes) of vararg type
9685 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9686 // 8 ) Align : Alignment of type
9687 // 9 ) EFLAGS (implicit-def)
9689 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9690 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9692 unsigned DestReg = MI->getOperand(0).getReg();
9693 MachineOperand &Base = MI->getOperand(1);
9694 MachineOperand &Scale = MI->getOperand(2);
9695 MachineOperand &Index = MI->getOperand(3);
9696 MachineOperand &Disp = MI->getOperand(4);
9697 MachineOperand &Segment = MI->getOperand(5);
9698 unsigned ArgSize = MI->getOperand(6).getImm();
9699 unsigned ArgMode = MI->getOperand(7).getImm();
9700 unsigned Align = MI->getOperand(8).getImm();
9703 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9704 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9705 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9707 // Machine Information
9708 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9709 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9710 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9711 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9712 DebugLoc DL = MI->getDebugLoc();
9717 // i64 overflow_area (address)
9718 // i64 reg_save_area (address)
9720 // sizeof(va_list) = 24
9721 // alignment(va_list) = 8
9723 unsigned TotalNumIntRegs = 6;
9724 unsigned TotalNumXMMRegs = 8;
9725 bool UseGPOffset = (ArgMode == 1);
9726 bool UseFPOffset = (ArgMode == 2);
9727 unsigned MaxOffset = TotalNumIntRegs * 8 +
9728 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9730 /* Align ArgSize to a multiple of 8 */
9731 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9732 bool NeedsAlign = (Align > 8);
9734 MachineBasicBlock *thisMBB = MBB;
9735 MachineBasicBlock *overflowMBB;
9736 MachineBasicBlock *offsetMBB;
9737 MachineBasicBlock *endMBB;
9739 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9740 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9741 unsigned OffsetReg = 0;
9743 if (!UseGPOffset && !UseFPOffset) {
9744 // If we only pull from the overflow region, we don't create a branch.
9745 // We don't need to alter control flow.
9746 OffsetDestReg = 0; // unused
9747 OverflowDestReg = DestReg;
9750 overflowMBB = thisMBB;
9753 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9754 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9755 // If not, pull from overflow_area. (branch to overflowMBB)
9760 // offsetMBB overflowMBB
9765 // Registers for the PHI in endMBB
9766 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9767 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9769 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9770 MachineFunction *MF = MBB->getParent();
9771 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9772 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9773 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9775 MachineFunction::iterator MBBIter = MBB;
9778 // Insert the new basic blocks
9779 MF->insert(MBBIter, offsetMBB);
9780 MF->insert(MBBIter, overflowMBB);
9781 MF->insert(MBBIter, endMBB);
9783 // Transfer the remainder of MBB and its successor edges to endMBB.
9784 endMBB->splice(endMBB->begin(), thisMBB,
9785 llvm::next(MachineBasicBlock::iterator(MI)),
9787 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9789 // Make offsetMBB and overflowMBB successors of thisMBB
9790 thisMBB->addSuccessor(offsetMBB);
9791 thisMBB->addSuccessor(overflowMBB);
9793 // endMBB is a successor of both offsetMBB and overflowMBB
9794 offsetMBB->addSuccessor(endMBB);
9795 overflowMBB->addSuccessor(endMBB);
9797 // Load the offset value into a register
9798 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9799 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9803 .addDisp(Disp, UseFPOffset ? 4 : 0)
9804 .addOperand(Segment)
9805 .setMemRefs(MMOBegin, MMOEnd);
9807 // Check if there is enough room left to pull this argument.
9808 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9810 .addImm(MaxOffset + 8 - ArgSizeA8);
9812 // Branch to "overflowMBB" if offset >= max
9813 // Fall through to "offsetMBB" otherwise
9814 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9815 .addMBB(overflowMBB);
9818 // In offsetMBB, emit code to use the reg_save_area.
9820 assert(OffsetReg != 0);
9822 // Read the reg_save_area address.
9823 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9824 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9829 .addOperand(Segment)
9830 .setMemRefs(MMOBegin, MMOEnd);
9832 // Zero-extend the offset
9833 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9834 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9837 .addImm(X86::sub_32bit);
9839 // Add the offset to the reg_save_area to get the final address.
9840 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9841 .addReg(OffsetReg64)
9842 .addReg(RegSaveReg);
9844 // Compute the offset for the next argument
9845 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9846 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9848 .addImm(UseFPOffset ? 16 : 8);
9850 // Store it back into the va_list.
9851 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9855 .addDisp(Disp, UseFPOffset ? 4 : 0)
9856 .addOperand(Segment)
9857 .addReg(NextOffsetReg)
9858 .setMemRefs(MMOBegin, MMOEnd);
9861 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9866 // Emit code to use overflow area
9869 // Load the overflow_area address into a register.
9870 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9871 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9876 .addOperand(Segment)
9877 .setMemRefs(MMOBegin, MMOEnd);
9879 // If we need to align it, do so. Otherwise, just copy the address
9880 // to OverflowDestReg.
9882 // Align the overflow address
9883 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9884 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9886 // aligned_addr = (addr + (align-1)) & ~(align-1)
9887 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9888 .addReg(OverflowAddrReg)
9891 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9893 .addImm(~(uint64_t)(Align-1));
9895 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9896 .addReg(OverflowAddrReg);
9899 // Compute the next overflow address after this argument.
9900 // (the overflow address should be kept 8-byte aligned)
9901 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9902 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9903 .addReg(OverflowDestReg)
9906 // Store the new overflow address.
9907 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9912 .addOperand(Segment)
9913 .addReg(NextAddrReg)
9914 .setMemRefs(MMOBegin, MMOEnd);
9916 // If we branched, emit the PHI to the front of endMBB.
9918 BuildMI(*endMBB, endMBB->begin(), DL,
9919 TII->get(X86::PHI), DestReg)
9920 .addReg(OffsetDestReg).addMBB(offsetMBB)
9921 .addReg(OverflowDestReg).addMBB(overflowMBB);
9924 // Erase the pseudo instruction
9925 MI->eraseFromParent();
9931 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9933 MachineBasicBlock *MBB) const {
9934 // Emit code to save XMM registers to the stack. The ABI says that the
9935 // number of registers to save is given in %al, so it's theoretically
9936 // possible to do an indirect jump trick to avoid saving all of them,
9937 // however this code takes a simpler approach and just executes all
9938 // of the stores if %al is non-zero. It's less code, and it's probably
9939 // easier on the hardware branch predictor, and stores aren't all that
9940 // expensive anyway.
9942 // Create the new basic blocks. One block contains all the XMM stores,
9943 // and one block is the final destination regardless of whether any
9944 // stores were performed.
9945 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9946 MachineFunction *F = MBB->getParent();
9947 MachineFunction::iterator MBBIter = MBB;
9949 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9950 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9951 F->insert(MBBIter, XMMSaveMBB);
9952 F->insert(MBBIter, EndMBB);
9954 // Transfer the remainder of MBB and its successor edges to EndMBB.
9955 EndMBB->splice(EndMBB->begin(), MBB,
9956 llvm::next(MachineBasicBlock::iterator(MI)),
9958 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9960 // The original block will now fall through to the XMM save block.
9961 MBB->addSuccessor(XMMSaveMBB);
9962 // The XMMSaveMBB will fall through to the end block.
9963 XMMSaveMBB->addSuccessor(EndMBB);
9965 // Now add the instructions.
9966 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9967 DebugLoc DL = MI->getDebugLoc();
9969 unsigned CountReg = MI->getOperand(0).getReg();
9970 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9971 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9973 if (!Subtarget->isTargetWin64()) {
9974 // If %al is 0, branch around the XMM save block.
9975 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9976 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9977 MBB->addSuccessor(EndMBB);
9980 // In the XMM save block, save all the XMM argument registers.
9981 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9982 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9983 MachineMemOperand *MMO =
9984 F->getMachineMemOperand(
9985 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9986 MachineMemOperand::MOStore,
9987 /*Size=*/16, /*Align=*/16);
9988 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9989 .addFrameIndex(RegSaveFrameIndex)
9990 .addImm(/*Scale=*/1)
9991 .addReg(/*IndexReg=*/0)
9992 .addImm(/*Disp=*/Offset)
9993 .addReg(/*Segment=*/0)
9994 .addReg(MI->getOperand(i).getReg())
9995 .addMemOperand(MMO);
9998 MI->eraseFromParent(); // The pseudo instruction is gone now.
10003 MachineBasicBlock *
10004 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10005 MachineBasicBlock *BB) const {
10006 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10007 DebugLoc DL = MI->getDebugLoc();
10009 // To "insert" a SELECT_CC instruction, we actually have to insert the
10010 // diamond control-flow pattern. The incoming instruction knows the
10011 // destination vreg to set, the condition code register to branch on, the
10012 // true/false values to select between, and a branch opcode to use.
10013 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10014 MachineFunction::iterator It = BB;
10020 // cmpTY ccX, r1, r2
10022 // fallthrough --> copy0MBB
10023 MachineBasicBlock *thisMBB = BB;
10024 MachineFunction *F = BB->getParent();
10025 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10026 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10027 F->insert(It, copy0MBB);
10028 F->insert(It, sinkMBB);
10030 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10031 // live into the sink and copy blocks.
10032 const MachineFunction *MF = BB->getParent();
10033 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10034 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10036 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10037 const MachineOperand &MO = MI->getOperand(I);
10038 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10039 unsigned Reg = MO.getReg();
10040 if (Reg != X86::EFLAGS) continue;
10041 copy0MBB->addLiveIn(Reg);
10042 sinkMBB->addLiveIn(Reg);
10045 // Transfer the remainder of BB and its successor edges to sinkMBB.
10046 sinkMBB->splice(sinkMBB->begin(), BB,
10047 llvm::next(MachineBasicBlock::iterator(MI)),
10049 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10051 // Add the true and fallthrough blocks as its successors.
10052 BB->addSuccessor(copy0MBB);
10053 BB->addSuccessor(sinkMBB);
10055 // Create the conditional branch instruction.
10057 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10058 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10061 // %FalseValue = ...
10062 // # fallthrough to sinkMBB
10063 copy0MBB->addSuccessor(sinkMBB);
10066 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10068 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10069 TII->get(X86::PHI), MI->getOperand(0).getReg())
10070 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10071 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10073 MI->eraseFromParent(); // The pseudo instruction is gone now.
10077 MachineBasicBlock *
10078 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10079 MachineBasicBlock *BB) const {
10080 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10081 DebugLoc DL = MI->getDebugLoc();
10083 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10084 // non-trivial part is impdef of ESP.
10085 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10088 const char *StackProbeSymbol =
10089 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10091 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10092 .addExternalSymbol(StackProbeSymbol)
10093 .addReg(X86::EAX, RegState::Implicit)
10094 .addReg(X86::ESP, RegState::Implicit)
10095 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10096 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10097 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10099 MI->eraseFromParent(); // The pseudo instruction is gone now.
10103 MachineBasicBlock *
10104 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10105 MachineBasicBlock *BB) const {
10106 // This is pretty easy. We're taking the value that we received from
10107 // our load from the relocation, sticking it in either RDI (x86-64)
10108 // or EAX and doing an indirect call. The return value will then
10109 // be in the normal return register.
10110 const X86InstrInfo *TII
10111 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10112 DebugLoc DL = MI->getDebugLoc();
10113 MachineFunction *F = BB->getParent();
10115 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10116 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10118 if (Subtarget->is64Bit()) {
10119 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10120 TII->get(X86::MOV64rm), X86::RDI)
10122 .addImm(0).addReg(0)
10123 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10124 MI->getOperand(3).getTargetFlags())
10126 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10127 addDirectMem(MIB, X86::RDI);
10128 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10129 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10130 TII->get(X86::MOV32rm), X86::EAX)
10132 .addImm(0).addReg(0)
10133 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10134 MI->getOperand(3).getTargetFlags())
10136 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10137 addDirectMem(MIB, X86::EAX);
10139 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10140 TII->get(X86::MOV32rm), X86::EAX)
10141 .addReg(TII->getGlobalBaseReg(F))
10142 .addImm(0).addReg(0)
10143 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10144 MI->getOperand(3).getTargetFlags())
10146 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10147 addDirectMem(MIB, X86::EAX);
10150 MI->eraseFromParent(); // The pseudo instruction is gone now.
10154 MachineBasicBlock *
10155 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10156 MachineBasicBlock *BB) const {
10157 switch (MI->getOpcode()) {
10158 default: assert(false && "Unexpected instr type to insert");
10159 case X86::TAILJMPd64:
10160 case X86::TAILJMPr64:
10161 case X86::TAILJMPm64:
10162 assert(!"TAILJMP64 would not be touched here.");
10163 case X86::TCRETURNdi64:
10164 case X86::TCRETURNri64:
10165 case X86::TCRETURNmi64:
10166 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10167 // On AMD64, additional defs should be added before register allocation.
10168 if (!Subtarget->isTargetWin64()) {
10169 MI->addRegisterDefined(X86::RSI);
10170 MI->addRegisterDefined(X86::RDI);
10171 MI->addRegisterDefined(X86::XMM6);
10172 MI->addRegisterDefined(X86::XMM7);
10173 MI->addRegisterDefined(X86::XMM8);
10174 MI->addRegisterDefined(X86::XMM9);
10175 MI->addRegisterDefined(X86::XMM10);
10176 MI->addRegisterDefined(X86::XMM11);
10177 MI->addRegisterDefined(X86::XMM12);
10178 MI->addRegisterDefined(X86::XMM13);
10179 MI->addRegisterDefined(X86::XMM14);
10180 MI->addRegisterDefined(X86::XMM15);
10183 case X86::WIN_ALLOCA:
10184 return EmitLoweredWinAlloca(MI, BB);
10185 case X86::TLSCall_32:
10186 case X86::TLSCall_64:
10187 return EmitLoweredTLSCall(MI, BB);
10188 case X86::CMOV_GR8:
10189 case X86::CMOV_FR32:
10190 case X86::CMOV_FR64:
10191 case X86::CMOV_V4F32:
10192 case X86::CMOV_V2F64:
10193 case X86::CMOV_V2I64:
10194 case X86::CMOV_GR16:
10195 case X86::CMOV_GR32:
10196 case X86::CMOV_RFP32:
10197 case X86::CMOV_RFP64:
10198 case X86::CMOV_RFP80:
10199 return EmitLoweredSelect(MI, BB);
10201 case X86::FP32_TO_INT16_IN_MEM:
10202 case X86::FP32_TO_INT32_IN_MEM:
10203 case X86::FP32_TO_INT64_IN_MEM:
10204 case X86::FP64_TO_INT16_IN_MEM:
10205 case X86::FP64_TO_INT32_IN_MEM:
10206 case X86::FP64_TO_INT64_IN_MEM:
10207 case X86::FP80_TO_INT16_IN_MEM:
10208 case X86::FP80_TO_INT32_IN_MEM:
10209 case X86::FP80_TO_INT64_IN_MEM: {
10210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10211 DebugLoc DL = MI->getDebugLoc();
10213 // Change the floating point control register to use "round towards zero"
10214 // mode when truncating to an integer value.
10215 MachineFunction *F = BB->getParent();
10216 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10217 addFrameReference(BuildMI(*BB, MI, DL,
10218 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10220 // Load the old value of the high byte of the control word...
10222 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10223 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10226 // Set the high part to be round to zero...
10227 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10230 // Reload the modified control word now...
10231 addFrameReference(BuildMI(*BB, MI, DL,
10232 TII->get(X86::FLDCW16m)), CWFrameIdx);
10234 // Restore the memory image of control word to original value
10235 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10238 // Get the X86 opcode to use.
10240 switch (MI->getOpcode()) {
10241 default: llvm_unreachable("illegal opcode!");
10242 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10243 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10244 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10245 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10246 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10247 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10248 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10249 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10250 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10254 MachineOperand &Op = MI->getOperand(0);
10256 AM.BaseType = X86AddressMode::RegBase;
10257 AM.Base.Reg = Op.getReg();
10259 AM.BaseType = X86AddressMode::FrameIndexBase;
10260 AM.Base.FrameIndex = Op.getIndex();
10262 Op = MI->getOperand(1);
10264 AM.Scale = Op.getImm();
10265 Op = MI->getOperand(2);
10267 AM.IndexReg = Op.getImm();
10268 Op = MI->getOperand(3);
10269 if (Op.isGlobal()) {
10270 AM.GV = Op.getGlobal();
10272 AM.Disp = Op.getImm();
10274 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10275 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10277 // Reload the original control word now.
10278 addFrameReference(BuildMI(*BB, MI, DL,
10279 TII->get(X86::FLDCW16m)), CWFrameIdx);
10281 MI->eraseFromParent(); // The pseudo instruction is gone now.
10284 // String/text processing lowering.
10285 case X86::PCMPISTRM128REG:
10286 case X86::VPCMPISTRM128REG:
10287 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10288 case X86::PCMPISTRM128MEM:
10289 case X86::VPCMPISTRM128MEM:
10290 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10291 case X86::PCMPESTRM128REG:
10292 case X86::VPCMPESTRM128REG:
10293 return EmitPCMP(MI, BB, 5, false /* in mem */);
10294 case X86::PCMPESTRM128MEM:
10295 case X86::VPCMPESTRM128MEM:
10296 return EmitPCMP(MI, BB, 5, true /* in mem */);
10298 // Thread synchronization.
10300 return EmitMonitor(MI, BB);
10302 return EmitMwait(MI, BB);
10304 // Atomic Lowering.
10305 case X86::ATOMAND32:
10306 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10307 X86::AND32ri, X86::MOV32rm,
10309 X86::NOT32r, X86::EAX,
10310 X86::GR32RegisterClass);
10311 case X86::ATOMOR32:
10312 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10313 X86::OR32ri, X86::MOV32rm,
10315 X86::NOT32r, X86::EAX,
10316 X86::GR32RegisterClass);
10317 case X86::ATOMXOR32:
10318 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10319 X86::XOR32ri, X86::MOV32rm,
10321 X86::NOT32r, X86::EAX,
10322 X86::GR32RegisterClass);
10323 case X86::ATOMNAND32:
10324 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10325 X86::AND32ri, X86::MOV32rm,
10327 X86::NOT32r, X86::EAX,
10328 X86::GR32RegisterClass, true);
10329 case X86::ATOMMIN32:
10330 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10331 case X86::ATOMMAX32:
10332 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10333 case X86::ATOMUMIN32:
10334 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10335 case X86::ATOMUMAX32:
10336 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10338 case X86::ATOMAND16:
10339 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10340 X86::AND16ri, X86::MOV16rm,
10342 X86::NOT16r, X86::AX,
10343 X86::GR16RegisterClass);
10344 case X86::ATOMOR16:
10345 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10346 X86::OR16ri, X86::MOV16rm,
10348 X86::NOT16r, X86::AX,
10349 X86::GR16RegisterClass);
10350 case X86::ATOMXOR16:
10351 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10352 X86::XOR16ri, X86::MOV16rm,
10354 X86::NOT16r, X86::AX,
10355 X86::GR16RegisterClass);
10356 case X86::ATOMNAND16:
10357 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10358 X86::AND16ri, X86::MOV16rm,
10360 X86::NOT16r, X86::AX,
10361 X86::GR16RegisterClass, true);
10362 case X86::ATOMMIN16:
10363 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10364 case X86::ATOMMAX16:
10365 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10366 case X86::ATOMUMIN16:
10367 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10368 case X86::ATOMUMAX16:
10369 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10371 case X86::ATOMAND8:
10372 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10373 X86::AND8ri, X86::MOV8rm,
10375 X86::NOT8r, X86::AL,
10376 X86::GR8RegisterClass);
10378 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10379 X86::OR8ri, X86::MOV8rm,
10381 X86::NOT8r, X86::AL,
10382 X86::GR8RegisterClass);
10383 case X86::ATOMXOR8:
10384 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10385 X86::XOR8ri, X86::MOV8rm,
10387 X86::NOT8r, X86::AL,
10388 X86::GR8RegisterClass);
10389 case X86::ATOMNAND8:
10390 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10391 X86::AND8ri, X86::MOV8rm,
10393 X86::NOT8r, X86::AL,
10394 X86::GR8RegisterClass, true);
10395 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10396 // This group is for 64-bit host.
10397 case X86::ATOMAND64:
10398 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10399 X86::AND64ri32, X86::MOV64rm,
10401 X86::NOT64r, X86::RAX,
10402 X86::GR64RegisterClass);
10403 case X86::ATOMOR64:
10404 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10405 X86::OR64ri32, X86::MOV64rm,
10407 X86::NOT64r, X86::RAX,
10408 X86::GR64RegisterClass);
10409 case X86::ATOMXOR64:
10410 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10411 X86::XOR64ri32, X86::MOV64rm,
10413 X86::NOT64r, X86::RAX,
10414 X86::GR64RegisterClass);
10415 case X86::ATOMNAND64:
10416 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10417 X86::AND64ri32, X86::MOV64rm,
10419 X86::NOT64r, X86::RAX,
10420 X86::GR64RegisterClass, true);
10421 case X86::ATOMMIN64:
10422 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10423 case X86::ATOMMAX64:
10424 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10425 case X86::ATOMUMIN64:
10426 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10427 case X86::ATOMUMAX64:
10428 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10430 // This group does 64-bit operations on a 32-bit host.
10431 case X86::ATOMAND6432:
10432 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10433 X86::AND32rr, X86::AND32rr,
10434 X86::AND32ri, X86::AND32ri,
10436 case X86::ATOMOR6432:
10437 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10438 X86::OR32rr, X86::OR32rr,
10439 X86::OR32ri, X86::OR32ri,
10441 case X86::ATOMXOR6432:
10442 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10443 X86::XOR32rr, X86::XOR32rr,
10444 X86::XOR32ri, X86::XOR32ri,
10446 case X86::ATOMNAND6432:
10447 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10448 X86::AND32rr, X86::AND32rr,
10449 X86::AND32ri, X86::AND32ri,
10451 case X86::ATOMADD6432:
10452 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10453 X86::ADD32rr, X86::ADC32rr,
10454 X86::ADD32ri, X86::ADC32ri,
10456 case X86::ATOMSUB6432:
10457 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10458 X86::SUB32rr, X86::SBB32rr,
10459 X86::SUB32ri, X86::SBB32ri,
10461 case X86::ATOMSWAP6432:
10462 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10463 X86::MOV32rr, X86::MOV32rr,
10464 X86::MOV32ri, X86::MOV32ri,
10466 case X86::VASTART_SAVE_XMM_REGS:
10467 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10469 case X86::VAARG_64:
10470 return EmitVAARG64WithCustomInserter(MI, BB);
10474 //===----------------------------------------------------------------------===//
10475 // X86 Optimization Hooks
10476 //===----------------------------------------------------------------------===//
10478 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10482 const SelectionDAG &DAG,
10483 unsigned Depth) const {
10484 unsigned Opc = Op.getOpcode();
10485 assert((Opc >= ISD::BUILTIN_OP_END ||
10486 Opc == ISD::INTRINSIC_WO_CHAIN ||
10487 Opc == ISD::INTRINSIC_W_CHAIN ||
10488 Opc == ISD::INTRINSIC_VOID) &&
10489 "Should use MaskedValueIsZero if you don't know whether Op"
10490 " is a target node!");
10492 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10506 // These nodes' second result is a boolean.
10507 if (Op.getResNo() == 0)
10510 case X86ISD::SETCC:
10511 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10512 Mask.getBitWidth() - 1);
10517 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10518 unsigned Depth) const {
10519 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10520 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10521 return Op.getValueType().getScalarType().getSizeInBits();
10527 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10528 /// node is a GlobalAddress + offset.
10529 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10530 const GlobalValue* &GA,
10531 int64_t &Offset) const {
10532 if (N->getOpcode() == X86ISD::Wrapper) {
10533 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10534 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10535 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10539 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10542 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10543 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10544 /// if the load addresses are consecutive, non-overlapping, and in the right
10546 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10547 TargetLowering::DAGCombinerInfo &DCI) {
10548 DebugLoc dl = N->getDebugLoc();
10549 EVT VT = N->getValueType(0);
10551 if (VT.getSizeInBits() != 128)
10554 // Don't create instructions with illegal types after legalize types has run.
10555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10556 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10559 SmallVector<SDValue, 16> Elts;
10560 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10561 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10563 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10566 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10567 /// generation and convert it from being a bunch of shuffles and extracts
10568 /// to a simple store and scalar loads to extract the elements.
10569 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10570 const TargetLowering &TLI) {
10571 SDValue InputVector = N->getOperand(0);
10573 // Only operate on vectors of 4 elements, where the alternative shuffling
10574 // gets to be more expensive.
10575 if (InputVector.getValueType() != MVT::v4i32)
10578 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10579 // single use which is a sign-extend or zero-extend, and all elements are
10581 SmallVector<SDNode *, 4> Uses;
10582 unsigned ExtractedElements = 0;
10583 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10584 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10585 if (UI.getUse().getResNo() != InputVector.getResNo())
10588 SDNode *Extract = *UI;
10589 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10592 if (Extract->getValueType(0) != MVT::i32)
10594 if (!Extract->hasOneUse())
10596 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10597 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10599 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10602 // Record which element was extracted.
10603 ExtractedElements |=
10604 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10606 Uses.push_back(Extract);
10609 // If not all the elements were used, this may not be worthwhile.
10610 if (ExtractedElements != 15)
10613 // Ok, we've now decided to do the transformation.
10614 DebugLoc dl = InputVector.getDebugLoc();
10616 // Store the value to a temporary stack slot.
10617 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10618 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10619 MachinePointerInfo(), false, false, 0);
10621 // Replace each use (extract) with a load of the appropriate element.
10622 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10623 UE = Uses.end(); UI != UE; ++UI) {
10624 SDNode *Extract = *UI;
10626 // Compute the element's address.
10627 SDValue Idx = Extract->getOperand(1);
10629 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10630 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10631 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10633 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10634 StackPtr, OffsetVal);
10636 // Load the scalar.
10637 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10638 ScalarAddr, MachinePointerInfo(),
10641 // Replace the exact with the load.
10642 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10645 // The replacement was made in place; don't return anything.
10649 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10650 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10651 const X86Subtarget *Subtarget) {
10652 DebugLoc DL = N->getDebugLoc();
10653 SDValue Cond = N->getOperand(0);
10654 // Get the LHS/RHS of the select.
10655 SDValue LHS = N->getOperand(1);
10656 SDValue RHS = N->getOperand(2);
10658 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10659 // instructions match the semantics of the common C idiom x<y?x:y but not
10660 // x<=y?x:y, because of how they handle negative zero (which can be
10661 // ignored in unsafe-math mode).
10662 if (Subtarget->hasSSE2() &&
10663 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10664 Cond.getOpcode() == ISD::SETCC) {
10665 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10667 unsigned Opcode = 0;
10668 // Check for x CC y ? x : y.
10669 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10670 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10674 // Converting this to a min would handle NaNs incorrectly, and swapping
10675 // the operands would cause it to handle comparisons between positive
10676 // and negative zero incorrectly.
10677 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10678 if (!UnsafeFPMath &&
10679 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10681 std::swap(LHS, RHS);
10683 Opcode = X86ISD::FMIN;
10686 // Converting this to a min would handle comparisons between positive
10687 // and negative zero incorrectly.
10688 if (!UnsafeFPMath &&
10689 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10691 Opcode = X86ISD::FMIN;
10694 // Converting this to a min would handle both negative zeros and NaNs
10695 // incorrectly, but we can swap the operands to fix both.
10696 std::swap(LHS, RHS);
10700 Opcode = X86ISD::FMIN;
10704 // Converting this to a max would handle comparisons between positive
10705 // and negative zero incorrectly.
10706 if (!UnsafeFPMath &&
10707 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10709 Opcode = X86ISD::FMAX;
10712 // Converting this to a max would handle NaNs incorrectly, and swapping
10713 // the operands would cause it to handle comparisons between positive
10714 // and negative zero incorrectly.
10715 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10716 if (!UnsafeFPMath &&
10717 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10719 std::swap(LHS, RHS);
10721 Opcode = X86ISD::FMAX;
10724 // Converting this to a max would handle both negative zeros and NaNs
10725 // incorrectly, but we can swap the operands to fix both.
10726 std::swap(LHS, RHS);
10730 Opcode = X86ISD::FMAX;
10733 // Check for x CC y ? y : x -- a min/max with reversed arms.
10734 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10735 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10739 // Converting this to a min would handle comparisons between positive
10740 // and negative zero incorrectly, and swapping the operands would
10741 // cause it to handle NaNs incorrectly.
10742 if (!UnsafeFPMath &&
10743 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10744 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10746 std::swap(LHS, RHS);
10748 Opcode = X86ISD::FMIN;
10751 // Converting this to a min would handle NaNs incorrectly.
10752 if (!UnsafeFPMath &&
10753 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10755 Opcode = X86ISD::FMIN;
10758 // Converting this to a min would handle both negative zeros and NaNs
10759 // incorrectly, but we can swap the operands to fix both.
10760 std::swap(LHS, RHS);
10764 Opcode = X86ISD::FMIN;
10768 // Converting this to a max would handle NaNs incorrectly.
10769 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10771 Opcode = X86ISD::FMAX;
10774 // Converting this to a max would handle comparisons between positive
10775 // and negative zero incorrectly, and swapping the operands would
10776 // cause it to handle NaNs incorrectly.
10777 if (!UnsafeFPMath &&
10778 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10779 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10781 std::swap(LHS, RHS);
10783 Opcode = X86ISD::FMAX;
10786 // Converting this to a max would handle both negative zeros and NaNs
10787 // incorrectly, but we can swap the operands to fix both.
10788 std::swap(LHS, RHS);
10792 Opcode = X86ISD::FMAX;
10798 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10801 // If this is a select between two integer constants, try to do some
10803 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10804 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10805 // Don't do this for crazy integer types.
10806 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10807 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10808 // so that TrueC (the true value) is larger than FalseC.
10809 bool NeedsCondInvert = false;
10811 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10812 // Efficiently invertible.
10813 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10814 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10815 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10816 NeedsCondInvert = true;
10817 std::swap(TrueC, FalseC);
10820 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10821 if (FalseC->getAPIntValue() == 0 &&
10822 TrueC->getAPIntValue().isPowerOf2()) {
10823 if (NeedsCondInvert) // Invert the condition if needed.
10824 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10825 DAG.getConstant(1, Cond.getValueType()));
10827 // Zero extend the condition if needed.
10828 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10830 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10831 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10832 DAG.getConstant(ShAmt, MVT::i8));
10835 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10836 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10837 if (NeedsCondInvert) // Invert the condition if needed.
10838 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10839 DAG.getConstant(1, Cond.getValueType()));
10841 // Zero extend the condition if needed.
10842 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10843 FalseC->getValueType(0), Cond);
10844 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10845 SDValue(FalseC, 0));
10848 // Optimize cases that will turn into an LEA instruction. This requires
10849 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10850 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10851 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10852 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10854 bool isFastMultiplier = false;
10856 switch ((unsigned char)Diff) {
10858 case 1: // result = add base, cond
10859 case 2: // result = lea base( , cond*2)
10860 case 3: // result = lea base(cond, cond*2)
10861 case 4: // result = lea base( , cond*4)
10862 case 5: // result = lea base(cond, cond*4)
10863 case 8: // result = lea base( , cond*8)
10864 case 9: // result = lea base(cond, cond*8)
10865 isFastMultiplier = true;
10870 if (isFastMultiplier) {
10871 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10872 if (NeedsCondInvert) // Invert the condition if needed.
10873 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10874 DAG.getConstant(1, Cond.getValueType()));
10876 // Zero extend the condition if needed.
10877 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10879 // Scale the condition by the difference.
10881 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10882 DAG.getConstant(Diff, Cond.getValueType()));
10884 // Add the base if non-zero.
10885 if (FalseC->getAPIntValue() != 0)
10886 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10887 SDValue(FalseC, 0));
10897 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10898 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10899 TargetLowering::DAGCombinerInfo &DCI) {
10900 DebugLoc DL = N->getDebugLoc();
10902 // If the flag operand isn't dead, don't touch this CMOV.
10903 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10906 // If this is a select between two integer constants, try to do some
10907 // optimizations. Note that the operands are ordered the opposite of SELECT
10909 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10910 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10911 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10912 // larger than FalseC (the false value).
10913 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10915 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10916 CC = X86::GetOppositeBranchCondition(CC);
10917 std::swap(TrueC, FalseC);
10920 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10921 // This is efficient for any integer data type (including i8/i16) and
10923 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10924 SDValue Cond = N->getOperand(3);
10925 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10926 DAG.getConstant(CC, MVT::i8), Cond);
10928 // Zero extend the condition if needed.
10929 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10931 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10932 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10933 DAG.getConstant(ShAmt, MVT::i8));
10934 if (N->getNumValues() == 2) // Dead flag value?
10935 return DCI.CombineTo(N, Cond, SDValue());
10939 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10940 // for any integer data type, including i8/i16.
10941 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10942 SDValue Cond = N->getOperand(3);
10943 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10944 DAG.getConstant(CC, MVT::i8), Cond);
10946 // Zero extend the condition if needed.
10947 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10948 FalseC->getValueType(0), Cond);
10949 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10950 SDValue(FalseC, 0));
10952 if (N->getNumValues() == 2) // Dead flag value?
10953 return DCI.CombineTo(N, Cond, SDValue());
10957 // Optimize cases that will turn into an LEA instruction. This requires
10958 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10959 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10960 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10961 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10963 bool isFastMultiplier = false;
10965 switch ((unsigned char)Diff) {
10967 case 1: // result = add base, cond
10968 case 2: // result = lea base( , cond*2)
10969 case 3: // result = lea base(cond, cond*2)
10970 case 4: // result = lea base( , cond*4)
10971 case 5: // result = lea base(cond, cond*4)
10972 case 8: // result = lea base( , cond*8)
10973 case 9: // result = lea base(cond, cond*8)
10974 isFastMultiplier = true;
10979 if (isFastMultiplier) {
10980 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10981 SDValue Cond = N->getOperand(3);
10982 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10983 DAG.getConstant(CC, MVT::i8), Cond);
10984 // Zero extend the condition if needed.
10985 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10987 // Scale the condition by the difference.
10989 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10990 DAG.getConstant(Diff, Cond.getValueType()));
10992 // Add the base if non-zero.
10993 if (FalseC->getAPIntValue() != 0)
10994 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10995 SDValue(FalseC, 0));
10996 if (N->getNumValues() == 2) // Dead flag value?
10997 return DCI.CombineTo(N, Cond, SDValue());
11007 /// PerformMulCombine - Optimize a single multiply with constant into two
11008 /// in order to implement it with two cheaper instructions, e.g.
11009 /// LEA + SHL, LEA + LEA.
11010 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11011 TargetLowering::DAGCombinerInfo &DCI) {
11012 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11015 EVT VT = N->getValueType(0);
11016 if (VT != MVT::i64)
11019 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11022 uint64_t MulAmt = C->getZExtValue();
11023 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11026 uint64_t MulAmt1 = 0;
11027 uint64_t MulAmt2 = 0;
11028 if ((MulAmt % 9) == 0) {
11030 MulAmt2 = MulAmt / 9;
11031 } else if ((MulAmt % 5) == 0) {
11033 MulAmt2 = MulAmt / 5;
11034 } else if ((MulAmt % 3) == 0) {
11036 MulAmt2 = MulAmt / 3;
11039 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11040 DebugLoc DL = N->getDebugLoc();
11042 if (isPowerOf2_64(MulAmt2) &&
11043 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11044 // If second multiplifer is pow2, issue it first. We want the multiply by
11045 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11047 std::swap(MulAmt1, MulAmt2);
11050 if (isPowerOf2_64(MulAmt1))
11051 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11052 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11054 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11055 DAG.getConstant(MulAmt1, VT));
11057 if (isPowerOf2_64(MulAmt2))
11058 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11059 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11061 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11062 DAG.getConstant(MulAmt2, VT));
11064 // Do not add new nodes to DAG combiner worklist.
11065 DCI.CombineTo(N, NewMul, false);
11070 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11071 SDValue N0 = N->getOperand(0);
11072 SDValue N1 = N->getOperand(1);
11073 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11074 EVT VT = N0.getValueType();
11076 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11077 // since the result of setcc_c is all zero's or all ones.
11078 if (N1C && N0.getOpcode() == ISD::AND &&
11079 N0.getOperand(1).getOpcode() == ISD::Constant) {
11080 SDValue N00 = N0.getOperand(0);
11081 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11082 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11083 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11084 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11085 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11086 APInt ShAmt = N1C->getAPIntValue();
11087 Mask = Mask.shl(ShAmt);
11089 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11090 N00, DAG.getConstant(Mask, VT));
11097 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11099 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11100 const X86Subtarget *Subtarget) {
11101 EVT VT = N->getValueType(0);
11102 if (!VT.isVector() && VT.isInteger() &&
11103 N->getOpcode() == ISD::SHL)
11104 return PerformSHLCombine(N, DAG);
11106 // On X86 with SSE2 support, we can transform this to a vector shift if
11107 // all elements are shifted by the same amount. We can't do this in legalize
11108 // because the a constant vector is typically transformed to a constant pool
11109 // so we have no knowledge of the shift amount.
11110 if (!Subtarget->hasSSE2())
11113 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11116 SDValue ShAmtOp = N->getOperand(1);
11117 EVT EltVT = VT.getVectorElementType();
11118 DebugLoc DL = N->getDebugLoc();
11119 SDValue BaseShAmt = SDValue();
11120 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11121 unsigned NumElts = VT.getVectorNumElements();
11123 for (; i != NumElts; ++i) {
11124 SDValue Arg = ShAmtOp.getOperand(i);
11125 if (Arg.getOpcode() == ISD::UNDEF) continue;
11129 for (; i != NumElts; ++i) {
11130 SDValue Arg = ShAmtOp.getOperand(i);
11131 if (Arg.getOpcode() == ISD::UNDEF) continue;
11132 if (Arg != BaseShAmt) {
11136 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11137 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11138 SDValue InVec = ShAmtOp.getOperand(0);
11139 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11140 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11142 for (; i != NumElts; ++i) {
11143 SDValue Arg = InVec.getOperand(i);
11144 if (Arg.getOpcode() == ISD::UNDEF) continue;
11148 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11150 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11151 if (C->getZExtValue() == SplatIdx)
11152 BaseShAmt = InVec.getOperand(1);
11155 if (BaseShAmt.getNode() == 0)
11156 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11157 DAG.getIntPtrConstant(0));
11161 // The shift amount is an i32.
11162 if (EltVT.bitsGT(MVT::i32))
11163 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11164 else if (EltVT.bitsLT(MVT::i32))
11165 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11167 // The shift amount is identical so we can do a vector shift.
11168 SDValue ValOp = N->getOperand(0);
11169 switch (N->getOpcode()) {
11171 llvm_unreachable("Unknown shift opcode!");
11174 if (VT == MVT::v2i64)
11175 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11176 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11178 if (VT == MVT::v4i32)
11179 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11180 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11182 if (VT == MVT::v8i16)
11183 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11184 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11188 if (VT == MVT::v4i32)
11189 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11190 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11192 if (VT == MVT::v8i16)
11193 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11194 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11198 if (VT == MVT::v2i64)
11199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11200 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11202 if (VT == MVT::v4i32)
11203 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11204 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11206 if (VT == MVT::v8i16)
11207 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11208 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11216 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11217 TargetLowering::DAGCombinerInfo &DCI,
11218 const X86Subtarget *Subtarget) {
11219 if (DCI.isBeforeLegalizeOps())
11222 // Want to form PANDN nodes, in the hopes of then easily combining them with
11223 // OR and AND nodes to form PBLEND/PSIGN.
11224 EVT VT = N->getValueType(0);
11225 if (VT != MVT::v2i64)
11228 SDValue N0 = N->getOperand(0);
11229 SDValue N1 = N->getOperand(1);
11230 DebugLoc DL = N->getDebugLoc();
11232 // Check LHS for vnot
11233 if (N0.getOpcode() == ISD::XOR &&
11234 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11235 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11237 // Check RHS for vnot
11238 if (N1.getOpcode() == ISD::XOR &&
11239 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11240 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11245 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11246 TargetLowering::DAGCombinerInfo &DCI,
11247 const X86Subtarget *Subtarget) {
11248 if (DCI.isBeforeLegalizeOps())
11251 EVT VT = N->getValueType(0);
11252 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11255 SDValue N0 = N->getOperand(0);
11256 SDValue N1 = N->getOperand(1);
11258 // look for psign/blend
11259 if (Subtarget->hasSSSE3()) {
11260 if (VT == MVT::v2i64) {
11261 // Canonicalize pandn to RHS
11262 if (N0.getOpcode() == X86ISD::PANDN)
11264 // or (and (m, x), (pandn m, y))
11265 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11266 SDValue Mask = N1.getOperand(0);
11267 SDValue X = N1.getOperand(1);
11269 if (N0.getOperand(0) == Mask)
11270 Y = N0.getOperand(1);
11271 if (N0.getOperand(1) == Mask)
11272 Y = N0.getOperand(0);
11274 // Check to see if the mask appeared in both the AND and PANDN and
11278 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11279 if (Mask.getOpcode() != ISD::BITCAST ||
11280 X.getOpcode() != ISD::BITCAST ||
11281 Y.getOpcode() != ISD::BITCAST)
11284 // Look through mask bitcast.
11285 Mask = Mask.getOperand(0);
11286 EVT MaskVT = Mask.getValueType();
11288 // Validate that the Mask operand is a vector sra node. The sra node
11289 // will be an intrinsic.
11290 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11293 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11294 // there is no psrai.b
11295 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11296 case Intrinsic::x86_sse2_psrai_w:
11297 case Intrinsic::x86_sse2_psrai_d:
11299 default: return SDValue();
11302 // Check that the SRA is all signbits.
11303 SDValue SraC = Mask.getOperand(2);
11304 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11305 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11306 if ((SraAmt + 1) != EltBits)
11309 DebugLoc DL = N->getDebugLoc();
11311 // Now we know we at least have a plendvb with the mask val. See if
11312 // we can form a psignb/w/d.
11313 // psign = x.type == y.type == mask.type && y = sub(0, x);
11314 X = X.getOperand(0);
11315 Y = Y.getOperand(0);
11316 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11317 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11318 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11321 case 8: Opc = X86ISD::PSIGNB; break;
11322 case 16: Opc = X86ISD::PSIGNW; break;
11323 case 32: Opc = X86ISD::PSIGND; break;
11327 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11328 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11331 // PBLENDVB only available on SSE 4.1
11332 if (!Subtarget->hasSSE41())
11335 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11336 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11337 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11338 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11339 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11344 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11345 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11347 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11349 if (!N0.hasOneUse() || !N1.hasOneUse())
11352 SDValue ShAmt0 = N0.getOperand(1);
11353 if (ShAmt0.getValueType() != MVT::i8)
11355 SDValue ShAmt1 = N1.getOperand(1);
11356 if (ShAmt1.getValueType() != MVT::i8)
11358 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11359 ShAmt0 = ShAmt0.getOperand(0);
11360 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11361 ShAmt1 = ShAmt1.getOperand(0);
11363 DebugLoc DL = N->getDebugLoc();
11364 unsigned Opc = X86ISD::SHLD;
11365 SDValue Op0 = N0.getOperand(0);
11366 SDValue Op1 = N1.getOperand(0);
11367 if (ShAmt0.getOpcode() == ISD::SUB) {
11368 Opc = X86ISD::SHRD;
11369 std::swap(Op0, Op1);
11370 std::swap(ShAmt0, ShAmt1);
11373 unsigned Bits = VT.getSizeInBits();
11374 if (ShAmt1.getOpcode() == ISD::SUB) {
11375 SDValue Sum = ShAmt1.getOperand(0);
11376 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11377 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11378 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11379 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11380 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11381 return DAG.getNode(Opc, DL, VT,
11383 DAG.getNode(ISD::TRUNCATE, DL,
11386 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11387 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11389 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11390 return DAG.getNode(Opc, DL, VT,
11391 N0.getOperand(0), N1.getOperand(0),
11392 DAG.getNode(ISD::TRUNCATE, DL,
11399 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11400 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11401 const X86Subtarget *Subtarget) {
11402 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11403 // the FP state in cases where an emms may be missing.
11404 // A preferable solution to the general problem is to figure out the right
11405 // places to insert EMMS. This qualifies as a quick hack.
11407 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11408 StoreSDNode *St = cast<StoreSDNode>(N);
11409 EVT VT = St->getValue().getValueType();
11410 if (VT.getSizeInBits() != 64)
11413 const Function *F = DAG.getMachineFunction().getFunction();
11414 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11415 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11416 && Subtarget->hasSSE2();
11417 if ((VT.isVector() ||
11418 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11419 isa<LoadSDNode>(St->getValue()) &&
11420 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11421 St->getChain().hasOneUse() && !St->isVolatile()) {
11422 SDNode* LdVal = St->getValue().getNode();
11423 LoadSDNode *Ld = 0;
11424 int TokenFactorIndex = -1;
11425 SmallVector<SDValue, 8> Ops;
11426 SDNode* ChainVal = St->getChain().getNode();
11427 // Must be a store of a load. We currently handle two cases: the load
11428 // is a direct child, and it's under an intervening TokenFactor. It is
11429 // possible to dig deeper under nested TokenFactors.
11430 if (ChainVal == LdVal)
11431 Ld = cast<LoadSDNode>(St->getChain());
11432 else if (St->getValue().hasOneUse() &&
11433 ChainVal->getOpcode() == ISD::TokenFactor) {
11434 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11435 if (ChainVal->getOperand(i).getNode() == LdVal) {
11436 TokenFactorIndex = i;
11437 Ld = cast<LoadSDNode>(St->getValue());
11439 Ops.push_back(ChainVal->getOperand(i));
11443 if (!Ld || !ISD::isNormalLoad(Ld))
11446 // If this is not the MMX case, i.e. we are just turning i64 load/store
11447 // into f64 load/store, avoid the transformation if there are multiple
11448 // uses of the loaded value.
11449 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11452 DebugLoc LdDL = Ld->getDebugLoc();
11453 DebugLoc StDL = N->getDebugLoc();
11454 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11455 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11457 if (Subtarget->is64Bit() || F64IsLegal) {
11458 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11459 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11460 Ld->getPointerInfo(), Ld->isVolatile(),
11461 Ld->isNonTemporal(), Ld->getAlignment());
11462 SDValue NewChain = NewLd.getValue(1);
11463 if (TokenFactorIndex != -1) {
11464 Ops.push_back(NewChain);
11465 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11468 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11469 St->getPointerInfo(),
11470 St->isVolatile(), St->isNonTemporal(),
11471 St->getAlignment());
11474 // Otherwise, lower to two pairs of 32-bit loads / stores.
11475 SDValue LoAddr = Ld->getBasePtr();
11476 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11477 DAG.getConstant(4, MVT::i32));
11479 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11480 Ld->getPointerInfo(),
11481 Ld->isVolatile(), Ld->isNonTemporal(),
11482 Ld->getAlignment());
11483 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11484 Ld->getPointerInfo().getWithOffset(4),
11485 Ld->isVolatile(), Ld->isNonTemporal(),
11486 MinAlign(Ld->getAlignment(), 4));
11488 SDValue NewChain = LoLd.getValue(1);
11489 if (TokenFactorIndex != -1) {
11490 Ops.push_back(LoLd);
11491 Ops.push_back(HiLd);
11492 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11496 LoAddr = St->getBasePtr();
11497 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11498 DAG.getConstant(4, MVT::i32));
11500 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11501 St->getPointerInfo(),
11502 St->isVolatile(), St->isNonTemporal(),
11503 St->getAlignment());
11504 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11505 St->getPointerInfo().getWithOffset(4),
11507 St->isNonTemporal(),
11508 MinAlign(St->getAlignment(), 4));
11509 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11514 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11515 /// X86ISD::FXOR nodes.
11516 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11517 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11518 // F[X]OR(0.0, x) -> x
11519 // F[X]OR(x, 0.0) -> x
11520 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11521 if (C->getValueAPF().isPosZero())
11522 return N->getOperand(1);
11523 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11524 if (C->getValueAPF().isPosZero())
11525 return N->getOperand(0);
11529 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11530 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11531 // FAND(0.0, x) -> 0.0
11532 // FAND(x, 0.0) -> 0.0
11533 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11534 if (C->getValueAPF().isPosZero())
11535 return N->getOperand(0);
11536 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11537 if (C->getValueAPF().isPosZero())
11538 return N->getOperand(1);
11542 static SDValue PerformBTCombine(SDNode *N,
11544 TargetLowering::DAGCombinerInfo &DCI) {
11545 // BT ignores high bits in the bit index operand.
11546 SDValue Op1 = N->getOperand(1);
11547 if (Op1.hasOneUse()) {
11548 unsigned BitWidth = Op1.getValueSizeInBits();
11549 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11550 APInt KnownZero, KnownOne;
11551 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11552 !DCI.isBeforeLegalizeOps());
11553 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11554 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11555 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11556 DCI.CommitTargetLoweringOpt(TLO);
11561 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11562 SDValue Op = N->getOperand(0);
11563 if (Op.getOpcode() == ISD::BITCAST)
11564 Op = Op.getOperand(0);
11565 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11566 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11567 VT.getVectorElementType().getSizeInBits() ==
11568 OpVT.getVectorElementType().getSizeInBits()) {
11569 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11574 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11575 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11576 // (and (i32 x86isd::setcc_carry), 1)
11577 // This eliminates the zext. This transformation is necessary because
11578 // ISD::SETCC is always legalized to i8.
11579 DebugLoc dl = N->getDebugLoc();
11580 SDValue N0 = N->getOperand(0);
11581 EVT VT = N->getValueType(0);
11582 if (N0.getOpcode() == ISD::AND &&
11584 N0.getOperand(0).hasOneUse()) {
11585 SDValue N00 = N0.getOperand(0);
11586 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11588 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11589 if (!C || C->getZExtValue() != 1)
11591 return DAG.getNode(ISD::AND, dl, VT,
11592 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11593 N00.getOperand(0), N00.getOperand(1)),
11594 DAG.getConstant(1, VT));
11600 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11601 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11602 unsigned X86CC = N->getConstantOperandVal(0);
11603 SDValue EFLAG = N->getOperand(1);
11604 DebugLoc DL = N->getDebugLoc();
11606 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11607 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11609 if (X86CC == X86::COND_B)
11610 return DAG.getNode(ISD::AND, DL, MVT::i8,
11611 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11612 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11613 DAG.getConstant(1, MVT::i8));
11618 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11619 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11620 X86TargetLowering::DAGCombinerInfo &DCI) {
11621 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11622 // the result is either zero or one (depending on the input carry bit).
11623 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11624 if (X86::isZeroNode(N->getOperand(0)) &&
11625 X86::isZeroNode(N->getOperand(1)) &&
11626 // We don't have a good way to replace an EFLAGS use, so only do this when
11628 SDValue(N, 1).use_empty()) {
11629 DebugLoc DL = N->getDebugLoc();
11630 EVT VT = N->getValueType(0);
11631 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11632 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11633 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11634 DAG.getConstant(X86::COND_B,MVT::i8),
11636 DAG.getConstant(1, VT));
11637 return DCI.CombineTo(N, Res1, CarryOut);
11643 // fold (add Y, (sete X, 0)) -> adc 0, Y
11644 // (add Y, (setne X, 0)) -> sbb -1, Y
11645 // (sub (sete X, 0), Y) -> sbb 0, Y
11646 // (sub (setne X, 0), Y) -> adc -1, Y
11647 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11648 DebugLoc DL = N->getDebugLoc();
11650 // Look through ZExts.
11651 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11652 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11655 SDValue SetCC = Ext.getOperand(0);
11656 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11659 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11660 if (CC != X86::COND_E && CC != X86::COND_NE)
11663 SDValue Cmp = SetCC.getOperand(1);
11664 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11665 !X86::isZeroNode(Cmp.getOperand(1)) ||
11666 !Cmp.getOperand(0).getValueType().isInteger())
11669 SDValue CmpOp0 = Cmp.getOperand(0);
11670 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11671 DAG.getConstant(1, CmpOp0.getValueType()));
11673 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11674 if (CC == X86::COND_NE)
11675 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11676 DL, OtherVal.getValueType(), OtherVal,
11677 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11678 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11679 DL, OtherVal.getValueType(), OtherVal,
11680 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11683 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11684 DAGCombinerInfo &DCI) const {
11685 SelectionDAG &DAG = DCI.DAG;
11686 switch (N->getOpcode()) {
11688 case ISD::EXTRACT_VECTOR_ELT:
11689 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11690 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11691 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11693 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
11694 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
11695 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11698 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11699 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11700 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11701 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11703 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11704 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11705 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11706 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11707 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11708 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
11709 case X86ISD::SHUFPS: // Handle all target specific shuffles
11710 case X86ISD::SHUFPD:
11711 case X86ISD::PALIGN:
11712 case X86ISD::PUNPCKHBW:
11713 case X86ISD::PUNPCKHWD:
11714 case X86ISD::PUNPCKHDQ:
11715 case X86ISD::PUNPCKHQDQ:
11716 case X86ISD::UNPCKHPS:
11717 case X86ISD::UNPCKHPD:
11718 case X86ISD::PUNPCKLBW:
11719 case X86ISD::PUNPCKLWD:
11720 case X86ISD::PUNPCKLDQ:
11721 case X86ISD::PUNPCKLQDQ:
11722 case X86ISD::UNPCKLPS:
11723 case X86ISD::UNPCKLPD:
11724 case X86ISD::MOVHLPS:
11725 case X86ISD::MOVLHPS:
11726 case X86ISD::PSHUFD:
11727 case X86ISD::PSHUFHW:
11728 case X86ISD::PSHUFLW:
11729 case X86ISD::MOVSS:
11730 case X86ISD::MOVSD:
11731 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11737 /// isTypeDesirableForOp - Return true if the target has native support for
11738 /// the specified value type and it is 'desirable' to use the type for the
11739 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11740 /// instruction encodings are longer and some i16 instructions are slow.
11741 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11742 if (!isTypeLegal(VT))
11744 if (VT != MVT::i16)
11751 case ISD::SIGN_EXTEND:
11752 case ISD::ZERO_EXTEND:
11753 case ISD::ANY_EXTEND:
11766 /// IsDesirableToPromoteOp - This method query the target whether it is
11767 /// beneficial for dag combiner to promote the specified node. If true, it
11768 /// should return the desired promotion type by reference.
11769 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11770 EVT VT = Op.getValueType();
11771 if (VT != MVT::i16)
11774 bool Promote = false;
11775 bool Commute = false;
11776 switch (Op.getOpcode()) {
11779 LoadSDNode *LD = cast<LoadSDNode>(Op);
11780 // If the non-extending load has a single use and it's not live out, then it
11781 // might be folded.
11782 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11783 Op.hasOneUse()*/) {
11784 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11785 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11786 // The only case where we'd want to promote LOAD (rather then it being
11787 // promoted as an operand is when it's only use is liveout.
11788 if (UI->getOpcode() != ISD::CopyToReg)
11795 case ISD::SIGN_EXTEND:
11796 case ISD::ZERO_EXTEND:
11797 case ISD::ANY_EXTEND:
11802 SDValue N0 = Op.getOperand(0);
11803 // Look out for (store (shl (load), x)).
11804 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11817 SDValue N0 = Op.getOperand(0);
11818 SDValue N1 = Op.getOperand(1);
11819 if (!Commute && MayFoldLoad(N1))
11821 // Avoid disabling potential load folding opportunities.
11822 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11824 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11834 //===----------------------------------------------------------------------===//
11835 // X86 Inline Assembly Support
11836 //===----------------------------------------------------------------------===//
11838 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11839 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11841 std::string AsmStr = IA->getAsmString();
11843 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11844 SmallVector<StringRef, 4> AsmPieces;
11845 SplitString(AsmStr, AsmPieces, ";\n");
11847 switch (AsmPieces.size()) {
11848 default: return false;
11850 AsmStr = AsmPieces[0];
11852 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11854 // FIXME: this should verify that we are targetting a 486 or better. If not,
11855 // we will turn this bswap into something that will be lowered to logical ops
11856 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11857 // so don't worry about this.
11859 if (AsmPieces.size() == 2 &&
11860 (AsmPieces[0] == "bswap" ||
11861 AsmPieces[0] == "bswapq" ||
11862 AsmPieces[0] == "bswapl") &&
11863 (AsmPieces[1] == "$0" ||
11864 AsmPieces[1] == "${0:q}")) {
11865 // No need to check constraints, nothing other than the equivalent of
11866 // "=r,0" would be valid here.
11867 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11868 if (!Ty || Ty->getBitWidth() % 16 != 0)
11870 return IntrinsicLowering::LowerToByteSwap(CI);
11872 // rorw $$8, ${0:w} --> llvm.bswap.i16
11873 if (CI->getType()->isIntegerTy(16) &&
11874 AsmPieces.size() == 3 &&
11875 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11876 AsmPieces[1] == "$$8," &&
11877 AsmPieces[2] == "${0:w}" &&
11878 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11880 const std::string &ConstraintsStr = IA->getConstraintString();
11881 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
11882 std::sort(AsmPieces.begin(), AsmPieces.end());
11883 if (AsmPieces.size() == 4 &&
11884 AsmPieces[0] == "~{cc}" &&
11885 AsmPieces[1] == "~{dirflag}" &&
11886 AsmPieces[2] == "~{flags}" &&
11887 AsmPieces[3] == "~{fpsr}") {
11888 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11889 if (!Ty || Ty->getBitWidth() % 16 != 0)
11891 return IntrinsicLowering::LowerToByteSwap(CI);
11896 if (CI->getType()->isIntegerTy(32) &&
11897 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11898 SmallVector<StringRef, 4> Words;
11899 SplitString(AsmPieces[0], Words, " \t,");
11900 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11901 Words[2] == "${0:w}") {
11903 SplitString(AsmPieces[1], Words, " \t,");
11904 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11905 Words[2] == "$0") {
11907 SplitString(AsmPieces[2], Words, " \t,");
11908 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11909 Words[2] == "${0:w}") {
11911 const std::string &ConstraintsStr = IA->getConstraintString();
11912 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
11913 std::sort(AsmPieces.begin(), AsmPieces.end());
11914 if (AsmPieces.size() == 4 &&
11915 AsmPieces[0] == "~{cc}" &&
11916 AsmPieces[1] == "~{dirflag}" &&
11917 AsmPieces[2] == "~{flags}" &&
11918 AsmPieces[3] == "~{fpsr}") {
11919 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11920 if (!Ty || Ty->getBitWidth() % 16 != 0)
11922 return IntrinsicLowering::LowerToByteSwap(CI);
11929 if (CI->getType()->isIntegerTy(64)) {
11930 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11931 if (Constraints.size() >= 2 &&
11932 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11933 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11934 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11935 SmallVector<StringRef, 4> Words;
11936 SplitString(AsmPieces[0], Words, " \t");
11937 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11939 SplitString(AsmPieces[1], Words, " \t");
11940 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11942 SplitString(AsmPieces[2], Words, " \t,");
11943 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11944 Words[2] == "%edx") {
11945 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11946 if (!Ty || Ty->getBitWidth() % 16 != 0)
11948 return IntrinsicLowering::LowerToByteSwap(CI);
11961 /// getConstraintType - Given a constraint letter, return the type of
11962 /// constraint it is for this target.
11963 X86TargetLowering::ConstraintType
11964 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11965 if (Constraint.size() == 1) {
11966 switch (Constraint[0]) {
11976 return C_RegisterClass;
12000 return TargetLowering::getConstraintType(Constraint);
12003 /// Examine constraint type and operand type and determine a weight value.
12004 /// This object must already have been set up with the operand type
12005 /// and the current alternative constraint selected.
12006 TargetLowering::ConstraintWeight
12007 X86TargetLowering::getSingleConstraintMatchWeight(
12008 AsmOperandInfo &info, const char *constraint) const {
12009 ConstraintWeight weight = CW_Invalid;
12010 Value *CallOperandVal = info.CallOperandVal;
12011 // If we don't have a value, we can't do a match,
12012 // but allow it at the lowest weight.
12013 if (CallOperandVal == NULL)
12015 const Type *type = CallOperandVal->getType();
12016 // Look at the constraint type.
12017 switch (*constraint) {
12019 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12030 if (CallOperandVal->getType()->isIntegerTy())
12031 weight = CW_SpecificReg;
12036 if (type->isFloatingPointTy())
12037 weight = CW_SpecificReg;
12040 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12041 weight = CW_SpecificReg;
12045 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12046 weight = CW_Register;
12049 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12050 if (C->getZExtValue() <= 31)
12051 weight = CW_Constant;
12055 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12056 if (C->getZExtValue() <= 63)
12057 weight = CW_Constant;
12061 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12062 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12063 weight = CW_Constant;
12067 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12068 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12069 weight = CW_Constant;
12073 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12074 if (C->getZExtValue() <= 3)
12075 weight = CW_Constant;
12079 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12080 if (C->getZExtValue() <= 0xff)
12081 weight = CW_Constant;
12086 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12087 weight = CW_Constant;
12091 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12092 if ((C->getSExtValue() >= -0x80000000LL) &&
12093 (C->getSExtValue() <= 0x7fffffffLL))
12094 weight = CW_Constant;
12098 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12099 if (C->getZExtValue() <= 0xffffffff)
12100 weight = CW_Constant;
12107 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12108 /// with another that has more specific requirements based on the type of the
12109 /// corresponding operand.
12110 const char *X86TargetLowering::
12111 LowerXConstraint(EVT ConstraintVT) const {
12112 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12113 // 'f' like normal targets.
12114 if (ConstraintVT.isFloatingPoint()) {
12115 if (Subtarget->hasXMMInt())
12117 if (Subtarget->hasXMM())
12121 return TargetLowering::LowerXConstraint(ConstraintVT);
12124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12125 /// vector. If it is invalid, don't add anything to Ops.
12126 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12128 std::vector<SDValue>&Ops,
12129 SelectionDAG &DAG) const {
12130 SDValue Result(0, 0);
12132 switch (Constraint) {
12135 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12136 if (C->getZExtValue() <= 31) {
12137 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12143 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12144 if (C->getZExtValue() <= 63) {
12145 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12151 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12152 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12153 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12159 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12160 if (C->getZExtValue() <= 255) {
12161 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12167 // 32-bit signed value
12168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12169 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12170 C->getSExtValue())) {
12171 // Widen to 64 bits here to get it sign extended.
12172 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12175 // FIXME gcc accepts some relocatable values here too, but only in certain
12176 // memory models; it's complicated.
12181 // 32-bit unsigned value
12182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12183 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12184 C->getZExtValue())) {
12185 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12189 // FIXME gcc accepts some relocatable values here too, but only in certain
12190 // memory models; it's complicated.
12194 // Literal immediates are always ok.
12195 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12196 // Widen to 64 bits here to get it sign extended.
12197 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12201 // In any sort of PIC mode addresses need to be computed at runtime by
12202 // adding in a register or some sort of table lookup. These can't
12203 // be used as immediates.
12204 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12207 // If we are in non-pic codegen mode, we allow the address of a global (with
12208 // an optional displacement) to be used with 'i'.
12209 GlobalAddressSDNode *GA = 0;
12210 int64_t Offset = 0;
12212 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12214 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12215 Offset += GA->getOffset();
12217 } else if (Op.getOpcode() == ISD::ADD) {
12218 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12219 Offset += C->getZExtValue();
12220 Op = Op.getOperand(0);
12223 } else if (Op.getOpcode() == ISD::SUB) {
12224 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12225 Offset += -C->getZExtValue();
12226 Op = Op.getOperand(0);
12231 // Otherwise, this isn't something we can handle, reject it.
12235 const GlobalValue *GV = GA->getGlobal();
12236 // If we require an extra load to get this address, as in PIC mode, we
12237 // can't accept it.
12238 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12239 getTargetMachine())))
12242 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12243 GA->getValueType(0), Offset);
12248 if (Result.getNode()) {
12249 Ops.push_back(Result);
12252 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12255 std::vector<unsigned> X86TargetLowering::
12256 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12258 if (Constraint.size() == 1) {
12259 // FIXME: not handling fp-stack yet!
12260 switch (Constraint[0]) { // GCC X86 Constraint Letters
12261 default: break; // Unknown constraint letter
12262 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12263 if (Subtarget->is64Bit()) {
12264 if (VT == MVT::i32)
12265 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12266 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12267 X86::R10D,X86::R11D,X86::R12D,
12268 X86::R13D,X86::R14D,X86::R15D,
12269 X86::EBP, X86::ESP, 0);
12270 else if (VT == MVT::i16)
12271 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12272 X86::SI, X86::DI, X86::R8W,X86::R9W,
12273 X86::R10W,X86::R11W,X86::R12W,
12274 X86::R13W,X86::R14W,X86::R15W,
12275 X86::BP, X86::SP, 0);
12276 else if (VT == MVT::i8)
12277 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12278 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12279 X86::R10B,X86::R11B,X86::R12B,
12280 X86::R13B,X86::R14B,X86::R15B,
12281 X86::BPL, X86::SPL, 0);
12283 else if (VT == MVT::i64)
12284 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12285 X86::RSI, X86::RDI, X86::R8, X86::R9,
12286 X86::R10, X86::R11, X86::R12,
12287 X86::R13, X86::R14, X86::R15,
12288 X86::RBP, X86::RSP, 0);
12292 // 32-bit fallthrough
12293 case 'Q': // Q_REGS
12294 if (VT == MVT::i32)
12295 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12296 else if (VT == MVT::i16)
12297 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12298 else if (VT == MVT::i8)
12299 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12300 else if (VT == MVT::i64)
12301 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12306 return std::vector<unsigned>();
12309 std::pair<unsigned, const TargetRegisterClass*>
12310 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12312 // First, see if this is a constraint that directly corresponds to an LLVM
12314 if (Constraint.size() == 1) {
12315 // GCC Constraint Letters
12316 switch (Constraint[0]) {
12318 case 'r': // GENERAL_REGS
12319 case 'l': // INDEX_REGS
12321 return std::make_pair(0U, X86::GR8RegisterClass);
12322 if (VT == MVT::i16)
12323 return std::make_pair(0U, X86::GR16RegisterClass);
12324 if (VT == MVT::i32 || !Subtarget->is64Bit())
12325 return std::make_pair(0U, X86::GR32RegisterClass);
12326 return std::make_pair(0U, X86::GR64RegisterClass);
12327 case 'R': // LEGACY_REGS
12329 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12330 if (VT == MVT::i16)
12331 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12332 if (VT == MVT::i32 || !Subtarget->is64Bit())
12333 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12334 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12335 case 'f': // FP Stack registers.
12336 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12337 // value to the correct fpstack register class.
12338 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12339 return std::make_pair(0U, X86::RFP32RegisterClass);
12340 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12341 return std::make_pair(0U, X86::RFP64RegisterClass);
12342 return std::make_pair(0U, X86::RFP80RegisterClass);
12343 case 'y': // MMX_REGS if MMX allowed.
12344 if (!Subtarget->hasMMX()) break;
12345 return std::make_pair(0U, X86::VR64RegisterClass);
12346 case 'Y': // SSE_REGS if SSE2 allowed
12347 if (!Subtarget->hasXMMInt()) break;
12349 case 'x': // SSE_REGS if SSE1 allowed
12350 if (!Subtarget->hasXMM()) break;
12352 switch (VT.getSimpleVT().SimpleTy) {
12354 // Scalar SSE types.
12357 return std::make_pair(0U, X86::FR32RegisterClass);
12360 return std::make_pair(0U, X86::FR64RegisterClass);
12368 return std::make_pair(0U, X86::VR128RegisterClass);
12374 // Use the default implementation in TargetLowering to convert the register
12375 // constraint into a member of a register class.
12376 std::pair<unsigned, const TargetRegisterClass*> Res;
12377 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12379 // Not found as a standard register?
12380 if (Res.second == 0) {
12381 // Map st(0) -> st(7) -> ST0
12382 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12383 tolower(Constraint[1]) == 's' &&
12384 tolower(Constraint[2]) == 't' &&
12385 Constraint[3] == '(' &&
12386 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12387 Constraint[5] == ')' &&
12388 Constraint[6] == '}') {
12390 Res.first = X86::ST0+Constraint[4]-'0';
12391 Res.second = X86::RFP80RegisterClass;
12395 // GCC allows "st(0)" to be called just plain "st".
12396 if (StringRef("{st}").equals_lower(Constraint)) {
12397 Res.first = X86::ST0;
12398 Res.second = X86::RFP80RegisterClass;
12403 if (StringRef("{flags}").equals_lower(Constraint)) {
12404 Res.first = X86::EFLAGS;
12405 Res.second = X86::CCRRegisterClass;
12409 // 'A' means EAX + EDX.
12410 if (Constraint == "A") {
12411 Res.first = X86::EAX;
12412 Res.second = X86::GR32_ADRegisterClass;
12418 // Otherwise, check to see if this is a register class of the wrong value
12419 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12420 // turn into {ax},{dx}.
12421 if (Res.second->hasType(VT))
12422 return Res; // Correct type already, nothing to do.
12424 // All of the single-register GCC register classes map their values onto
12425 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12426 // really want an 8-bit or 32-bit register, map to the appropriate register
12427 // class and return the appropriate register.
12428 if (Res.second == X86::GR16RegisterClass) {
12429 if (VT == MVT::i8) {
12430 unsigned DestReg = 0;
12431 switch (Res.first) {
12433 case X86::AX: DestReg = X86::AL; break;
12434 case X86::DX: DestReg = X86::DL; break;
12435 case X86::CX: DestReg = X86::CL; break;
12436 case X86::BX: DestReg = X86::BL; break;
12439 Res.first = DestReg;
12440 Res.second = X86::GR8RegisterClass;
12442 } else if (VT == MVT::i32) {
12443 unsigned DestReg = 0;
12444 switch (Res.first) {
12446 case X86::AX: DestReg = X86::EAX; break;
12447 case X86::DX: DestReg = X86::EDX; break;
12448 case X86::CX: DestReg = X86::ECX; break;
12449 case X86::BX: DestReg = X86::EBX; break;
12450 case X86::SI: DestReg = X86::ESI; break;
12451 case X86::DI: DestReg = X86::EDI; break;
12452 case X86::BP: DestReg = X86::EBP; break;
12453 case X86::SP: DestReg = X86::ESP; break;
12456 Res.first = DestReg;
12457 Res.second = X86::GR32RegisterClass;
12459 } else if (VT == MVT::i64) {
12460 unsigned DestReg = 0;
12461 switch (Res.first) {
12463 case X86::AX: DestReg = X86::RAX; break;
12464 case X86::DX: DestReg = X86::RDX; break;
12465 case X86::CX: DestReg = X86::RCX; break;
12466 case X86::BX: DestReg = X86::RBX; break;
12467 case X86::SI: DestReg = X86::RSI; break;
12468 case X86::DI: DestReg = X86::RDI; break;
12469 case X86::BP: DestReg = X86::RBP; break;
12470 case X86::SP: DestReg = X86::RSP; break;
12473 Res.first = DestReg;
12474 Res.second = X86::GR64RegisterClass;
12477 } else if (Res.second == X86::FR32RegisterClass ||
12478 Res.second == X86::FR64RegisterClass ||
12479 Res.second == X86::VR128RegisterClass) {
12480 // Handle references to XMM physical registers that got mapped into the
12481 // wrong class. This can happen with constraints like {xmm0} where the
12482 // target independent register mapper will just pick the first match it can
12483 // find, ignoring the required type.
12484 if (VT == MVT::f32)
12485 Res.second = X86::FR32RegisterClass;
12486 else if (VT == MVT::f64)
12487 Res.second = X86::FR64RegisterClass;
12488 else if (X86::VR128RegisterClass->hasType(VT))
12489 Res.second = X86::VR128RegisterClass;