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/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
64 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
66 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
68 return new X8664_MachoTargetObjectFile();
69 return new TargetLoweringObjectFileMachO();
72 if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
74 return new X8664_ELFTargetObjectFile(TM);
75 return new X8632_ELFTargetObjectFile(TM);
77 if (TM.getSubtarget<X86Subtarget>().isTargetCOFF())
78 return new TargetLoweringObjectFileCOFF();
79 llvm_unreachable("unknown subtarget type");
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83 : TargetLowering(TM, createTLOF(TM)) {
84 Subtarget = &TM.getSubtarget<X86Subtarget>();
85 X86ScalarSSEf64 = Subtarget->hasXMMInt();
86 X86ScalarSSEf32 = Subtarget->hasXMM();
87 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89 RegInfo = TM.getRegisterInfo();
92 // Set up the TargetLowering object.
93 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
95 // X86 is weird, it always uses i8 for shift amounts and setcc results.
96 setShiftAmountType(MVT::i8);
97 setBooleanContents(ZeroOrOneBooleanContent);
98 setSchedulingPreference(Sched::RegPressure);
99 setStackPointerRegisterToSaveRestore(X86StackPtr);
101 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
102 // Setup Windows compiler runtime calls.
103 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
104 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
105 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
106 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
107 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
108 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
109 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
110 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
113 if (Subtarget->isTargetDarwin()) {
114 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
115 setUseUnderscoreSetJmp(false);
116 setUseUnderscoreLongJmp(false);
117 } else if (Subtarget->isTargetMingw()) {
118 // MS runtime is weird: it exports _setjmp, but longjmp!
119 setUseUnderscoreSetJmp(true);
120 setUseUnderscoreLongJmp(false);
122 setUseUnderscoreSetJmp(true);
123 setUseUnderscoreLongJmp(true);
126 // Set up the register classes.
127 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
128 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
129 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
130 if (Subtarget->is64Bit())
131 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135 // We don't accept any truncstore of integer registers.
136 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
137 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
140 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
141 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
143 // SETOEQ and SETUNE require checking two conditions.
144 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
145 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
146 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
148 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
149 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
151 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
153 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
154 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
155 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
157 if (Subtarget->is64Bit()) {
158 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
159 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
160 } else if (!UseSoftFloat) {
161 // We have an algorithm for SSE2->double, and we turn this into a
162 // 64-bit FILD followed by conditional FADD for other targets.
163 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
164 // We have an algorithm for SSE2, and we turn this into a 64-bit
165 // FILD for other targets.
166 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
169 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
171 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
175 // SSE has no i16 to fp conversion, only i32
176 if (X86ScalarSSEf32) {
177 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
178 // f32 and f64 cases are Legal, f80 case is not
179 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
182 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
189 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
190 // are Legal, f80 is custom lowered.
191 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
192 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
194 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
196 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
197 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
199 if (X86ScalarSSEf32) {
200 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
201 // f32 and f64 cases are Legal, f80 case is not
202 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
204 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
205 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
208 // Handle FP_TO_UINT by promoting the destination to a larger signed
210 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
211 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
212 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
214 if (Subtarget->is64Bit()) {
215 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
216 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
217 } else if (!UseSoftFloat) {
218 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
219 // Expand FP_TO_UINT into a select.
220 // FIXME: We would like to use a Custom expander here eventually to do
221 // the optimal thing for SSE vs. the default expansion in the legalizer.
222 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
224 // With SSE3 we can use fisttpll to convert to a signed i64; without
225 // SSE, we're stuck with a fistpll.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
229 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
230 if (!X86ScalarSSEf64) {
231 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
232 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
233 if (Subtarget->is64Bit()) {
234 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
235 // Without SSE, i64->f64 goes through memory.
236 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
240 // Scalar integer divide and remainder are lowered to use operations that
241 // produce two results, to match the available instructions. This exposes
242 // the two-result form to trivial CSE, which is able to combine x/y and x%y
243 // into a single instruction.
245 // Scalar integer multiply-high is also lowered to use two-result
246 // operations, to match the available instructions. However, plain multiply
247 // (low) operations are left as Legal, as there are single-result
248 // instructions for this in x86. Using the two-result multiply instructions
249 // when both high and low results are needed must be arranged by dagcombine.
250 for (unsigned i = 0, e = 4; i != e; ++i) {
252 setOperationAction(ISD::MULHS, VT, Expand);
253 setOperationAction(ISD::MULHU, VT, Expand);
254 setOperationAction(ISD::SDIV, VT, Expand);
255 setOperationAction(ISD::UDIV, VT, Expand);
256 setOperationAction(ISD::SREM, VT, Expand);
257 setOperationAction(ISD::UREM, VT, Expand);
260 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
261 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
262 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
263 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
264 if (Subtarget->is64Bit())
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
269 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
270 setOperationAction(ISD::FREM , MVT::f32 , Expand);
271 setOperationAction(ISD::FREM , MVT::f64 , Expand);
272 setOperationAction(ISD::FREM , MVT::f80 , Expand);
273 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
275 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
277 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
278 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
279 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
280 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
281 if (Subtarget->is64Bit()) {
282 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
283 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
286 if (Subtarget->hasPOPCNT()) {
287 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
289 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
290 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
291 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
292 if (Subtarget->is64Bit())
293 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
296 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
297 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
299 // These should be promoted to a larger select which is supported.
300 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
301 // X86 wants to expand cmov itself.
302 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
303 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
304 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
305 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
306 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
307 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
309 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
310 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
311 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
312 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
313 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
316 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
318 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
321 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
322 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
323 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
324 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
325 if (Subtarget->is64Bit())
326 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
327 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
328 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
329 if (Subtarget->is64Bit()) {
330 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
331 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
332 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
333 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
334 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
336 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
337 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
338 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
339 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
340 if (Subtarget->is64Bit()) {
341 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
342 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
343 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
346 if (Subtarget->hasXMM())
347 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
349 // We may not have a libcall for MEMBARRIER so we should lower this.
350 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
352 // On X86 and X86-64, atomic operations are lowered to locked instructions.
353 // Locked instructions, in turn, have implicit fence semantics (all memory
354 // operations are flushed before issuing the locked instruction, and they
355 // are not buffered), so we can fold away the common pattern of
356 // fence-atomic-fence.
357 setShouldFoldAtomicFences(true);
359 // Expand certain atomics
360 for (unsigned i = 0, e = 4; i != e; ++i) {
362 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
366 if (!Subtarget->is64Bit()) {
367 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
376 // FIXME - use subtarget debug flags
377 if (!Subtarget->isTargetDarwin() &&
378 !Subtarget->isTargetELF() &&
379 !Subtarget->isTargetCygMing()) {
380 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
383 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
384 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
385 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
386 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
387 if (Subtarget->is64Bit()) {
388 setExceptionPointerRegister(X86::RAX);
389 setExceptionSelectorRegister(X86::RDX);
391 setExceptionPointerRegister(X86::EAX);
392 setExceptionSelectorRegister(X86::EDX);
394 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
397 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
399 setOperationAction(ISD::TRAP, MVT::Other, Legal);
401 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
402 setOperationAction(ISD::VASTART , MVT::Other, Custom);
403 setOperationAction(ISD::VAEND , MVT::Other, Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::VAARG , MVT::Other, Custom);
406 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
408 setOperationAction(ISD::VAARG , MVT::Other, Expand);
409 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
412 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
413 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
414 if (Subtarget->is64Bit())
415 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
416 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421 if (!UseSoftFloat && X86ScalarSSEf64) {
422 // f32 and f64 use SSE.
423 // Set up the FP register classes.
424 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
425 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
427 // Use ANDPD to simulate FABS.
428 setOperationAction(ISD::FABS , MVT::f64, Custom);
429 setOperationAction(ISD::FABS , MVT::f32, Custom);
431 // Use XORP to simulate FNEG.
432 setOperationAction(ISD::FNEG , MVT::f64, Custom);
433 setOperationAction(ISD::FNEG , MVT::f32, Custom);
435 // Use ANDPD and ORPD to simulate FCOPYSIGN.
436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439 // We don't support sin/cos/fmod
440 setOperationAction(ISD::FSIN , MVT::f64, Expand);
441 setOperationAction(ISD::FCOS , MVT::f64, Expand);
442 setOperationAction(ISD::FSIN , MVT::f32, Expand);
443 setOperationAction(ISD::FCOS , MVT::f32, Expand);
445 // Expand FP immediates into loads from the stack, except for the special
447 addLegalFPImmediate(APFloat(+0.0)); // xorpd
448 addLegalFPImmediate(APFloat(+0.0f)); // xorps
449 } else if (!UseSoftFloat && X86ScalarSSEf32) {
450 // Use SSE for f32, x87 for f64.
451 // Set up the FP register classes.
452 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
453 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
455 // Use ANDPS to simulate FABS.
456 setOperationAction(ISD::FABS , MVT::f32, Custom);
458 // Use XORP to simulate FNEG.
459 setOperationAction(ISD::FNEG , MVT::f32, Custom);
461 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
463 // Use ANDPS and ORPS to simulate FCOPYSIGN.
464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
467 // We don't support sin/cos/fmod
468 setOperationAction(ISD::FSIN , MVT::f32, Expand);
469 setOperationAction(ISD::FCOS , MVT::f32, Expand);
471 // Special cases we handle for FP constants.
472 addLegalFPImmediate(APFloat(+0.0f)); // xorps
473 addLegalFPImmediate(APFloat(+0.0)); // FLD0
474 addLegalFPImmediate(APFloat(+1.0)); // FLD1
475 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
476 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
479 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
480 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
482 } else if (!UseSoftFloat) {
483 // f32 and f64 in x87.
484 // Set up the FP register classes.
485 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
486 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
488 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
489 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
490 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
494 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
495 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
497 addLegalFPImmediate(APFloat(+0.0)); // FLD0
498 addLegalFPImmediate(APFloat(+1.0)); // FLD1
499 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
500 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
501 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
502 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
503 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
504 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
507 // Long double always uses X87.
509 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
510 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
511 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
513 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
514 addLegalFPImmediate(TmpFlt); // FLD0
516 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
519 APFloat TmpFlt2(+1.0);
520 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
522 addLegalFPImmediate(TmpFlt2); // FLD1
523 TmpFlt2.changeSign();
524 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
528 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
529 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
533 // Always use a library call for pow.
534 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
535 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
536 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
538 setOperationAction(ISD::FLOG, MVT::f80, Expand);
539 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
540 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
541 setOperationAction(ISD::FEXP, MVT::f80, Expand);
542 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
544 // First set operation action for all vector types to either promote
545 // (for widening) or expand (for scalarization). Then we will selectively
546 // turn on ones that can be effectively codegen'd.
547 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
548 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
549 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
564 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
565 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
598 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
602 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
603 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
604 setTruncStoreAction((MVT::SimpleValueType)VT,
605 (MVT::SimpleValueType)InnerVT, Expand);
606 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
607 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
608 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
611 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
612 // with -msoft-float, disable use of MMX as well.
613 if (!UseSoftFloat && Subtarget->hasMMX()) {
614 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
615 // No operations on x86mmx supported, everything uses intrinsics.
618 // MMX-sized vectors (other than x86mmx) are expected to be expanded
619 // into smaller operations.
620 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
621 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
622 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
623 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
624 setOperationAction(ISD::AND, MVT::v8i8, Expand);
625 setOperationAction(ISD::AND, MVT::v4i16, Expand);
626 setOperationAction(ISD::AND, MVT::v2i32, Expand);
627 setOperationAction(ISD::AND, MVT::v1i64, Expand);
628 setOperationAction(ISD::OR, MVT::v8i8, Expand);
629 setOperationAction(ISD::OR, MVT::v4i16, Expand);
630 setOperationAction(ISD::OR, MVT::v2i32, Expand);
631 setOperationAction(ISD::OR, MVT::v1i64, Expand);
632 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
633 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
634 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
635 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
641 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
642 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
643 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
644 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
645 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
646 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
647 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
648 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
650 if (!UseSoftFloat && Subtarget->hasXMM()) {
651 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
653 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
654 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
655 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
656 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
657 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
658 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
659 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
661 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
663 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
664 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
667 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
668 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
670 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
671 // registers cannot be used even for integer operations.
672 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
673 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
674 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
675 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
677 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
678 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
679 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
680 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
681 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
682 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
683 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
684 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
685 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
686 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
687 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
688 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
689 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
690 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
691 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
692 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
694 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
697 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
699 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
700 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
703 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
705 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
706 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
707 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
708 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
709 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
711 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
712 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
713 EVT VT = (MVT::SimpleValueType)i;
714 // Do not attempt to custom lower non-power-of-2 vectors
715 if (!isPowerOf2_32(VT.getVectorNumElements()))
717 // Do not attempt to custom lower non-128-bit vectors
718 if (!VT.is128BitVector())
720 setOperationAction(ISD::BUILD_VECTOR,
721 VT.getSimpleVT().SimpleTy, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE,
723 VT.getSimpleVT().SimpleTy, Custom);
724 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
725 VT.getSimpleVT().SimpleTy, Custom);
728 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
729 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
730 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
731 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
735 if (Subtarget->is64Bit()) {
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
740 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
741 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
742 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
745 // Do not attempt to promote non-128-bit vectors
746 if (!VT.is128BitVector())
749 setOperationAction(ISD::AND, SVT, Promote);
750 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
751 setOperationAction(ISD::OR, SVT, Promote);
752 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
753 setOperationAction(ISD::XOR, SVT, Promote);
754 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
755 setOperationAction(ISD::LOAD, SVT, Promote);
756 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
757 setOperationAction(ISD::SELECT, SVT, Promote);
758 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
761 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
763 // Custom lower v2i64 and v2f64 selects.
764 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
765 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
766 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
767 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
769 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
770 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
773 if (Subtarget->hasSSE41()) {
774 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
775 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
776 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
777 setOperationAction(ISD::FRINT, MVT::f32, Legal);
778 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
779 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
780 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
781 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
782 setOperationAction(ISD::FRINT, MVT::f64, Legal);
783 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
785 // FIXME: Do we need to handle scalar-to-vector here?
786 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
788 // Can turn SHL into an integer multiply.
789 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
790 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
792 // i8 and i16 vectors are custom , because the source register and source
793 // source memory operand types are not the same width. f32 vectors are
794 // custom since the immediate controlling the insert encodes additional
796 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
797 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
798 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
799 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
802 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
804 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806 if (Subtarget->is64Bit()) {
807 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
812 if (Subtarget->hasSSE42())
813 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
815 if (!UseSoftFloat && Subtarget->hasAVX()) {
816 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
817 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
818 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
819 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
820 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
822 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
823 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
824 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
825 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
826 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
827 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
828 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
829 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
831 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
832 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
833 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
834 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
835 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
836 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
838 // Operations to consider commented out -v16i16 v32i8
839 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
840 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
841 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
842 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
843 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
844 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
845 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
846 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
847 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
848 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
849 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
850 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
851 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
852 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
854 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
855 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
856 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
857 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
859 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
860 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
861 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
863 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
865 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
867 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
870 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
873 // Not sure we want to do this since there are no 256-bit integer
876 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877 // This includes 256-bit vectors
878 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
879 EVT VT = (MVT::SimpleValueType)i;
881 // Do not attempt to custom lower non-power-of-2 vectors
882 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
890 if (Subtarget->is64Bit()) {
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
897 // Not sure we want to do this since there are no 256-bit integer
900 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
901 // Including 256-bit vectors
902 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
903 EVT VT = (MVT::SimpleValueType)i;
905 if (!VT.is256BitVector()) {
908 setOperationAction(ISD::AND, VT, Promote);
909 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
910 setOperationAction(ISD::OR, VT, Promote);
911 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
912 setOperationAction(ISD::XOR, VT, Promote);
913 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
914 setOperationAction(ISD::LOAD, VT, Promote);
915 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
916 setOperationAction(ISD::SELECT, VT, Promote);
917 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
920 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
924 // We want to custom lower some of our intrinsics.
925 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
928 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
929 // handle type legalization for these operations here.
931 // FIXME: We really should do custom legalization for addition and
932 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
933 // than generic legalization for 64-bit multiplication-with-overflow, though.
934 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
935 // Add/Sub/Mul with overflow operations are custom lowered.
937 setOperationAction(ISD::SADDO, VT, Custom);
938 setOperationAction(ISD::UADDO, VT, Custom);
939 setOperationAction(ISD::SSUBO, VT, Custom);
940 setOperationAction(ISD::USUBO, VT, Custom);
941 setOperationAction(ISD::SMULO, VT, Custom);
942 setOperationAction(ISD::UMULO, VT, Custom);
945 // There are no 8-bit 3-address imul/mul instructions
946 setOperationAction(ISD::SMULO, MVT::i8, Expand);
947 setOperationAction(ISD::UMULO, MVT::i8, Expand);
949 if (!Subtarget->is64Bit()) {
950 // These libcalls are not available in 32-bit.
951 setLibcallName(RTLIB::SHL_I128, 0);
952 setLibcallName(RTLIB::SRL_I128, 0);
953 setLibcallName(RTLIB::SRA_I128, 0);
956 // We have target-specific dag combine patterns for the following nodes:
957 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
958 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
959 setTargetDAGCombine(ISD::BUILD_VECTOR);
960 setTargetDAGCombine(ISD::SELECT);
961 setTargetDAGCombine(ISD::SHL);
962 setTargetDAGCombine(ISD::SRA);
963 setTargetDAGCombine(ISD::SRL);
964 setTargetDAGCombine(ISD::OR);
965 setTargetDAGCombine(ISD::AND);
966 setTargetDAGCombine(ISD::STORE);
967 setTargetDAGCombine(ISD::ZERO_EXTEND);
968 if (Subtarget->is64Bit())
969 setTargetDAGCombine(ISD::MUL);
971 computeRegisterProperties();
973 // FIXME: These should be based on subtarget info. Plus, the values should
974 // be smaller when we are in optimizing for size mode.
975 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
976 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
977 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
978 setPrefLoopAlignment(16);
979 benefitFromCodePlacementOpt = true;
983 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
988 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
989 /// the desired ByVal argument alignment.
990 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
993 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
994 if (VTy->getBitWidth() == 128)
996 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
997 unsigned EltAlign = 0;
998 getMaxByValAlign(ATy->getElementType(), EltAlign);
999 if (EltAlign > MaxAlign)
1000 MaxAlign = EltAlign;
1001 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1002 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1003 unsigned EltAlign = 0;
1004 getMaxByValAlign(STy->getElementType(i), EltAlign);
1005 if (EltAlign > MaxAlign)
1006 MaxAlign = EltAlign;
1014 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1015 /// function arguments in the caller parameter area. For X86, aggregates
1016 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1017 /// are at 4-byte boundaries.
1018 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1019 if (Subtarget->is64Bit()) {
1020 // Max of 8 and alignment of type.
1021 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1028 if (Subtarget->hasXMM())
1029 getMaxByValAlign(Ty, Align);
1033 /// getOptimalMemOpType - Returns the target specific optimal type for load
1034 /// and store operations as a result of memset, memcpy, and memmove
1035 /// lowering. If DstAlign is zero that means it's safe to destination
1036 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1037 /// means there isn't a need to check it against alignment requirement,
1038 /// probably because the source does not need to be loaded. If
1039 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1040 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1041 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1042 /// constant so it does not need to be loaded.
1043 /// It returns EVT::Other if the type should be determined using generic
1044 /// target-independent logic.
1046 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1047 unsigned DstAlign, unsigned SrcAlign,
1048 bool NonScalarIntSafe,
1050 MachineFunction &MF) const {
1051 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1052 // linux. This is because the stack realignment code can't handle certain
1053 // cases like PR2962. This should be removed when PR2962 is fixed.
1054 const Function *F = MF.getFunction();
1055 if (NonScalarIntSafe &&
1056 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1058 (Subtarget->isUnalignedMemAccessFast() ||
1059 ((DstAlign == 0 || DstAlign >= 16) &&
1060 (SrcAlign == 0 || SrcAlign >= 16))) &&
1061 Subtarget->getStackAlignment() >= 16) {
1062 if (Subtarget->hasSSE2())
1064 if (Subtarget->hasSSE1())
1066 } else if (!MemcpyStrSrc && Size >= 8 &&
1067 !Subtarget->is64Bit() &&
1068 Subtarget->getStackAlignment() >= 8 &&
1069 Subtarget->hasXMMInt()) {
1070 // Do not use f64 to lower memcpy if source is string constant. It's
1071 // better to use i32 to avoid the loads.
1075 if (Subtarget->is64Bit() && Size >= 8)
1080 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1081 /// current function. The returned value is a member of the
1082 /// MachineJumpTableInfo::JTEntryKind enum.
1083 unsigned X86TargetLowering::getJumpTableEncoding() const {
1084 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1086 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1087 Subtarget->isPICStyleGOT())
1088 return MachineJumpTableInfo::EK_Custom32;
1090 // Otherwise, use the normal jump table encoding heuristics.
1091 return TargetLowering::getJumpTableEncoding();
1095 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1096 const MachineBasicBlock *MBB,
1097 unsigned uid,MCContext &Ctx) const{
1098 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1099 Subtarget->isPICStyleGOT());
1100 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1102 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1103 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1106 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1108 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1109 SelectionDAG &DAG) const {
1110 if (!Subtarget->is64Bit())
1111 // This doesn't have DebugLoc associated with it, but is not really the
1112 // same as a Register.
1113 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1117 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1118 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1120 const MCExpr *X86TargetLowering::
1121 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1122 MCContext &Ctx) const {
1123 // X86-64 uses RIP relative addressing based on the jump table label.
1124 if (Subtarget->isPICStyleRIPRel())
1125 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1127 // Otherwise, the reference is relative to the PIC base.
1128 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1131 /// getFunctionAlignment - Return the Log2 alignment of this function.
1132 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1133 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1136 std::pair<const TargetRegisterClass*, uint8_t>
1137 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1138 const TargetRegisterClass *RRC = 0;
1140 switch (VT.getSimpleVT().SimpleTy) {
1142 return TargetLowering::findRepresentativeClass(VT);
1143 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1144 RRC = (Subtarget->is64Bit()
1145 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1148 RRC = X86::VR64RegisterClass;
1150 case MVT::f32: case MVT::f64:
1151 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1152 case MVT::v4f32: case MVT::v2f64:
1153 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1155 RRC = X86::VR128RegisterClass;
1158 return std::make_pair(RRC, Cost);
1162 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1163 MachineFunction &MF) const {
1164 const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1166 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1167 switch (RC->getID()) {
1170 case X86::GR32RegClassID:
1172 case X86::GR64RegClassID:
1174 case X86::VR128RegClassID:
1175 return Subtarget->is64Bit() ? 10 : 4;
1176 case X86::VR64RegClassID:
1181 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1182 unsigned &Offset) const {
1183 if (!Subtarget->isTargetLinux())
1186 if (Subtarget->is64Bit()) {
1187 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1189 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1202 //===----------------------------------------------------------------------===//
1203 // Return Value Calling Convention Implementation
1204 //===----------------------------------------------------------------------===//
1206 #include "X86GenCallingConv.inc"
1209 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1210 const SmallVectorImpl<ISD::OutputArg> &Outs,
1211 LLVMContext &Context) const {
1212 SmallVector<CCValAssign, 16> RVLocs;
1213 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1215 return CCInfo.CheckReturn(Outs, RetCC_X86);
1219 X86TargetLowering::LowerReturn(SDValue Chain,
1220 CallingConv::ID CallConv, bool isVarArg,
1221 const SmallVectorImpl<ISD::OutputArg> &Outs,
1222 const SmallVectorImpl<SDValue> &OutVals,
1223 DebugLoc dl, SelectionDAG &DAG) const {
1224 MachineFunction &MF = DAG.getMachineFunction();
1225 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1227 SmallVector<CCValAssign, 16> RVLocs;
1228 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1229 RVLocs, *DAG.getContext());
1230 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1232 // Add the regs to the liveout set for the function.
1233 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1234 for (unsigned i = 0; i != RVLocs.size(); ++i)
1235 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1236 MRI.addLiveOut(RVLocs[i].getLocReg());
1240 SmallVector<SDValue, 6> RetOps;
1241 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1242 // Operand #1 = Bytes To Pop
1243 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1246 // Copy the result values into the output registers.
1247 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1248 CCValAssign &VA = RVLocs[i];
1249 assert(VA.isRegLoc() && "Can only return in registers!");
1250 SDValue ValToCopy = OutVals[i];
1251 EVT ValVT = ValToCopy.getValueType();
1253 // If this is x86-64, and we disabled SSE, we can't return FP values,
1254 // or SSE or MMX vectors.
1255 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1256 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1257 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1258 report_fatal_error("SSE register return with SSE disabled");
1260 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1261 // llvm-gcc has never done it right and no one has noticed, so this
1262 // should be OK for now.
1263 if (ValVT == MVT::f64 &&
1264 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1265 report_fatal_error("SSE2 register return with SSE2 disabled");
1267 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1268 // the RET instruction and handled by the FP Stackifier.
1269 if (VA.getLocReg() == X86::ST0 ||
1270 VA.getLocReg() == X86::ST1) {
1271 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1272 // change the value to the FP stack register class.
1273 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1274 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1275 RetOps.push_back(ValToCopy);
1276 // Don't emit a copytoreg.
1280 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1281 // which is returned in RAX / RDX.
1282 if (Subtarget->is64Bit()) {
1283 if (ValVT == MVT::x86mmx) {
1284 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1285 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1286 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1288 // If we don't have SSE2 available, convert to v4f32 so the generated
1289 // register is legal.
1290 if (!Subtarget->hasSSE2())
1291 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1296 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1297 Flag = Chain.getValue(1);
1300 // The x86-64 ABI for returning structs by value requires that we copy
1301 // the sret argument into %rax for the return. We saved the argument into
1302 // a virtual register in the entry block, so now we copy the value out
1304 if (Subtarget->is64Bit() &&
1305 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1306 MachineFunction &MF = DAG.getMachineFunction();
1307 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1308 unsigned Reg = FuncInfo->getSRetReturnReg();
1310 "SRetReturnReg should have been set in LowerFormalArguments().");
1311 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1313 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1314 Flag = Chain.getValue(1);
1316 // RAX now acts like a return value.
1317 MRI.addLiveOut(X86::RAX);
1320 RetOps[0] = Chain; // Update chain.
1322 // Add the flag if we have it.
1324 RetOps.push_back(Flag);
1326 return DAG.getNode(X86ISD::RET_FLAG, dl,
1327 MVT::Other, &RetOps[0], RetOps.size());
1330 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1331 if (N->getNumValues() != 1)
1333 if (!N->hasNUsesOfValue(1, 0))
1336 SDNode *Copy = *N->use_begin();
1337 if (Copy->getOpcode() != ISD::CopyToReg &&
1338 Copy->getOpcode() != ISD::FP_EXTEND)
1341 bool HasRet = false;
1342 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1344 if (UI->getOpcode() != X86ISD::RET_FLAG)
1352 /// LowerCallResult - Lower the result values of a call into the
1353 /// appropriate copies out of appropriate physical registers.
1356 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1357 CallingConv::ID CallConv, bool isVarArg,
1358 const SmallVectorImpl<ISD::InputArg> &Ins,
1359 DebugLoc dl, SelectionDAG &DAG,
1360 SmallVectorImpl<SDValue> &InVals) const {
1362 // Assign locations to each value returned by this call.
1363 SmallVector<CCValAssign, 16> RVLocs;
1364 bool Is64Bit = Subtarget->is64Bit();
1365 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1366 RVLocs, *DAG.getContext());
1367 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1369 // Copy all of the result registers out of their specified physreg.
1370 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1371 CCValAssign &VA = RVLocs[i];
1372 EVT CopyVT = VA.getValVT();
1374 // If this is x86-64, and we disabled SSE, we can't return FP values
1375 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1376 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1377 report_fatal_error("SSE register return with SSE disabled");
1382 // If this is a call to a function that returns an fp value on the floating
1383 // point stack, we must guarantee the the value is popped from the stack, so
1384 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1385 // if the return value is not used. We use the FpGET_ST0 instructions
1387 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1388 // If we prefer to use the value in xmm registers, copy it out as f80 and
1389 // use a truncate to move it from fp stack reg to xmm reg.
1390 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1391 bool isST0 = VA.getLocReg() == X86::ST0;
1393 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1394 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1395 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1396 SDValue Ops[] = { Chain, InFlag };
1397 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1399 Val = Chain.getValue(0);
1401 // Round the f80 to the right size, which also moves it to the appropriate
1403 if (CopyVT != VA.getValVT())
1404 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1405 // This truncation won't change the value.
1406 DAG.getIntPtrConstant(1));
1407 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1408 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1409 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1410 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1411 MVT::v2i64, InFlag).getValue(1);
1412 Val = Chain.getValue(0);
1413 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1414 Val, DAG.getConstant(0, MVT::i64));
1416 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1417 MVT::i64, InFlag).getValue(1);
1418 Val = Chain.getValue(0);
1420 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1422 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1423 CopyVT, InFlag).getValue(1);
1424 Val = Chain.getValue(0);
1426 InFlag = Chain.getValue(2);
1427 InVals.push_back(Val);
1434 //===----------------------------------------------------------------------===//
1435 // C & StdCall & Fast Calling Convention implementation
1436 //===----------------------------------------------------------------------===//
1437 // StdCall calling convention seems to be standard for many Windows' API
1438 // routines and around. It differs from C calling convention just a little:
1439 // callee should clean up the stack, not caller. Symbols should be also
1440 // decorated in some fancy way :) It doesn't support any vector arguments.
1441 // For info on fast calling convention see Fast Calling Convention (tail call)
1442 // implementation LowerX86_32FastCCCallTo.
1444 /// CallIsStructReturn - Determines whether a call uses struct return
1446 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1450 return Outs[0].Flags.isSRet();
1453 /// ArgsAreStructReturn - Determines whether a function uses struct
1454 /// return semantics.
1456 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1460 return Ins[0].Flags.isSRet();
1463 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1464 /// by "Src" to address "Dst" with size and alignment information specified by
1465 /// the specific parameter attribute. The copy will be passed as a byval
1466 /// function parameter.
1468 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1469 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1471 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1473 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1474 /*isVolatile*/false, /*AlwaysInline=*/true,
1475 MachinePointerInfo(), MachinePointerInfo());
1478 /// IsTailCallConvention - Return true if the calling convention is one that
1479 /// supports tail call optimization.
1480 static bool IsTailCallConvention(CallingConv::ID CC) {
1481 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1484 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1485 /// a tailcall target by changing its ABI.
1486 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1487 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1491 X86TargetLowering::LowerMemArgument(SDValue Chain,
1492 CallingConv::ID CallConv,
1493 const SmallVectorImpl<ISD::InputArg> &Ins,
1494 DebugLoc dl, SelectionDAG &DAG,
1495 const CCValAssign &VA,
1496 MachineFrameInfo *MFI,
1498 // Create the nodes corresponding to a load from this parameter slot.
1499 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1500 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1501 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1504 // If value is passed by pointer we have address passed instead of the value
1506 if (VA.getLocInfo() == CCValAssign::Indirect)
1507 ValVT = VA.getLocVT();
1509 ValVT = VA.getValVT();
1511 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1512 // changed with more analysis.
1513 // In case of tail call optimization mark all arguments mutable. Since they
1514 // could be overwritten by lowering of arguments in case of a tail call.
1515 if (Flags.isByVal()) {
1516 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1517 VA.getLocMemOffset(), isImmutable);
1518 return DAG.getFrameIndex(FI, getPointerTy());
1520 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1521 VA.getLocMemOffset(), isImmutable);
1522 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1523 return DAG.getLoad(ValVT, dl, Chain, FIN,
1524 MachinePointerInfo::getFixedStack(FI),
1530 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1531 CallingConv::ID CallConv,
1533 const SmallVectorImpl<ISD::InputArg> &Ins,
1536 SmallVectorImpl<SDValue> &InVals)
1538 MachineFunction &MF = DAG.getMachineFunction();
1539 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1541 const Function* Fn = MF.getFunction();
1542 if (Fn->hasExternalLinkage() &&
1543 Subtarget->isTargetCygMing() &&
1544 Fn->getName() == "main")
1545 FuncInfo->setForceFramePointer(true);
1547 MachineFrameInfo *MFI = MF.getFrameInfo();
1548 bool Is64Bit = Subtarget->is64Bit();
1549 bool IsWin64 = Subtarget->isTargetWin64();
1551 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1552 "Var args not supported with calling convention fastcc or ghc");
1554 // Assign locations to all of the incoming arguments.
1555 SmallVector<CCValAssign, 16> ArgLocs;
1556 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1557 ArgLocs, *DAG.getContext());
1558 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1560 unsigned LastVal = ~0U;
1562 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1563 CCValAssign &VA = ArgLocs[i];
1564 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1566 assert(VA.getValNo() != LastVal &&
1567 "Don't support value assigned to multiple locs yet");
1568 LastVal = VA.getValNo();
1570 if (VA.isRegLoc()) {
1571 EVT RegVT = VA.getLocVT();
1572 TargetRegisterClass *RC = NULL;
1573 if (RegVT == MVT::i32)
1574 RC = X86::GR32RegisterClass;
1575 else if (Is64Bit && RegVT == MVT::i64)
1576 RC = X86::GR64RegisterClass;
1577 else if (RegVT == MVT::f32)
1578 RC = X86::FR32RegisterClass;
1579 else if (RegVT == MVT::f64)
1580 RC = X86::FR64RegisterClass;
1581 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1582 RC = X86::VR256RegisterClass;
1583 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1584 RC = X86::VR128RegisterClass;
1585 else if (RegVT == MVT::x86mmx)
1586 RC = X86::VR64RegisterClass;
1588 llvm_unreachable("Unknown argument type!");
1590 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1591 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1593 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1594 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1596 if (VA.getLocInfo() == CCValAssign::SExt)
1597 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1598 DAG.getValueType(VA.getValVT()));
1599 else if (VA.getLocInfo() == CCValAssign::ZExt)
1600 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1601 DAG.getValueType(VA.getValVT()));
1602 else if (VA.getLocInfo() == CCValAssign::BCvt)
1603 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1605 if (VA.isExtInLoc()) {
1606 // Handle MMX values passed in XMM regs.
1607 if (RegVT.isVector()) {
1608 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1611 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1614 assert(VA.isMemLoc());
1615 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1618 // If value is passed via pointer - do a load.
1619 if (VA.getLocInfo() == CCValAssign::Indirect)
1620 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1621 MachinePointerInfo(), false, false, 0);
1623 InVals.push_back(ArgValue);
1626 // The x86-64 ABI for returning structs by value requires that we copy
1627 // the sret argument into %rax for the return. Save the argument into
1628 // a virtual register so that we can access it from the return points.
1629 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1630 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1631 unsigned Reg = FuncInfo->getSRetReturnReg();
1633 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1634 FuncInfo->setSRetReturnReg(Reg);
1636 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1637 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1640 unsigned StackSize = CCInfo.getNextStackOffset();
1641 // Align stack specially for tail calls.
1642 if (FuncIsMadeTailCallSafe(CallConv))
1643 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1645 // If the function takes variable number of arguments, make a frame index for
1646 // the start of the first vararg value... for expansion of llvm.va_start.
1648 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1649 CallConv != CallingConv::X86_ThisCall))) {
1650 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1653 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1655 // FIXME: We should really autogenerate these arrays
1656 static const unsigned GPR64ArgRegsWin64[] = {
1657 X86::RCX, X86::RDX, X86::R8, X86::R9
1659 static const unsigned GPR64ArgRegs64Bit[] = {
1660 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1662 static const unsigned XMMArgRegs64Bit[] = {
1663 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1664 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1666 const unsigned *GPR64ArgRegs;
1667 unsigned NumXMMRegs = 0;
1670 // The XMM registers which might contain var arg parameters are shadowed
1671 // in their paired GPR. So we only need to save the GPR to their home
1673 TotalNumIntRegs = 4;
1674 GPR64ArgRegs = GPR64ArgRegsWin64;
1676 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1677 GPR64ArgRegs = GPR64ArgRegs64Bit;
1679 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1681 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1684 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1685 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1686 "SSE register cannot be used when SSE is disabled!");
1687 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1688 "SSE register cannot be used when SSE is disabled!");
1689 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1690 // Kernel mode asks for SSE to be disabled, so don't push them
1692 TotalNumXMMRegs = 0;
1695 const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1696 // Get to the caller-allocated home save location. Add 8 to account
1697 // for the return address.
1698 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1699 FuncInfo->setRegSaveFrameIndex(
1700 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1701 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1703 // For X86-64, if there are vararg parameters that are passed via
1704 // registers, then we must store them to their spots on the stack so they
1705 // may be loaded by deferencing the result of va_next.
1706 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1707 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1708 FuncInfo->setRegSaveFrameIndex(
1709 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1713 // Store the integer parameter registers.
1714 SmallVector<SDValue, 8> MemOps;
1715 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1717 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1718 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1719 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1720 DAG.getIntPtrConstant(Offset));
1721 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1722 X86::GR64RegisterClass);
1723 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1725 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1726 MachinePointerInfo::getFixedStack(
1727 FuncInfo->getRegSaveFrameIndex(), Offset),
1729 MemOps.push_back(Store);
1733 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1734 // Now store the XMM (fp + vector) parameter registers.
1735 SmallVector<SDValue, 11> SaveXMMOps;
1736 SaveXMMOps.push_back(Chain);
1738 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1739 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1740 SaveXMMOps.push_back(ALVal);
1742 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1743 FuncInfo->getRegSaveFrameIndex()));
1744 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1745 FuncInfo->getVarArgsFPOffset()));
1747 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1748 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1749 X86::VR128RegisterClass);
1750 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1751 SaveXMMOps.push_back(Val);
1753 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1755 &SaveXMMOps[0], SaveXMMOps.size()));
1758 if (!MemOps.empty())
1759 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1760 &MemOps[0], MemOps.size());
1764 // Some CCs need callee pop.
1765 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1766 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1768 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1769 // If this is an sret function, the return should pop the hidden pointer.
1770 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1771 FuncInfo->setBytesToPopOnReturn(4);
1775 // RegSaveFrameIndex is X86-64 only.
1776 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1777 if (CallConv == CallingConv::X86_FastCall ||
1778 CallConv == CallingConv::X86_ThisCall)
1779 // fastcc functions can't have varargs.
1780 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1787 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1788 SDValue StackPtr, SDValue Arg,
1789 DebugLoc dl, SelectionDAG &DAG,
1790 const CCValAssign &VA,
1791 ISD::ArgFlagsTy Flags) const {
1792 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1793 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1794 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1795 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1796 if (Flags.isByVal())
1797 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1799 return DAG.getStore(Chain, dl, Arg, PtrOff,
1800 MachinePointerInfo::getStack(LocMemOffset),
1804 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1805 /// optimization is performed and it is required.
1807 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1808 SDValue &OutRetAddr, SDValue Chain,
1809 bool IsTailCall, bool Is64Bit,
1810 int FPDiff, DebugLoc dl) const {
1811 // Adjust the Return address stack slot.
1812 EVT VT = getPointerTy();
1813 OutRetAddr = getReturnAddressFrameIndex(DAG);
1815 // Load the "old" Return address.
1816 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1818 return SDValue(OutRetAddr.getNode(), 1);
1821 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1822 /// optimization is performed and it is required (FPDiff!=0).
1824 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1825 SDValue Chain, SDValue RetAddrFrIdx,
1826 bool Is64Bit, int FPDiff, DebugLoc dl) {
1827 // Store the return address to the appropriate stack slot.
1828 if (!FPDiff) return Chain;
1829 // Calculate the new stack slot for the return address.
1830 int SlotSize = Is64Bit ? 8 : 4;
1831 int NewReturnAddrFI =
1832 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1833 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1834 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1835 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1836 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1842 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1843 CallingConv::ID CallConv, bool isVarArg,
1845 const SmallVectorImpl<ISD::OutputArg> &Outs,
1846 const SmallVectorImpl<SDValue> &OutVals,
1847 const SmallVectorImpl<ISD::InputArg> &Ins,
1848 DebugLoc dl, SelectionDAG &DAG,
1849 SmallVectorImpl<SDValue> &InVals) const {
1850 MachineFunction &MF = DAG.getMachineFunction();
1851 bool Is64Bit = Subtarget->is64Bit();
1852 bool IsStructRet = CallIsStructReturn(Outs);
1853 bool IsSibcall = false;
1856 // Check if it's really possible to do a tail call.
1857 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1858 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1859 Outs, OutVals, Ins, DAG);
1861 // Sibcalls are automatically detected tailcalls which do not require
1863 if (!GuaranteedTailCallOpt && isTailCall)
1870 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1871 "Var args not supported with calling convention fastcc or ghc");
1873 // Analyze operands of the call, assigning locations to each operand.
1874 SmallVector<CCValAssign, 16> ArgLocs;
1875 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1876 ArgLocs, *DAG.getContext());
1877 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1879 // Get a count of how many bytes are to be pushed on the stack.
1880 unsigned NumBytes = CCInfo.getNextStackOffset();
1882 // This is a sibcall. The memory operands are available in caller's
1883 // own caller's stack.
1885 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1886 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1889 if (isTailCall && !IsSibcall) {
1890 // Lower arguments at fp - stackoffset + fpdiff.
1891 unsigned NumBytesCallerPushed =
1892 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1893 FPDiff = NumBytesCallerPushed - NumBytes;
1895 // Set the delta of movement of the returnaddr stackslot.
1896 // But only set if delta is greater than previous delta.
1897 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1898 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1902 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1904 SDValue RetAddrFrIdx;
1905 // Load return adress for tail calls.
1906 if (isTailCall && FPDiff)
1907 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1908 Is64Bit, FPDiff, dl);
1910 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1911 SmallVector<SDValue, 8> MemOpChains;
1914 // Walk the register/memloc assignments, inserting copies/loads. In the case
1915 // of tail call optimization arguments are handle later.
1916 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1917 CCValAssign &VA = ArgLocs[i];
1918 EVT RegVT = VA.getLocVT();
1919 SDValue Arg = OutVals[i];
1920 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1921 bool isByVal = Flags.isByVal();
1923 // Promote the value if needed.
1924 switch (VA.getLocInfo()) {
1925 default: llvm_unreachable("Unknown loc info!");
1926 case CCValAssign::Full: break;
1927 case CCValAssign::SExt:
1928 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1930 case CCValAssign::ZExt:
1931 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1933 case CCValAssign::AExt:
1934 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1935 // Special case: passing MMX values in XMM registers.
1936 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1937 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1938 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1940 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1942 case CCValAssign::BCvt:
1943 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1945 case CCValAssign::Indirect: {
1946 // Store the argument.
1947 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1948 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1949 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1950 MachinePointerInfo::getFixedStack(FI),
1957 if (VA.isRegLoc()) {
1958 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1959 if (isVarArg && Subtarget->isTargetWin64()) {
1960 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1961 // shadow reg if callee is a varargs function.
1962 unsigned ShadowReg = 0;
1963 switch (VA.getLocReg()) {
1964 case X86::XMM0: ShadowReg = X86::RCX; break;
1965 case X86::XMM1: ShadowReg = X86::RDX; break;
1966 case X86::XMM2: ShadowReg = X86::R8; break;
1967 case X86::XMM3: ShadowReg = X86::R9; break;
1970 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1972 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1973 assert(VA.isMemLoc());
1974 if (StackPtr.getNode() == 0)
1975 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1976 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1977 dl, DAG, VA, Flags));
1981 if (!MemOpChains.empty())
1982 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1983 &MemOpChains[0], MemOpChains.size());
1985 // Build a sequence of copy-to-reg nodes chained together with token chain
1986 // and flag operands which copy the outgoing args into registers.
1988 // Tail call byval lowering might overwrite argument registers so in case of
1989 // tail call optimization the copies to registers are lowered later.
1991 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1992 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1993 RegsToPass[i].second, InFlag);
1994 InFlag = Chain.getValue(1);
1997 if (Subtarget->isPICStyleGOT()) {
1998 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2001 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2002 DAG.getNode(X86ISD::GlobalBaseReg,
2003 DebugLoc(), getPointerTy()),
2005 InFlag = Chain.getValue(1);
2007 // If we are tail calling and generating PIC/GOT style code load the
2008 // address of the callee into ECX. The value in ecx is used as target of
2009 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2010 // for tail calls on PIC/GOT architectures. Normally we would just put the
2011 // address of GOT into ebx and then call target@PLT. But for tail calls
2012 // ebx would be restored (since ebx is callee saved) before jumping to the
2015 // Note: The actual moving to ECX is done further down.
2016 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2017 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2018 !G->getGlobal()->hasProtectedVisibility())
2019 Callee = LowerGlobalAddress(Callee, DAG);
2020 else if (isa<ExternalSymbolSDNode>(Callee))
2021 Callee = LowerExternalSymbol(Callee, DAG);
2025 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2026 // From AMD64 ABI document:
2027 // For calls that may call functions that use varargs or stdargs
2028 // (prototype-less calls or calls to functions containing ellipsis (...) in
2029 // the declaration) %al is used as hidden argument to specify the number
2030 // of SSE registers used. The contents of %al do not need to match exactly
2031 // the number of registers, but must be an ubound on the number of SSE
2032 // registers used and is in the range 0 - 8 inclusive.
2034 // Count the number of XMM registers allocated.
2035 static const unsigned XMMArgRegs[] = {
2036 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2037 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2039 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2040 assert((Subtarget->hasXMM() || !NumXMMRegs)
2041 && "SSE registers cannot be used when SSE is disabled");
2043 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2044 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2045 InFlag = Chain.getValue(1);
2049 // For tail calls lower the arguments to the 'real' stack slot.
2051 // Force all the incoming stack arguments to be loaded from the stack
2052 // before any new outgoing arguments are stored to the stack, because the
2053 // outgoing stack slots may alias the incoming argument stack slots, and
2054 // the alias isn't otherwise explicit. This is slightly more conservative
2055 // than necessary, because it means that each store effectively depends
2056 // on every argument instead of just those arguments it would clobber.
2057 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2059 SmallVector<SDValue, 8> MemOpChains2;
2062 // Do not flag preceeding copytoreg stuff together with the following stuff.
2064 if (GuaranteedTailCallOpt) {
2065 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2066 CCValAssign &VA = ArgLocs[i];
2069 assert(VA.isMemLoc());
2070 SDValue Arg = OutVals[i];
2071 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2072 // Create frame index.
2073 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2074 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2075 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2076 FIN = DAG.getFrameIndex(FI, getPointerTy());
2078 if (Flags.isByVal()) {
2079 // Copy relative to framepointer.
2080 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2081 if (StackPtr.getNode() == 0)
2082 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2084 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2086 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2090 // Store relative to framepointer.
2091 MemOpChains2.push_back(
2092 DAG.getStore(ArgChain, dl, Arg, FIN,
2093 MachinePointerInfo::getFixedStack(FI),
2099 if (!MemOpChains2.empty())
2100 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2101 &MemOpChains2[0], MemOpChains2.size());
2103 // Copy arguments to their registers.
2104 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2105 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2106 RegsToPass[i].second, InFlag);
2107 InFlag = Chain.getValue(1);
2111 // Store the return address to the appropriate stack slot.
2112 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2116 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2117 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2118 // In the 64-bit large code model, we have to make all calls
2119 // through a register, since the call instruction's 32-bit
2120 // pc-relative offset may not be large enough to hold the whole
2122 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2123 // If the callee is a GlobalAddress node (quite common, every direct call
2124 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2127 // We should use extra load for direct calls to dllimported functions in
2129 const GlobalValue *GV = G->getGlobal();
2130 if (!GV->hasDLLImportLinkage()) {
2131 unsigned char OpFlags = 0;
2133 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2134 // external symbols most go through the PLT in PIC mode. If the symbol
2135 // has hidden or protected visibility, or if it is static or local, then
2136 // we don't need to use the PLT - we can directly call it.
2137 if (Subtarget->isTargetELF() &&
2138 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2139 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2140 OpFlags = X86II::MO_PLT;
2141 } else if (Subtarget->isPICStyleStubAny() &&
2142 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2143 Subtarget->getDarwinVers() < 9) {
2144 // PC-relative references to external symbols should go through $stub,
2145 // unless we're building with the leopard linker or later, which
2146 // automatically synthesizes these stubs.
2147 OpFlags = X86II::MO_DARWIN_STUB;
2150 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2151 G->getOffset(), OpFlags);
2153 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2154 unsigned char OpFlags = 0;
2156 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2157 // external symbols should go through the PLT.
2158 if (Subtarget->isTargetELF() &&
2159 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2160 OpFlags = X86II::MO_PLT;
2161 } else if (Subtarget->isPICStyleStubAny() &&
2162 Subtarget->getDarwinVers() < 9) {
2163 // PC-relative references to external symbols should go through $stub,
2164 // unless we're building with the leopard linker or later, which
2165 // automatically synthesizes these stubs.
2166 OpFlags = X86II::MO_DARWIN_STUB;
2169 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2173 // Returns a chain & a flag for retval copy to use.
2174 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2175 SmallVector<SDValue, 8> Ops;
2177 if (!IsSibcall && isTailCall) {
2178 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2179 DAG.getIntPtrConstant(0, true), InFlag);
2180 InFlag = Chain.getValue(1);
2183 Ops.push_back(Chain);
2184 Ops.push_back(Callee);
2187 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2189 // Add argument registers to the end of the list so that they are known live
2191 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2192 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2193 RegsToPass[i].second.getValueType()));
2195 // Add an implicit use GOT pointer in EBX.
2196 if (!isTailCall && Subtarget->isPICStyleGOT())
2197 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2199 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2200 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2201 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2203 if (InFlag.getNode())
2204 Ops.push_back(InFlag);
2208 //// If this is the first return lowered for this function, add the regs
2209 //// to the liveout set for the function.
2210 // This isn't right, although it's probably harmless on x86; liveouts
2211 // should be computed from returns not tail calls. Consider a void
2212 // function making a tail call to a function returning int.
2213 return DAG.getNode(X86ISD::TC_RETURN, dl,
2214 NodeTys, &Ops[0], Ops.size());
2217 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2218 InFlag = Chain.getValue(1);
2220 // Create the CALLSEQ_END node.
2221 unsigned NumBytesForCalleeToPush;
2222 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2223 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2224 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2225 // If this is a call to a struct-return function, the callee
2226 // pops the hidden struct pointer, so we have to push it back.
2227 // This is common for Darwin/X86, Linux & Mingw32 targets.
2228 NumBytesForCalleeToPush = 4;
2230 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2232 // Returns a flag for retval copy to use.
2234 Chain = DAG.getCALLSEQ_END(Chain,
2235 DAG.getIntPtrConstant(NumBytes, true),
2236 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2239 InFlag = Chain.getValue(1);
2242 // Handle result values, copying them out of physregs into vregs that we
2244 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2245 Ins, dl, DAG, InVals);
2249 //===----------------------------------------------------------------------===//
2250 // Fast Calling Convention (tail call) implementation
2251 //===----------------------------------------------------------------------===//
2253 // Like std call, callee cleans arguments, convention except that ECX is
2254 // reserved for storing the tail called function address. Only 2 registers are
2255 // free for argument passing (inreg). Tail call optimization is performed
2257 // * tailcallopt is enabled
2258 // * caller/callee are fastcc
2259 // On X86_64 architecture with GOT-style position independent code only local
2260 // (within module) calls are supported at the moment.
2261 // To keep the stack aligned according to platform abi the function
2262 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2263 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2264 // If a tail called function callee has more arguments than the caller the
2265 // caller needs to make sure that there is room to move the RETADDR to. This is
2266 // achieved by reserving an area the size of the argument delta right after the
2267 // original REtADDR, but before the saved framepointer or the spilled registers
2268 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2280 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2281 /// for a 16 byte align requirement.
2283 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2284 SelectionDAG& DAG) const {
2285 MachineFunction &MF = DAG.getMachineFunction();
2286 const TargetMachine &TM = MF.getTarget();
2287 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2288 unsigned StackAlignment = TFI.getStackAlignment();
2289 uint64_t AlignMask = StackAlignment - 1;
2290 int64_t Offset = StackSize;
2291 uint64_t SlotSize = TD->getPointerSize();
2292 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2293 // Number smaller than 12 so just add the difference.
2294 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2296 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2297 Offset = ((~AlignMask) & Offset) + StackAlignment +
2298 (StackAlignment-SlotSize);
2303 /// MatchingStackOffset - Return true if the given stack call argument is
2304 /// already available in the same position (relatively) of the caller's
2305 /// incoming argument stack.
2307 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2308 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2309 const X86InstrInfo *TII) {
2310 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2312 if (Arg.getOpcode() == ISD::CopyFromReg) {
2313 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2314 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2316 MachineInstr *Def = MRI->getVRegDef(VR);
2319 if (!Flags.isByVal()) {
2320 if (!TII->isLoadFromStackSlot(Def, FI))
2323 unsigned Opcode = Def->getOpcode();
2324 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2325 Def->getOperand(1).isFI()) {
2326 FI = Def->getOperand(1).getIndex();
2327 Bytes = Flags.getByValSize();
2331 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2332 if (Flags.isByVal())
2333 // ByVal argument is passed in as a pointer but it's now being
2334 // dereferenced. e.g.
2335 // define @foo(%struct.X* %A) {
2336 // tail call @bar(%struct.X* byval %A)
2339 SDValue Ptr = Ld->getBasePtr();
2340 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2343 FI = FINode->getIndex();
2347 assert(FI != INT_MAX);
2348 if (!MFI->isFixedObjectIndex(FI))
2350 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2353 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2354 /// for tail call optimization. Targets which want to do tail call
2355 /// optimization should implement this function.
2357 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2358 CallingConv::ID CalleeCC,
2360 bool isCalleeStructRet,
2361 bool isCallerStructRet,
2362 const SmallVectorImpl<ISD::OutputArg> &Outs,
2363 const SmallVectorImpl<SDValue> &OutVals,
2364 const SmallVectorImpl<ISD::InputArg> &Ins,
2365 SelectionDAG& DAG) const {
2366 if (!IsTailCallConvention(CalleeCC) &&
2367 CalleeCC != CallingConv::C)
2370 // If -tailcallopt is specified, make fastcc functions tail-callable.
2371 const MachineFunction &MF = DAG.getMachineFunction();
2372 const Function *CallerF = DAG.getMachineFunction().getFunction();
2373 CallingConv::ID CallerCC = CallerF->getCallingConv();
2374 bool CCMatch = CallerCC == CalleeCC;
2376 if (GuaranteedTailCallOpt) {
2377 if (IsTailCallConvention(CalleeCC) && CCMatch)
2382 // Look for obvious safe cases to perform tail call optimization that do not
2383 // require ABI changes. This is what gcc calls sibcall.
2385 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2386 // emit a special epilogue.
2387 if (RegInfo->needsStackRealignment(MF))
2390 // Do not sibcall optimize vararg calls unless the call site is not passing
2392 if (isVarArg && !Outs.empty())
2395 // Also avoid sibcall optimization if either caller or callee uses struct
2396 // return semantics.
2397 if (isCalleeStructRet || isCallerStructRet)
2400 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2401 // Therefore if it's not used by the call it is not safe to optimize this into
2403 bool Unused = false;
2404 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2411 SmallVector<CCValAssign, 16> RVLocs;
2412 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2413 RVLocs, *DAG.getContext());
2414 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2415 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2416 CCValAssign &VA = RVLocs[i];
2417 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2422 // If the calling conventions do not match, then we'd better make sure the
2423 // results are returned in the same way as what the caller expects.
2425 SmallVector<CCValAssign, 16> RVLocs1;
2426 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2427 RVLocs1, *DAG.getContext());
2428 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2430 SmallVector<CCValAssign, 16> RVLocs2;
2431 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2432 RVLocs2, *DAG.getContext());
2433 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2435 if (RVLocs1.size() != RVLocs2.size())
2437 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2438 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2440 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2442 if (RVLocs1[i].isRegLoc()) {
2443 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2446 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2452 // If the callee takes no arguments then go on to check the results of the
2454 if (!Outs.empty()) {
2455 // Check if stack adjustment is needed. For now, do not do this if any
2456 // argument is passed on the stack.
2457 SmallVector<CCValAssign, 16> ArgLocs;
2458 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2459 ArgLocs, *DAG.getContext());
2460 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2461 if (CCInfo.getNextStackOffset()) {
2462 MachineFunction &MF = DAG.getMachineFunction();
2463 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2465 if (Subtarget->isTargetWin64())
2466 // Win64 ABI has additional complications.
2469 // Check if the arguments are already laid out in the right way as
2470 // the caller's fixed stack objects.
2471 MachineFrameInfo *MFI = MF.getFrameInfo();
2472 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2473 const X86InstrInfo *TII =
2474 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2475 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2476 CCValAssign &VA = ArgLocs[i];
2477 SDValue Arg = OutVals[i];
2478 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2479 if (VA.getLocInfo() == CCValAssign::Indirect)
2481 if (!VA.isRegLoc()) {
2482 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2489 // If the tailcall address may be in a register, then make sure it's
2490 // possible to register allocate for it. In 32-bit, the call address can
2491 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2492 // callee-saved registers are restored. These happen to be the same
2493 // registers used to pass 'inreg' arguments so watch out for those.
2494 if (!Subtarget->is64Bit() &&
2495 !isa<GlobalAddressSDNode>(Callee) &&
2496 !isa<ExternalSymbolSDNode>(Callee)) {
2497 unsigned NumInRegs = 0;
2498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2499 CCValAssign &VA = ArgLocs[i];
2502 unsigned Reg = VA.getLocReg();
2505 case X86::EAX: case X86::EDX: case X86::ECX:
2506 if (++NumInRegs == 3)
2514 // An stdcall caller is expected to clean up its arguments; the callee
2515 // isn't going to do that.
2516 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2523 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2524 return X86::createFastISel(funcInfo);
2528 //===----------------------------------------------------------------------===//
2529 // Other Lowering Hooks
2530 //===----------------------------------------------------------------------===//
2532 static bool MayFoldLoad(SDValue Op) {
2533 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2536 static bool MayFoldIntoStore(SDValue Op) {
2537 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2540 static bool isTargetShuffle(unsigned Opcode) {
2542 default: return false;
2543 case X86ISD::PSHUFD:
2544 case X86ISD::PSHUFHW:
2545 case X86ISD::PSHUFLW:
2546 case X86ISD::SHUFPD:
2547 case X86ISD::PALIGN:
2548 case X86ISD::SHUFPS:
2549 case X86ISD::MOVLHPS:
2550 case X86ISD::MOVLHPD:
2551 case X86ISD::MOVHLPS:
2552 case X86ISD::MOVLPS:
2553 case X86ISD::MOVLPD:
2554 case X86ISD::MOVSHDUP:
2555 case X86ISD::MOVSLDUP:
2556 case X86ISD::MOVDDUP:
2559 case X86ISD::UNPCKLPS:
2560 case X86ISD::UNPCKLPD:
2561 case X86ISD::PUNPCKLWD:
2562 case X86ISD::PUNPCKLBW:
2563 case X86ISD::PUNPCKLDQ:
2564 case X86ISD::PUNPCKLQDQ:
2565 case X86ISD::UNPCKHPS:
2566 case X86ISD::UNPCKHPD:
2567 case X86ISD::PUNPCKHWD:
2568 case X86ISD::PUNPCKHBW:
2569 case X86ISD::PUNPCKHDQ:
2570 case X86ISD::PUNPCKHQDQ:
2576 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2577 SDValue V1, SelectionDAG &DAG) {
2579 default: llvm_unreachable("Unknown x86 shuffle node");
2580 case X86ISD::MOVSHDUP:
2581 case X86ISD::MOVSLDUP:
2582 case X86ISD::MOVDDUP:
2583 return DAG.getNode(Opc, dl, VT, V1);
2589 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2590 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2592 default: llvm_unreachable("Unknown x86 shuffle node");
2593 case X86ISD::PSHUFD:
2594 case X86ISD::PSHUFHW:
2595 case X86ISD::PSHUFLW:
2596 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2602 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2603 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2605 default: llvm_unreachable("Unknown x86 shuffle node");
2606 case X86ISD::PALIGN:
2607 case X86ISD::SHUFPD:
2608 case X86ISD::SHUFPS:
2609 return DAG.getNode(Opc, dl, VT, V1, V2,
2610 DAG.getConstant(TargetMask, MVT::i8));
2615 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2616 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2618 default: llvm_unreachable("Unknown x86 shuffle node");
2619 case X86ISD::MOVLHPS:
2620 case X86ISD::MOVLHPD:
2621 case X86ISD::MOVHLPS:
2622 case X86ISD::MOVLPS:
2623 case X86ISD::MOVLPD:
2626 case X86ISD::UNPCKLPS:
2627 case X86ISD::UNPCKLPD:
2628 case X86ISD::PUNPCKLWD:
2629 case X86ISD::PUNPCKLBW:
2630 case X86ISD::PUNPCKLDQ:
2631 case X86ISD::PUNPCKLQDQ:
2632 case X86ISD::UNPCKHPS:
2633 case X86ISD::UNPCKHPD:
2634 case X86ISD::PUNPCKHWD:
2635 case X86ISD::PUNPCKHBW:
2636 case X86ISD::PUNPCKHDQ:
2637 case X86ISD::PUNPCKHQDQ:
2638 return DAG.getNode(Opc, dl, VT, V1, V2);
2643 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2644 MachineFunction &MF = DAG.getMachineFunction();
2645 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2646 int ReturnAddrIndex = FuncInfo->getRAIndex();
2648 if (ReturnAddrIndex == 0) {
2649 // Set up a frame object for the return address.
2650 uint64_t SlotSize = TD->getPointerSize();
2651 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2653 FuncInfo->setRAIndex(ReturnAddrIndex);
2656 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2660 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2661 bool hasSymbolicDisplacement) {
2662 // Offset should fit into 32 bit immediate field.
2663 if (!isInt<32>(Offset))
2666 // If we don't have a symbolic displacement - we don't have any extra
2668 if (!hasSymbolicDisplacement)
2671 // FIXME: Some tweaks might be needed for medium code model.
2672 if (M != CodeModel::Small && M != CodeModel::Kernel)
2675 // For small code model we assume that latest object is 16MB before end of 31
2676 // bits boundary. We may also accept pretty large negative constants knowing
2677 // that all objects are in the positive half of address space.
2678 if (M == CodeModel::Small && Offset < 16*1024*1024)
2681 // For kernel code model we know that all object resist in the negative half
2682 // of 32bits address space. We may not accept negative offsets, since they may
2683 // be just off and we may accept pretty large positive ones.
2684 if (M == CodeModel::Kernel && Offset > 0)
2690 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2691 /// specific condition code, returning the condition code and the LHS/RHS of the
2692 /// comparison to make.
2693 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2694 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2696 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2697 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2698 // X > -1 -> X == 0, jump !sign.
2699 RHS = DAG.getConstant(0, RHS.getValueType());
2700 return X86::COND_NS;
2701 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2702 // X < 0 -> X == 0, jump on sign.
2704 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2706 RHS = DAG.getConstant(0, RHS.getValueType());
2707 return X86::COND_LE;
2711 switch (SetCCOpcode) {
2712 default: llvm_unreachable("Invalid integer condition!");
2713 case ISD::SETEQ: return X86::COND_E;
2714 case ISD::SETGT: return X86::COND_G;
2715 case ISD::SETGE: return X86::COND_GE;
2716 case ISD::SETLT: return X86::COND_L;
2717 case ISD::SETLE: return X86::COND_LE;
2718 case ISD::SETNE: return X86::COND_NE;
2719 case ISD::SETULT: return X86::COND_B;
2720 case ISD::SETUGT: return X86::COND_A;
2721 case ISD::SETULE: return X86::COND_BE;
2722 case ISD::SETUGE: return X86::COND_AE;
2726 // First determine if it is required or is profitable to flip the operands.
2728 // If LHS is a foldable load, but RHS is not, flip the condition.
2729 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2730 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2731 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2732 std::swap(LHS, RHS);
2735 switch (SetCCOpcode) {
2741 std::swap(LHS, RHS);
2745 // On a floating point condition, the flags are set as follows:
2747 // 0 | 0 | 0 | X > Y
2748 // 0 | 0 | 1 | X < Y
2749 // 1 | 0 | 0 | X == Y
2750 // 1 | 1 | 1 | unordered
2751 switch (SetCCOpcode) {
2752 default: llvm_unreachable("Condcode should be pre-legalized away");
2754 case ISD::SETEQ: return X86::COND_E;
2755 case ISD::SETOLT: // flipped
2757 case ISD::SETGT: return X86::COND_A;
2758 case ISD::SETOLE: // flipped
2760 case ISD::SETGE: return X86::COND_AE;
2761 case ISD::SETUGT: // flipped
2763 case ISD::SETLT: return X86::COND_B;
2764 case ISD::SETUGE: // flipped
2766 case ISD::SETLE: return X86::COND_BE;
2768 case ISD::SETNE: return X86::COND_NE;
2769 case ISD::SETUO: return X86::COND_P;
2770 case ISD::SETO: return X86::COND_NP;
2772 case ISD::SETUNE: return X86::COND_INVALID;
2776 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2777 /// code. Current x86 isa includes the following FP cmov instructions:
2778 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2779 static bool hasFPCMov(unsigned X86CC) {
2795 /// isFPImmLegal - Returns true if the target can instruction select the
2796 /// specified FP immediate natively. If false, the legalizer will
2797 /// materialize the FP immediate as a load from a constant pool.
2798 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2799 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2800 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2806 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2807 /// the specified range (L, H].
2808 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2809 return (Val < 0) || (Val >= Low && Val < Hi);
2812 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2813 /// specified value.
2814 static bool isUndefOrEqual(int Val, int CmpVal) {
2815 if (Val < 0 || Val == CmpVal)
2820 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2821 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2822 /// the second operand.
2823 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2824 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2825 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2826 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2827 return (Mask[0] < 2 && Mask[1] < 2);
2831 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2832 SmallVector<int, 8> M;
2834 return ::isPSHUFDMask(M, N->getValueType(0));
2837 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2838 /// is suitable for input to PSHUFHW.
2839 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2840 if (VT != MVT::v8i16)
2843 // Lower quadword copied in order or undef.
2844 for (int i = 0; i != 4; ++i)
2845 if (Mask[i] >= 0 && Mask[i] != i)
2848 // Upper quadword shuffled.
2849 for (int i = 4; i != 8; ++i)
2850 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2856 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2857 SmallVector<int, 8> M;
2859 return ::isPSHUFHWMask(M, N->getValueType(0));
2862 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2863 /// is suitable for input to PSHUFLW.
2864 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2865 if (VT != MVT::v8i16)
2868 // Upper quadword copied in order.
2869 for (int i = 4; i != 8; ++i)
2870 if (Mask[i] >= 0 && Mask[i] != i)
2873 // Lower quadword shuffled.
2874 for (int i = 0; i != 4; ++i)
2881 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2882 SmallVector<int, 8> M;
2884 return ::isPSHUFLWMask(M, N->getValueType(0));
2887 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2888 /// is suitable for input to PALIGNR.
2889 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2891 int i, e = VT.getVectorNumElements();
2893 // Do not handle v2i64 / v2f64 shuffles with palignr.
2894 if (e < 4 || !hasSSSE3)
2897 for (i = 0; i != e; ++i)
2901 // All undef, not a palignr.
2905 // Determine if it's ok to perform a palignr with only the LHS, since we
2906 // don't have access to the actual shuffle elements to see if RHS is undef.
2907 bool Unary = Mask[i] < (int)e;
2908 bool NeedsUnary = false;
2910 int s = Mask[i] - i;
2912 // Check the rest of the elements to see if they are consecutive.
2913 for (++i; i != e; ++i) {
2918 Unary = Unary && (m < (int)e);
2919 NeedsUnary = NeedsUnary || (m < s);
2921 if (NeedsUnary && !Unary)
2923 if (Unary && m != ((s+i) & (e-1)))
2925 if (!Unary && m != (s+i))
2931 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2932 SmallVector<int, 8> M;
2934 return ::isPALIGNRMask(M, N->getValueType(0), true);
2937 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2938 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2939 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2940 int NumElems = VT.getVectorNumElements();
2941 if (NumElems != 2 && NumElems != 4)
2944 int Half = NumElems / 2;
2945 for (int i = 0; i < Half; ++i)
2946 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2948 for (int i = Half; i < NumElems; ++i)
2949 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2955 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2956 SmallVector<int, 8> M;
2958 return ::isSHUFPMask(M, N->getValueType(0));
2961 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2962 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2963 /// half elements to come from vector 1 (which would equal the dest.) and
2964 /// the upper half to come from vector 2.
2965 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2966 int NumElems = VT.getVectorNumElements();
2968 if (NumElems != 2 && NumElems != 4)
2971 int Half = NumElems / 2;
2972 for (int i = 0; i < Half; ++i)
2973 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2975 for (int i = Half; i < NumElems; ++i)
2976 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2981 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2982 SmallVector<int, 8> M;
2984 return isCommutedSHUFPMask(M, N->getValueType(0));
2987 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2988 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2989 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2990 if (N->getValueType(0).getVectorNumElements() != 4)
2993 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2994 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2995 isUndefOrEqual(N->getMaskElt(1), 7) &&
2996 isUndefOrEqual(N->getMaskElt(2), 2) &&
2997 isUndefOrEqual(N->getMaskElt(3), 3);
3000 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3001 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3003 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3004 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3009 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3010 isUndefOrEqual(N->getMaskElt(1), 3) &&
3011 isUndefOrEqual(N->getMaskElt(2), 2) &&
3012 isUndefOrEqual(N->getMaskElt(3), 3);
3015 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3016 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3017 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3018 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3020 if (NumElems != 2 && NumElems != 4)
3023 for (unsigned i = 0; i < NumElems/2; ++i)
3024 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3027 for (unsigned i = NumElems/2; i < NumElems; ++i)
3028 if (!isUndefOrEqual(N->getMaskElt(i), i))
3034 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3036 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3037 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3039 if (NumElems != 2 && NumElems != 4)
3042 for (unsigned i = 0; i < NumElems/2; ++i)
3043 if (!isUndefOrEqual(N->getMaskElt(i), i))
3046 for (unsigned i = 0; i < NumElems/2; ++i)
3047 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3053 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3054 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3055 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3056 bool V2IsSplat = false) {
3057 int NumElts = VT.getVectorNumElements();
3058 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3061 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3063 int BitI1 = Mask[i+1];
3064 if (!isUndefOrEqual(BitI, j))
3067 if (!isUndefOrEqual(BitI1, NumElts))
3070 if (!isUndefOrEqual(BitI1, j + NumElts))
3077 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3078 SmallVector<int, 8> M;
3080 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3085 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3086 bool V2IsSplat = false) {
3087 int NumElts = VT.getVectorNumElements();
3088 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3091 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3093 int BitI1 = Mask[i+1];
3094 if (!isUndefOrEqual(BitI, j + NumElts/2))
3097 if (isUndefOrEqual(BitI1, NumElts))
3100 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3107 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3108 SmallVector<int, 8> M;
3110 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3113 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3114 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3116 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3117 int NumElems = VT.getVectorNumElements();
3118 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3121 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3123 int BitI1 = Mask[i+1];
3124 if (!isUndefOrEqual(BitI, j))
3126 if (!isUndefOrEqual(BitI1, j))
3132 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3133 SmallVector<int, 8> M;
3135 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3138 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3139 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3141 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3142 int NumElems = VT.getVectorNumElements();
3143 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3146 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3148 int BitI1 = Mask[i+1];
3149 if (!isUndefOrEqual(BitI, j))
3151 if (!isUndefOrEqual(BitI1, j))
3157 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3158 SmallVector<int, 8> M;
3160 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3163 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3164 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3165 /// MOVSD, and MOVD, i.e. setting the lowest element.
3166 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3167 if (VT.getVectorElementType().getSizeInBits() < 32)
3170 int NumElts = VT.getVectorNumElements();
3172 if (!isUndefOrEqual(Mask[0], NumElts))
3175 for (int i = 1; i < NumElts; ++i)
3176 if (!isUndefOrEqual(Mask[i], i))
3182 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3183 SmallVector<int, 8> M;
3185 return ::isMOVLMask(M, N->getValueType(0));
3188 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3189 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3190 /// element of vector 2 and the other elements to come from vector 1 in order.
3191 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3192 bool V2IsSplat = false, bool V2IsUndef = false) {
3193 int NumOps = VT.getVectorNumElements();
3194 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3197 if (!isUndefOrEqual(Mask[0], 0))
3200 for (int i = 1; i < NumOps; ++i)
3201 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3202 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3203 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3209 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3210 bool V2IsUndef = false) {
3211 SmallVector<int, 8> M;
3213 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3216 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3217 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3218 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3219 if (N->getValueType(0).getVectorNumElements() != 4)
3222 // Expect 1, 1, 3, 3
3223 for (unsigned i = 0; i < 2; ++i) {
3224 int Elt = N->getMaskElt(i);
3225 if (Elt >= 0 && Elt != 1)
3230 for (unsigned i = 2; i < 4; ++i) {
3231 int Elt = N->getMaskElt(i);
3232 if (Elt >= 0 && Elt != 3)
3237 // Don't use movshdup if it can be done with a shufps.
3238 // FIXME: verify that matching u, u, 3, 3 is what we want.
3242 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3243 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3244 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3245 if (N->getValueType(0).getVectorNumElements() != 4)
3248 // Expect 0, 0, 2, 2
3249 for (unsigned i = 0; i < 2; ++i)
3250 if (N->getMaskElt(i) > 0)
3254 for (unsigned i = 2; i < 4; ++i) {
3255 int Elt = N->getMaskElt(i);
3256 if (Elt >= 0 && Elt != 2)
3261 // Don't use movsldup if it can be done with a shufps.
3265 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3266 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3267 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3268 int e = N->getValueType(0).getVectorNumElements() / 2;
3270 for (int i = 0; i < e; ++i)
3271 if (!isUndefOrEqual(N->getMaskElt(i), i))
3273 for (int i = 0; i < e; ++i)
3274 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3279 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3280 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3281 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3282 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3283 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3285 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3287 for (int i = 0; i < NumOperands; ++i) {
3288 int Val = SVOp->getMaskElt(NumOperands-i-1);
3289 if (Val < 0) Val = 0;
3290 if (Val >= NumOperands) Val -= NumOperands;
3292 if (i != NumOperands - 1)
3298 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3299 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3300 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3303 // 8 nodes, but we only care about the last 4.
3304 for (unsigned i = 7; i >= 4; --i) {
3305 int Val = SVOp->getMaskElt(i);
3314 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3315 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3316 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3319 // 8 nodes, but we only care about the first 4.
3320 for (int i = 3; i >= 0; --i) {
3321 int Val = SVOp->getMaskElt(i);
3330 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3332 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3333 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334 EVT VVT = N->getValueType(0);
3335 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3339 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3340 Val = SVOp->getMaskElt(i);
3344 return (Val - i) * EltSize;
3347 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3349 bool X86::isZeroNode(SDValue Elt) {
3350 return ((isa<ConstantSDNode>(Elt) &&
3351 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3352 (isa<ConstantFPSDNode>(Elt) &&
3353 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3356 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3357 /// their permute mask.
3358 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3359 SelectionDAG &DAG) {
3360 EVT VT = SVOp->getValueType(0);
3361 unsigned NumElems = VT.getVectorNumElements();
3362 SmallVector<int, 8> MaskVec;
3364 for (unsigned i = 0; i != NumElems; ++i) {
3365 int idx = SVOp->getMaskElt(i);
3367 MaskVec.push_back(idx);
3368 else if (idx < (int)NumElems)
3369 MaskVec.push_back(idx + NumElems);
3371 MaskVec.push_back(idx - NumElems);
3373 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3374 SVOp->getOperand(0), &MaskVec[0]);
3377 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3378 /// the two vector operands have swapped position.
3379 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3380 unsigned NumElems = VT.getVectorNumElements();
3381 for (unsigned i = 0; i != NumElems; ++i) {
3385 else if (idx < (int)NumElems)
3386 Mask[i] = idx + NumElems;
3388 Mask[i] = idx - NumElems;
3392 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3393 /// match movhlps. The lower half elements should come from upper half of
3394 /// V1 (and in order), and the upper half elements should come from the upper
3395 /// half of V2 (and in order).
3396 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3397 if (Op->getValueType(0).getVectorNumElements() != 4)
3399 for (unsigned i = 0, e = 2; i != e; ++i)
3400 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3402 for (unsigned i = 2; i != 4; ++i)
3403 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3408 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3409 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3411 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3412 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3414 N = N->getOperand(0).getNode();
3415 if (!ISD::isNON_EXTLoad(N))
3418 *LD = cast<LoadSDNode>(N);
3422 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3423 /// match movlp{s|d}. The lower half elements should come from lower half of
3424 /// V1 (and in order), and the upper half elements should come from the upper
3425 /// half of V2 (and in order). And since V1 will become the source of the
3426 /// MOVLP, it must be either a vector load or a scalar load to vector.
3427 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3428 ShuffleVectorSDNode *Op) {
3429 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3431 // Is V2 is a vector load, don't do this transformation. We will try to use
3432 // load folding shufps op.
3433 if (ISD::isNON_EXTLoad(V2))
3436 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3438 if (NumElems != 2 && NumElems != 4)
3440 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3441 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3443 for (unsigned i = NumElems/2; i != NumElems; ++i)
3444 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3449 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3451 static bool isSplatVector(SDNode *N) {
3452 if (N->getOpcode() != ISD::BUILD_VECTOR)
3455 SDValue SplatValue = N->getOperand(0);
3456 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3457 if (N->getOperand(i) != SplatValue)
3462 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3463 /// to an zero vector.
3464 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3465 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3466 SDValue V1 = N->getOperand(0);
3467 SDValue V2 = N->getOperand(1);
3468 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3469 for (unsigned i = 0; i != NumElems; ++i) {
3470 int Idx = N->getMaskElt(i);
3471 if (Idx >= (int)NumElems) {
3472 unsigned Opc = V2.getOpcode();
3473 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3475 if (Opc != ISD::BUILD_VECTOR ||
3476 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3478 } else if (Idx >= 0) {
3479 unsigned Opc = V1.getOpcode();
3480 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3482 if (Opc != ISD::BUILD_VECTOR ||
3483 !X86::isZeroNode(V1.getOperand(Idx)))
3490 /// getZeroVector - Returns a vector of specified type with all zero elements.
3492 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3494 assert(VT.isVector() && "Expected a vector type");
3496 // Always build SSE zero vectors as <4 x i32> bitcasted
3497 // to their dest type. This ensures they get CSE'd.
3499 if (VT.getSizeInBits() == 128) { // SSE
3500 if (HasSSE2) { // SSE2
3501 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3502 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3504 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3505 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3507 } else if (VT.getSizeInBits() == 256) { // AVX
3508 // 256-bit logic and arithmetic instructions in AVX are
3509 // all floating-point, no support for integer ops. Default
3510 // to emitting fp zeroed vectors then.
3511 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3512 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3513 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3515 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3518 /// getOnesVector - Returns a vector of specified type with all bits set.
3520 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3521 assert(VT.isVector() && "Expected a vector type");
3523 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3524 // type. This ensures they get CSE'd.
3525 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3527 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3528 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3532 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3533 /// that point to V2 points to its first element.
3534 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3535 EVT VT = SVOp->getValueType(0);
3536 unsigned NumElems = VT.getVectorNumElements();
3538 bool Changed = false;
3539 SmallVector<int, 8> MaskVec;
3540 SVOp->getMask(MaskVec);
3542 for (unsigned i = 0; i != NumElems; ++i) {
3543 if (MaskVec[i] > (int)NumElems) {
3544 MaskVec[i] = NumElems;
3549 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3550 SVOp->getOperand(1), &MaskVec[0]);
3551 return SDValue(SVOp, 0);
3554 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3555 /// operation of specified width.
3556 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3558 unsigned NumElems = VT.getVectorNumElements();
3559 SmallVector<int, 8> Mask;
3560 Mask.push_back(NumElems);
3561 for (unsigned i = 1; i != NumElems; ++i)
3563 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3566 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3567 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3569 unsigned NumElems = VT.getVectorNumElements();
3570 SmallVector<int, 8> Mask;
3571 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3573 Mask.push_back(i + NumElems);
3575 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3578 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3579 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3581 unsigned NumElems = VT.getVectorNumElements();
3582 unsigned Half = NumElems/2;
3583 SmallVector<int, 8> Mask;
3584 for (unsigned i = 0; i != Half; ++i) {
3585 Mask.push_back(i + Half);
3586 Mask.push_back(i + NumElems + Half);
3588 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3591 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3592 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3593 EVT PVT = MVT::v4f32;
3594 EVT VT = SV->getValueType(0);
3595 DebugLoc dl = SV->getDebugLoc();
3596 SDValue V1 = SV->getOperand(0);
3597 int NumElems = VT.getVectorNumElements();
3598 int EltNo = SV->getSplatIndex();
3600 // unpack elements to the correct location
3601 while (NumElems > 4) {
3602 if (EltNo < NumElems/2) {
3603 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3605 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3606 EltNo -= NumElems/2;
3611 // Perform the splat.
3612 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3613 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3614 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3615 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3618 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3619 /// vector of zero or undef vector. This produces a shuffle where the low
3620 /// element of V2 is swizzled into the zero/undef vector, landing at element
3621 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3622 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3623 bool isZero, bool HasSSE2,
3624 SelectionDAG &DAG) {
3625 EVT VT = V2.getValueType();
3627 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3628 unsigned NumElems = VT.getVectorNumElements();
3629 SmallVector<int, 16> MaskVec;
3630 for (unsigned i = 0; i != NumElems; ++i)
3631 // If this is the insertion idx, put the low elt of V2 here.
3632 MaskVec.push_back(i == Idx ? NumElems : i);
3633 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3636 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3637 /// element of the result of the vector shuffle.
3638 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3641 return SDValue(); // Limit search depth.
3643 SDValue V = SDValue(N, 0);
3644 EVT VT = V.getValueType();
3645 unsigned Opcode = V.getOpcode();
3647 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3648 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3649 Index = SV->getMaskElt(Index);
3652 return DAG.getUNDEF(VT.getVectorElementType());
3654 int NumElems = VT.getVectorNumElements();
3655 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3656 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3659 // Recurse into target specific vector shuffles to find scalars.
3660 if (isTargetShuffle(Opcode)) {
3661 int NumElems = VT.getVectorNumElements();
3662 SmallVector<unsigned, 16> ShuffleMask;
3666 case X86ISD::SHUFPS:
3667 case X86ISD::SHUFPD:
3668 ImmN = N->getOperand(N->getNumOperands()-1);
3669 DecodeSHUFPSMask(NumElems,
3670 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3673 case X86ISD::PUNPCKHBW:
3674 case X86ISD::PUNPCKHWD:
3675 case X86ISD::PUNPCKHDQ:
3676 case X86ISD::PUNPCKHQDQ:
3677 DecodePUNPCKHMask(NumElems, ShuffleMask);
3679 case X86ISD::UNPCKHPS:
3680 case X86ISD::UNPCKHPD:
3681 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3683 case X86ISD::PUNPCKLBW:
3684 case X86ISD::PUNPCKLWD:
3685 case X86ISD::PUNPCKLDQ:
3686 case X86ISD::PUNPCKLQDQ:
3687 DecodePUNPCKLMask(NumElems, ShuffleMask);
3689 case X86ISD::UNPCKLPS:
3690 case X86ISD::UNPCKLPD:
3691 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3693 case X86ISD::MOVHLPS:
3694 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3696 case X86ISD::MOVLHPS:
3697 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3699 case X86ISD::PSHUFD:
3700 ImmN = N->getOperand(N->getNumOperands()-1);
3701 DecodePSHUFMask(NumElems,
3702 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3705 case X86ISD::PSHUFHW:
3706 ImmN = N->getOperand(N->getNumOperands()-1);
3707 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3710 case X86ISD::PSHUFLW:
3711 ImmN = N->getOperand(N->getNumOperands()-1);
3712 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3716 case X86ISD::MOVSD: {
3717 // The index 0 always comes from the first element of the second source,
3718 // this is why MOVSS and MOVSD are used in the first place. The other
3719 // elements come from the other positions of the first source vector.
3720 unsigned OpNum = (Index == 0) ? 1 : 0;
3721 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3725 assert("not implemented for target shuffle node");
3729 Index = ShuffleMask[Index];
3731 return DAG.getUNDEF(VT.getVectorElementType());
3733 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3734 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3738 // Actual nodes that may contain scalar elements
3739 if (Opcode == ISD::BITCAST) {
3740 V = V.getOperand(0);
3741 EVT SrcVT = V.getValueType();
3742 unsigned NumElems = VT.getVectorNumElements();
3744 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3748 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3749 return (Index == 0) ? V.getOperand(0)
3750 : DAG.getUNDEF(VT.getVectorElementType());
3752 if (V.getOpcode() == ISD::BUILD_VECTOR)
3753 return V.getOperand(Index);
3758 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3759 /// shuffle operation which come from a consecutively from a zero. The
3760 /// search can start in two diferent directions, from left or right.
3762 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3763 bool ZerosFromLeft, SelectionDAG &DAG) {
3766 while (i < NumElems) {
3767 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3768 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3769 if (!(Elt.getNode() &&
3770 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3778 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3779 /// MaskE correspond consecutively to elements from one of the vector operands,
3780 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3782 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3783 int OpIdx, int NumElems, unsigned &OpNum) {
3784 bool SeenV1 = false;
3785 bool SeenV2 = false;
3787 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3788 int Idx = SVOp->getMaskElt(i);
3789 // Ignore undef indicies
3798 // Only accept consecutive elements from the same vector
3799 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3803 OpNum = SeenV1 ? 0 : 1;
3807 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3808 /// logical left shift of a vector.
3809 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3810 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3811 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3812 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3813 false /* check zeros from right */, DAG);
3819 // Considering the elements in the mask that are not consecutive zeros,
3820 // check if they consecutively come from only one of the source vectors.
3822 // V1 = {X, A, B, C} 0
3824 // vector_shuffle V1, V2 <1, 2, 3, X>
3826 if (!isShuffleMaskConsecutive(SVOp,
3827 0, // Mask Start Index
3828 NumElems-NumZeros-1, // Mask End Index
3829 NumZeros, // Where to start looking in the src vector
3830 NumElems, // Number of elements in vector
3831 OpSrc)) // Which source operand ?
3836 ShVal = SVOp->getOperand(OpSrc);
3840 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3841 /// logical left shift of a vector.
3842 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3843 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3844 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3845 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3846 true /* check zeros from left */, DAG);
3852 // Considering the elements in the mask that are not consecutive zeros,
3853 // check if they consecutively come from only one of the source vectors.
3855 // 0 { A, B, X, X } = V2
3857 // vector_shuffle V1, V2 <X, X, 4, 5>
3859 if (!isShuffleMaskConsecutive(SVOp,
3860 NumZeros, // Mask Start Index
3861 NumElems-1, // Mask End Index
3862 0, // Where to start looking in the src vector
3863 NumElems, // Number of elements in vector
3864 OpSrc)) // Which source operand ?
3869 ShVal = SVOp->getOperand(OpSrc);
3873 /// isVectorShift - Returns true if the shuffle can be implemented as a
3874 /// logical left or right shift of a vector.
3875 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3876 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3877 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3878 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3884 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3886 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3887 unsigned NumNonZero, unsigned NumZero,
3889 const TargetLowering &TLI) {
3893 DebugLoc dl = Op.getDebugLoc();
3896 for (unsigned i = 0; i < 16; ++i) {
3897 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3898 if (ThisIsNonZero && First) {
3900 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3902 V = DAG.getUNDEF(MVT::v8i16);
3907 SDValue ThisElt(0, 0), LastElt(0, 0);
3908 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3909 if (LastIsNonZero) {
3910 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3911 MVT::i16, Op.getOperand(i-1));
3913 if (ThisIsNonZero) {
3914 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3915 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3916 ThisElt, DAG.getConstant(8, MVT::i8));
3918 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3922 if (ThisElt.getNode())
3923 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3924 DAG.getIntPtrConstant(i/2));
3928 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3931 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3933 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3934 unsigned NumNonZero, unsigned NumZero,
3936 const TargetLowering &TLI) {
3940 DebugLoc dl = Op.getDebugLoc();
3943 for (unsigned i = 0; i < 8; ++i) {
3944 bool isNonZero = (NonZeros & (1 << i)) != 0;
3948 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3950 V = DAG.getUNDEF(MVT::v8i16);
3953 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3954 MVT::v8i16, V, Op.getOperand(i),
3955 DAG.getIntPtrConstant(i));
3962 /// getVShift - Return a vector logical shift node.
3964 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3965 unsigned NumBits, SelectionDAG &DAG,
3966 const TargetLowering &TLI, DebugLoc dl) {
3967 EVT ShVT = MVT::v2i64;
3968 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3969 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3970 return DAG.getNode(ISD::BITCAST, dl, VT,
3971 DAG.getNode(Opc, dl, ShVT, SrcOp,
3972 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3976 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3977 SelectionDAG &DAG) const {
3979 // Check if the scalar load can be widened into a vector load. And if
3980 // the address is "base + cst" see if the cst can be "absorbed" into
3981 // the shuffle mask.
3982 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3983 SDValue Ptr = LD->getBasePtr();
3984 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3986 EVT PVT = LD->getValueType(0);
3987 if (PVT != MVT::i32 && PVT != MVT::f32)
3992 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3993 FI = FINode->getIndex();
3995 } else if (Ptr.getOpcode() == ISD::ADD &&
3996 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3997 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3998 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3999 Offset = Ptr.getConstantOperandVal(1);
4000 Ptr = Ptr.getOperand(0);
4005 SDValue Chain = LD->getChain();
4006 // Make sure the stack object alignment is at least 16.
4007 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4008 if (DAG.InferPtrAlignment(Ptr) < 16) {
4009 if (MFI->isFixedObjectIndex(FI)) {
4010 // Can't change the alignment. FIXME: It's possible to compute
4011 // the exact stack offset and reference FI + adjust offset instead.
4012 // If someone *really* cares about this. That's the way to implement it.
4015 MFI->setObjectAlignment(FI, 16);
4019 // (Offset % 16) must be multiple of 4. Then address is then
4020 // Ptr + (Offset & ~15).
4023 if ((Offset % 16) & 3)
4025 int64_t StartOffset = Offset & ~15;
4027 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4028 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4030 int EltNo = (Offset - StartOffset) >> 2;
4031 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4032 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4033 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4034 LD->getPointerInfo().getWithOffset(StartOffset),
4036 // Canonicalize it to a v4i32 shuffle.
4037 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4038 return DAG.getNode(ISD::BITCAST, dl, VT,
4039 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4040 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4046 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4047 /// vector of type 'VT', see if the elements can be replaced by a single large
4048 /// load which has the same value as a build_vector whose operands are 'elts'.
4050 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4052 /// FIXME: we'd also like to handle the case where the last elements are zero
4053 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4054 /// There's even a handy isZeroNode for that purpose.
4055 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4056 DebugLoc &DL, SelectionDAG &DAG) {
4057 EVT EltVT = VT.getVectorElementType();
4058 unsigned NumElems = Elts.size();
4060 LoadSDNode *LDBase = NULL;
4061 unsigned LastLoadedElt = -1U;
4063 // For each element in the initializer, see if we've found a load or an undef.
4064 // If we don't find an initial load element, or later load elements are
4065 // non-consecutive, bail out.
4066 for (unsigned i = 0; i < NumElems; ++i) {
4067 SDValue Elt = Elts[i];
4069 if (!Elt.getNode() ||
4070 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4073 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4075 LDBase = cast<LoadSDNode>(Elt.getNode());
4079 if (Elt.getOpcode() == ISD::UNDEF)
4082 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4083 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4088 // If we have found an entire vector of loads and undefs, then return a large
4089 // load of the entire vector width starting at the base pointer. If we found
4090 // consecutive loads for the low half, generate a vzext_load node.
4091 if (LastLoadedElt == NumElems - 1) {
4092 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4093 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4094 LDBase->getPointerInfo(),
4095 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4096 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4097 LDBase->getPointerInfo(),
4098 LDBase->isVolatile(), LDBase->isNonTemporal(),
4099 LDBase->getAlignment());
4100 } else if (NumElems == 4 && LastLoadedElt == 1) {
4101 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4102 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4103 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4105 LDBase->getMemOperand());
4106 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4112 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4113 DebugLoc dl = Op.getDebugLoc();
4114 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4115 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4116 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4117 // is present, so AllOnes is ignored.
4118 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4119 (Op.getValueType().getSizeInBits() != 256 &&
4120 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4121 // Canonicalize this to <4 x i32> (SSE) to
4122 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4123 // eliminated on x86-32 hosts.
4124 if (Op.getValueType() == MVT::v4i32)
4127 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4128 return getOnesVector(Op.getValueType(), DAG, dl);
4129 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4132 EVT VT = Op.getValueType();
4133 EVT ExtVT = VT.getVectorElementType();
4134 unsigned EVTBits = ExtVT.getSizeInBits();
4136 unsigned NumElems = Op.getNumOperands();
4137 unsigned NumZero = 0;
4138 unsigned NumNonZero = 0;
4139 unsigned NonZeros = 0;
4140 bool IsAllConstants = true;
4141 SmallSet<SDValue, 8> Values;
4142 for (unsigned i = 0; i < NumElems; ++i) {
4143 SDValue Elt = Op.getOperand(i);
4144 if (Elt.getOpcode() == ISD::UNDEF)
4147 if (Elt.getOpcode() != ISD::Constant &&
4148 Elt.getOpcode() != ISD::ConstantFP)
4149 IsAllConstants = false;
4150 if (X86::isZeroNode(Elt))
4153 NonZeros |= (1 << i);
4158 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4159 if (NumNonZero == 0)
4160 return DAG.getUNDEF(VT);
4162 // Special case for single non-zero, non-undef, element.
4163 if (NumNonZero == 1) {
4164 unsigned Idx = CountTrailingZeros_32(NonZeros);
4165 SDValue Item = Op.getOperand(Idx);
4167 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4168 // the value are obviously zero, truncate the value to i32 and do the
4169 // insertion that way. Only do this if the value is non-constant or if the
4170 // value is a constant being inserted into element 0. It is cheaper to do
4171 // a constant pool load than it is to do a movd + shuffle.
4172 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4173 (!IsAllConstants || Idx == 0)) {
4174 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4176 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4177 EVT VecVT = MVT::v4i32;
4178 unsigned VecElts = 4;
4180 // Truncate the value (which may itself be a constant) to i32, and
4181 // convert it to a vector with movd (S2V+shuffle to zero extend).
4182 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4183 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4184 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4185 Subtarget->hasSSE2(), DAG);
4187 // Now we have our 32-bit value zero extended in the low element of
4188 // a vector. If Idx != 0, swizzle it into place.
4190 SmallVector<int, 4> Mask;
4191 Mask.push_back(Idx);
4192 for (unsigned i = 1; i != VecElts; ++i)
4194 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4195 DAG.getUNDEF(Item.getValueType()),
4198 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4202 // If we have a constant or non-constant insertion into the low element of
4203 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4204 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4205 // depending on what the source datatype is.
4208 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4209 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4210 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4211 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4212 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4213 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4215 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4216 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4217 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4218 EVT MiddleVT = MVT::v4i32;
4219 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4220 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4221 Subtarget->hasSSE2(), DAG);
4222 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4226 // Is it a vector logical left shift?
4227 if (NumElems == 2 && Idx == 1 &&
4228 X86::isZeroNode(Op.getOperand(0)) &&
4229 !X86::isZeroNode(Op.getOperand(1))) {
4230 unsigned NumBits = VT.getSizeInBits();
4231 return getVShift(true, VT,
4232 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4233 VT, Op.getOperand(1)),
4234 NumBits/2, DAG, *this, dl);
4237 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4240 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4241 // is a non-constant being inserted into an element other than the low one,
4242 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4243 // movd/movss) to move this into the low element, then shuffle it into
4245 if (EVTBits == 32) {
4246 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4248 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4249 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4250 Subtarget->hasSSE2(), DAG);
4251 SmallVector<int, 8> MaskVec;
4252 for (unsigned i = 0; i < NumElems; i++)
4253 MaskVec.push_back(i == Idx ? 0 : 1);
4254 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4258 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4259 if (Values.size() == 1) {
4260 if (EVTBits == 32) {
4261 // Instead of a shuffle like this:
4262 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4263 // Check if it's possible to issue this instead.
4264 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4265 unsigned Idx = CountTrailingZeros_32(NonZeros);
4266 SDValue Item = Op.getOperand(Idx);
4267 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4268 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4273 // A vector full of immediates; various special cases are already
4274 // handled, so this is best done with a single constant-pool load.
4278 // Let legalizer expand 2-wide build_vectors.
4279 if (EVTBits == 64) {
4280 if (NumNonZero == 1) {
4281 // One half is zero or undef.
4282 unsigned Idx = CountTrailingZeros_32(NonZeros);
4283 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4284 Op.getOperand(Idx));
4285 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4286 Subtarget->hasSSE2(), DAG);
4291 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4292 if (EVTBits == 8 && NumElems == 16) {
4293 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4295 if (V.getNode()) return V;
4298 if (EVTBits == 16 && NumElems == 8) {
4299 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4301 if (V.getNode()) return V;
4304 // If element VT is == 32 bits, turn it into a number of shuffles.
4305 SmallVector<SDValue, 8> V;
4307 if (NumElems == 4 && NumZero > 0) {
4308 for (unsigned i = 0; i < 4; ++i) {
4309 bool isZero = !(NonZeros & (1 << i));
4311 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4313 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4316 for (unsigned i = 0; i < 2; ++i) {
4317 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4320 V[i] = V[i*2]; // Must be a zero vector.
4323 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4326 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4329 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4334 SmallVector<int, 8> MaskVec;
4335 bool Reverse = (NonZeros & 0x3) == 2;
4336 for (unsigned i = 0; i < 2; ++i)
4337 MaskVec.push_back(Reverse ? 1-i : i);
4338 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4339 for (unsigned i = 0; i < 2; ++i)
4340 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4341 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4344 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4345 // Check for a build vector of consecutive loads.
4346 for (unsigned i = 0; i < NumElems; ++i)
4347 V[i] = Op.getOperand(i);
4349 // Check for elements which are consecutive loads.
4350 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4354 // For SSE 4.1, use insertps to put the high elements into the low element.
4355 if (getSubtarget()->hasSSE41()) {
4357 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4358 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4360 Result = DAG.getUNDEF(VT);
4362 for (unsigned i = 1; i < NumElems; ++i) {
4363 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4364 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4365 Op.getOperand(i), DAG.getIntPtrConstant(i));
4370 // Otherwise, expand into a number of unpckl*, start by extending each of
4371 // our (non-undef) elements to the full vector width with the element in the
4372 // bottom slot of the vector (which generates no code for SSE).
4373 for (unsigned i = 0; i < NumElems; ++i) {
4374 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4375 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4377 V[i] = DAG.getUNDEF(VT);
4380 // Next, we iteratively mix elements, e.g. for v4f32:
4381 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4382 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4383 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4384 unsigned EltStride = NumElems >> 1;
4385 while (EltStride != 0) {
4386 for (unsigned i = 0; i < EltStride; ++i) {
4387 // If V[i+EltStride] is undef and this is the first round of mixing,
4388 // then it is safe to just drop this shuffle: V[i] is already in the
4389 // right place, the one element (since it's the first round) being
4390 // inserted as undef can be dropped. This isn't safe for successive
4391 // rounds because they will permute elements within both vectors.
4392 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4393 EltStride == NumElems/2)
4396 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4406 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4407 // We support concatenate two MMX registers and place them in a MMX
4408 // register. This is better than doing a stack convert.
4409 DebugLoc dl = Op.getDebugLoc();
4410 EVT ResVT = Op.getValueType();
4411 assert(Op.getNumOperands() == 2);
4412 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4413 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4415 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4416 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4417 InVec = Op.getOperand(1);
4418 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4419 unsigned NumElts = ResVT.getVectorNumElements();
4420 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4421 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4422 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4424 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4425 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4426 Mask[0] = 0; Mask[1] = 2;
4427 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4429 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4432 // v8i16 shuffles - Prefer shuffles in the following order:
4433 // 1. [all] pshuflw, pshufhw, optional move
4434 // 2. [ssse3] 1 x pshufb
4435 // 3. [ssse3] 2 x pshufb + 1 x por
4436 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4438 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4439 SelectionDAG &DAG) const {
4440 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4441 SDValue V1 = SVOp->getOperand(0);
4442 SDValue V2 = SVOp->getOperand(1);
4443 DebugLoc dl = SVOp->getDebugLoc();
4444 SmallVector<int, 8> MaskVals;
4446 // Determine if more than 1 of the words in each of the low and high quadwords
4447 // of the result come from the same quadword of one of the two inputs. Undef
4448 // mask values count as coming from any quadword, for better codegen.
4449 SmallVector<unsigned, 4> LoQuad(4);
4450 SmallVector<unsigned, 4> HiQuad(4);
4451 BitVector InputQuads(4);
4452 for (unsigned i = 0; i < 8; ++i) {
4453 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4454 int EltIdx = SVOp->getMaskElt(i);
4455 MaskVals.push_back(EltIdx);
4464 InputQuads.set(EltIdx / 4);
4467 int BestLoQuad = -1;
4468 unsigned MaxQuad = 1;
4469 for (unsigned i = 0; i < 4; ++i) {
4470 if (LoQuad[i] > MaxQuad) {
4472 MaxQuad = LoQuad[i];
4476 int BestHiQuad = -1;
4478 for (unsigned i = 0; i < 4; ++i) {
4479 if (HiQuad[i] > MaxQuad) {
4481 MaxQuad = HiQuad[i];
4485 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4486 // of the two input vectors, shuffle them into one input vector so only a
4487 // single pshufb instruction is necessary. If There are more than 2 input
4488 // quads, disable the next transformation since it does not help SSSE3.
4489 bool V1Used = InputQuads[0] || InputQuads[1];
4490 bool V2Used = InputQuads[2] || InputQuads[3];
4491 if (Subtarget->hasSSSE3()) {
4492 if (InputQuads.count() == 2 && V1Used && V2Used) {
4493 BestLoQuad = InputQuads.find_first();
4494 BestHiQuad = InputQuads.find_next(BestLoQuad);
4496 if (InputQuads.count() > 2) {
4502 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4503 // the shuffle mask. If a quad is scored as -1, that means that it contains
4504 // words from all 4 input quadwords.
4506 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4507 SmallVector<int, 8> MaskV;
4508 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4509 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4510 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4511 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4512 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4513 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4515 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4516 // source words for the shuffle, to aid later transformations.
4517 bool AllWordsInNewV = true;
4518 bool InOrder[2] = { true, true };
4519 for (unsigned i = 0; i != 8; ++i) {
4520 int idx = MaskVals[i];
4522 InOrder[i/4] = false;
4523 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4525 AllWordsInNewV = false;
4529 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4530 if (AllWordsInNewV) {
4531 for (int i = 0; i != 8; ++i) {
4532 int idx = MaskVals[i];
4535 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4536 if ((idx != i) && idx < 4)
4538 if ((idx != i) && idx > 3)
4547 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4548 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4549 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4550 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4551 unsigned TargetMask = 0;
4552 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4553 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4554 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4555 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4556 V1 = NewV.getOperand(0);
4557 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4561 // If we have SSSE3, and all words of the result are from 1 input vector,
4562 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4563 // is present, fall back to case 4.
4564 if (Subtarget->hasSSSE3()) {
4565 SmallVector<SDValue,16> pshufbMask;
4567 // If we have elements from both input vectors, set the high bit of the
4568 // shuffle mask element to zero out elements that come from V2 in the V1
4569 // mask, and elements that come from V1 in the V2 mask, so that the two
4570 // results can be OR'd together.
4571 bool TwoInputs = V1Used && V2Used;
4572 for (unsigned i = 0; i != 8; ++i) {
4573 int EltIdx = MaskVals[i] * 2;
4574 if (TwoInputs && (EltIdx >= 16)) {
4575 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4576 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4579 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4580 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4582 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4583 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4584 DAG.getNode(ISD::BUILD_VECTOR, dl,
4585 MVT::v16i8, &pshufbMask[0], 16));
4587 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4589 // Calculate the shuffle mask for the second input, shuffle it, and
4590 // OR it with the first shuffled input.
4592 for (unsigned i = 0; i != 8; ++i) {
4593 int EltIdx = MaskVals[i] * 2;
4595 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4596 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4599 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4600 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4602 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4603 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4604 DAG.getNode(ISD::BUILD_VECTOR, dl,
4605 MVT::v16i8, &pshufbMask[0], 16));
4606 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4607 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4610 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4611 // and update MaskVals with new element order.
4612 BitVector InOrder(8);
4613 if (BestLoQuad >= 0) {
4614 SmallVector<int, 8> MaskV;
4615 for (int i = 0; i != 4; ++i) {
4616 int idx = MaskVals[i];
4618 MaskV.push_back(-1);
4620 } else if ((idx / 4) == BestLoQuad) {
4621 MaskV.push_back(idx & 3);
4624 MaskV.push_back(-1);
4627 for (unsigned i = 4; i != 8; ++i)
4629 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4632 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4633 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4635 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4639 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4640 // and update MaskVals with the new element order.
4641 if (BestHiQuad >= 0) {
4642 SmallVector<int, 8> MaskV;
4643 for (unsigned i = 0; i != 4; ++i)
4645 for (unsigned i = 4; i != 8; ++i) {
4646 int idx = MaskVals[i];
4648 MaskV.push_back(-1);
4650 } else if ((idx / 4) == BestHiQuad) {
4651 MaskV.push_back((idx & 3) + 4);
4654 MaskV.push_back(-1);
4657 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4660 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4661 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4663 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4667 // In case BestHi & BestLo were both -1, which means each quadword has a word
4668 // from each of the four input quadwords, calculate the InOrder bitvector now
4669 // before falling through to the insert/extract cleanup.
4670 if (BestLoQuad == -1 && BestHiQuad == -1) {
4672 for (int i = 0; i != 8; ++i)
4673 if (MaskVals[i] < 0 || MaskVals[i] == i)
4677 // The other elements are put in the right place using pextrw and pinsrw.
4678 for (unsigned i = 0; i != 8; ++i) {
4681 int EltIdx = MaskVals[i];
4684 SDValue ExtOp = (EltIdx < 8)
4685 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4686 DAG.getIntPtrConstant(EltIdx))
4687 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4688 DAG.getIntPtrConstant(EltIdx - 8));
4689 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4690 DAG.getIntPtrConstant(i));
4695 // v16i8 shuffles - Prefer shuffles in the following order:
4696 // 1. [ssse3] 1 x pshufb
4697 // 2. [ssse3] 2 x pshufb + 1 x por
4698 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4700 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4702 const X86TargetLowering &TLI) {
4703 SDValue V1 = SVOp->getOperand(0);
4704 SDValue V2 = SVOp->getOperand(1);
4705 DebugLoc dl = SVOp->getDebugLoc();
4706 SmallVector<int, 16> MaskVals;
4707 SVOp->getMask(MaskVals);
4709 // If we have SSSE3, case 1 is generated when all result bytes come from
4710 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4711 // present, fall back to case 3.
4712 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4715 for (unsigned i = 0; i < 16; ++i) {
4716 int EltIdx = MaskVals[i];
4725 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4726 if (TLI.getSubtarget()->hasSSSE3()) {
4727 SmallVector<SDValue,16> pshufbMask;
4729 // If all result elements are from one input vector, then only translate
4730 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4732 // Otherwise, we have elements from both input vectors, and must zero out
4733 // elements that come from V2 in the first mask, and V1 in the second mask
4734 // so that we can OR them together.
4735 bool TwoInputs = !(V1Only || V2Only);
4736 for (unsigned i = 0; i != 16; ++i) {
4737 int EltIdx = MaskVals[i];
4738 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4739 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4742 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4744 // If all the elements are from V2, assign it to V1 and return after
4745 // building the first pshufb.
4748 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4749 DAG.getNode(ISD::BUILD_VECTOR, dl,
4750 MVT::v16i8, &pshufbMask[0], 16));
4754 // Calculate the shuffle mask for the second input, shuffle it, and
4755 // OR it with the first shuffled input.
4757 for (unsigned i = 0; i != 16; ++i) {
4758 int EltIdx = MaskVals[i];
4760 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4763 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4765 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4766 DAG.getNode(ISD::BUILD_VECTOR, dl,
4767 MVT::v16i8, &pshufbMask[0], 16));
4768 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4771 // No SSSE3 - Calculate in place words and then fix all out of place words
4772 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4773 // the 16 different words that comprise the two doublequadword input vectors.
4774 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4775 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4776 SDValue NewV = V2Only ? V2 : V1;
4777 for (int i = 0; i != 8; ++i) {
4778 int Elt0 = MaskVals[i*2];
4779 int Elt1 = MaskVals[i*2+1];
4781 // This word of the result is all undef, skip it.
4782 if (Elt0 < 0 && Elt1 < 0)
4785 // This word of the result is already in the correct place, skip it.
4786 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4788 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4791 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4792 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4795 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4796 // using a single extract together, load it and store it.
4797 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4798 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4799 DAG.getIntPtrConstant(Elt1 / 2));
4800 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4801 DAG.getIntPtrConstant(i));
4805 // If Elt1 is defined, extract it from the appropriate source. If the
4806 // source byte is not also odd, shift the extracted word left 8 bits
4807 // otherwise clear the bottom 8 bits if we need to do an or.
4809 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4810 DAG.getIntPtrConstant(Elt1 / 2));
4811 if ((Elt1 & 1) == 0)
4812 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4813 DAG.getConstant(8, TLI.getShiftAmountTy()));
4815 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4816 DAG.getConstant(0xFF00, MVT::i16));
4818 // If Elt0 is defined, extract it from the appropriate source. If the
4819 // source byte is not also even, shift the extracted word right 8 bits. If
4820 // Elt1 was also defined, OR the extracted values together before
4821 // inserting them in the result.
4823 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4824 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4825 if ((Elt0 & 1) != 0)
4826 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4827 DAG.getConstant(8, TLI.getShiftAmountTy()));
4829 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4830 DAG.getConstant(0x00FF, MVT::i16));
4831 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4834 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4835 DAG.getIntPtrConstant(i));
4837 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4840 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4841 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4842 /// done when every pair / quad of shuffle mask elements point to elements in
4843 /// the right sequence. e.g.
4844 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4846 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4847 SelectionDAG &DAG, DebugLoc dl) {
4848 EVT VT = SVOp->getValueType(0);
4849 SDValue V1 = SVOp->getOperand(0);
4850 SDValue V2 = SVOp->getOperand(1);
4851 unsigned NumElems = VT.getVectorNumElements();
4852 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4854 switch (VT.getSimpleVT().SimpleTy) {
4855 default: assert(false && "Unexpected!");
4856 case MVT::v4f32: NewVT = MVT::v2f64; break;
4857 case MVT::v4i32: NewVT = MVT::v2i64; break;
4858 case MVT::v8i16: NewVT = MVT::v4i32; break;
4859 case MVT::v16i8: NewVT = MVT::v4i32; break;
4862 int Scale = NumElems / NewWidth;
4863 SmallVector<int, 8> MaskVec;
4864 for (unsigned i = 0; i < NumElems; i += Scale) {
4866 for (int j = 0; j < Scale; ++j) {
4867 int EltIdx = SVOp->getMaskElt(i+j);
4871 StartIdx = EltIdx - (EltIdx % Scale);
4872 if (EltIdx != StartIdx + j)
4876 MaskVec.push_back(-1);
4878 MaskVec.push_back(StartIdx / Scale);
4881 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4882 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4883 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4886 /// getVZextMovL - Return a zero-extending vector move low node.
4888 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4889 SDValue SrcOp, SelectionDAG &DAG,
4890 const X86Subtarget *Subtarget, DebugLoc dl) {
4891 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4892 LoadSDNode *LD = NULL;
4893 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4894 LD = dyn_cast<LoadSDNode>(SrcOp);
4896 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4898 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4899 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4900 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4901 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4902 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4904 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4905 return DAG.getNode(ISD::BITCAST, dl, VT,
4906 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4907 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4915 return DAG.getNode(ISD::BITCAST, dl, VT,
4916 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4917 DAG.getNode(ISD::BITCAST, dl,
4921 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4924 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4925 SDValue V1 = SVOp->getOperand(0);
4926 SDValue V2 = SVOp->getOperand(1);
4927 DebugLoc dl = SVOp->getDebugLoc();
4928 EVT VT = SVOp->getValueType(0);
4930 SmallVector<std::pair<int, int>, 8> Locs;
4932 SmallVector<int, 8> Mask1(4U, -1);
4933 SmallVector<int, 8> PermMask;
4934 SVOp->getMask(PermMask);
4938 for (unsigned i = 0; i != 4; ++i) {
4939 int Idx = PermMask[i];
4941 Locs[i] = std::make_pair(-1, -1);
4943 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4945 Locs[i] = std::make_pair(0, NumLo);
4949 Locs[i] = std::make_pair(1, NumHi);
4951 Mask1[2+NumHi] = Idx;
4957 if (NumLo <= 2 && NumHi <= 2) {
4958 // If no more than two elements come from either vector. This can be
4959 // implemented with two shuffles. First shuffle gather the elements.
4960 // The second shuffle, which takes the first shuffle as both of its
4961 // vector operands, put the elements into the right order.
4962 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4964 SmallVector<int, 8> Mask2(4U, -1);
4966 for (unsigned i = 0; i != 4; ++i) {
4967 if (Locs[i].first == -1)
4970 unsigned Idx = (i < 2) ? 0 : 4;
4971 Idx += Locs[i].first * 2 + Locs[i].second;
4976 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4977 } else if (NumLo == 3 || NumHi == 3) {
4978 // Otherwise, we must have three elements from one vector, call it X, and
4979 // one element from the other, call it Y. First, use a shufps to build an
4980 // intermediate vector with the one element from Y and the element from X
4981 // that will be in the same half in the final destination (the indexes don't
4982 // matter). Then, use a shufps to build the final vector, taking the half
4983 // containing the element from Y from the intermediate, and the other half
4986 // Normalize it so the 3 elements come from V1.
4987 CommuteVectorShuffleMask(PermMask, VT);
4991 // Find the element from V2.
4993 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4994 int Val = PermMask[HiIndex];
5001 Mask1[0] = PermMask[HiIndex];
5003 Mask1[2] = PermMask[HiIndex^1];
5005 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5008 Mask1[0] = PermMask[0];
5009 Mask1[1] = PermMask[1];
5010 Mask1[2] = HiIndex & 1 ? 6 : 4;
5011 Mask1[3] = HiIndex & 1 ? 4 : 6;
5012 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5014 Mask1[0] = HiIndex & 1 ? 2 : 0;
5015 Mask1[1] = HiIndex & 1 ? 0 : 2;
5016 Mask1[2] = PermMask[2];
5017 Mask1[3] = PermMask[3];
5022 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5026 // Break it into (shuffle shuffle_hi, shuffle_lo).
5028 SmallVector<int,8> LoMask(4U, -1);
5029 SmallVector<int,8> HiMask(4U, -1);
5031 SmallVector<int,8> *MaskPtr = &LoMask;
5032 unsigned MaskIdx = 0;
5035 for (unsigned i = 0; i != 4; ++i) {
5042 int Idx = PermMask[i];
5044 Locs[i] = std::make_pair(-1, -1);
5045 } else if (Idx < 4) {
5046 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5047 (*MaskPtr)[LoIdx] = Idx;
5050 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5051 (*MaskPtr)[HiIdx] = Idx;
5056 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5057 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5058 SmallVector<int, 8> MaskOps;
5059 for (unsigned i = 0; i != 4; ++i) {
5060 if (Locs[i].first == -1) {
5061 MaskOps.push_back(-1);
5063 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5064 MaskOps.push_back(Idx);
5067 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5070 static bool MayFoldVectorLoad(SDValue V) {
5071 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5072 V = V.getOperand(0);
5073 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5074 V = V.getOperand(0);
5080 // FIXME: the version above should always be used. Since there's
5081 // a bug where several vector shuffles can't be folded because the
5082 // DAG is not updated during lowering and a node claims to have two
5083 // uses while it only has one, use this version, and let isel match
5084 // another instruction if the load really happens to have more than
5085 // one use. Remove this version after this bug get fixed.
5086 // rdar://8434668, PR8156
5087 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5088 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5089 V = V.getOperand(0);
5090 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5091 V = V.getOperand(0);
5092 if (ISD::isNormalLoad(V.getNode()))
5097 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5098 /// a vector extract, and if both can be later optimized into a single load.
5099 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5100 /// here because otherwise a target specific shuffle node is going to be
5101 /// emitted for this shuffle, and the optimization not done.
5102 /// FIXME: This is probably not the best approach, but fix the problem
5103 /// until the right path is decided.
5105 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5106 const TargetLowering &TLI) {
5107 EVT VT = V.getValueType();
5108 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5110 // Be sure that the vector shuffle is present in a pattern like this:
5111 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5115 SDNode *N = *V.getNode()->use_begin();
5116 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5119 SDValue EltNo = N->getOperand(1);
5120 if (!isa<ConstantSDNode>(EltNo))
5123 // If the bit convert changed the number of elements, it is unsafe
5124 // to examine the mask.
5125 bool HasShuffleIntoBitcast = false;
5126 if (V.getOpcode() == ISD::BITCAST) {
5127 EVT SrcVT = V.getOperand(0).getValueType();
5128 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5130 V = V.getOperand(0);
5131 HasShuffleIntoBitcast = true;
5134 // Select the input vector, guarding against out of range extract vector.
5135 unsigned NumElems = VT.getVectorNumElements();
5136 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5137 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5138 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5140 // Skip one more bit_convert if necessary
5141 if (V.getOpcode() == ISD::BITCAST)
5142 V = V.getOperand(0);
5144 if (ISD::isNormalLoad(V.getNode())) {
5145 // Is the original load suitable?
5146 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5148 // FIXME: avoid the multi-use bug that is preventing lots of
5149 // of foldings to be detected, this is still wrong of course, but
5150 // give the temporary desired behavior, and if it happens that
5151 // the load has real more uses, during isel it will not fold, and
5152 // will generate poor code.
5153 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5156 if (!HasShuffleIntoBitcast)
5159 // If there's a bitcast before the shuffle, check if the load type and
5160 // alignment is valid.
5161 unsigned Align = LN0->getAlignment();
5163 TLI.getTargetData()->getABITypeAlignment(
5164 VT.getTypeForEVT(*DAG.getContext()));
5166 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5174 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5175 EVT VT = Op.getValueType();
5177 // Canonizalize to v2f64.
5178 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5179 return DAG.getNode(ISD::BITCAST, dl, VT,
5180 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5185 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5187 SDValue V1 = Op.getOperand(0);
5188 SDValue V2 = Op.getOperand(1);
5189 EVT VT = Op.getValueType();
5191 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5193 if (HasSSE2 && VT == MVT::v2f64)
5194 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5197 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5201 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5202 SDValue V1 = Op.getOperand(0);
5203 SDValue V2 = Op.getOperand(1);
5204 EVT VT = Op.getValueType();
5206 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5207 "unsupported shuffle type");
5209 if (V2.getOpcode() == ISD::UNDEF)
5213 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5217 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5218 SDValue V1 = Op.getOperand(0);
5219 SDValue V2 = Op.getOperand(1);
5220 EVT VT = Op.getValueType();
5221 unsigned NumElems = VT.getVectorNumElements();
5223 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5224 // operand of these instructions is only memory, so check if there's a
5225 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5227 bool CanFoldLoad = false;
5229 // Trivial case, when V2 comes from a load.
5230 if (MayFoldVectorLoad(V2))
5233 // When V1 is a load, it can be folded later into a store in isel, example:
5234 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5236 // (MOVLPSmr addr:$src1, VR128:$src2)
5237 // So, recognize this potential and also use MOVLPS or MOVLPD
5238 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5242 if (HasSSE2 && NumElems == 2)
5243 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5246 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5250 // movl and movlp will both match v2i64, but v2i64 is never matched by
5251 // movl earlier because we make it strict to avoid messing with the movlp load
5252 // folding logic (see the code above getMOVLP call). Match it here then,
5253 // this is horrible, but will stay like this until we move all shuffle
5254 // matching to x86 specific nodes. Note that for the 1st condition all
5255 // types are matched with movsd.
5256 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5257 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5259 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5262 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5264 // Invert the operand order and use SHUFPS to match it.
5265 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5266 X86::getShuffleSHUFImmediate(SVOp), DAG);
5269 static inline unsigned getUNPCKLOpcode(EVT VT) {
5270 switch(VT.getSimpleVT().SimpleTy) {
5271 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5272 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5273 case MVT::v4f32: return X86ISD::UNPCKLPS;
5274 case MVT::v2f64: return X86ISD::UNPCKLPD;
5275 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5276 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5278 llvm_unreachable("Unknow type for unpckl");
5283 static inline unsigned getUNPCKHOpcode(EVT VT) {
5284 switch(VT.getSimpleVT().SimpleTy) {
5285 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5286 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5287 case MVT::v4f32: return X86ISD::UNPCKHPS;
5288 case MVT::v2f64: return X86ISD::UNPCKHPD;
5289 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5290 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5292 llvm_unreachable("Unknow type for unpckh");
5298 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5299 const TargetLowering &TLI,
5300 const X86Subtarget *Subtarget) {
5301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5302 EVT VT = Op.getValueType();
5303 DebugLoc dl = Op.getDebugLoc();
5304 SDValue V1 = Op.getOperand(0);
5305 SDValue V2 = Op.getOperand(1);
5307 if (isZeroShuffle(SVOp))
5308 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5310 // Handle splat operations
5311 if (SVOp->isSplat()) {
5312 // Special case, this is the only place now where it's
5313 // allowed to return a vector_shuffle operation without
5314 // using a target specific node, because *hopefully* it
5315 // will be optimized away by the dag combiner.
5316 if (VT.getVectorNumElements() <= 4 &&
5317 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5320 // Handle splats by matching through known masks
5321 if (VT.getVectorNumElements() <= 4)
5324 // Canonicalize all of the remaining to v4f32.
5325 return PromoteSplat(SVOp, DAG);
5328 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5330 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5331 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5332 if (NewOp.getNode())
5333 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5334 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5335 // FIXME: Figure out a cleaner way to do this.
5336 // Try to make use of movq to zero out the top part.
5337 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5338 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5339 if (NewOp.getNode()) {
5340 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5341 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5342 DAG, Subtarget, dl);
5344 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5345 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5346 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5347 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5348 DAG, Subtarget, dl);
5355 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5356 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5357 SDValue V1 = Op.getOperand(0);
5358 SDValue V2 = Op.getOperand(1);
5359 EVT VT = Op.getValueType();
5360 DebugLoc dl = Op.getDebugLoc();
5361 unsigned NumElems = VT.getVectorNumElements();
5362 bool isMMX = VT.getSizeInBits() == 64;
5363 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5364 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5365 bool V1IsSplat = false;
5366 bool V2IsSplat = false;
5367 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5368 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5369 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5370 MachineFunction &MF = DAG.getMachineFunction();
5371 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5373 // Shuffle operations on MMX not supported.
5377 // Vector shuffle lowering takes 3 steps:
5379 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5380 // narrowing and commutation of operands should be handled.
5381 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5383 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5384 // so the shuffle can be broken into other shuffles and the legalizer can
5385 // try the lowering again.
5387 // The general ideia is that no vector_shuffle operation should be left to
5388 // be matched during isel, all of them must be converted to a target specific
5391 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5392 // narrowing and commutation of operands should be handled. The actual code
5393 // doesn't include all of those, work in progress...
5394 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5395 if (NewOp.getNode())
5398 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5399 // unpckh_undef). Only use pshufd if speed is more important than size.
5400 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5401 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5402 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5403 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5404 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5405 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5407 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5408 RelaxedMayFoldVectorLoad(V1))
5409 return getMOVDDup(Op, dl, V1, DAG);
5411 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5412 return getMOVHighToLow(Op, dl, DAG);
5414 // Use to match splats
5415 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5416 (VT == MVT::v2f64 || VT == MVT::v2i64))
5417 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5419 if (X86::isPSHUFDMask(SVOp)) {
5420 // The actual implementation will match the mask in the if above and then
5421 // during isel it can match several different instructions, not only pshufd
5422 // as its name says, sad but true, emulate the behavior for now...
5423 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5424 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5426 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5428 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5429 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5431 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5432 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5435 if (VT == MVT::v4f32)
5436 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5440 // Check if this can be converted into a logical shift.
5441 bool isLeft = false;
5444 bool isShift = getSubtarget()->hasSSE2() &&
5445 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5446 if (isShift && ShVal.hasOneUse()) {
5447 // If the shifted value has multiple uses, it may be cheaper to use
5448 // v_set0 + movlhps or movhlps, etc.
5449 EVT EltVT = VT.getVectorElementType();
5450 ShAmt *= EltVT.getSizeInBits();
5451 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5454 if (X86::isMOVLMask(SVOp)) {
5457 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5458 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5459 if (!X86::isMOVLPMask(SVOp)) {
5460 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5461 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5463 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5464 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5468 // FIXME: fold these into legal mask.
5469 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5470 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5472 if (X86::isMOVHLPSMask(SVOp))
5473 return getMOVHighToLow(Op, dl, DAG);
5475 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5476 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5478 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5479 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5481 if (X86::isMOVLPMask(SVOp))
5482 return getMOVLP(Op, dl, DAG, HasSSE2);
5484 if (ShouldXformToMOVHLPS(SVOp) ||
5485 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5486 return CommuteVectorShuffle(SVOp, DAG);
5489 // No better options. Use a vshl / vsrl.
5490 EVT EltVT = VT.getVectorElementType();
5491 ShAmt *= EltVT.getSizeInBits();
5492 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5495 bool Commuted = false;
5496 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5497 // 1,1,1,1 -> v8i16 though.
5498 V1IsSplat = isSplatVector(V1.getNode());
5499 V2IsSplat = isSplatVector(V2.getNode());
5501 // Canonicalize the splat or undef, if present, to be on the RHS.
5502 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5503 Op = CommuteVectorShuffle(SVOp, DAG);
5504 SVOp = cast<ShuffleVectorSDNode>(Op);
5505 V1 = SVOp->getOperand(0);
5506 V2 = SVOp->getOperand(1);
5507 std::swap(V1IsSplat, V2IsSplat);
5508 std::swap(V1IsUndef, V2IsUndef);
5512 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5513 // Shuffling low element of v1 into undef, just return v1.
5516 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5517 // the instruction selector will not match, so get a canonical MOVL with
5518 // swapped operands to undo the commute.
5519 return getMOVL(DAG, dl, VT, V2, V1);
5522 if (X86::isUNPCKLMask(SVOp))
5523 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5525 if (X86::isUNPCKHMask(SVOp))
5526 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5529 // Normalize mask so all entries that point to V2 points to its first
5530 // element then try to match unpck{h|l} again. If match, return a
5531 // new vector_shuffle with the corrected mask.
5532 SDValue NewMask = NormalizeMask(SVOp, DAG);
5533 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5534 if (NSVOp != SVOp) {
5535 if (X86::isUNPCKLMask(NSVOp, true)) {
5537 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5544 // Commute is back and try unpck* again.
5545 // FIXME: this seems wrong.
5546 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5547 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5549 if (X86::isUNPCKLMask(NewSVOp))
5550 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5552 if (X86::isUNPCKHMask(NewSVOp))
5553 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5556 // Normalize the node to match x86 shuffle ops if needed
5557 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5558 return CommuteVectorShuffle(SVOp, DAG);
5560 // The checks below are all present in isShuffleMaskLegal, but they are
5561 // inlined here right now to enable us to directly emit target specific
5562 // nodes, and remove one by one until they don't return Op anymore.
5563 SmallVector<int, 16> M;
5566 if (isPALIGNRMask(M, VT, HasSSSE3))
5567 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5568 X86::getShufflePALIGNRImmediate(SVOp),
5571 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5572 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5573 if (VT == MVT::v2f64)
5574 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5575 if (VT == MVT::v2i64)
5576 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5579 if (isPSHUFHWMask(M, VT))
5580 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5581 X86::getShufflePSHUFHWImmediate(SVOp),
5584 if (isPSHUFLWMask(M, VT))
5585 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5586 X86::getShufflePSHUFLWImmediate(SVOp),
5589 if (isSHUFPMask(M, VT)) {
5590 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5591 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5592 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5594 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5595 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5599 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5600 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5601 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5602 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5603 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5604 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5606 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5607 if (VT == MVT::v8i16) {
5608 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5609 if (NewOp.getNode())
5613 if (VT == MVT::v16i8) {
5614 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5615 if (NewOp.getNode())
5619 // Handle all 4 wide cases with a number of shuffles.
5621 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5627 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5628 SelectionDAG &DAG) const {
5629 EVT VT = Op.getValueType();
5630 DebugLoc dl = Op.getDebugLoc();
5631 if (VT.getSizeInBits() == 8) {
5632 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5633 Op.getOperand(0), Op.getOperand(1));
5634 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5635 DAG.getValueType(VT));
5636 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5637 } else if (VT.getSizeInBits() == 16) {
5638 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5639 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5641 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5642 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5643 DAG.getNode(ISD::BITCAST, dl,
5647 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5648 Op.getOperand(0), Op.getOperand(1));
5649 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5650 DAG.getValueType(VT));
5651 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5652 } else if (VT == MVT::f32) {
5653 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5654 // the result back to FR32 register. It's only worth matching if the
5655 // result has a single use which is a store or a bitcast to i32. And in
5656 // the case of a store, it's not worth it if the index is a constant 0,
5657 // because a MOVSSmr can be used instead, which is smaller and faster.
5658 if (!Op.hasOneUse())
5660 SDNode *User = *Op.getNode()->use_begin();
5661 if ((User->getOpcode() != ISD::STORE ||
5662 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5663 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5664 (User->getOpcode() != ISD::BITCAST ||
5665 User->getValueType(0) != MVT::i32))
5667 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5668 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5671 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5672 } else if (VT == MVT::i32) {
5673 // ExtractPS works with constant index.
5674 if (isa<ConstantSDNode>(Op.getOperand(1)))
5682 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5683 SelectionDAG &DAG) const {
5684 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5687 if (Subtarget->hasSSE41()) {
5688 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5693 EVT VT = Op.getValueType();
5694 DebugLoc dl = Op.getDebugLoc();
5695 // TODO: handle v16i8.
5696 if (VT.getSizeInBits() == 16) {
5697 SDValue Vec = Op.getOperand(0);
5698 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5700 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5701 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5702 DAG.getNode(ISD::BITCAST, dl,
5705 // Transform it so it match pextrw which produces a 32-bit result.
5706 EVT EltVT = MVT::i32;
5707 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5708 Op.getOperand(0), Op.getOperand(1));
5709 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5710 DAG.getValueType(VT));
5711 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5712 } else if (VT.getSizeInBits() == 32) {
5713 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5717 // SHUFPS the element to the lowest double word, then movss.
5718 int Mask[4] = { Idx, -1, -1, -1 };
5719 EVT VVT = Op.getOperand(0).getValueType();
5720 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5721 DAG.getUNDEF(VVT), Mask);
5722 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5723 DAG.getIntPtrConstant(0));
5724 } else if (VT.getSizeInBits() == 64) {
5725 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5726 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5727 // to match extract_elt for f64.
5728 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5732 // UNPCKHPD the element to the lowest double word, then movsd.
5733 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5734 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5735 int Mask[2] = { 1, -1 };
5736 EVT VVT = Op.getOperand(0).getValueType();
5737 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5738 DAG.getUNDEF(VVT), Mask);
5739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5740 DAG.getIntPtrConstant(0));
5747 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5748 SelectionDAG &DAG) const {
5749 EVT VT = Op.getValueType();
5750 EVT EltVT = VT.getVectorElementType();
5751 DebugLoc dl = Op.getDebugLoc();
5753 SDValue N0 = Op.getOperand(0);
5754 SDValue N1 = Op.getOperand(1);
5755 SDValue N2 = Op.getOperand(2);
5757 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5758 isa<ConstantSDNode>(N2)) {
5760 if (VT == MVT::v8i16)
5761 Opc = X86ISD::PINSRW;
5762 else if (VT == MVT::v16i8)
5763 Opc = X86ISD::PINSRB;
5765 Opc = X86ISD::PINSRB;
5767 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5769 if (N1.getValueType() != MVT::i32)
5770 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5771 if (N2.getValueType() != MVT::i32)
5772 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5773 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5774 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5775 // Bits [7:6] of the constant are the source select. This will always be
5776 // zero here. The DAG Combiner may combine an extract_elt index into these
5777 // bits. For example (insert (extract, 3), 2) could be matched by putting
5778 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5779 // Bits [5:4] of the constant are the destination select. This is the
5780 // value of the incoming immediate.
5781 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5782 // combine either bitwise AND or insert of float 0.0 to set these bits.
5783 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5784 // Create this as a scalar to vector..
5785 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5786 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5787 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5788 // PINSR* works with constant index.
5795 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5796 EVT VT = Op.getValueType();
5797 EVT EltVT = VT.getVectorElementType();
5799 if (Subtarget->hasSSE41())
5800 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5802 if (EltVT == MVT::i8)
5805 DebugLoc dl = Op.getDebugLoc();
5806 SDValue N0 = Op.getOperand(0);
5807 SDValue N1 = Op.getOperand(1);
5808 SDValue N2 = Op.getOperand(2);
5810 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5811 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5812 // as its second argument.
5813 if (N1.getValueType() != MVT::i32)
5814 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5815 if (N2.getValueType() != MVT::i32)
5816 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5817 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5823 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5824 DebugLoc dl = Op.getDebugLoc();
5826 if (Op.getValueType() == MVT::v1i64 &&
5827 Op.getOperand(0).getValueType() == MVT::i64)
5828 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5830 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5831 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5832 "Expected an SSE type!");
5833 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5834 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5837 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5838 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5839 // one of the above mentioned nodes. It has to be wrapped because otherwise
5840 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5841 // be used to form addressing mode. These wrapped nodes will be selected
5844 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5845 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5847 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5849 unsigned char OpFlag = 0;
5850 unsigned WrapperKind = X86ISD::Wrapper;
5851 CodeModel::Model M = getTargetMachine().getCodeModel();
5853 if (Subtarget->isPICStyleRIPRel() &&
5854 (M == CodeModel::Small || M == CodeModel::Kernel))
5855 WrapperKind = X86ISD::WrapperRIP;
5856 else if (Subtarget->isPICStyleGOT())
5857 OpFlag = X86II::MO_GOTOFF;
5858 else if (Subtarget->isPICStyleStubPIC())
5859 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5861 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5863 CP->getOffset(), OpFlag);
5864 DebugLoc DL = CP->getDebugLoc();
5865 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5866 // With PIC, the address is actually $g + Offset.
5868 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5869 DAG.getNode(X86ISD::GlobalBaseReg,
5870 DebugLoc(), getPointerTy()),
5877 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5878 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5880 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5882 unsigned char OpFlag = 0;
5883 unsigned WrapperKind = X86ISD::Wrapper;
5884 CodeModel::Model M = getTargetMachine().getCodeModel();
5886 if (Subtarget->isPICStyleRIPRel() &&
5887 (M == CodeModel::Small || M == CodeModel::Kernel))
5888 WrapperKind = X86ISD::WrapperRIP;
5889 else if (Subtarget->isPICStyleGOT())
5890 OpFlag = X86II::MO_GOTOFF;
5891 else if (Subtarget->isPICStyleStubPIC())
5892 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5894 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5896 DebugLoc DL = JT->getDebugLoc();
5897 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5899 // With PIC, the address is actually $g + Offset.
5901 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5902 DAG.getNode(X86ISD::GlobalBaseReg,
5903 DebugLoc(), getPointerTy()),
5910 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5911 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5913 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5915 unsigned char OpFlag = 0;
5916 unsigned WrapperKind = X86ISD::Wrapper;
5917 CodeModel::Model M = getTargetMachine().getCodeModel();
5919 if (Subtarget->isPICStyleRIPRel() &&
5920 (M == CodeModel::Small || M == CodeModel::Kernel))
5921 WrapperKind = X86ISD::WrapperRIP;
5922 else if (Subtarget->isPICStyleGOT())
5923 OpFlag = X86II::MO_GOTOFF;
5924 else if (Subtarget->isPICStyleStubPIC())
5925 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5927 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5929 DebugLoc DL = Op.getDebugLoc();
5930 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5933 // With PIC, the address is actually $g + Offset.
5934 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5935 !Subtarget->is64Bit()) {
5936 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5937 DAG.getNode(X86ISD::GlobalBaseReg,
5938 DebugLoc(), getPointerTy()),
5946 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5947 // Create the TargetBlockAddressAddress node.
5948 unsigned char OpFlags =
5949 Subtarget->ClassifyBlockAddressReference();
5950 CodeModel::Model M = getTargetMachine().getCodeModel();
5951 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5952 DebugLoc dl = Op.getDebugLoc();
5953 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5954 /*isTarget=*/true, OpFlags);
5956 if (Subtarget->isPICStyleRIPRel() &&
5957 (M == CodeModel::Small || M == CodeModel::Kernel))
5958 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5960 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5962 // With PIC, the address is actually $g + Offset.
5963 if (isGlobalRelativeToPICBase(OpFlags)) {
5964 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5965 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5973 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5975 SelectionDAG &DAG) const {
5976 // Create the TargetGlobalAddress node, folding in the constant
5977 // offset if it is legal.
5978 unsigned char OpFlags =
5979 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5980 CodeModel::Model M = getTargetMachine().getCodeModel();
5982 if (OpFlags == X86II::MO_NO_FLAG &&
5983 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5984 // A direct static reference to a global.
5985 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5988 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5991 if (Subtarget->isPICStyleRIPRel() &&
5992 (M == CodeModel::Small || M == CodeModel::Kernel))
5993 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5995 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5997 // With PIC, the address is actually $g + Offset.
5998 if (isGlobalRelativeToPICBase(OpFlags)) {
5999 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6000 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6004 // For globals that require a load from a stub to get the address, emit the
6006 if (isGlobalStubReference(OpFlags))
6007 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6008 MachinePointerInfo::getGOT(), false, false, 0);
6010 // If there was a non-zero offset that we didn't fold, create an explicit
6013 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6014 DAG.getConstant(Offset, getPointerTy()));
6020 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6021 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6022 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6023 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6027 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6028 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6029 unsigned char OperandFlags) {
6030 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6031 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6032 DebugLoc dl = GA->getDebugLoc();
6033 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6034 GA->getValueType(0),
6038 SDValue Ops[] = { Chain, TGA, *InFlag };
6039 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6041 SDValue Ops[] = { Chain, TGA };
6042 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6045 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6046 MFI->setAdjustsStack(true);
6048 SDValue Flag = Chain.getValue(1);
6049 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6052 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6054 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6057 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6058 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6059 DAG.getNode(X86ISD::GlobalBaseReg,
6060 DebugLoc(), PtrVT), InFlag);
6061 InFlag = Chain.getValue(1);
6063 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6066 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6068 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6070 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6071 X86::RAX, X86II::MO_TLSGD);
6074 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6075 // "local exec" model.
6076 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6077 const EVT PtrVT, TLSModel::Model model,
6079 DebugLoc dl = GA->getDebugLoc();
6081 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6082 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6083 is64Bit ? 257 : 256));
6085 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6086 DAG.getIntPtrConstant(0),
6087 MachinePointerInfo(Ptr), false, false, 0);
6089 unsigned char OperandFlags = 0;
6090 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6092 unsigned WrapperKind = X86ISD::Wrapper;
6093 if (model == TLSModel::LocalExec) {
6094 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6095 } else if (is64Bit) {
6096 assert(model == TLSModel::InitialExec);
6097 OperandFlags = X86II::MO_GOTTPOFF;
6098 WrapperKind = X86ISD::WrapperRIP;
6100 assert(model == TLSModel::InitialExec);
6101 OperandFlags = X86II::MO_INDNTPOFF;
6104 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6106 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6107 GA->getValueType(0),
6108 GA->getOffset(), OperandFlags);
6109 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6111 if (model == TLSModel::InitialExec)
6112 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6113 MachinePointerInfo::getGOT(), false, false, 0);
6115 // The address of the thread local variable is the add of the thread
6116 // pointer with the offset of the variable.
6117 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6121 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6123 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6124 const GlobalValue *GV = GA->getGlobal();
6126 if (Subtarget->isTargetELF()) {
6127 // TODO: implement the "local dynamic" model
6128 // TODO: implement the "initial exec"model for pic executables
6130 // If GV is an alias then use the aliasee for determining
6131 // thread-localness.
6132 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6133 GV = GA->resolveAliasedGlobal(false);
6135 TLSModel::Model model
6136 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6139 case TLSModel::GeneralDynamic:
6140 case TLSModel::LocalDynamic: // not implemented
6141 if (Subtarget->is64Bit())
6142 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6143 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6145 case TLSModel::InitialExec:
6146 case TLSModel::LocalExec:
6147 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6148 Subtarget->is64Bit());
6150 } else if (Subtarget->isTargetDarwin()) {
6151 // Darwin only has one model of TLS. Lower to that.
6152 unsigned char OpFlag = 0;
6153 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6154 X86ISD::WrapperRIP : X86ISD::Wrapper;
6156 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6158 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6159 !Subtarget->is64Bit();
6161 OpFlag = X86II::MO_TLVP_PIC_BASE;
6163 OpFlag = X86II::MO_TLVP;
6164 DebugLoc DL = Op.getDebugLoc();
6165 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6166 GA->getValueType(0),
6167 GA->getOffset(), OpFlag);
6168 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6170 // With PIC32, the address is actually $g + Offset.
6172 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6173 DAG.getNode(X86ISD::GlobalBaseReg,
6174 DebugLoc(), getPointerTy()),
6177 // Lowering the machine isd will make sure everything is in the right
6179 SDValue Chain = DAG.getEntryNode();
6180 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6181 SDValue Args[] = { Chain, Offset };
6182 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6184 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6185 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6186 MFI->setAdjustsStack(true);
6188 // And our return value (tls address) is in the standard call return value
6190 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6191 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6195 "TLS not implemented for this target.");
6197 llvm_unreachable("Unreachable");
6202 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6203 /// take a 2 x i32 value to shift plus a shift amount.
6204 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6205 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6206 EVT VT = Op.getValueType();
6207 unsigned VTBits = VT.getSizeInBits();
6208 DebugLoc dl = Op.getDebugLoc();
6209 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6210 SDValue ShOpLo = Op.getOperand(0);
6211 SDValue ShOpHi = Op.getOperand(1);
6212 SDValue ShAmt = Op.getOperand(2);
6213 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6214 DAG.getConstant(VTBits - 1, MVT::i8))
6215 : DAG.getConstant(0, VT);
6218 if (Op.getOpcode() == ISD::SHL_PARTS) {
6219 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6220 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6222 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6223 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6226 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6227 DAG.getConstant(VTBits, MVT::i8));
6228 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6229 AndNode, DAG.getConstant(0, MVT::i8));
6232 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6233 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6234 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6236 if (Op.getOpcode() == ISD::SHL_PARTS) {
6237 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6238 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6240 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6241 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6244 SDValue Ops[2] = { Lo, Hi };
6245 return DAG.getMergeValues(Ops, 2, dl);
6248 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6249 SelectionDAG &DAG) const {
6250 EVT SrcVT = Op.getOperand(0).getValueType();
6252 if (SrcVT.isVector())
6255 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6256 "Unknown SINT_TO_FP to lower!");
6258 // These are really Legal; return the operand so the caller accepts it as
6260 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6262 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6263 Subtarget->is64Bit()) {
6267 DebugLoc dl = Op.getDebugLoc();
6268 unsigned Size = SrcVT.getSizeInBits()/8;
6269 MachineFunction &MF = DAG.getMachineFunction();
6270 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6271 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6272 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6274 MachinePointerInfo::getFixedStack(SSFI),
6276 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6279 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6281 SelectionDAG &DAG) const {
6283 DebugLoc DL = Op.getDebugLoc();
6285 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6287 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6289 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6291 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6293 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6294 MachineMemOperand *MMO =
6295 DAG.getMachineFunction()
6296 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6297 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6299 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6300 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6302 Tys, Ops, array_lengthof(Ops),
6306 Chain = Result.getValue(1);
6307 SDValue InFlag = Result.getValue(2);
6309 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6310 // shouldn't be necessary except that RFP cannot be live across
6311 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6312 MachineFunction &MF = DAG.getMachineFunction();
6313 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6314 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6315 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6316 Tys = DAG.getVTList(MVT::Other);
6318 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6320 MachineMemOperand *MMO =
6321 DAG.getMachineFunction()
6322 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6323 MachineMemOperand::MOStore, SSFISize, SSFISize);
6325 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6326 Ops, array_lengthof(Ops),
6327 Op.getValueType(), MMO);
6328 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6329 MachinePointerInfo::getFixedStack(SSFI),
6336 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6337 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6338 SelectionDAG &DAG) const {
6339 // This algorithm is not obvious. Here it is in C code, more or less:
6341 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6342 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6343 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6345 // Copy ints to xmm registers.
6346 __m128i xh = _mm_cvtsi32_si128( hi );
6347 __m128i xl = _mm_cvtsi32_si128( lo );
6349 // Combine into low half of a single xmm register.
6350 __m128i x = _mm_unpacklo_epi32( xh, xl );
6354 // Merge in appropriate exponents to give the integer bits the right
6356 x = _mm_unpacklo_epi32( x, exp );
6358 // Subtract away the biases to deal with the IEEE-754 double precision
6360 d = _mm_sub_pd( (__m128d) x, bias );
6362 // All conversions up to here are exact. The correctly rounded result is
6363 // calculated using the current rounding mode using the following
6365 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6366 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6367 // store doesn't really need to be here (except
6368 // maybe to zero the other double)
6373 DebugLoc dl = Op.getDebugLoc();
6374 LLVMContext *Context = DAG.getContext();
6376 // Build some magic constants.
6377 std::vector<Constant*> CV0;
6378 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6379 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6380 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6381 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6382 Constant *C0 = ConstantVector::get(CV0);
6383 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6385 std::vector<Constant*> CV1;
6387 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6389 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6390 Constant *C1 = ConstantVector::get(CV1);
6391 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6393 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6394 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6396 DAG.getIntPtrConstant(1)));
6397 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6398 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6400 DAG.getIntPtrConstant(0)));
6401 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6402 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6403 MachinePointerInfo::getConstantPool(),
6405 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6406 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6407 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6408 MachinePointerInfo::getConstantPool(),
6410 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6412 // Add the halves; easiest way is to swap them into another reg first.
6413 int ShufMask[2] = { 1, -1 };
6414 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6415 DAG.getUNDEF(MVT::v2f64), ShufMask);
6416 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6417 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6418 DAG.getIntPtrConstant(0));
6421 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6422 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6423 SelectionDAG &DAG) const {
6424 DebugLoc dl = Op.getDebugLoc();
6425 // FP constant to bias correct the final result.
6426 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6429 // Load the 32-bit value into an XMM register.
6430 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6431 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6433 DAG.getIntPtrConstant(0)));
6435 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6436 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6437 DAG.getIntPtrConstant(0));
6439 // Or the load with the bias.
6440 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6441 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6442 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6444 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6445 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6446 MVT::v2f64, Bias)));
6447 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6448 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6449 DAG.getIntPtrConstant(0));
6451 // Subtract the bias.
6452 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6454 // Handle final rounding.
6455 EVT DestVT = Op.getValueType();
6457 if (DestVT.bitsLT(MVT::f64)) {
6458 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6459 DAG.getIntPtrConstant(0));
6460 } else if (DestVT.bitsGT(MVT::f64)) {
6461 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6464 // Handle final rounding.
6468 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6469 SelectionDAG &DAG) const {
6470 SDValue N0 = Op.getOperand(0);
6471 DebugLoc dl = Op.getDebugLoc();
6473 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6474 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6475 // the optimization here.
6476 if (DAG.SignBitIsZero(N0))
6477 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6479 EVT SrcVT = N0.getValueType();
6480 EVT DstVT = Op.getValueType();
6481 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6482 return LowerUINT_TO_FP_i64(Op, DAG);
6483 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6484 return LowerUINT_TO_FP_i32(Op, DAG);
6486 // Make a 64-bit buffer, and use it to build an FILD.
6487 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6488 if (SrcVT == MVT::i32) {
6489 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6490 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6491 getPointerTy(), StackSlot, WordOff);
6492 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6493 StackSlot, MachinePointerInfo(),
6495 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6496 OffsetSlot, MachinePointerInfo(),
6498 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6502 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6503 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6504 StackSlot, MachinePointerInfo(),
6506 // For i64 source, we need to add the appropriate power of 2 if the input
6507 // was negative. This is the same as the optimization in
6508 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6509 // we must be careful to do the computation in x87 extended precision, not
6510 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6511 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6512 MachineMemOperand *MMO =
6513 DAG.getMachineFunction()
6514 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6515 MachineMemOperand::MOLoad, 8, 8);
6517 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6518 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6519 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6522 APInt FF(32, 0x5F800000ULL);
6524 // Check whether the sign bit is set.
6525 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6526 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6529 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6530 SDValue FudgePtr = DAG.getConstantPool(
6531 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6534 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6535 SDValue Zero = DAG.getIntPtrConstant(0);
6536 SDValue Four = DAG.getIntPtrConstant(4);
6537 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6539 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6541 // Load the value out, extending it from f32 to f80.
6542 // FIXME: Avoid the extend by constructing the right constant pool?
6543 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6544 FudgePtr, MachinePointerInfo::getConstantPool(),
6545 MVT::f32, false, false, 4);
6546 // Extend everything to 80 bits to force it to be done on x87.
6547 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6548 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6551 std::pair<SDValue,SDValue> X86TargetLowering::
6552 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6553 DebugLoc DL = Op.getDebugLoc();
6555 EVT DstTy = Op.getValueType();
6558 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6562 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6563 DstTy.getSimpleVT() >= MVT::i16 &&
6564 "Unknown FP_TO_SINT to lower!");
6566 // These are really Legal.
6567 if (DstTy == MVT::i32 &&
6568 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6569 return std::make_pair(SDValue(), SDValue());
6570 if (Subtarget->is64Bit() &&
6571 DstTy == MVT::i64 &&
6572 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6573 return std::make_pair(SDValue(), SDValue());
6575 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6577 MachineFunction &MF = DAG.getMachineFunction();
6578 unsigned MemSize = DstTy.getSizeInBits()/8;
6579 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6580 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6585 switch (DstTy.getSimpleVT().SimpleTy) {
6586 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6587 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6588 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6589 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6592 SDValue Chain = DAG.getEntryNode();
6593 SDValue Value = Op.getOperand(0);
6594 EVT TheVT = Op.getOperand(0).getValueType();
6595 if (isScalarFPTypeInSSEReg(TheVT)) {
6596 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6597 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6598 MachinePointerInfo::getFixedStack(SSFI),
6600 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6602 Chain, StackSlot, DAG.getValueType(TheVT)
6605 MachineMemOperand *MMO =
6606 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6607 MachineMemOperand::MOLoad, MemSize, MemSize);
6608 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6610 Chain = Value.getValue(1);
6611 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6612 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6615 MachineMemOperand *MMO =
6616 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6617 MachineMemOperand::MOStore, MemSize, MemSize);
6619 // Build the FP_TO_INT*_IN_MEM
6620 SDValue Ops[] = { Chain, Value, StackSlot };
6621 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6622 Ops, 3, DstTy, MMO);
6624 return std::make_pair(FIST, StackSlot);
6627 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6628 SelectionDAG &DAG) const {
6629 if (Op.getValueType().isVector())
6632 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6633 SDValue FIST = Vals.first, StackSlot = Vals.second;
6634 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6635 if (FIST.getNode() == 0) return Op;
6638 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6639 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6642 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6643 SelectionDAG &DAG) const {
6644 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6645 SDValue FIST = Vals.first, StackSlot = Vals.second;
6646 assert(FIST.getNode() && "Unexpected failure");
6649 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6650 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6653 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6654 SelectionDAG &DAG) const {
6655 LLVMContext *Context = DAG.getContext();
6656 DebugLoc dl = Op.getDebugLoc();
6657 EVT VT = Op.getValueType();
6660 EltVT = VT.getVectorElementType();
6661 std::vector<Constant*> CV;
6662 if (EltVT == MVT::f64) {
6663 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6667 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6673 Constant *C = ConstantVector::get(CV);
6674 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6675 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6676 MachinePointerInfo::getConstantPool(),
6678 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6681 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6682 LLVMContext *Context = DAG.getContext();
6683 DebugLoc dl = Op.getDebugLoc();
6684 EVT VT = Op.getValueType();
6687 EltVT = VT.getVectorElementType();
6688 std::vector<Constant*> CV;
6689 if (EltVT == MVT::f64) {
6690 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6694 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6700 Constant *C = ConstantVector::get(CV);
6701 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6702 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6703 MachinePointerInfo::getConstantPool(),
6705 if (VT.isVector()) {
6706 return DAG.getNode(ISD::BITCAST, dl, VT,
6707 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6708 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6710 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6712 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6716 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6717 LLVMContext *Context = DAG.getContext();
6718 SDValue Op0 = Op.getOperand(0);
6719 SDValue Op1 = Op.getOperand(1);
6720 DebugLoc dl = Op.getDebugLoc();
6721 EVT VT = Op.getValueType();
6722 EVT SrcVT = Op1.getValueType();
6724 // If second operand is smaller, extend it first.
6725 if (SrcVT.bitsLT(VT)) {
6726 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6729 // And if it is bigger, shrink it first.
6730 if (SrcVT.bitsGT(VT)) {
6731 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6735 // At this point the operands and the result should have the same
6736 // type, and that won't be f80 since that is not custom lowered.
6738 // First get the sign bit of second operand.
6739 std::vector<Constant*> CV;
6740 if (SrcVT == MVT::f64) {
6741 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6742 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6744 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6745 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6746 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6747 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6749 Constant *C = ConstantVector::get(CV);
6750 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6751 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6752 MachinePointerInfo::getConstantPool(),
6754 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6756 // Shift sign bit right or left if the two operands have different types.
6757 if (SrcVT.bitsGT(VT)) {
6758 // Op0 is MVT::f32, Op1 is MVT::f64.
6759 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6760 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6761 DAG.getConstant(32, MVT::i32));
6762 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6763 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6764 DAG.getIntPtrConstant(0));
6767 // Clear first operand sign bit.
6769 if (VT == MVT::f64) {
6770 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6771 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6773 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6774 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6775 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6776 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6778 C = ConstantVector::get(CV);
6779 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6780 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6781 MachinePointerInfo::getConstantPool(),
6783 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6785 // Or the value with the sign bit.
6786 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6789 /// Emit nodes that will be selected as "test Op0,Op0", or something
6791 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6792 SelectionDAG &DAG) const {
6793 DebugLoc dl = Op.getDebugLoc();
6795 // CF and OF aren't always set the way we want. Determine which
6796 // of these we need.
6797 bool NeedCF = false;
6798 bool NeedOF = false;
6801 case X86::COND_A: case X86::COND_AE:
6802 case X86::COND_B: case X86::COND_BE:
6805 case X86::COND_G: case X86::COND_GE:
6806 case X86::COND_L: case X86::COND_LE:
6807 case X86::COND_O: case X86::COND_NO:
6812 // See if we can use the EFLAGS value from the operand instead of
6813 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6814 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6815 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6816 // Emit a CMP with 0, which is the TEST pattern.
6817 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6818 DAG.getConstant(0, Op.getValueType()));
6820 unsigned Opcode = 0;
6821 unsigned NumOperands = 0;
6822 switch (Op.getNode()->getOpcode()) {
6824 // Due to an isel shortcoming, be conservative if this add is likely to be
6825 // selected as part of a load-modify-store instruction. When the root node
6826 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6827 // uses of other nodes in the match, such as the ADD in this case. This
6828 // leads to the ADD being left around and reselected, with the result being
6829 // two adds in the output. Alas, even if none our users are stores, that
6830 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6831 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6832 // climbing the DAG back to the root, and it doesn't seem to be worth the
6834 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6835 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6836 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6839 if (ConstantSDNode *C =
6840 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6841 // An add of one will be selected as an INC.
6842 if (C->getAPIntValue() == 1) {
6843 Opcode = X86ISD::INC;
6848 // An add of negative one (subtract of one) will be selected as a DEC.
6849 if (C->getAPIntValue().isAllOnesValue()) {
6850 Opcode = X86ISD::DEC;
6856 // Otherwise use a regular EFLAGS-setting add.
6857 Opcode = X86ISD::ADD;
6861 // If the primary and result isn't used, don't bother using X86ISD::AND,
6862 // because a TEST instruction will be better.
6863 bool NonFlagUse = false;
6864 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6865 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6867 unsigned UOpNo = UI.getOperandNo();
6868 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6869 // Look pass truncate.
6870 UOpNo = User->use_begin().getOperandNo();
6871 User = *User->use_begin();
6874 if (User->getOpcode() != ISD::BRCOND &&
6875 User->getOpcode() != ISD::SETCC &&
6876 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6889 // Due to the ISEL shortcoming noted above, be conservative if this op is
6890 // likely to be selected as part of a load-modify-store instruction.
6891 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6892 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6893 if (UI->getOpcode() == ISD::STORE)
6896 // Otherwise use a regular EFLAGS-setting instruction.
6897 switch (Op.getNode()->getOpcode()) {
6898 default: llvm_unreachable("unexpected operator!");
6899 case ISD::SUB: Opcode = X86ISD::SUB; break;
6900 case ISD::OR: Opcode = X86ISD::OR; break;
6901 case ISD::XOR: Opcode = X86ISD::XOR; break;
6902 case ISD::AND: Opcode = X86ISD::AND; break;
6914 return SDValue(Op.getNode(), 1);
6921 // Emit a CMP with 0, which is the TEST pattern.
6922 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6923 DAG.getConstant(0, Op.getValueType()));
6925 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6926 SmallVector<SDValue, 4> Ops;
6927 for (unsigned i = 0; i != NumOperands; ++i)
6928 Ops.push_back(Op.getOperand(i));
6930 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6931 DAG.ReplaceAllUsesWith(Op, New);
6932 return SDValue(New.getNode(), 1);
6935 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6937 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6938 SelectionDAG &DAG) const {
6939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6940 if (C->getAPIntValue() == 0)
6941 return EmitTest(Op0, X86CC, DAG);
6943 DebugLoc dl = Op0.getDebugLoc();
6944 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6947 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6948 /// if it's possible.
6949 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6950 DebugLoc dl, SelectionDAG &DAG) const {
6951 SDValue Op0 = And.getOperand(0);
6952 SDValue Op1 = And.getOperand(1);
6953 if (Op0.getOpcode() == ISD::TRUNCATE)
6954 Op0 = Op0.getOperand(0);
6955 if (Op1.getOpcode() == ISD::TRUNCATE)
6956 Op1 = Op1.getOperand(0);
6959 if (Op1.getOpcode() == ISD::SHL)
6960 std::swap(Op0, Op1);
6961 if (Op0.getOpcode() == ISD::SHL) {
6962 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6963 if (And00C->getZExtValue() == 1) {
6964 // If we looked past a truncate, check that it's only truncating away
6966 unsigned BitWidth = Op0.getValueSizeInBits();
6967 unsigned AndBitWidth = And.getValueSizeInBits();
6968 if (BitWidth > AndBitWidth) {
6969 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6970 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6971 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6975 RHS = Op0.getOperand(1);
6977 } else if (Op1.getOpcode() == ISD::Constant) {
6978 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6979 SDValue AndLHS = Op0;
6980 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6981 LHS = AndLHS.getOperand(0);
6982 RHS = AndLHS.getOperand(1);
6986 if (LHS.getNode()) {
6987 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6988 // instruction. Since the shift amount is in-range-or-undefined, we know
6989 // that doing a bittest on the i32 value is ok. We extend to i32 because
6990 // the encoding for the i16 version is larger than the i32 version.
6991 // Also promote i16 to i32 for performance / code size reason.
6992 if (LHS.getValueType() == MVT::i8 ||
6993 LHS.getValueType() == MVT::i16)
6994 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6996 // If the operand types disagree, extend the shift amount to match. Since
6997 // BT ignores high bits (like shifts) we can use anyextend.
6998 if (LHS.getValueType() != RHS.getValueType())
6999 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7001 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7002 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7003 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7004 DAG.getConstant(Cond, MVT::i8), BT);
7010 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7011 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7012 SDValue Op0 = Op.getOperand(0);
7013 SDValue Op1 = Op.getOperand(1);
7014 DebugLoc dl = Op.getDebugLoc();
7015 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7017 // Optimize to BT if possible.
7018 // Lower (X & (1 << N)) == 0 to BT(X, N).
7019 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7020 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7021 if (Op0.getOpcode() == ISD::AND &&
7023 Op1.getOpcode() == ISD::Constant &&
7024 cast<ConstantSDNode>(Op1)->isNullValue() &&
7025 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7026 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7027 if (NewSetCC.getNode())
7031 // Look for "(setcc) == / != 1" to avoid unnecessary setcc.
7032 if (Op0.getOpcode() == X86ISD::SETCC &&
7033 Op1.getOpcode() == ISD::Constant &&
7034 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7035 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7036 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7037 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7038 bool Invert = (CC == ISD::SETNE) ^
7039 cast<ConstantSDNode>(Op1)->isNullValue();
7041 CCode = X86::GetOppositeBranchCondition(CCode);
7042 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7043 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7046 bool isFP = Op1.getValueType().isFloatingPoint();
7047 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7048 if (X86CC == X86::COND_INVALID)
7051 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7053 // Use sbb x, x to materialize carry bit into a GPR.
7054 if (X86CC == X86::COND_B)
7055 return DAG.getNode(ISD::AND, dl, MVT::i8,
7056 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7057 DAG.getConstant(X86CC, MVT::i8), Cond),
7058 DAG.getConstant(1, MVT::i8));
7060 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7061 DAG.getConstant(X86CC, MVT::i8), Cond);
7064 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7066 SDValue Op0 = Op.getOperand(0);
7067 SDValue Op1 = Op.getOperand(1);
7068 SDValue CC = Op.getOperand(2);
7069 EVT VT = Op.getValueType();
7070 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7071 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7072 DebugLoc dl = Op.getDebugLoc();
7076 EVT VT0 = Op0.getValueType();
7077 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7078 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7081 switch (SetCCOpcode) {
7084 case ISD::SETEQ: SSECC = 0; break;
7086 case ISD::SETGT: Swap = true; // Fallthrough
7088 case ISD::SETOLT: SSECC = 1; break;
7090 case ISD::SETGE: Swap = true; // Fallthrough
7092 case ISD::SETOLE: SSECC = 2; break;
7093 case ISD::SETUO: SSECC = 3; break;
7095 case ISD::SETNE: SSECC = 4; break;
7096 case ISD::SETULE: Swap = true;
7097 case ISD::SETUGE: SSECC = 5; break;
7098 case ISD::SETULT: Swap = true;
7099 case ISD::SETUGT: SSECC = 6; break;
7100 case ISD::SETO: SSECC = 7; break;
7103 std::swap(Op0, Op1);
7105 // In the two special cases we can't handle, emit two comparisons.
7107 if (SetCCOpcode == ISD::SETUEQ) {
7109 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7110 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7111 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7113 else if (SetCCOpcode == ISD::SETONE) {
7115 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7116 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7117 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7119 llvm_unreachable("Illegal FP comparison");
7121 // Handle all other FP comparisons here.
7122 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7125 // We are handling one of the integer comparisons here. Since SSE only has
7126 // GT and EQ comparisons for integer, swapping operands and multiple
7127 // operations may be required for some comparisons.
7128 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7129 bool Swap = false, Invert = false, FlipSigns = false;
7131 switch (VT.getSimpleVT().SimpleTy) {
7133 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7134 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7135 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7136 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7139 switch (SetCCOpcode) {
7141 case ISD::SETNE: Invert = true;
7142 case ISD::SETEQ: Opc = EQOpc; break;
7143 case ISD::SETLT: Swap = true;
7144 case ISD::SETGT: Opc = GTOpc; break;
7145 case ISD::SETGE: Swap = true;
7146 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7147 case ISD::SETULT: Swap = true;
7148 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7149 case ISD::SETUGE: Swap = true;
7150 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7153 std::swap(Op0, Op1);
7155 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7156 // bits of the inputs before performing those operations.
7158 EVT EltVT = VT.getVectorElementType();
7159 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7161 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7162 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7164 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7165 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7168 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7170 // If the logical-not of the result is required, perform that now.
7172 Result = DAG.getNOT(dl, Result, VT);
7177 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7178 static bool isX86LogicalCmp(SDValue Op) {
7179 unsigned Opc = Op.getNode()->getOpcode();
7180 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7182 if (Op.getResNo() == 1 &&
7183 (Opc == X86ISD::ADD ||
7184 Opc == X86ISD::SUB ||
7185 Opc == X86ISD::SMUL ||
7186 Opc == X86ISD::UMUL ||
7187 Opc == X86ISD::INC ||
7188 Opc == X86ISD::DEC ||
7189 Opc == X86ISD::OR ||
7190 Opc == X86ISD::XOR ||
7191 Opc == X86ISD::AND))
7194 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7200 static bool isZero(SDValue V) {
7201 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7202 return C && C->isNullValue();
7205 static bool isAllOnes(SDValue V) {
7206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7207 return C && C->isAllOnesValue();
7210 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7211 bool addTest = true;
7212 SDValue Cond = Op.getOperand(0);
7213 SDValue Op1 = Op.getOperand(1);
7214 SDValue Op2 = Op.getOperand(2);
7215 DebugLoc DL = Op.getDebugLoc();
7218 if (Cond.getOpcode() == ISD::SETCC) {
7219 SDValue NewCond = LowerSETCC(Cond, DAG);
7220 if (NewCond.getNode())
7224 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7225 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7226 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7227 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7228 if (Cond.getOpcode() == X86ISD::SETCC &&
7229 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7230 isZero(Cond.getOperand(1).getOperand(1))) {
7231 SDValue Cmp = Cond.getOperand(1);
7233 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7235 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7236 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7237 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7239 SDValue CmpOp0 = Cmp.getOperand(0);
7240 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7241 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7243 SDValue Res = // Res = 0 or -1.
7244 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7245 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7247 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7248 Res = DAG.getNOT(DL, Res, Res.getValueType());
7250 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7251 if (N2C == 0 || !N2C->isNullValue())
7252 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7257 // Look past (and (setcc_carry (cmp ...)), 1).
7258 if (Cond.getOpcode() == ISD::AND &&
7259 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7260 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7261 if (C && C->getAPIntValue() == 1)
7262 Cond = Cond.getOperand(0);
7265 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7266 // setting operand in place of the X86ISD::SETCC.
7267 if (Cond.getOpcode() == X86ISD::SETCC ||
7268 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7269 CC = Cond.getOperand(0);
7271 SDValue Cmp = Cond.getOperand(1);
7272 unsigned Opc = Cmp.getOpcode();
7273 EVT VT = Op.getValueType();
7275 bool IllegalFPCMov = false;
7276 if (VT.isFloatingPoint() && !VT.isVector() &&
7277 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7278 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7280 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7281 Opc == X86ISD::BT) { // FIXME
7288 // Look pass the truncate.
7289 if (Cond.getOpcode() == ISD::TRUNCATE)
7290 Cond = Cond.getOperand(0);
7292 // We know the result of AND is compared against zero. Try to match
7294 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7295 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7296 if (NewSetCC.getNode()) {
7297 CC = NewSetCC.getOperand(0);
7298 Cond = NewSetCC.getOperand(1);
7305 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7306 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7309 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7310 // condition is true.
7311 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7312 SDValue Ops[] = { Op2, Op1, CC, Cond };
7313 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7316 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7317 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7318 // from the AND / OR.
7319 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7320 Opc = Op.getOpcode();
7321 if (Opc != ISD::OR && Opc != ISD::AND)
7323 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7324 Op.getOperand(0).hasOneUse() &&
7325 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7326 Op.getOperand(1).hasOneUse());
7329 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7330 // 1 and that the SETCC node has a single use.
7331 static bool isXor1OfSetCC(SDValue Op) {
7332 if (Op.getOpcode() != ISD::XOR)
7334 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7335 if (N1C && N1C->getAPIntValue() == 1) {
7336 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7337 Op.getOperand(0).hasOneUse();
7342 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7343 bool addTest = true;
7344 SDValue Chain = Op.getOperand(0);
7345 SDValue Cond = Op.getOperand(1);
7346 SDValue Dest = Op.getOperand(2);
7347 DebugLoc dl = Op.getDebugLoc();
7350 if (Cond.getOpcode() == ISD::SETCC) {
7351 SDValue NewCond = LowerSETCC(Cond, DAG);
7352 if (NewCond.getNode())
7356 // FIXME: LowerXALUO doesn't handle these!!
7357 else if (Cond.getOpcode() == X86ISD::ADD ||
7358 Cond.getOpcode() == X86ISD::SUB ||
7359 Cond.getOpcode() == X86ISD::SMUL ||
7360 Cond.getOpcode() == X86ISD::UMUL)
7361 Cond = LowerXALUO(Cond, DAG);
7364 // Look pass (and (setcc_carry (cmp ...)), 1).
7365 if (Cond.getOpcode() == ISD::AND &&
7366 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7368 if (C && C->getAPIntValue() == 1)
7369 Cond = Cond.getOperand(0);
7372 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7373 // setting operand in place of the X86ISD::SETCC.
7374 if (Cond.getOpcode() == X86ISD::SETCC ||
7375 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7376 CC = Cond.getOperand(0);
7378 SDValue Cmp = Cond.getOperand(1);
7379 unsigned Opc = Cmp.getOpcode();
7380 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7381 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7385 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7389 // These can only come from an arithmetic instruction with overflow,
7390 // e.g. SADDO, UADDO.
7391 Cond = Cond.getNode()->getOperand(1);
7398 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7399 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7400 if (CondOpc == ISD::OR) {
7401 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7402 // two branches instead of an explicit OR instruction with a
7404 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7405 isX86LogicalCmp(Cmp)) {
7406 CC = Cond.getOperand(0).getOperand(0);
7407 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7408 Chain, Dest, CC, Cmp);
7409 CC = Cond.getOperand(1).getOperand(0);
7413 } else { // ISD::AND
7414 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7415 // two branches instead of an explicit AND instruction with a
7416 // separate test. However, we only do this if this block doesn't
7417 // have a fall-through edge, because this requires an explicit
7418 // jmp when the condition is false.
7419 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7420 isX86LogicalCmp(Cmp) &&
7421 Op.getNode()->hasOneUse()) {
7422 X86::CondCode CCode =
7423 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7424 CCode = X86::GetOppositeBranchCondition(CCode);
7425 CC = DAG.getConstant(CCode, MVT::i8);
7426 SDNode *User = *Op.getNode()->use_begin();
7427 // Look for an unconditional branch following this conditional branch.
7428 // We need this because we need to reverse the successors in order
7429 // to implement FCMP_OEQ.
7430 if (User->getOpcode() == ISD::BR) {
7431 SDValue FalseBB = User->getOperand(1);
7433 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7434 assert(NewBR == User);
7438 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7439 Chain, Dest, CC, Cmp);
7440 X86::CondCode CCode =
7441 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7442 CCode = X86::GetOppositeBranchCondition(CCode);
7443 CC = DAG.getConstant(CCode, MVT::i8);
7449 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7450 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7451 // It should be transformed during dag combiner except when the condition
7452 // is set by a arithmetics with overflow node.
7453 X86::CondCode CCode =
7454 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7455 CCode = X86::GetOppositeBranchCondition(CCode);
7456 CC = DAG.getConstant(CCode, MVT::i8);
7457 Cond = Cond.getOperand(0).getOperand(1);
7463 // Look pass the truncate.
7464 if (Cond.getOpcode() == ISD::TRUNCATE)
7465 Cond = Cond.getOperand(0);
7467 // We know the result of AND is compared against zero. Try to match
7469 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7470 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7471 if (NewSetCC.getNode()) {
7472 CC = NewSetCC.getOperand(0);
7473 Cond = NewSetCC.getOperand(1);
7480 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7481 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7483 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7484 Chain, Dest, CC, Cond);
7488 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7489 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7490 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7491 // that the guard pages used by the OS virtual memory manager are allocated in
7492 // correct sequence.
7494 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7495 SelectionDAG &DAG) const {
7496 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7497 "This should be used only on Windows targets");
7498 DebugLoc dl = Op.getDebugLoc();
7501 SDValue Chain = Op.getOperand(0);
7502 SDValue Size = Op.getOperand(1);
7503 // FIXME: Ensure alignment here
7507 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7509 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7510 Flag = Chain.getValue(1);
7512 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7514 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7515 Flag = Chain.getValue(1);
7517 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7519 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7520 return DAG.getMergeValues(Ops1, 2, dl);
7523 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7524 MachineFunction &MF = DAG.getMachineFunction();
7525 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7527 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7528 DebugLoc DL = Op.getDebugLoc();
7530 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7531 // vastart just stores the address of the VarArgsFrameIndex slot into the
7532 // memory location argument.
7533 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7535 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7536 MachinePointerInfo(SV), false, false, 0);
7540 // gp_offset (0 - 6 * 8)
7541 // fp_offset (48 - 48 + 8 * 16)
7542 // overflow_arg_area (point to parameters coming in memory).
7544 SmallVector<SDValue, 8> MemOps;
7545 SDValue FIN = Op.getOperand(1);
7547 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7548 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7550 FIN, MachinePointerInfo(SV), false, false, 0);
7551 MemOps.push_back(Store);
7554 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7555 FIN, DAG.getIntPtrConstant(4));
7556 Store = DAG.getStore(Op.getOperand(0), DL,
7557 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7559 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7560 MemOps.push_back(Store);
7562 // Store ptr to overflow_arg_area
7563 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7564 FIN, DAG.getIntPtrConstant(4));
7565 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7567 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7568 MachinePointerInfo(SV, 8),
7570 MemOps.push_back(Store);
7572 // Store ptr to reg_save_area.
7573 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7574 FIN, DAG.getIntPtrConstant(8));
7575 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7577 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7578 MachinePointerInfo(SV, 16), false, false, 0);
7579 MemOps.push_back(Store);
7580 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7581 &MemOps[0], MemOps.size());
7584 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7585 assert(Subtarget->is64Bit() &&
7586 "LowerVAARG only handles 64-bit va_arg!");
7587 assert((Subtarget->isTargetLinux() ||
7588 Subtarget->isTargetDarwin()) &&
7589 "Unhandled target in LowerVAARG");
7590 assert(Op.getNode()->getNumOperands() == 4);
7591 SDValue Chain = Op.getOperand(0);
7592 SDValue SrcPtr = Op.getOperand(1);
7593 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7594 unsigned Align = Op.getConstantOperandVal(3);
7595 DebugLoc dl = Op.getDebugLoc();
7597 EVT ArgVT = Op.getNode()->getValueType(0);
7598 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7599 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7602 // Decide which area this value should be read from.
7603 // TODO: Implement the AMD64 ABI in its entirety. This simple
7604 // selection mechanism works only for the basic types.
7605 if (ArgVT == MVT::f80) {
7606 llvm_unreachable("va_arg for f80 not yet implemented");
7607 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7608 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7609 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7610 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7612 llvm_unreachable("Unhandled argument type in LowerVAARG");
7616 // Sanity Check: Make sure using fp_offset makes sense.
7617 assert(!UseSoftFloat &&
7618 !(DAG.getMachineFunction()
7619 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7620 Subtarget->hasXMM());
7623 // Insert VAARG_64 node into the DAG
7624 // VAARG_64 returns two values: Variable Argument Address, Chain
7625 SmallVector<SDValue, 11> InstOps;
7626 InstOps.push_back(Chain);
7627 InstOps.push_back(SrcPtr);
7628 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7629 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7630 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7631 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7632 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7633 VTs, &InstOps[0], InstOps.size(),
7635 MachinePointerInfo(SV),
7640 Chain = VAARG.getValue(1);
7642 // Load the next argument and return it
7643 return DAG.getLoad(ArgVT, dl,
7646 MachinePointerInfo(),
7650 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7651 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7652 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7653 SDValue Chain = Op.getOperand(0);
7654 SDValue DstPtr = Op.getOperand(1);
7655 SDValue SrcPtr = Op.getOperand(2);
7656 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7657 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7658 DebugLoc DL = Op.getDebugLoc();
7660 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7661 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7663 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7667 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7668 DebugLoc dl = Op.getDebugLoc();
7669 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7671 default: return SDValue(); // Don't custom lower most intrinsics.
7672 // Comparison intrinsics.
7673 case Intrinsic::x86_sse_comieq_ss:
7674 case Intrinsic::x86_sse_comilt_ss:
7675 case Intrinsic::x86_sse_comile_ss:
7676 case Intrinsic::x86_sse_comigt_ss:
7677 case Intrinsic::x86_sse_comige_ss:
7678 case Intrinsic::x86_sse_comineq_ss:
7679 case Intrinsic::x86_sse_ucomieq_ss:
7680 case Intrinsic::x86_sse_ucomilt_ss:
7681 case Intrinsic::x86_sse_ucomile_ss:
7682 case Intrinsic::x86_sse_ucomigt_ss:
7683 case Intrinsic::x86_sse_ucomige_ss:
7684 case Intrinsic::x86_sse_ucomineq_ss:
7685 case Intrinsic::x86_sse2_comieq_sd:
7686 case Intrinsic::x86_sse2_comilt_sd:
7687 case Intrinsic::x86_sse2_comile_sd:
7688 case Intrinsic::x86_sse2_comigt_sd:
7689 case Intrinsic::x86_sse2_comige_sd:
7690 case Intrinsic::x86_sse2_comineq_sd:
7691 case Intrinsic::x86_sse2_ucomieq_sd:
7692 case Intrinsic::x86_sse2_ucomilt_sd:
7693 case Intrinsic::x86_sse2_ucomile_sd:
7694 case Intrinsic::x86_sse2_ucomigt_sd:
7695 case Intrinsic::x86_sse2_ucomige_sd:
7696 case Intrinsic::x86_sse2_ucomineq_sd: {
7698 ISD::CondCode CC = ISD::SETCC_INVALID;
7701 case Intrinsic::x86_sse_comieq_ss:
7702 case Intrinsic::x86_sse2_comieq_sd:
7706 case Intrinsic::x86_sse_comilt_ss:
7707 case Intrinsic::x86_sse2_comilt_sd:
7711 case Intrinsic::x86_sse_comile_ss:
7712 case Intrinsic::x86_sse2_comile_sd:
7716 case Intrinsic::x86_sse_comigt_ss:
7717 case Intrinsic::x86_sse2_comigt_sd:
7721 case Intrinsic::x86_sse_comige_ss:
7722 case Intrinsic::x86_sse2_comige_sd:
7726 case Intrinsic::x86_sse_comineq_ss:
7727 case Intrinsic::x86_sse2_comineq_sd:
7731 case Intrinsic::x86_sse_ucomieq_ss:
7732 case Intrinsic::x86_sse2_ucomieq_sd:
7733 Opc = X86ISD::UCOMI;
7736 case Intrinsic::x86_sse_ucomilt_ss:
7737 case Intrinsic::x86_sse2_ucomilt_sd:
7738 Opc = X86ISD::UCOMI;
7741 case Intrinsic::x86_sse_ucomile_ss:
7742 case Intrinsic::x86_sse2_ucomile_sd:
7743 Opc = X86ISD::UCOMI;
7746 case Intrinsic::x86_sse_ucomigt_ss:
7747 case Intrinsic::x86_sse2_ucomigt_sd:
7748 Opc = X86ISD::UCOMI;
7751 case Intrinsic::x86_sse_ucomige_ss:
7752 case Intrinsic::x86_sse2_ucomige_sd:
7753 Opc = X86ISD::UCOMI;
7756 case Intrinsic::x86_sse_ucomineq_ss:
7757 case Intrinsic::x86_sse2_ucomineq_sd:
7758 Opc = X86ISD::UCOMI;
7763 SDValue LHS = Op.getOperand(1);
7764 SDValue RHS = Op.getOperand(2);
7765 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7766 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7767 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7768 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7769 DAG.getConstant(X86CC, MVT::i8), Cond);
7770 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7772 // ptest and testp intrinsics. The intrinsic these come from are designed to
7773 // return an integer value, not just an instruction so lower it to the ptest
7774 // or testp pattern and a setcc for the result.
7775 case Intrinsic::x86_sse41_ptestz:
7776 case Intrinsic::x86_sse41_ptestc:
7777 case Intrinsic::x86_sse41_ptestnzc:
7778 case Intrinsic::x86_avx_ptestz_256:
7779 case Intrinsic::x86_avx_ptestc_256:
7780 case Intrinsic::x86_avx_ptestnzc_256:
7781 case Intrinsic::x86_avx_vtestz_ps:
7782 case Intrinsic::x86_avx_vtestc_ps:
7783 case Intrinsic::x86_avx_vtestnzc_ps:
7784 case Intrinsic::x86_avx_vtestz_pd:
7785 case Intrinsic::x86_avx_vtestc_pd:
7786 case Intrinsic::x86_avx_vtestnzc_pd:
7787 case Intrinsic::x86_avx_vtestz_ps_256:
7788 case Intrinsic::x86_avx_vtestc_ps_256:
7789 case Intrinsic::x86_avx_vtestnzc_ps_256:
7790 case Intrinsic::x86_avx_vtestz_pd_256:
7791 case Intrinsic::x86_avx_vtestc_pd_256:
7792 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7793 bool IsTestPacked = false;
7796 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7797 case Intrinsic::x86_avx_vtestz_ps:
7798 case Intrinsic::x86_avx_vtestz_pd:
7799 case Intrinsic::x86_avx_vtestz_ps_256:
7800 case Intrinsic::x86_avx_vtestz_pd_256:
7801 IsTestPacked = true; // Fallthrough
7802 case Intrinsic::x86_sse41_ptestz:
7803 case Intrinsic::x86_avx_ptestz_256:
7805 X86CC = X86::COND_E;
7807 case Intrinsic::x86_avx_vtestc_ps:
7808 case Intrinsic::x86_avx_vtestc_pd:
7809 case Intrinsic::x86_avx_vtestc_ps_256:
7810 case Intrinsic::x86_avx_vtestc_pd_256:
7811 IsTestPacked = true; // Fallthrough
7812 case Intrinsic::x86_sse41_ptestc:
7813 case Intrinsic::x86_avx_ptestc_256:
7815 X86CC = X86::COND_B;
7817 case Intrinsic::x86_avx_vtestnzc_ps:
7818 case Intrinsic::x86_avx_vtestnzc_pd:
7819 case Intrinsic::x86_avx_vtestnzc_ps_256:
7820 case Intrinsic::x86_avx_vtestnzc_pd_256:
7821 IsTestPacked = true; // Fallthrough
7822 case Intrinsic::x86_sse41_ptestnzc:
7823 case Intrinsic::x86_avx_ptestnzc_256:
7825 X86CC = X86::COND_A;
7829 SDValue LHS = Op.getOperand(1);
7830 SDValue RHS = Op.getOperand(2);
7831 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7832 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7833 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7834 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7835 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7838 // Fix vector shift instructions where the last operand is a non-immediate
7840 case Intrinsic::x86_sse2_pslli_w:
7841 case Intrinsic::x86_sse2_pslli_d:
7842 case Intrinsic::x86_sse2_pslli_q:
7843 case Intrinsic::x86_sse2_psrli_w:
7844 case Intrinsic::x86_sse2_psrli_d:
7845 case Intrinsic::x86_sse2_psrli_q:
7846 case Intrinsic::x86_sse2_psrai_w:
7847 case Intrinsic::x86_sse2_psrai_d:
7848 case Intrinsic::x86_mmx_pslli_w:
7849 case Intrinsic::x86_mmx_pslli_d:
7850 case Intrinsic::x86_mmx_pslli_q:
7851 case Intrinsic::x86_mmx_psrli_w:
7852 case Intrinsic::x86_mmx_psrli_d:
7853 case Intrinsic::x86_mmx_psrli_q:
7854 case Intrinsic::x86_mmx_psrai_w:
7855 case Intrinsic::x86_mmx_psrai_d: {
7856 SDValue ShAmt = Op.getOperand(2);
7857 if (isa<ConstantSDNode>(ShAmt))
7860 unsigned NewIntNo = 0;
7861 EVT ShAmtVT = MVT::v4i32;
7863 case Intrinsic::x86_sse2_pslli_w:
7864 NewIntNo = Intrinsic::x86_sse2_psll_w;
7866 case Intrinsic::x86_sse2_pslli_d:
7867 NewIntNo = Intrinsic::x86_sse2_psll_d;
7869 case Intrinsic::x86_sse2_pslli_q:
7870 NewIntNo = Intrinsic::x86_sse2_psll_q;
7872 case Intrinsic::x86_sse2_psrli_w:
7873 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7875 case Intrinsic::x86_sse2_psrli_d:
7876 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7878 case Intrinsic::x86_sse2_psrli_q:
7879 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7881 case Intrinsic::x86_sse2_psrai_w:
7882 NewIntNo = Intrinsic::x86_sse2_psra_w;
7884 case Intrinsic::x86_sse2_psrai_d:
7885 NewIntNo = Intrinsic::x86_sse2_psra_d;
7888 ShAmtVT = MVT::v2i32;
7890 case Intrinsic::x86_mmx_pslli_w:
7891 NewIntNo = Intrinsic::x86_mmx_psll_w;
7893 case Intrinsic::x86_mmx_pslli_d:
7894 NewIntNo = Intrinsic::x86_mmx_psll_d;
7896 case Intrinsic::x86_mmx_pslli_q:
7897 NewIntNo = Intrinsic::x86_mmx_psll_q;
7899 case Intrinsic::x86_mmx_psrli_w:
7900 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7902 case Intrinsic::x86_mmx_psrli_d:
7903 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7905 case Intrinsic::x86_mmx_psrli_q:
7906 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7908 case Intrinsic::x86_mmx_psrai_w:
7909 NewIntNo = Intrinsic::x86_mmx_psra_w;
7911 case Intrinsic::x86_mmx_psrai_d:
7912 NewIntNo = Intrinsic::x86_mmx_psra_d;
7914 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7920 // The vector shift intrinsics with scalars uses 32b shift amounts but
7921 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7925 ShOps[1] = DAG.getConstant(0, MVT::i32);
7926 if (ShAmtVT == MVT::v4i32) {
7927 ShOps[2] = DAG.getUNDEF(MVT::i32);
7928 ShOps[3] = DAG.getUNDEF(MVT::i32);
7929 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7931 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7932 // FIXME this must be lowered to get rid of the invalid type.
7935 EVT VT = Op.getValueType();
7936 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7937 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7938 DAG.getConstant(NewIntNo, MVT::i32),
7939 Op.getOperand(1), ShAmt);
7944 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7945 SelectionDAG &DAG) const {
7946 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7947 MFI->setReturnAddressIsTaken(true);
7949 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7950 DebugLoc dl = Op.getDebugLoc();
7953 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7955 DAG.getConstant(TD->getPointerSize(),
7956 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7957 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7958 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7960 MachinePointerInfo(), false, false, 0);
7963 // Just load the return address.
7964 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7965 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7966 RetAddrFI, MachinePointerInfo(), false, false, 0);
7969 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7970 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7971 MFI->setFrameAddressIsTaken(true);
7973 EVT VT = Op.getValueType();
7974 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7975 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7976 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7977 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7979 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7980 MachinePointerInfo(),
7985 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7986 SelectionDAG &DAG) const {
7987 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7990 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7991 MachineFunction &MF = DAG.getMachineFunction();
7992 SDValue Chain = Op.getOperand(0);
7993 SDValue Offset = Op.getOperand(1);
7994 SDValue Handler = Op.getOperand(2);
7995 DebugLoc dl = Op.getDebugLoc();
7997 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7998 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8000 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8002 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8003 DAG.getIntPtrConstant(TD->getPointerSize()));
8004 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8005 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8007 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8008 MF.getRegInfo().addLiveOut(StoreAddrReg);
8010 return DAG.getNode(X86ISD::EH_RETURN, dl,
8012 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8015 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8016 SelectionDAG &DAG) const {
8017 SDValue Root = Op.getOperand(0);
8018 SDValue Trmp = Op.getOperand(1); // trampoline
8019 SDValue FPtr = Op.getOperand(2); // nested function
8020 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8021 DebugLoc dl = Op.getDebugLoc();
8023 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8025 if (Subtarget->is64Bit()) {
8026 SDValue OutChains[6];
8028 // Large code-model.
8029 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8030 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8032 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8033 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8035 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8037 // Load the pointer to the nested function into R11.
8038 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8039 SDValue Addr = Trmp;
8040 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8041 Addr, MachinePointerInfo(TrmpAddr),
8044 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8045 DAG.getConstant(2, MVT::i64));
8046 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8047 MachinePointerInfo(TrmpAddr, 2),
8050 // Load the 'nest' parameter value into R10.
8051 // R10 is specified in X86CallingConv.td
8052 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8053 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8054 DAG.getConstant(10, MVT::i64));
8055 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8056 Addr, MachinePointerInfo(TrmpAddr, 10),
8059 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8060 DAG.getConstant(12, MVT::i64));
8061 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8062 MachinePointerInfo(TrmpAddr, 12),
8065 // Jump to the nested function.
8066 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8067 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8068 DAG.getConstant(20, MVT::i64));
8069 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8070 Addr, MachinePointerInfo(TrmpAddr, 20),
8073 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8075 DAG.getConstant(22, MVT::i64));
8076 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8077 MachinePointerInfo(TrmpAddr, 22),
8081 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8082 return DAG.getMergeValues(Ops, 2, dl);
8084 const Function *Func =
8085 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8086 CallingConv::ID CC = Func->getCallingConv();
8091 llvm_unreachable("Unsupported calling convention");
8092 case CallingConv::C:
8093 case CallingConv::X86_StdCall: {
8094 // Pass 'nest' parameter in ECX.
8095 // Must be kept in sync with X86CallingConv.td
8098 // Check that ECX wasn't needed by an 'inreg' parameter.
8099 const FunctionType *FTy = Func->getFunctionType();
8100 const AttrListPtr &Attrs = Func->getAttributes();
8102 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8103 unsigned InRegCount = 0;
8106 for (FunctionType::param_iterator I = FTy->param_begin(),
8107 E = FTy->param_end(); I != E; ++I, ++Idx)
8108 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8109 // FIXME: should only count parameters that are lowered to integers.
8110 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8112 if (InRegCount > 2) {
8113 report_fatal_error("Nest register in use - reduce number of inreg"
8119 case CallingConv::X86_FastCall:
8120 case CallingConv::X86_ThisCall:
8121 case CallingConv::Fast:
8122 // Pass 'nest' parameter in EAX.
8123 // Must be kept in sync with X86CallingConv.td
8128 SDValue OutChains[4];
8131 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8132 DAG.getConstant(10, MVT::i32));
8133 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8135 // This is storing the opcode for MOV32ri.
8136 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8137 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8138 OutChains[0] = DAG.getStore(Root, dl,
8139 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8140 Trmp, MachinePointerInfo(TrmpAddr),
8143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8144 DAG.getConstant(1, MVT::i32));
8145 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8146 MachinePointerInfo(TrmpAddr, 1),
8149 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8150 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8151 DAG.getConstant(5, MVT::i32));
8152 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8153 MachinePointerInfo(TrmpAddr, 5),
8156 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8157 DAG.getConstant(6, MVT::i32));
8158 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8159 MachinePointerInfo(TrmpAddr, 6),
8163 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8164 return DAG.getMergeValues(Ops, 2, dl);
8168 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8169 SelectionDAG &DAG) const {
8171 The rounding mode is in bits 11:10 of FPSR, and has the following
8178 FLT_ROUNDS, on the other hand, expects the following:
8185 To perform the conversion, we do:
8186 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8189 MachineFunction &MF = DAG.getMachineFunction();
8190 const TargetMachine &TM = MF.getTarget();
8191 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8192 unsigned StackAlignment = TFI.getStackAlignment();
8193 EVT VT = Op.getValueType();
8194 DebugLoc DL = Op.getDebugLoc();
8196 // Save FP Control Word to stack slot
8197 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8198 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8201 MachineMemOperand *MMO =
8202 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8203 MachineMemOperand::MOStore, 2, 2);
8205 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8206 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8207 DAG.getVTList(MVT::Other),
8208 Ops, 2, MVT::i16, MMO);
8210 // Load FP Control Word from stack slot
8211 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8212 MachinePointerInfo(), false, false, 0);
8214 // Transform as necessary
8216 DAG.getNode(ISD::SRL, DL, MVT::i16,
8217 DAG.getNode(ISD::AND, DL, MVT::i16,
8218 CWD, DAG.getConstant(0x800, MVT::i16)),
8219 DAG.getConstant(11, MVT::i8));
8221 DAG.getNode(ISD::SRL, DL, MVT::i16,
8222 DAG.getNode(ISD::AND, DL, MVT::i16,
8223 CWD, DAG.getConstant(0x400, MVT::i16)),
8224 DAG.getConstant(9, MVT::i8));
8227 DAG.getNode(ISD::AND, DL, MVT::i16,
8228 DAG.getNode(ISD::ADD, DL, MVT::i16,
8229 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8230 DAG.getConstant(1, MVT::i16)),
8231 DAG.getConstant(3, MVT::i16));
8234 return DAG.getNode((VT.getSizeInBits() < 16 ?
8235 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8238 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8239 EVT VT = Op.getValueType();
8241 unsigned NumBits = VT.getSizeInBits();
8242 DebugLoc dl = Op.getDebugLoc();
8244 Op = Op.getOperand(0);
8245 if (VT == MVT::i8) {
8246 // Zero extend to i32 since there is not an i8 bsr.
8248 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8251 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8252 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8253 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8255 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8258 DAG.getConstant(NumBits+NumBits-1, OpVT),
8259 DAG.getConstant(X86::COND_E, MVT::i8),
8262 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8264 // Finally xor with NumBits-1.
8265 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8268 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8272 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8273 EVT VT = Op.getValueType();
8275 unsigned NumBits = VT.getSizeInBits();
8276 DebugLoc dl = Op.getDebugLoc();
8278 Op = Op.getOperand(0);
8279 if (VT == MVT::i8) {
8281 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8284 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8285 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8286 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8288 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8291 DAG.getConstant(NumBits, OpVT),
8292 DAG.getConstant(X86::COND_E, MVT::i8),
8295 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8298 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8302 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8303 EVT VT = Op.getValueType();
8304 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8305 DebugLoc dl = Op.getDebugLoc();
8307 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8308 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8309 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8310 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8311 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8313 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8314 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8315 // return AloBlo + AloBhi + AhiBlo;
8317 SDValue A = Op.getOperand(0);
8318 SDValue B = Op.getOperand(1);
8320 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8321 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8322 A, DAG.getConstant(32, MVT::i32));
8323 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8324 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8325 B, DAG.getConstant(32, MVT::i32));
8326 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8327 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8329 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8330 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8332 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8333 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8335 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8336 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8337 AloBhi, DAG.getConstant(32, MVT::i32));
8338 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8340 AhiBlo, DAG.getConstant(32, MVT::i32));
8341 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8342 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8346 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8347 EVT VT = Op.getValueType();
8348 DebugLoc dl = Op.getDebugLoc();
8349 SDValue R = Op.getOperand(0);
8351 LLVMContext *Context = DAG.getContext();
8353 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8355 if (VT == MVT::v4i32) {
8356 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8357 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8358 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8360 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8362 std::vector<Constant*> CV(4, CI);
8363 Constant *C = ConstantVector::get(CV);
8364 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8365 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8366 MachinePointerInfo::getConstantPool(),
8369 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8370 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8371 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8372 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8374 if (VT == MVT::v16i8) {
8376 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8377 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8378 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8380 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8381 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8383 std::vector<Constant*> CVM1(16, CM1);
8384 std::vector<Constant*> CVM2(16, CM2);
8385 Constant *C = ConstantVector::get(CVM1);
8386 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8387 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8388 MachinePointerInfo::getConstantPool(),
8391 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8392 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8393 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8394 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8395 DAG.getConstant(4, MVT::i32));
8396 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8397 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8400 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8402 C = ConstantVector::get(CVM2);
8403 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8404 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8405 MachinePointerInfo::getConstantPool(),
8408 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8409 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8410 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8411 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8412 DAG.getConstant(2, MVT::i32));
8413 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8414 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8417 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8419 // return pblendv(r, r+r, a);
8420 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8421 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8422 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8428 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8429 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8430 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8431 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8432 // has only one use.
8433 SDNode *N = Op.getNode();
8434 SDValue LHS = N->getOperand(0);
8435 SDValue RHS = N->getOperand(1);
8436 unsigned BaseOp = 0;
8438 DebugLoc DL = Op.getDebugLoc();
8439 switch (Op.getOpcode()) {
8440 default: llvm_unreachable("Unknown ovf instruction!");
8442 // A subtract of one will be selected as a INC. Note that INC doesn't
8443 // set CF, so we can't do this for UADDO.
8444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8445 if (C->getAPIntValue() == 1) {
8446 BaseOp = X86ISD::INC;
8450 BaseOp = X86ISD::ADD;
8454 BaseOp = X86ISD::ADD;
8458 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8459 // set CF, so we can't do this for USUBO.
8460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8461 if (C->getAPIntValue() == 1) {
8462 BaseOp = X86ISD::DEC;
8466 BaseOp = X86ISD::SUB;
8470 BaseOp = X86ISD::SUB;
8474 BaseOp = X86ISD::SMUL;
8477 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8478 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8480 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8483 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8484 DAG.getConstant(X86::COND_O, MVT::i32),
8485 SDValue(Sum.getNode(), 2));
8487 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8492 // Also sets EFLAGS.
8493 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8494 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8497 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8498 DAG.getConstant(Cond, MVT::i32),
8499 SDValue(Sum.getNode(), 1));
8501 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8505 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8506 DebugLoc dl = Op.getDebugLoc();
8508 if (!Subtarget->hasSSE2()) {
8509 SDValue Chain = Op.getOperand(0);
8510 SDValue Zero = DAG.getConstant(0,
8511 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8513 DAG.getRegister(X86::ESP, MVT::i32), // Base
8514 DAG.getTargetConstant(1, MVT::i8), // Scale
8515 DAG.getRegister(0, MVT::i32), // Index
8516 DAG.getTargetConstant(0, MVT::i32), // Disp
8517 DAG.getRegister(0, MVT::i32), // Segment.
8522 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8523 array_lengthof(Ops));
8524 return SDValue(Res, 0);
8527 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8529 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8531 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8532 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8533 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8534 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8536 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8537 if (!Op1 && !Op2 && !Op3 && Op4)
8538 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8540 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8541 if (Op1 && !Op2 && !Op3 && !Op4)
8542 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8544 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8546 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8549 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8550 EVT T = Op.getValueType();
8551 DebugLoc DL = Op.getDebugLoc();
8554 switch(T.getSimpleVT().SimpleTy) {
8556 assert(false && "Invalid value type!");
8557 case MVT::i8: Reg = X86::AL; size = 1; break;
8558 case MVT::i16: Reg = X86::AX; size = 2; break;
8559 case MVT::i32: Reg = X86::EAX; size = 4; break;
8561 assert(Subtarget->is64Bit() && "Node not type legal!");
8562 Reg = X86::RAX; size = 8;
8565 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8566 Op.getOperand(2), SDValue());
8567 SDValue Ops[] = { cpIn.getValue(0),
8570 DAG.getTargetConstant(size, MVT::i8),
8572 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8573 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8574 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8577 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8581 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8582 SelectionDAG &DAG) const {
8583 assert(Subtarget->is64Bit() && "Result not type legalized?");
8584 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8585 SDValue TheChain = Op.getOperand(0);
8586 DebugLoc dl = Op.getDebugLoc();
8587 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8588 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8589 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8591 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8592 DAG.getConstant(32, MVT::i8));
8594 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8597 return DAG.getMergeValues(Ops, 2, dl);
8600 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8601 SelectionDAG &DAG) const {
8602 EVT SrcVT = Op.getOperand(0).getValueType();
8603 EVT DstVT = Op.getValueType();
8604 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8605 Subtarget->hasMMX() && "Unexpected custom BITCAST");
8606 assert((DstVT == MVT::i64 ||
8607 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8608 "Unexpected custom BITCAST");
8609 // i64 <=> MMX conversions are Legal.
8610 if (SrcVT==MVT::i64 && DstVT.isVector())
8612 if (DstVT==MVT::i64 && SrcVT.isVector())
8614 // MMX <=> MMX conversions are Legal.
8615 if (SrcVT.isVector() && DstVT.isVector())
8617 // All other conversions need to be expanded.
8620 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8621 SDNode *Node = Op.getNode();
8622 DebugLoc dl = Node->getDebugLoc();
8623 EVT T = Node->getValueType(0);
8624 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8625 DAG.getConstant(0, T), Node->getOperand(2));
8626 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8627 cast<AtomicSDNode>(Node)->getMemoryVT(),
8628 Node->getOperand(0),
8629 Node->getOperand(1), negOp,
8630 cast<AtomicSDNode>(Node)->getSrcValue(),
8631 cast<AtomicSDNode>(Node)->getAlignment());
8634 /// LowerOperation - Provide custom lowering hooks for some operations.
8636 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8637 switch (Op.getOpcode()) {
8638 default: llvm_unreachable("Should not custom lower this!");
8639 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8640 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8641 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8642 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8643 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8644 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8645 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8646 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8647 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8648 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8649 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8650 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8651 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8652 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8653 case ISD::SHL_PARTS:
8654 case ISD::SRA_PARTS:
8655 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8656 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8657 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8658 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8659 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8660 case ISD::FABS: return LowerFABS(Op, DAG);
8661 case ISD::FNEG: return LowerFNEG(Op, DAG);
8662 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8663 case ISD::SETCC: return LowerSETCC(Op, DAG);
8664 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8665 case ISD::SELECT: return LowerSELECT(Op, DAG);
8666 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8667 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8668 case ISD::VASTART: return LowerVASTART(Op, DAG);
8669 case ISD::VAARG: return LowerVAARG(Op, DAG);
8670 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8671 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8672 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8673 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8674 case ISD::FRAME_TO_ARGS_OFFSET:
8675 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8676 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8677 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8678 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8679 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8680 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8681 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8682 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8683 case ISD::SHL: return LowerSHL(Op, DAG);
8689 case ISD::UMULO: return LowerXALUO(Op, DAG);
8690 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8691 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
8695 void X86TargetLowering::
8696 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8697 SelectionDAG &DAG, unsigned NewOp) const {
8698 EVT T = Node->getValueType(0);
8699 DebugLoc dl = Node->getDebugLoc();
8700 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8702 SDValue Chain = Node->getOperand(0);
8703 SDValue In1 = Node->getOperand(1);
8704 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8705 Node->getOperand(2), DAG.getIntPtrConstant(0));
8706 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8707 Node->getOperand(2), DAG.getIntPtrConstant(1));
8708 SDValue Ops[] = { Chain, In1, In2L, In2H };
8709 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8711 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8712 cast<MemSDNode>(Node)->getMemOperand());
8713 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8714 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8715 Results.push_back(Result.getValue(2));
8718 /// ReplaceNodeResults - Replace a node with an illegal result type
8719 /// with a new node built out of custom code.
8720 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8721 SmallVectorImpl<SDValue>&Results,
8722 SelectionDAG &DAG) const {
8723 DebugLoc dl = N->getDebugLoc();
8724 switch (N->getOpcode()) {
8726 assert(false && "Do not know how to custom type legalize this operation!");
8728 case ISD::FP_TO_SINT: {
8729 std::pair<SDValue,SDValue> Vals =
8730 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8731 SDValue FIST = Vals.first, StackSlot = Vals.second;
8732 if (FIST.getNode() != 0) {
8733 EVT VT = N->getValueType(0);
8734 // Return a load from the stack slot.
8735 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8736 MachinePointerInfo(), false, false, 0));
8740 case ISD::READCYCLECOUNTER: {
8741 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8742 SDValue TheChain = N->getOperand(0);
8743 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8744 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8746 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8748 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8749 SDValue Ops[] = { eax, edx };
8750 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8751 Results.push_back(edx.getValue(1));
8754 case ISD::ATOMIC_CMP_SWAP: {
8755 EVT T = N->getValueType(0);
8756 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8757 SDValue cpInL, cpInH;
8758 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8759 DAG.getConstant(0, MVT::i32));
8760 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8761 DAG.getConstant(1, MVT::i32));
8762 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8763 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8765 SDValue swapInL, swapInH;
8766 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8767 DAG.getConstant(0, MVT::i32));
8768 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8769 DAG.getConstant(1, MVT::i32));
8770 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8772 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8773 swapInL.getValue(1));
8774 SDValue Ops[] = { swapInH.getValue(0),
8776 swapInH.getValue(1) };
8777 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8778 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8779 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8781 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8782 MVT::i32, Result.getValue(1));
8783 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8784 MVT::i32, cpOutL.getValue(2));
8785 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8786 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8787 Results.push_back(cpOutH.getValue(1));
8790 case ISD::ATOMIC_LOAD_ADD:
8791 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8793 case ISD::ATOMIC_LOAD_AND:
8794 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8796 case ISD::ATOMIC_LOAD_NAND:
8797 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8799 case ISD::ATOMIC_LOAD_OR:
8800 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8802 case ISD::ATOMIC_LOAD_SUB:
8803 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8805 case ISD::ATOMIC_LOAD_XOR:
8806 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8808 case ISD::ATOMIC_SWAP:
8809 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8814 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8816 default: return NULL;
8817 case X86ISD::BSF: return "X86ISD::BSF";
8818 case X86ISD::BSR: return "X86ISD::BSR";
8819 case X86ISD::SHLD: return "X86ISD::SHLD";
8820 case X86ISD::SHRD: return "X86ISD::SHRD";
8821 case X86ISD::FAND: return "X86ISD::FAND";
8822 case X86ISD::FOR: return "X86ISD::FOR";
8823 case X86ISD::FXOR: return "X86ISD::FXOR";
8824 case X86ISD::FSRL: return "X86ISD::FSRL";
8825 case X86ISD::FILD: return "X86ISD::FILD";
8826 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8827 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8828 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8829 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8830 case X86ISD::FLD: return "X86ISD::FLD";
8831 case X86ISD::FST: return "X86ISD::FST";
8832 case X86ISD::CALL: return "X86ISD::CALL";
8833 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8834 case X86ISD::BT: return "X86ISD::BT";
8835 case X86ISD::CMP: return "X86ISD::CMP";
8836 case X86ISD::COMI: return "X86ISD::COMI";
8837 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8838 case X86ISD::SETCC: return "X86ISD::SETCC";
8839 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8840 case X86ISD::CMOV: return "X86ISD::CMOV";
8841 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8842 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8843 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8844 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8845 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8846 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8847 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8848 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8849 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8850 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8851 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8852 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8853 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8854 case X86ISD::PANDN: return "X86ISD::PANDN";
8855 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
8856 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
8857 case X86ISD::PSIGND: return "X86ISD::PSIGND";
8858 case X86ISD::FMAX: return "X86ISD::FMAX";
8859 case X86ISD::FMIN: return "X86ISD::FMIN";
8860 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8861 case X86ISD::FRCP: return "X86ISD::FRCP";
8862 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8863 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8864 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8865 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8866 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8867 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8868 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8869 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8870 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8871 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8872 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8873 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8874 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8875 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8876 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8877 case X86ISD::VSHL: return "X86ISD::VSHL";
8878 case X86ISD::VSRL: return "X86ISD::VSRL";
8879 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8880 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8881 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8882 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8883 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8884 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8885 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8886 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8887 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8888 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8889 case X86ISD::ADD: return "X86ISD::ADD";
8890 case X86ISD::SUB: return "X86ISD::SUB";
8891 case X86ISD::SMUL: return "X86ISD::SMUL";
8892 case X86ISD::UMUL: return "X86ISD::UMUL";
8893 case X86ISD::INC: return "X86ISD::INC";
8894 case X86ISD::DEC: return "X86ISD::DEC";
8895 case X86ISD::OR: return "X86ISD::OR";
8896 case X86ISD::XOR: return "X86ISD::XOR";
8897 case X86ISD::AND: return "X86ISD::AND";
8898 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8899 case X86ISD::PTEST: return "X86ISD::PTEST";
8900 case X86ISD::TESTP: return "X86ISD::TESTP";
8901 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8902 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8903 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8904 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8905 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8906 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8907 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8908 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8909 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8910 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8911 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8912 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8913 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8914 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8915 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8916 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8917 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8918 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8919 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8920 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8921 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8922 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8923 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8924 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8925 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8926 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8927 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8928 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8929 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8930 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8931 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8932 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8933 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8934 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8935 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
8936 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
8940 // isLegalAddressingMode - Return true if the addressing mode represented
8941 // by AM is legal for this target, for a load/store of the specified type.
8942 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8943 const Type *Ty) const {
8944 // X86 supports extremely general addressing modes.
8945 CodeModel::Model M = getTargetMachine().getCodeModel();
8946 Reloc::Model R = getTargetMachine().getRelocationModel();
8948 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8949 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8954 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8956 // If a reference to this global requires an extra load, we can't fold it.
8957 if (isGlobalStubReference(GVFlags))
8960 // If BaseGV requires a register for the PIC base, we cannot also have a
8961 // BaseReg specified.
8962 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8965 // If lower 4G is not available, then we must use rip-relative addressing.
8966 if ((M != CodeModel::Small || R != Reloc::Static) &&
8967 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8977 // These scales always work.
8982 // These scales are formed with basereg+scalereg. Only accept if there is
8987 default: // Other stuff never works.
8995 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8996 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8998 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8999 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9000 if (NumBits1 <= NumBits2)
9005 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9006 if (!VT1.isInteger() || !VT2.isInteger())
9008 unsigned NumBits1 = VT1.getSizeInBits();
9009 unsigned NumBits2 = VT2.getSizeInBits();
9010 if (NumBits1 <= NumBits2)
9015 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9016 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9017 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9020 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9021 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9022 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9025 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9026 // i16 instructions are longer (0x66 prefix) and potentially slower.
9027 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9030 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9031 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9032 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9033 /// are assumed to be legal.
9035 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9037 // Very little shuffling can be done for 64-bit vectors right now.
9038 if (VT.getSizeInBits() == 64)
9039 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9041 // FIXME: pshufb, blends, shifts.
9042 return (VT.getVectorNumElements() == 2 ||
9043 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9044 isMOVLMask(M, VT) ||
9045 isSHUFPMask(M, VT) ||
9046 isPSHUFDMask(M, VT) ||
9047 isPSHUFHWMask(M, VT) ||
9048 isPSHUFLWMask(M, VT) ||
9049 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9050 isUNPCKLMask(M, VT) ||
9051 isUNPCKHMask(M, VT) ||
9052 isUNPCKL_v_undef_Mask(M, VT) ||
9053 isUNPCKH_v_undef_Mask(M, VT));
9057 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9059 unsigned NumElts = VT.getVectorNumElements();
9060 // FIXME: This collection of masks seems suspect.
9063 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9064 return (isMOVLMask(Mask, VT) ||
9065 isCommutedMOVLMask(Mask, VT, true) ||
9066 isSHUFPMask(Mask, VT) ||
9067 isCommutedSHUFPMask(Mask, VT));
9072 //===----------------------------------------------------------------------===//
9073 // X86 Scheduler Hooks
9074 //===----------------------------------------------------------------------===//
9076 // private utility function
9078 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9079 MachineBasicBlock *MBB,
9086 TargetRegisterClass *RC,
9087 bool invSrc) const {
9088 // For the atomic bitwise operator, we generate
9091 // ld t1 = [bitinstr.addr]
9092 // op t2 = t1, [bitinstr.val]
9094 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9096 // fallthrough -->nextMBB
9097 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9098 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9099 MachineFunction::iterator MBBIter = MBB;
9102 /// First build the CFG
9103 MachineFunction *F = MBB->getParent();
9104 MachineBasicBlock *thisMBB = MBB;
9105 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9106 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9107 F->insert(MBBIter, newMBB);
9108 F->insert(MBBIter, nextMBB);
9110 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9111 nextMBB->splice(nextMBB->begin(), thisMBB,
9112 llvm::next(MachineBasicBlock::iterator(bInstr)),
9114 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9116 // Update thisMBB to fall through to newMBB
9117 thisMBB->addSuccessor(newMBB);
9119 // newMBB jumps to itself and fall through to nextMBB
9120 newMBB->addSuccessor(nextMBB);
9121 newMBB->addSuccessor(newMBB);
9123 // Insert instructions into newMBB based on incoming instruction
9124 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9125 "unexpected number of operands");
9126 DebugLoc dl = bInstr->getDebugLoc();
9127 MachineOperand& destOper = bInstr->getOperand(0);
9128 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9129 int numArgs = bInstr->getNumOperands() - 1;
9130 for (int i=0; i < numArgs; ++i)
9131 argOpers[i] = &bInstr->getOperand(i+1);
9133 // x86 address has 4 operands: base, index, scale, and displacement
9134 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9135 int valArgIndx = lastAddrIndx + 1;
9137 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9138 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9139 for (int i=0; i <= lastAddrIndx; ++i)
9140 (*MIB).addOperand(*argOpers[i]);
9142 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9144 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9149 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9150 assert((argOpers[valArgIndx]->isReg() ||
9151 argOpers[valArgIndx]->isImm()) &&
9153 if (argOpers[valArgIndx]->isReg())
9154 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9156 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9158 (*MIB).addOperand(*argOpers[valArgIndx]);
9160 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9163 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9164 for (int i=0; i <= lastAddrIndx; ++i)
9165 (*MIB).addOperand(*argOpers[i]);
9167 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9168 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9169 bInstr->memoperands_end());
9171 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9175 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9177 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9181 // private utility function: 64 bit atomics on 32 bit host.
9183 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9184 MachineBasicBlock *MBB,
9189 bool invSrc) const {
9190 // For the atomic bitwise operator, we generate
9191 // thisMBB (instructions are in pairs, except cmpxchg8b)
9192 // ld t1,t2 = [bitinstr.addr]
9194 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9195 // op t5, t6 <- out1, out2, [bitinstr.val]
9196 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9197 // mov ECX, EBX <- t5, t6
9198 // mov EAX, EDX <- t1, t2
9199 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9200 // mov t3, t4 <- EAX, EDX
9202 // result in out1, out2
9203 // fallthrough -->nextMBB
9205 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9206 const unsigned LoadOpc = X86::MOV32rm;
9207 const unsigned NotOpc = X86::NOT32r;
9208 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9209 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9210 MachineFunction::iterator MBBIter = MBB;
9213 /// First build the CFG
9214 MachineFunction *F = MBB->getParent();
9215 MachineBasicBlock *thisMBB = MBB;
9216 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9217 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9218 F->insert(MBBIter, newMBB);
9219 F->insert(MBBIter, nextMBB);
9221 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9222 nextMBB->splice(nextMBB->begin(), thisMBB,
9223 llvm::next(MachineBasicBlock::iterator(bInstr)),
9225 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9227 // Update thisMBB to fall through to newMBB
9228 thisMBB->addSuccessor(newMBB);
9230 // newMBB jumps to itself and fall through to nextMBB
9231 newMBB->addSuccessor(nextMBB);
9232 newMBB->addSuccessor(newMBB);
9234 DebugLoc dl = bInstr->getDebugLoc();
9235 // Insert instructions into newMBB based on incoming instruction
9236 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9237 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9238 "unexpected number of operands");
9239 MachineOperand& dest1Oper = bInstr->getOperand(0);
9240 MachineOperand& dest2Oper = bInstr->getOperand(1);
9241 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9242 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9243 argOpers[i] = &bInstr->getOperand(i+2);
9245 // We use some of the operands multiple times, so conservatively just
9246 // clear any kill flags that might be present.
9247 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9248 argOpers[i]->setIsKill(false);
9251 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9252 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9254 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9255 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9256 for (int i=0; i <= lastAddrIndx; ++i)
9257 (*MIB).addOperand(*argOpers[i]);
9258 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9259 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9260 // add 4 to displacement.
9261 for (int i=0; i <= lastAddrIndx-2; ++i)
9262 (*MIB).addOperand(*argOpers[i]);
9263 MachineOperand newOp3 = *(argOpers[3]);
9265 newOp3.setImm(newOp3.getImm()+4);
9267 newOp3.setOffset(newOp3.getOffset()+4);
9268 (*MIB).addOperand(newOp3);
9269 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9271 // t3/4 are defined later, at the bottom of the loop
9272 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9273 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9274 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9275 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9276 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9277 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9279 // The subsequent operations should be using the destination registers of
9280 //the PHI instructions.
9282 t1 = F->getRegInfo().createVirtualRegister(RC);
9283 t2 = F->getRegInfo().createVirtualRegister(RC);
9284 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9285 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9287 t1 = dest1Oper.getReg();
9288 t2 = dest2Oper.getReg();
9291 int valArgIndx = lastAddrIndx + 1;
9292 assert((argOpers[valArgIndx]->isReg() ||
9293 argOpers[valArgIndx]->isImm()) &&
9295 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9296 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9297 if (argOpers[valArgIndx]->isReg())
9298 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9300 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9301 if (regOpcL != X86::MOV32rr)
9303 (*MIB).addOperand(*argOpers[valArgIndx]);
9304 assert(argOpers[valArgIndx + 1]->isReg() ==
9305 argOpers[valArgIndx]->isReg());
9306 assert(argOpers[valArgIndx + 1]->isImm() ==
9307 argOpers[valArgIndx]->isImm());
9308 if (argOpers[valArgIndx + 1]->isReg())
9309 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9311 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9312 if (regOpcH != X86::MOV32rr)
9314 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9316 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9318 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9321 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9323 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9326 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9327 for (int i=0; i <= lastAddrIndx; ++i)
9328 (*MIB).addOperand(*argOpers[i]);
9330 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9331 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9332 bInstr->memoperands_end());
9334 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9335 MIB.addReg(X86::EAX);
9336 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9337 MIB.addReg(X86::EDX);
9340 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9342 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9346 // private utility function
9348 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9349 MachineBasicBlock *MBB,
9350 unsigned cmovOpc) const {
9351 // For the atomic min/max operator, we generate
9354 // ld t1 = [min/max.addr]
9355 // mov t2 = [min/max.val]
9357 // cmov[cond] t2 = t1
9359 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9361 // fallthrough -->nextMBB
9363 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9364 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9365 MachineFunction::iterator MBBIter = MBB;
9368 /// First build the CFG
9369 MachineFunction *F = MBB->getParent();
9370 MachineBasicBlock *thisMBB = MBB;
9371 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9372 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9373 F->insert(MBBIter, newMBB);
9374 F->insert(MBBIter, nextMBB);
9376 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9377 nextMBB->splice(nextMBB->begin(), thisMBB,
9378 llvm::next(MachineBasicBlock::iterator(mInstr)),
9380 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9382 // Update thisMBB to fall through to newMBB
9383 thisMBB->addSuccessor(newMBB);
9385 // newMBB jumps to newMBB and fall through to nextMBB
9386 newMBB->addSuccessor(nextMBB);
9387 newMBB->addSuccessor(newMBB);
9389 DebugLoc dl = mInstr->getDebugLoc();
9390 // Insert instructions into newMBB based on incoming instruction
9391 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9392 "unexpected number of operands");
9393 MachineOperand& destOper = mInstr->getOperand(0);
9394 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9395 int numArgs = mInstr->getNumOperands() - 1;
9396 for (int i=0; i < numArgs; ++i)
9397 argOpers[i] = &mInstr->getOperand(i+1);
9399 // x86 address has 4 operands: base, index, scale, and displacement
9400 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9401 int valArgIndx = lastAddrIndx + 1;
9403 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9404 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9405 for (int i=0; i <= lastAddrIndx; ++i)
9406 (*MIB).addOperand(*argOpers[i]);
9408 // We only support register and immediate values
9409 assert((argOpers[valArgIndx]->isReg() ||
9410 argOpers[valArgIndx]->isImm()) &&
9413 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9414 if (argOpers[valArgIndx]->isReg())
9415 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9417 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9418 (*MIB).addOperand(*argOpers[valArgIndx]);
9420 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9423 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9428 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9429 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9433 // Cmp and exchange if none has modified the memory location
9434 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9435 for (int i=0; i <= lastAddrIndx; ++i)
9436 (*MIB).addOperand(*argOpers[i]);
9438 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9439 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9440 mInstr->memoperands_end());
9442 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9443 MIB.addReg(X86::EAX);
9446 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9448 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9452 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9453 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9456 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9457 unsigned numArgs, bool memArg) const {
9458 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9459 "Target must have SSE4.2 or AVX features enabled");
9461 DebugLoc dl = MI->getDebugLoc();
9462 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9464 if (!Subtarget->hasAVX()) {
9466 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9468 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9471 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9473 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9476 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9477 for (unsigned i = 0; i < numArgs; ++i) {
9478 MachineOperand &Op = MI->getOperand(i+1);
9479 if (!(Op.isReg() && Op.isImplicit()))
9482 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9485 MI->eraseFromParent();
9490 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9491 DebugLoc dl = MI->getDebugLoc();
9492 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9494 // Address into RAX/EAX, other two args into ECX, EDX.
9495 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9496 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9497 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9498 for (int i = 0; i < X86::AddrNumOperands; ++i)
9499 MIB.addOperand(MI->getOperand(i));
9501 unsigned ValOps = X86::AddrNumOperands;
9502 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9503 .addReg(MI->getOperand(ValOps).getReg());
9504 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9505 .addReg(MI->getOperand(ValOps+1).getReg());
9507 // The instruction doesn't actually take any operands though.
9508 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9510 MI->eraseFromParent(); // The pseudo is gone now.
9515 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9516 DebugLoc dl = MI->getDebugLoc();
9517 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9519 // First arg in ECX, the second in EAX.
9520 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9521 .addReg(MI->getOperand(0).getReg());
9522 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9523 .addReg(MI->getOperand(1).getReg());
9525 // The instruction doesn't actually take any operands though.
9526 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9528 MI->eraseFromParent(); // The pseudo is gone now.
9533 X86TargetLowering::EmitVAARG64WithCustomInserter(
9535 MachineBasicBlock *MBB) const {
9536 // Emit va_arg instruction on X86-64.
9538 // Operands to this pseudo-instruction:
9539 // 0 ) Output : destination address (reg)
9540 // 1-5) Input : va_list address (addr, i64mem)
9541 // 6 ) ArgSize : Size (in bytes) of vararg type
9542 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9543 // 8 ) Align : Alignment of type
9544 // 9 ) EFLAGS (implicit-def)
9546 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9547 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9549 unsigned DestReg = MI->getOperand(0).getReg();
9550 MachineOperand &Base = MI->getOperand(1);
9551 MachineOperand &Scale = MI->getOperand(2);
9552 MachineOperand &Index = MI->getOperand(3);
9553 MachineOperand &Disp = MI->getOperand(4);
9554 MachineOperand &Segment = MI->getOperand(5);
9555 unsigned ArgSize = MI->getOperand(6).getImm();
9556 unsigned ArgMode = MI->getOperand(7).getImm();
9557 unsigned Align = MI->getOperand(8).getImm();
9560 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9561 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9562 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9564 // Machine Information
9565 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9566 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9567 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9568 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9569 DebugLoc DL = MI->getDebugLoc();
9574 // i64 overflow_area (address)
9575 // i64 reg_save_area (address)
9577 // sizeof(va_list) = 24
9578 // alignment(va_list) = 8
9580 unsigned TotalNumIntRegs = 6;
9581 unsigned TotalNumXMMRegs = 8;
9582 bool UseGPOffset = (ArgMode == 1);
9583 bool UseFPOffset = (ArgMode == 2);
9584 unsigned MaxOffset = TotalNumIntRegs * 8 +
9585 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9587 /* Align ArgSize to a multiple of 8 */
9588 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9589 bool NeedsAlign = (Align > 8);
9591 MachineBasicBlock *thisMBB = MBB;
9592 MachineBasicBlock *overflowMBB;
9593 MachineBasicBlock *offsetMBB;
9594 MachineBasicBlock *endMBB;
9596 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9597 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9598 unsigned OffsetReg = 0;
9600 if (!UseGPOffset && !UseFPOffset) {
9601 // If we only pull from the overflow region, we don't create a branch.
9602 // We don't need to alter control flow.
9603 OffsetDestReg = 0; // unused
9604 OverflowDestReg = DestReg;
9607 overflowMBB = thisMBB;
9610 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9611 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9612 // If not, pull from overflow_area. (branch to overflowMBB)
9617 // offsetMBB overflowMBB
9622 // Registers for the PHI in endMBB
9623 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9624 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9626 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9627 MachineFunction *MF = MBB->getParent();
9628 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9629 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9630 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9632 MachineFunction::iterator MBBIter = MBB;
9635 // Insert the new basic blocks
9636 MF->insert(MBBIter, offsetMBB);
9637 MF->insert(MBBIter, overflowMBB);
9638 MF->insert(MBBIter, endMBB);
9640 // Transfer the remainder of MBB and its successor edges to endMBB.
9641 endMBB->splice(endMBB->begin(), thisMBB,
9642 llvm::next(MachineBasicBlock::iterator(MI)),
9644 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9646 // Make offsetMBB and overflowMBB successors of thisMBB
9647 thisMBB->addSuccessor(offsetMBB);
9648 thisMBB->addSuccessor(overflowMBB);
9650 // endMBB is a successor of both offsetMBB and overflowMBB
9651 offsetMBB->addSuccessor(endMBB);
9652 overflowMBB->addSuccessor(endMBB);
9654 // Load the offset value into a register
9655 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9656 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9660 .addDisp(Disp, UseFPOffset ? 4 : 0)
9661 .addOperand(Segment)
9662 .setMemRefs(MMOBegin, MMOEnd);
9664 // Check if there is enough room left to pull this argument.
9665 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9667 .addImm(MaxOffset + 8 - ArgSizeA8);
9669 // Branch to "overflowMBB" if offset >= max
9670 // Fall through to "offsetMBB" otherwise
9671 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9672 .addMBB(overflowMBB);
9675 // In offsetMBB, emit code to use the reg_save_area.
9677 assert(OffsetReg != 0);
9679 // Read the reg_save_area address.
9680 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9681 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9686 .addOperand(Segment)
9687 .setMemRefs(MMOBegin, MMOEnd);
9689 // Zero-extend the offset
9690 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9691 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9694 .addImm(X86::sub_32bit);
9696 // Add the offset to the reg_save_area to get the final address.
9697 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9698 .addReg(OffsetReg64)
9699 .addReg(RegSaveReg);
9701 // Compute the offset for the next argument
9702 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9703 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9705 .addImm(UseFPOffset ? 16 : 8);
9707 // Store it back into the va_list.
9708 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9712 .addDisp(Disp, UseFPOffset ? 4 : 0)
9713 .addOperand(Segment)
9714 .addReg(NextOffsetReg)
9715 .setMemRefs(MMOBegin, MMOEnd);
9718 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9723 // Emit code to use overflow area
9726 // Load the overflow_area address into a register.
9727 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9728 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9733 .addOperand(Segment)
9734 .setMemRefs(MMOBegin, MMOEnd);
9736 // If we need to align it, do so. Otherwise, just copy the address
9737 // to OverflowDestReg.
9739 // Align the overflow address
9740 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9741 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9743 // aligned_addr = (addr + (align-1)) & ~(align-1)
9744 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9745 .addReg(OverflowAddrReg)
9748 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9750 .addImm(~(uint64_t)(Align-1));
9752 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9753 .addReg(OverflowAddrReg);
9756 // Compute the next overflow address after this argument.
9757 // (the overflow address should be kept 8-byte aligned)
9758 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9759 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9760 .addReg(OverflowDestReg)
9763 // Store the new overflow address.
9764 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9769 .addOperand(Segment)
9770 .addReg(NextAddrReg)
9771 .setMemRefs(MMOBegin, MMOEnd);
9773 // If we branched, emit the PHI to the front of endMBB.
9775 BuildMI(*endMBB, endMBB->begin(), DL,
9776 TII->get(X86::PHI), DestReg)
9777 .addReg(OffsetDestReg).addMBB(offsetMBB)
9778 .addReg(OverflowDestReg).addMBB(overflowMBB);
9781 // Erase the pseudo instruction
9782 MI->eraseFromParent();
9788 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9790 MachineBasicBlock *MBB) const {
9791 // Emit code to save XMM registers to the stack. The ABI says that the
9792 // number of registers to save is given in %al, so it's theoretically
9793 // possible to do an indirect jump trick to avoid saving all of them,
9794 // however this code takes a simpler approach and just executes all
9795 // of the stores if %al is non-zero. It's less code, and it's probably
9796 // easier on the hardware branch predictor, and stores aren't all that
9797 // expensive anyway.
9799 // Create the new basic blocks. One block contains all the XMM stores,
9800 // and one block is the final destination regardless of whether any
9801 // stores were performed.
9802 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9803 MachineFunction *F = MBB->getParent();
9804 MachineFunction::iterator MBBIter = MBB;
9806 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9807 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9808 F->insert(MBBIter, XMMSaveMBB);
9809 F->insert(MBBIter, EndMBB);
9811 // Transfer the remainder of MBB and its successor edges to EndMBB.
9812 EndMBB->splice(EndMBB->begin(), MBB,
9813 llvm::next(MachineBasicBlock::iterator(MI)),
9815 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9817 // The original block will now fall through to the XMM save block.
9818 MBB->addSuccessor(XMMSaveMBB);
9819 // The XMMSaveMBB will fall through to the end block.
9820 XMMSaveMBB->addSuccessor(EndMBB);
9822 // Now add the instructions.
9823 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9824 DebugLoc DL = MI->getDebugLoc();
9826 unsigned CountReg = MI->getOperand(0).getReg();
9827 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9828 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9830 if (!Subtarget->isTargetWin64()) {
9831 // If %al is 0, branch around the XMM save block.
9832 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9833 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9834 MBB->addSuccessor(EndMBB);
9837 // In the XMM save block, save all the XMM argument registers.
9838 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9839 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9840 MachineMemOperand *MMO =
9841 F->getMachineMemOperand(
9842 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9843 MachineMemOperand::MOStore,
9844 /*Size=*/16, /*Align=*/16);
9845 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9846 .addFrameIndex(RegSaveFrameIndex)
9847 .addImm(/*Scale=*/1)
9848 .addReg(/*IndexReg=*/0)
9849 .addImm(/*Disp=*/Offset)
9850 .addReg(/*Segment=*/0)
9851 .addReg(MI->getOperand(i).getReg())
9852 .addMemOperand(MMO);
9855 MI->eraseFromParent(); // The pseudo instruction is gone now.
9861 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9862 MachineBasicBlock *BB) const {
9863 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9864 DebugLoc DL = MI->getDebugLoc();
9866 // To "insert" a SELECT_CC instruction, we actually have to insert the
9867 // diamond control-flow pattern. The incoming instruction knows the
9868 // destination vreg to set, the condition code register to branch on, the
9869 // true/false values to select between, and a branch opcode to use.
9870 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9871 MachineFunction::iterator It = BB;
9877 // cmpTY ccX, r1, r2
9879 // fallthrough --> copy0MBB
9880 MachineBasicBlock *thisMBB = BB;
9881 MachineFunction *F = BB->getParent();
9882 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9883 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9884 F->insert(It, copy0MBB);
9885 F->insert(It, sinkMBB);
9887 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9888 // live into the sink and copy blocks.
9889 const MachineFunction *MF = BB->getParent();
9890 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9891 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9893 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9894 const MachineOperand &MO = MI->getOperand(I);
9895 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9896 unsigned Reg = MO.getReg();
9897 if (Reg != X86::EFLAGS) continue;
9898 copy0MBB->addLiveIn(Reg);
9899 sinkMBB->addLiveIn(Reg);
9902 // Transfer the remainder of BB and its successor edges to sinkMBB.
9903 sinkMBB->splice(sinkMBB->begin(), BB,
9904 llvm::next(MachineBasicBlock::iterator(MI)),
9906 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9908 // Add the true and fallthrough blocks as its successors.
9909 BB->addSuccessor(copy0MBB);
9910 BB->addSuccessor(sinkMBB);
9912 // Create the conditional branch instruction.
9914 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9915 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9918 // %FalseValue = ...
9919 // # fallthrough to sinkMBB
9920 copy0MBB->addSuccessor(sinkMBB);
9923 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9925 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9926 TII->get(X86::PHI), MI->getOperand(0).getReg())
9927 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9928 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9930 MI->eraseFromParent(); // The pseudo instruction is gone now.
9935 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9936 MachineBasicBlock *BB) const {
9937 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9938 DebugLoc DL = MI->getDebugLoc();
9940 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9941 // non-trivial part is impdef of ESP.
9942 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9945 const char *StackProbeSymbol =
9946 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9948 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9949 .addExternalSymbol(StackProbeSymbol)
9950 .addReg(X86::EAX, RegState::Implicit)
9951 .addReg(X86::ESP, RegState::Implicit)
9952 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9953 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9954 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9956 MI->eraseFromParent(); // The pseudo instruction is gone now.
9961 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9962 MachineBasicBlock *BB) const {
9963 // This is pretty easy. We're taking the value that we received from
9964 // our load from the relocation, sticking it in either RDI (x86-64)
9965 // or EAX and doing an indirect call. The return value will then
9966 // be in the normal return register.
9967 const X86InstrInfo *TII
9968 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9969 DebugLoc DL = MI->getDebugLoc();
9970 MachineFunction *F = BB->getParent();
9972 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9973 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9975 if (Subtarget->is64Bit()) {
9976 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9977 TII->get(X86::MOV64rm), X86::RDI)
9979 .addImm(0).addReg(0)
9980 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9981 MI->getOperand(3).getTargetFlags())
9983 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9984 addDirectMem(MIB, X86::RDI);
9985 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9986 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9987 TII->get(X86::MOV32rm), X86::EAX)
9989 .addImm(0).addReg(0)
9990 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9991 MI->getOperand(3).getTargetFlags())
9993 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9994 addDirectMem(MIB, X86::EAX);
9996 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9997 TII->get(X86::MOV32rm), X86::EAX)
9998 .addReg(TII->getGlobalBaseReg(F))
9999 .addImm(0).addReg(0)
10000 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10001 MI->getOperand(3).getTargetFlags())
10003 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10004 addDirectMem(MIB, X86::EAX);
10007 MI->eraseFromParent(); // The pseudo instruction is gone now.
10011 MachineBasicBlock *
10012 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10013 MachineBasicBlock *BB) const {
10014 switch (MI->getOpcode()) {
10015 default: assert(false && "Unexpected instr type to insert");
10016 case X86::WIN_ALLOCA:
10017 return EmitLoweredWinAlloca(MI, BB);
10018 case X86::TLSCall_32:
10019 case X86::TLSCall_64:
10020 return EmitLoweredTLSCall(MI, BB);
10021 case X86::CMOV_GR8:
10022 case X86::CMOV_FR32:
10023 case X86::CMOV_FR64:
10024 case X86::CMOV_V4F32:
10025 case X86::CMOV_V2F64:
10026 case X86::CMOV_V2I64:
10027 case X86::CMOV_GR16:
10028 case X86::CMOV_GR32:
10029 case X86::CMOV_RFP32:
10030 case X86::CMOV_RFP64:
10031 case X86::CMOV_RFP80:
10032 return EmitLoweredSelect(MI, BB);
10034 case X86::FP32_TO_INT16_IN_MEM:
10035 case X86::FP32_TO_INT32_IN_MEM:
10036 case X86::FP32_TO_INT64_IN_MEM:
10037 case X86::FP64_TO_INT16_IN_MEM:
10038 case X86::FP64_TO_INT32_IN_MEM:
10039 case X86::FP64_TO_INT64_IN_MEM:
10040 case X86::FP80_TO_INT16_IN_MEM:
10041 case X86::FP80_TO_INT32_IN_MEM:
10042 case X86::FP80_TO_INT64_IN_MEM: {
10043 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10044 DebugLoc DL = MI->getDebugLoc();
10046 // Change the floating point control register to use "round towards zero"
10047 // mode when truncating to an integer value.
10048 MachineFunction *F = BB->getParent();
10049 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10050 addFrameReference(BuildMI(*BB, MI, DL,
10051 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10053 // Load the old value of the high byte of the control word...
10055 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10056 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10059 // Set the high part to be round to zero...
10060 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10063 // Reload the modified control word now...
10064 addFrameReference(BuildMI(*BB, MI, DL,
10065 TII->get(X86::FLDCW16m)), CWFrameIdx);
10067 // Restore the memory image of control word to original value
10068 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10071 // Get the X86 opcode to use.
10073 switch (MI->getOpcode()) {
10074 default: llvm_unreachable("illegal opcode!");
10075 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10076 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10077 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10078 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10079 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10080 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10081 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10082 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10083 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10087 MachineOperand &Op = MI->getOperand(0);
10089 AM.BaseType = X86AddressMode::RegBase;
10090 AM.Base.Reg = Op.getReg();
10092 AM.BaseType = X86AddressMode::FrameIndexBase;
10093 AM.Base.FrameIndex = Op.getIndex();
10095 Op = MI->getOperand(1);
10097 AM.Scale = Op.getImm();
10098 Op = MI->getOperand(2);
10100 AM.IndexReg = Op.getImm();
10101 Op = MI->getOperand(3);
10102 if (Op.isGlobal()) {
10103 AM.GV = Op.getGlobal();
10105 AM.Disp = Op.getImm();
10107 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10108 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10110 // Reload the original control word now.
10111 addFrameReference(BuildMI(*BB, MI, DL,
10112 TII->get(X86::FLDCW16m)), CWFrameIdx);
10114 MI->eraseFromParent(); // The pseudo instruction is gone now.
10117 // String/text processing lowering.
10118 case X86::PCMPISTRM128REG:
10119 case X86::VPCMPISTRM128REG:
10120 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10121 case X86::PCMPISTRM128MEM:
10122 case X86::VPCMPISTRM128MEM:
10123 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10124 case X86::PCMPESTRM128REG:
10125 case X86::VPCMPESTRM128REG:
10126 return EmitPCMP(MI, BB, 5, false /* in mem */);
10127 case X86::PCMPESTRM128MEM:
10128 case X86::VPCMPESTRM128MEM:
10129 return EmitPCMP(MI, BB, 5, true /* in mem */);
10131 // Thread synchronization.
10133 return EmitMonitor(MI, BB);
10135 return EmitMwait(MI, BB);
10137 // Atomic Lowering.
10138 case X86::ATOMAND32:
10139 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10140 X86::AND32ri, X86::MOV32rm,
10142 X86::NOT32r, X86::EAX,
10143 X86::GR32RegisterClass);
10144 case X86::ATOMOR32:
10145 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10146 X86::OR32ri, X86::MOV32rm,
10148 X86::NOT32r, X86::EAX,
10149 X86::GR32RegisterClass);
10150 case X86::ATOMXOR32:
10151 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10152 X86::XOR32ri, X86::MOV32rm,
10154 X86::NOT32r, X86::EAX,
10155 X86::GR32RegisterClass);
10156 case X86::ATOMNAND32:
10157 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10158 X86::AND32ri, X86::MOV32rm,
10160 X86::NOT32r, X86::EAX,
10161 X86::GR32RegisterClass, true);
10162 case X86::ATOMMIN32:
10163 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10164 case X86::ATOMMAX32:
10165 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10166 case X86::ATOMUMIN32:
10167 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10168 case X86::ATOMUMAX32:
10169 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10171 case X86::ATOMAND16:
10172 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10173 X86::AND16ri, X86::MOV16rm,
10175 X86::NOT16r, X86::AX,
10176 X86::GR16RegisterClass);
10177 case X86::ATOMOR16:
10178 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10179 X86::OR16ri, X86::MOV16rm,
10181 X86::NOT16r, X86::AX,
10182 X86::GR16RegisterClass);
10183 case X86::ATOMXOR16:
10184 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10185 X86::XOR16ri, X86::MOV16rm,
10187 X86::NOT16r, X86::AX,
10188 X86::GR16RegisterClass);
10189 case X86::ATOMNAND16:
10190 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10191 X86::AND16ri, X86::MOV16rm,
10193 X86::NOT16r, X86::AX,
10194 X86::GR16RegisterClass, true);
10195 case X86::ATOMMIN16:
10196 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10197 case X86::ATOMMAX16:
10198 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10199 case X86::ATOMUMIN16:
10200 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10201 case X86::ATOMUMAX16:
10202 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10204 case X86::ATOMAND8:
10205 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10206 X86::AND8ri, X86::MOV8rm,
10208 X86::NOT8r, X86::AL,
10209 X86::GR8RegisterClass);
10211 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10212 X86::OR8ri, X86::MOV8rm,
10214 X86::NOT8r, X86::AL,
10215 X86::GR8RegisterClass);
10216 case X86::ATOMXOR8:
10217 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10218 X86::XOR8ri, X86::MOV8rm,
10220 X86::NOT8r, X86::AL,
10221 X86::GR8RegisterClass);
10222 case X86::ATOMNAND8:
10223 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10224 X86::AND8ri, X86::MOV8rm,
10226 X86::NOT8r, X86::AL,
10227 X86::GR8RegisterClass, true);
10228 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10229 // This group is for 64-bit host.
10230 case X86::ATOMAND64:
10231 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10232 X86::AND64ri32, X86::MOV64rm,
10234 X86::NOT64r, X86::RAX,
10235 X86::GR64RegisterClass);
10236 case X86::ATOMOR64:
10237 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10238 X86::OR64ri32, X86::MOV64rm,
10240 X86::NOT64r, X86::RAX,
10241 X86::GR64RegisterClass);
10242 case X86::ATOMXOR64:
10243 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10244 X86::XOR64ri32, X86::MOV64rm,
10246 X86::NOT64r, X86::RAX,
10247 X86::GR64RegisterClass);
10248 case X86::ATOMNAND64:
10249 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10250 X86::AND64ri32, X86::MOV64rm,
10252 X86::NOT64r, X86::RAX,
10253 X86::GR64RegisterClass, true);
10254 case X86::ATOMMIN64:
10255 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10256 case X86::ATOMMAX64:
10257 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10258 case X86::ATOMUMIN64:
10259 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10260 case X86::ATOMUMAX64:
10261 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10263 // This group does 64-bit operations on a 32-bit host.
10264 case X86::ATOMAND6432:
10265 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10266 X86::AND32rr, X86::AND32rr,
10267 X86::AND32ri, X86::AND32ri,
10269 case X86::ATOMOR6432:
10270 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10271 X86::OR32rr, X86::OR32rr,
10272 X86::OR32ri, X86::OR32ri,
10274 case X86::ATOMXOR6432:
10275 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10276 X86::XOR32rr, X86::XOR32rr,
10277 X86::XOR32ri, X86::XOR32ri,
10279 case X86::ATOMNAND6432:
10280 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10281 X86::AND32rr, X86::AND32rr,
10282 X86::AND32ri, X86::AND32ri,
10284 case X86::ATOMADD6432:
10285 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10286 X86::ADD32rr, X86::ADC32rr,
10287 X86::ADD32ri, X86::ADC32ri,
10289 case X86::ATOMSUB6432:
10290 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10291 X86::SUB32rr, X86::SBB32rr,
10292 X86::SUB32ri, X86::SBB32ri,
10294 case X86::ATOMSWAP6432:
10295 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10296 X86::MOV32rr, X86::MOV32rr,
10297 X86::MOV32ri, X86::MOV32ri,
10299 case X86::VASTART_SAVE_XMM_REGS:
10300 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10302 case X86::VAARG_64:
10303 return EmitVAARG64WithCustomInserter(MI, BB);
10307 //===----------------------------------------------------------------------===//
10308 // X86 Optimization Hooks
10309 //===----------------------------------------------------------------------===//
10311 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10315 const SelectionDAG &DAG,
10316 unsigned Depth) const {
10317 unsigned Opc = Op.getOpcode();
10318 assert((Opc >= ISD::BUILTIN_OP_END ||
10319 Opc == ISD::INTRINSIC_WO_CHAIN ||
10320 Opc == ISD::INTRINSIC_W_CHAIN ||
10321 Opc == ISD::INTRINSIC_VOID) &&
10322 "Should use MaskedValueIsZero if you don't know whether Op"
10323 " is a target node!");
10325 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10337 // These nodes' second result is a boolean.
10338 if (Op.getResNo() == 0)
10341 case X86ISD::SETCC:
10342 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10343 Mask.getBitWidth() - 1);
10348 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10349 unsigned Depth) const {
10350 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10351 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10352 return Op.getValueType().getScalarType().getSizeInBits();
10358 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10359 /// node is a GlobalAddress + offset.
10360 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10361 const GlobalValue* &GA,
10362 int64_t &Offset) const {
10363 if (N->getOpcode() == X86ISD::Wrapper) {
10364 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10365 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10366 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10370 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10373 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10374 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10375 /// if the load addresses are consecutive, non-overlapping, and in the right
10377 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10378 const TargetLowering &TLI) {
10379 DebugLoc dl = N->getDebugLoc();
10380 EVT VT = N->getValueType(0);
10382 if (VT.getSizeInBits() != 128)
10385 SmallVector<SDValue, 16> Elts;
10386 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10387 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10389 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10392 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10393 /// generation and convert it from being a bunch of shuffles and extracts
10394 /// to a simple store and scalar loads to extract the elements.
10395 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10396 const TargetLowering &TLI) {
10397 SDValue InputVector = N->getOperand(0);
10399 // Only operate on vectors of 4 elements, where the alternative shuffling
10400 // gets to be more expensive.
10401 if (InputVector.getValueType() != MVT::v4i32)
10404 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10405 // single use which is a sign-extend or zero-extend, and all elements are
10407 SmallVector<SDNode *, 4> Uses;
10408 unsigned ExtractedElements = 0;
10409 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10410 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10411 if (UI.getUse().getResNo() != InputVector.getResNo())
10414 SDNode *Extract = *UI;
10415 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10418 if (Extract->getValueType(0) != MVT::i32)
10420 if (!Extract->hasOneUse())
10422 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10423 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10425 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10428 // Record which element was extracted.
10429 ExtractedElements |=
10430 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10432 Uses.push_back(Extract);
10435 // If not all the elements were used, this may not be worthwhile.
10436 if (ExtractedElements != 15)
10439 // Ok, we've now decided to do the transformation.
10440 DebugLoc dl = InputVector.getDebugLoc();
10442 // Store the value to a temporary stack slot.
10443 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10444 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10445 MachinePointerInfo(), false, false, 0);
10447 // Replace each use (extract) with a load of the appropriate element.
10448 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10449 UE = Uses.end(); UI != UE; ++UI) {
10450 SDNode *Extract = *UI;
10452 // Compute the element's address.
10453 SDValue Idx = Extract->getOperand(1);
10455 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10456 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10457 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10459 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10460 StackPtr, OffsetVal);
10462 // Load the scalar.
10463 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10464 ScalarAddr, MachinePointerInfo(),
10467 // Replace the exact with the load.
10468 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10471 // The replacement was made in place; don't return anything.
10475 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10476 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10477 const X86Subtarget *Subtarget) {
10478 DebugLoc DL = N->getDebugLoc();
10479 SDValue Cond = N->getOperand(0);
10480 // Get the LHS/RHS of the select.
10481 SDValue LHS = N->getOperand(1);
10482 SDValue RHS = N->getOperand(2);
10484 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10485 // instructions match the semantics of the common C idiom x<y?x:y but not
10486 // x<=y?x:y, because of how they handle negative zero (which can be
10487 // ignored in unsafe-math mode).
10488 if (Subtarget->hasSSE2() &&
10489 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10490 Cond.getOpcode() == ISD::SETCC) {
10491 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10493 unsigned Opcode = 0;
10494 // Check for x CC y ? x : y.
10495 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10496 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10500 // Converting this to a min would handle NaNs incorrectly, and swapping
10501 // the operands would cause it to handle comparisons between positive
10502 // and negative zero incorrectly.
10503 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10504 if (!UnsafeFPMath &&
10505 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10507 std::swap(LHS, RHS);
10509 Opcode = X86ISD::FMIN;
10512 // Converting this to a min would handle comparisons between positive
10513 // and negative zero incorrectly.
10514 if (!UnsafeFPMath &&
10515 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10517 Opcode = X86ISD::FMIN;
10520 // Converting this to a min would handle both negative zeros and NaNs
10521 // incorrectly, but we can swap the operands to fix both.
10522 std::swap(LHS, RHS);
10526 Opcode = X86ISD::FMIN;
10530 // Converting this to a max would handle comparisons between positive
10531 // and negative zero incorrectly.
10532 if (!UnsafeFPMath &&
10533 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10535 Opcode = X86ISD::FMAX;
10538 // Converting this to a max would handle NaNs incorrectly, and swapping
10539 // the operands would cause it to handle comparisons between positive
10540 // and negative zero incorrectly.
10541 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10542 if (!UnsafeFPMath &&
10543 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10545 std::swap(LHS, RHS);
10547 Opcode = X86ISD::FMAX;
10550 // Converting this to a max would handle both negative zeros and NaNs
10551 // incorrectly, but we can swap the operands to fix both.
10552 std::swap(LHS, RHS);
10556 Opcode = X86ISD::FMAX;
10559 // Check for x CC y ? y : x -- a min/max with reversed arms.
10560 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10561 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10565 // Converting this to a min would handle comparisons between positive
10566 // and negative zero incorrectly, and swapping the operands would
10567 // cause it to handle NaNs incorrectly.
10568 if (!UnsafeFPMath &&
10569 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10570 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10572 std::swap(LHS, RHS);
10574 Opcode = X86ISD::FMIN;
10577 // Converting this to a min would handle NaNs incorrectly.
10578 if (!UnsafeFPMath &&
10579 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10581 Opcode = X86ISD::FMIN;
10584 // Converting this to a min would handle both negative zeros and NaNs
10585 // incorrectly, but we can swap the operands to fix both.
10586 std::swap(LHS, RHS);
10590 Opcode = X86ISD::FMIN;
10594 // Converting this to a max would handle NaNs incorrectly.
10595 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10597 Opcode = X86ISD::FMAX;
10600 // Converting this to a max would handle comparisons between positive
10601 // and negative zero incorrectly, and swapping the operands would
10602 // cause it to handle NaNs incorrectly.
10603 if (!UnsafeFPMath &&
10604 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10605 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10607 std::swap(LHS, RHS);
10609 Opcode = X86ISD::FMAX;
10612 // Converting this to a max would handle both negative zeros and NaNs
10613 // incorrectly, but we can swap the operands to fix both.
10614 std::swap(LHS, RHS);
10618 Opcode = X86ISD::FMAX;
10624 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10627 // If this is a select between two integer constants, try to do some
10629 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10630 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10631 // Don't do this for crazy integer types.
10632 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10633 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10634 // so that TrueC (the true value) is larger than FalseC.
10635 bool NeedsCondInvert = false;
10637 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10638 // Efficiently invertible.
10639 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10640 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10641 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10642 NeedsCondInvert = true;
10643 std::swap(TrueC, FalseC);
10646 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10647 if (FalseC->getAPIntValue() == 0 &&
10648 TrueC->getAPIntValue().isPowerOf2()) {
10649 if (NeedsCondInvert) // Invert the condition if needed.
10650 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10651 DAG.getConstant(1, Cond.getValueType()));
10653 // Zero extend the condition if needed.
10654 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10656 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10657 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10658 DAG.getConstant(ShAmt, MVT::i8));
10661 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10662 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10663 if (NeedsCondInvert) // Invert the condition if needed.
10664 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10665 DAG.getConstant(1, Cond.getValueType()));
10667 // Zero extend the condition if needed.
10668 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10669 FalseC->getValueType(0), Cond);
10670 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10671 SDValue(FalseC, 0));
10674 // Optimize cases that will turn into an LEA instruction. This requires
10675 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10676 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10677 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10678 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10680 bool isFastMultiplier = false;
10682 switch ((unsigned char)Diff) {
10684 case 1: // result = add base, cond
10685 case 2: // result = lea base( , cond*2)
10686 case 3: // result = lea base(cond, cond*2)
10687 case 4: // result = lea base( , cond*4)
10688 case 5: // result = lea base(cond, cond*4)
10689 case 8: // result = lea base( , cond*8)
10690 case 9: // result = lea base(cond, cond*8)
10691 isFastMultiplier = true;
10696 if (isFastMultiplier) {
10697 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10698 if (NeedsCondInvert) // Invert the condition if needed.
10699 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10700 DAG.getConstant(1, Cond.getValueType()));
10702 // Zero extend the condition if needed.
10703 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10705 // Scale the condition by the difference.
10707 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10708 DAG.getConstant(Diff, Cond.getValueType()));
10710 // Add the base if non-zero.
10711 if (FalseC->getAPIntValue() != 0)
10712 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10713 SDValue(FalseC, 0));
10723 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10724 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10725 TargetLowering::DAGCombinerInfo &DCI) {
10726 DebugLoc DL = N->getDebugLoc();
10728 // If the flag operand isn't dead, don't touch this CMOV.
10729 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10732 // If this is a select between two integer constants, try to do some
10733 // optimizations. Note that the operands are ordered the opposite of SELECT
10735 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10736 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10737 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10738 // larger than FalseC (the false value).
10739 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10741 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10742 CC = X86::GetOppositeBranchCondition(CC);
10743 std::swap(TrueC, FalseC);
10746 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10747 // This is efficient for any integer data type (including i8/i16) and
10749 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10750 SDValue Cond = N->getOperand(3);
10751 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10752 DAG.getConstant(CC, MVT::i8), Cond);
10754 // Zero extend the condition if needed.
10755 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10757 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10758 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10759 DAG.getConstant(ShAmt, MVT::i8));
10760 if (N->getNumValues() == 2) // Dead flag value?
10761 return DCI.CombineTo(N, Cond, SDValue());
10765 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10766 // for any integer data type, including i8/i16.
10767 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10768 SDValue Cond = N->getOperand(3);
10769 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10770 DAG.getConstant(CC, MVT::i8), Cond);
10772 // Zero extend the condition if needed.
10773 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10774 FalseC->getValueType(0), Cond);
10775 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10776 SDValue(FalseC, 0));
10778 if (N->getNumValues() == 2) // Dead flag value?
10779 return DCI.CombineTo(N, Cond, SDValue());
10783 // Optimize cases that will turn into an LEA instruction. This requires
10784 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10785 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10786 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10787 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10789 bool isFastMultiplier = false;
10791 switch ((unsigned char)Diff) {
10793 case 1: // result = add base, cond
10794 case 2: // result = lea base( , cond*2)
10795 case 3: // result = lea base(cond, cond*2)
10796 case 4: // result = lea base( , cond*4)
10797 case 5: // result = lea base(cond, cond*4)
10798 case 8: // result = lea base( , cond*8)
10799 case 9: // result = lea base(cond, cond*8)
10800 isFastMultiplier = true;
10805 if (isFastMultiplier) {
10806 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10807 SDValue Cond = N->getOperand(3);
10808 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10809 DAG.getConstant(CC, MVT::i8), Cond);
10810 // Zero extend the condition if needed.
10811 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10813 // Scale the condition by the difference.
10815 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10816 DAG.getConstant(Diff, Cond.getValueType()));
10818 // Add the base if non-zero.
10819 if (FalseC->getAPIntValue() != 0)
10820 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10821 SDValue(FalseC, 0));
10822 if (N->getNumValues() == 2) // Dead flag value?
10823 return DCI.CombineTo(N, Cond, SDValue());
10833 /// PerformMulCombine - Optimize a single multiply with constant into two
10834 /// in order to implement it with two cheaper instructions, e.g.
10835 /// LEA + SHL, LEA + LEA.
10836 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10837 TargetLowering::DAGCombinerInfo &DCI) {
10838 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10841 EVT VT = N->getValueType(0);
10842 if (VT != MVT::i64)
10845 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10848 uint64_t MulAmt = C->getZExtValue();
10849 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10852 uint64_t MulAmt1 = 0;
10853 uint64_t MulAmt2 = 0;
10854 if ((MulAmt % 9) == 0) {
10856 MulAmt2 = MulAmt / 9;
10857 } else if ((MulAmt % 5) == 0) {
10859 MulAmt2 = MulAmt / 5;
10860 } else if ((MulAmt % 3) == 0) {
10862 MulAmt2 = MulAmt / 3;
10865 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10866 DebugLoc DL = N->getDebugLoc();
10868 if (isPowerOf2_64(MulAmt2) &&
10869 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10870 // If second multiplifer is pow2, issue it first. We want the multiply by
10871 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10873 std::swap(MulAmt1, MulAmt2);
10876 if (isPowerOf2_64(MulAmt1))
10877 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10878 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10880 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10881 DAG.getConstant(MulAmt1, VT));
10883 if (isPowerOf2_64(MulAmt2))
10884 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10885 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10887 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10888 DAG.getConstant(MulAmt2, VT));
10890 // Do not add new nodes to DAG combiner worklist.
10891 DCI.CombineTo(N, NewMul, false);
10896 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10897 SDValue N0 = N->getOperand(0);
10898 SDValue N1 = N->getOperand(1);
10899 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10900 EVT VT = N0.getValueType();
10902 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10903 // since the result of setcc_c is all zero's or all ones.
10904 if (N1C && N0.getOpcode() == ISD::AND &&
10905 N0.getOperand(1).getOpcode() == ISD::Constant) {
10906 SDValue N00 = N0.getOperand(0);
10907 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10908 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10909 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10910 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10911 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10912 APInt ShAmt = N1C->getAPIntValue();
10913 Mask = Mask.shl(ShAmt);
10915 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10916 N00, DAG.getConstant(Mask, VT));
10923 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10925 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10926 const X86Subtarget *Subtarget) {
10927 EVT VT = N->getValueType(0);
10928 if (!VT.isVector() && VT.isInteger() &&
10929 N->getOpcode() == ISD::SHL)
10930 return PerformSHLCombine(N, DAG);
10932 // On X86 with SSE2 support, we can transform this to a vector shift if
10933 // all elements are shifted by the same amount. We can't do this in legalize
10934 // because the a constant vector is typically transformed to a constant pool
10935 // so we have no knowledge of the shift amount.
10936 if (!Subtarget->hasSSE2())
10939 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10942 SDValue ShAmtOp = N->getOperand(1);
10943 EVT EltVT = VT.getVectorElementType();
10944 DebugLoc DL = N->getDebugLoc();
10945 SDValue BaseShAmt = SDValue();
10946 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10947 unsigned NumElts = VT.getVectorNumElements();
10949 for (; i != NumElts; ++i) {
10950 SDValue Arg = ShAmtOp.getOperand(i);
10951 if (Arg.getOpcode() == ISD::UNDEF) continue;
10955 for (; i != NumElts; ++i) {
10956 SDValue Arg = ShAmtOp.getOperand(i);
10957 if (Arg.getOpcode() == ISD::UNDEF) continue;
10958 if (Arg != BaseShAmt) {
10962 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10963 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10964 SDValue InVec = ShAmtOp.getOperand(0);
10965 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10966 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10968 for (; i != NumElts; ++i) {
10969 SDValue Arg = InVec.getOperand(i);
10970 if (Arg.getOpcode() == ISD::UNDEF) continue;
10974 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10975 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10976 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10977 if (C->getZExtValue() == SplatIdx)
10978 BaseShAmt = InVec.getOperand(1);
10981 if (BaseShAmt.getNode() == 0)
10982 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10983 DAG.getIntPtrConstant(0));
10987 // The shift amount is an i32.
10988 if (EltVT.bitsGT(MVT::i32))
10989 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10990 else if (EltVT.bitsLT(MVT::i32))
10991 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10993 // The shift amount is identical so we can do a vector shift.
10994 SDValue ValOp = N->getOperand(0);
10995 switch (N->getOpcode()) {
10997 llvm_unreachable("Unknown shift opcode!");
11000 if (VT == MVT::v2i64)
11001 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11002 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11004 if (VT == MVT::v4i32)
11005 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11006 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11008 if (VT == MVT::v8i16)
11009 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11010 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11014 if (VT == MVT::v4i32)
11015 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11016 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11018 if (VT == MVT::v8i16)
11019 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11020 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11024 if (VT == MVT::v2i64)
11025 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11026 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11028 if (VT == MVT::v4i32)
11029 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11030 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11032 if (VT == MVT::v8i16)
11033 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11034 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11042 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11043 TargetLowering::DAGCombinerInfo &DCI,
11044 const X86Subtarget *Subtarget) {
11045 if (DCI.isBeforeLegalizeOps())
11048 // Want to form PANDN nodes, in the hopes of then easily combining them with
11049 // OR and AND nodes to form PBLEND/PSIGN.
11050 EVT VT = N->getValueType(0);
11051 if (VT != MVT::v2i64)
11054 SDValue N0 = N->getOperand(0);
11055 SDValue N1 = N->getOperand(1);
11056 DebugLoc DL = N->getDebugLoc();
11058 // Check LHS for vnot
11059 if (N0.getOpcode() == ISD::XOR &&
11060 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11061 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11063 // Check RHS for vnot
11064 if (N1.getOpcode() == ISD::XOR &&
11065 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11066 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11071 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11072 TargetLowering::DAGCombinerInfo &DCI,
11073 const X86Subtarget *Subtarget) {
11074 if (DCI.isBeforeLegalizeOps())
11077 EVT VT = N->getValueType(0);
11078 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11081 SDValue N0 = N->getOperand(0);
11082 SDValue N1 = N->getOperand(1);
11084 // look for psign/blend
11085 if (Subtarget->hasSSSE3()) {
11086 if (VT == MVT::v2i64) {
11087 // Canonicalize pandn to RHS
11088 if (N0.getOpcode() == X86ISD::PANDN)
11090 // or (and (m, x), (pandn m, y))
11091 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11092 SDValue Mask = N1.getOperand(0);
11093 SDValue X = N1.getOperand(1);
11095 if (N0.getOperand(0) == Mask)
11096 Y = N0.getOperand(1);
11097 if (N0.getOperand(1) == Mask)
11098 Y = N0.getOperand(0);
11100 // Check to see if the mask appeared in both the AND and PANDN and
11104 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11105 if (Mask.getOpcode() != ISD::BITCAST ||
11106 X.getOpcode() != ISD::BITCAST ||
11107 Y.getOpcode() != ISD::BITCAST)
11110 // Look through mask bitcast.
11111 Mask = Mask.getOperand(0);
11112 EVT MaskVT = Mask.getValueType();
11114 // Validate that the Mask operand is a vector sra node. The sra node
11115 // will be an intrinsic.
11116 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11119 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11120 // there is no psrai.b
11121 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11122 case Intrinsic::x86_sse2_psrai_w:
11123 case Intrinsic::x86_sse2_psrai_d:
11125 default: return SDValue();
11128 // Check that the SRA is all signbits.
11129 SDValue SraC = Mask.getOperand(2);
11130 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11131 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11132 if ((SraAmt + 1) != EltBits)
11135 DebugLoc DL = N->getDebugLoc();
11137 // Now we know we at least have a plendvb with the mask val. See if
11138 // we can form a psignb/w/d.
11139 // psign = x.type == y.type == mask.type && y = sub(0, x);
11140 X = X.getOperand(0);
11141 Y = Y.getOperand(0);
11142 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11143 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11144 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11147 case 8: Opc = X86ISD::PSIGNB; break;
11148 case 16: Opc = X86ISD::PSIGNW; break;
11149 case 32: Opc = X86ISD::PSIGND; break;
11153 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11154 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11157 // PBLENDVB only available on SSE 4.1
11158 if (!Subtarget->hasSSE41())
11161 unsigned IID = Intrinsic::x86_sse41_pblendvb;
11162 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11163 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11164 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11165 Mask = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::v16i8,
11166 DAG.getConstant(IID, MVT::i32), X, Y, Mask);
11167 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11172 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11173 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11175 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11177 if (!N0.hasOneUse() || !N1.hasOneUse())
11180 SDValue ShAmt0 = N0.getOperand(1);
11181 if (ShAmt0.getValueType() != MVT::i8)
11183 SDValue ShAmt1 = N1.getOperand(1);
11184 if (ShAmt1.getValueType() != MVT::i8)
11186 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11187 ShAmt0 = ShAmt0.getOperand(0);
11188 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11189 ShAmt1 = ShAmt1.getOperand(0);
11191 DebugLoc DL = N->getDebugLoc();
11192 unsigned Opc = X86ISD::SHLD;
11193 SDValue Op0 = N0.getOperand(0);
11194 SDValue Op1 = N1.getOperand(0);
11195 if (ShAmt0.getOpcode() == ISD::SUB) {
11196 Opc = X86ISD::SHRD;
11197 std::swap(Op0, Op1);
11198 std::swap(ShAmt0, ShAmt1);
11201 unsigned Bits = VT.getSizeInBits();
11202 if (ShAmt1.getOpcode() == ISD::SUB) {
11203 SDValue Sum = ShAmt1.getOperand(0);
11204 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11205 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11206 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11207 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11208 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11209 return DAG.getNode(Opc, DL, VT,
11211 DAG.getNode(ISD::TRUNCATE, DL,
11214 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11215 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11217 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11218 return DAG.getNode(Opc, DL, VT,
11219 N0.getOperand(0), N1.getOperand(0),
11220 DAG.getNode(ISD::TRUNCATE, DL,
11227 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11228 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11229 const X86Subtarget *Subtarget) {
11230 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11231 // the FP state in cases where an emms may be missing.
11232 // A preferable solution to the general problem is to figure out the right
11233 // places to insert EMMS. This qualifies as a quick hack.
11235 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11236 StoreSDNode *St = cast<StoreSDNode>(N);
11237 EVT VT = St->getValue().getValueType();
11238 if (VT.getSizeInBits() != 64)
11241 const Function *F = DAG.getMachineFunction().getFunction();
11242 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11243 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11244 && Subtarget->hasSSE2();
11245 if ((VT.isVector() ||
11246 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11247 isa<LoadSDNode>(St->getValue()) &&
11248 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11249 St->getChain().hasOneUse() && !St->isVolatile()) {
11250 SDNode* LdVal = St->getValue().getNode();
11251 LoadSDNode *Ld = 0;
11252 int TokenFactorIndex = -1;
11253 SmallVector<SDValue, 8> Ops;
11254 SDNode* ChainVal = St->getChain().getNode();
11255 // Must be a store of a load. We currently handle two cases: the load
11256 // is a direct child, and it's under an intervening TokenFactor. It is
11257 // possible to dig deeper under nested TokenFactors.
11258 if (ChainVal == LdVal)
11259 Ld = cast<LoadSDNode>(St->getChain());
11260 else if (St->getValue().hasOneUse() &&
11261 ChainVal->getOpcode() == ISD::TokenFactor) {
11262 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11263 if (ChainVal->getOperand(i).getNode() == LdVal) {
11264 TokenFactorIndex = i;
11265 Ld = cast<LoadSDNode>(St->getValue());
11267 Ops.push_back(ChainVal->getOperand(i));
11271 if (!Ld || !ISD::isNormalLoad(Ld))
11274 // If this is not the MMX case, i.e. we are just turning i64 load/store
11275 // into f64 load/store, avoid the transformation if there are multiple
11276 // uses of the loaded value.
11277 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11280 DebugLoc LdDL = Ld->getDebugLoc();
11281 DebugLoc StDL = N->getDebugLoc();
11282 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11283 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11285 if (Subtarget->is64Bit() || F64IsLegal) {
11286 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11287 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11288 Ld->getPointerInfo(), Ld->isVolatile(),
11289 Ld->isNonTemporal(), Ld->getAlignment());
11290 SDValue NewChain = NewLd.getValue(1);
11291 if (TokenFactorIndex != -1) {
11292 Ops.push_back(NewChain);
11293 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11296 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11297 St->getPointerInfo(),
11298 St->isVolatile(), St->isNonTemporal(),
11299 St->getAlignment());
11302 // Otherwise, lower to two pairs of 32-bit loads / stores.
11303 SDValue LoAddr = Ld->getBasePtr();
11304 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11305 DAG.getConstant(4, MVT::i32));
11307 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11308 Ld->getPointerInfo(),
11309 Ld->isVolatile(), Ld->isNonTemporal(),
11310 Ld->getAlignment());
11311 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11312 Ld->getPointerInfo().getWithOffset(4),
11313 Ld->isVolatile(), Ld->isNonTemporal(),
11314 MinAlign(Ld->getAlignment(), 4));
11316 SDValue NewChain = LoLd.getValue(1);
11317 if (TokenFactorIndex != -1) {
11318 Ops.push_back(LoLd);
11319 Ops.push_back(HiLd);
11320 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11324 LoAddr = St->getBasePtr();
11325 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11326 DAG.getConstant(4, MVT::i32));
11328 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11329 St->getPointerInfo(),
11330 St->isVolatile(), St->isNonTemporal(),
11331 St->getAlignment());
11332 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11333 St->getPointerInfo().getWithOffset(4),
11335 St->isNonTemporal(),
11336 MinAlign(St->getAlignment(), 4));
11337 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11342 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11343 /// X86ISD::FXOR nodes.
11344 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11345 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11346 // F[X]OR(0.0, x) -> x
11347 // F[X]OR(x, 0.0) -> x
11348 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11349 if (C->getValueAPF().isPosZero())
11350 return N->getOperand(1);
11351 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11352 if (C->getValueAPF().isPosZero())
11353 return N->getOperand(0);
11357 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11358 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11359 // FAND(0.0, x) -> 0.0
11360 // FAND(x, 0.0) -> 0.0
11361 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11362 if (C->getValueAPF().isPosZero())
11363 return N->getOperand(0);
11364 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11365 if (C->getValueAPF().isPosZero())
11366 return N->getOperand(1);
11370 static SDValue PerformBTCombine(SDNode *N,
11372 TargetLowering::DAGCombinerInfo &DCI) {
11373 // BT ignores high bits in the bit index operand.
11374 SDValue Op1 = N->getOperand(1);
11375 if (Op1.hasOneUse()) {
11376 unsigned BitWidth = Op1.getValueSizeInBits();
11377 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11378 APInt KnownZero, KnownOne;
11379 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11380 !DCI.isBeforeLegalizeOps());
11381 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11382 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11383 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11384 DCI.CommitTargetLoweringOpt(TLO);
11389 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11390 SDValue Op = N->getOperand(0);
11391 if (Op.getOpcode() == ISD::BITCAST)
11392 Op = Op.getOperand(0);
11393 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11394 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11395 VT.getVectorElementType().getSizeInBits() ==
11396 OpVT.getVectorElementType().getSizeInBits()) {
11397 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11402 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11403 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11404 // (and (i32 x86isd::setcc_carry), 1)
11405 // This eliminates the zext. This transformation is necessary because
11406 // ISD::SETCC is always legalized to i8.
11407 DebugLoc dl = N->getDebugLoc();
11408 SDValue N0 = N->getOperand(0);
11409 EVT VT = N->getValueType(0);
11410 if (N0.getOpcode() == ISD::AND &&
11412 N0.getOperand(0).hasOneUse()) {
11413 SDValue N00 = N0.getOperand(0);
11414 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11416 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11417 if (!C || C->getZExtValue() != 1)
11419 return DAG.getNode(ISD::AND, dl, VT,
11420 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11421 N00.getOperand(0), N00.getOperand(1)),
11422 DAG.getConstant(1, VT));
11428 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11429 DAGCombinerInfo &DCI) const {
11430 SelectionDAG &DAG = DCI.DAG;
11431 switch (N->getOpcode()) {
11433 case ISD::EXTRACT_VECTOR_ELT:
11434 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11435 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11436 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11437 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11440 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11441 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11442 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11443 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11445 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11446 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11447 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11448 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11449 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11450 case X86ISD::SHUFPS: // Handle all target specific shuffles
11451 case X86ISD::SHUFPD:
11452 case X86ISD::PALIGN:
11453 case X86ISD::PUNPCKHBW:
11454 case X86ISD::PUNPCKHWD:
11455 case X86ISD::PUNPCKHDQ:
11456 case X86ISD::PUNPCKHQDQ:
11457 case X86ISD::UNPCKHPS:
11458 case X86ISD::UNPCKHPD:
11459 case X86ISD::PUNPCKLBW:
11460 case X86ISD::PUNPCKLWD:
11461 case X86ISD::PUNPCKLDQ:
11462 case X86ISD::PUNPCKLQDQ:
11463 case X86ISD::UNPCKLPS:
11464 case X86ISD::UNPCKLPD:
11465 case X86ISD::MOVHLPS:
11466 case X86ISD::MOVLHPS:
11467 case X86ISD::PSHUFD:
11468 case X86ISD::PSHUFHW:
11469 case X86ISD::PSHUFLW:
11470 case X86ISD::MOVSS:
11471 case X86ISD::MOVSD:
11472 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11478 /// isTypeDesirableForOp - Return true if the target has native support for
11479 /// the specified value type and it is 'desirable' to use the type for the
11480 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11481 /// instruction encodings are longer and some i16 instructions are slow.
11482 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11483 if (!isTypeLegal(VT))
11485 if (VT != MVT::i16)
11492 case ISD::SIGN_EXTEND:
11493 case ISD::ZERO_EXTEND:
11494 case ISD::ANY_EXTEND:
11507 /// IsDesirableToPromoteOp - This method query the target whether it is
11508 /// beneficial for dag combiner to promote the specified node. If true, it
11509 /// should return the desired promotion type by reference.
11510 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11511 EVT VT = Op.getValueType();
11512 if (VT != MVT::i16)
11515 bool Promote = false;
11516 bool Commute = false;
11517 switch (Op.getOpcode()) {
11520 LoadSDNode *LD = cast<LoadSDNode>(Op);
11521 // If the non-extending load has a single use and it's not live out, then it
11522 // might be folded.
11523 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11524 Op.hasOneUse()*/) {
11525 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11526 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11527 // The only case where we'd want to promote LOAD (rather then it being
11528 // promoted as an operand is when it's only use is liveout.
11529 if (UI->getOpcode() != ISD::CopyToReg)
11536 case ISD::SIGN_EXTEND:
11537 case ISD::ZERO_EXTEND:
11538 case ISD::ANY_EXTEND:
11543 SDValue N0 = Op.getOperand(0);
11544 // Look out for (store (shl (load), x)).
11545 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11558 SDValue N0 = Op.getOperand(0);
11559 SDValue N1 = Op.getOperand(1);
11560 if (!Commute && MayFoldLoad(N1))
11562 // Avoid disabling potential load folding opportunities.
11563 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11565 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11575 //===----------------------------------------------------------------------===//
11576 // X86 Inline Assembly Support
11577 //===----------------------------------------------------------------------===//
11579 static bool LowerToBSwap(CallInst *CI) {
11580 // FIXME: this should verify that we are targetting a 486 or better. If not,
11581 // we will turn this bswap into something that will be lowered to logical ops
11582 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11583 // so don't worry about this.
11585 // Verify this is a simple bswap.
11586 if (CI->getNumArgOperands() != 1 ||
11587 CI->getType() != CI->getArgOperand(0)->getType() ||
11588 !CI->getType()->isIntegerTy())
11591 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11592 if (!Ty || Ty->getBitWidth() % 16 != 0)
11595 // Okay, we can do this xform, do so now.
11596 const Type *Tys[] = { Ty };
11597 Module *M = CI->getParent()->getParent()->getParent();
11598 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11600 Value *Op = CI->getArgOperand(0);
11601 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11603 CI->replaceAllUsesWith(Op);
11604 CI->eraseFromParent();
11608 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11609 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11610 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11612 std::string AsmStr = IA->getAsmString();
11614 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11615 SmallVector<StringRef, 4> AsmPieces;
11616 SplitString(AsmStr, AsmPieces, ";\n");
11618 switch (AsmPieces.size()) {
11619 default: return false;
11621 AsmStr = AsmPieces[0];
11623 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11626 if (AsmPieces.size() == 2 &&
11627 (AsmPieces[0] == "bswap" ||
11628 AsmPieces[0] == "bswapq" ||
11629 AsmPieces[0] == "bswapl") &&
11630 (AsmPieces[1] == "$0" ||
11631 AsmPieces[1] == "${0:q}")) {
11632 // No need to check constraints, nothing other than the equivalent of
11633 // "=r,0" would be valid here.
11634 return LowerToBSwap(CI);
11636 // rorw $$8, ${0:w} --> llvm.bswap.i16
11637 if (CI->getType()->isIntegerTy(16) &&
11638 AsmPieces.size() == 3 &&
11639 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11640 AsmPieces[1] == "$$8," &&
11641 AsmPieces[2] == "${0:w}" &&
11642 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11644 const std::string &Constraints = IA->getConstraintString();
11645 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11646 std::sort(AsmPieces.begin(), AsmPieces.end());
11647 if (AsmPieces.size() == 4 &&
11648 AsmPieces[0] == "~{cc}" &&
11649 AsmPieces[1] == "~{dirflag}" &&
11650 AsmPieces[2] == "~{flags}" &&
11651 AsmPieces[3] == "~{fpsr}") {
11652 return LowerToBSwap(CI);
11657 if (CI->getType()->isIntegerTy(32) &&
11658 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11659 SmallVector<StringRef, 4> Words;
11660 SplitString(AsmPieces[0], Words, " \t,");
11661 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11662 Words[2] == "${0:w}") {
11664 SplitString(AsmPieces[1], Words, " \t,");
11665 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11666 Words[2] == "$0") {
11668 SplitString(AsmPieces[2], Words, " \t,");
11669 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11670 Words[2] == "${0:w}") {
11672 const std::string &Constraints = IA->getConstraintString();
11673 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11674 std::sort(AsmPieces.begin(), AsmPieces.end());
11675 if (AsmPieces.size() == 4 &&
11676 AsmPieces[0] == "~{cc}" &&
11677 AsmPieces[1] == "~{dirflag}" &&
11678 AsmPieces[2] == "~{flags}" &&
11679 AsmPieces[3] == "~{fpsr}") {
11680 return LowerToBSwap(CI);
11686 if (CI->getType()->isIntegerTy(64) &&
11687 Constraints.size() >= 2 &&
11688 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11689 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11690 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11691 SmallVector<StringRef, 4> Words;
11692 SplitString(AsmPieces[0], Words, " \t");
11693 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11695 SplitString(AsmPieces[1], Words, " \t");
11696 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11698 SplitString(AsmPieces[2], Words, " \t,");
11699 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11700 Words[2] == "%edx") {
11701 return LowerToBSwap(CI);
11713 /// getConstraintType - Given a constraint letter, return the type of
11714 /// constraint it is for this target.
11715 X86TargetLowering::ConstraintType
11716 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11717 if (Constraint.size() == 1) {
11718 switch (Constraint[0]) {
11728 return C_RegisterClass;
11752 return TargetLowering::getConstraintType(Constraint);
11755 /// Examine constraint type and operand type and determine a weight value.
11756 /// This object must already have been set up with the operand type
11757 /// and the current alternative constraint selected.
11758 TargetLowering::ConstraintWeight
11759 X86TargetLowering::getSingleConstraintMatchWeight(
11760 AsmOperandInfo &info, const char *constraint) const {
11761 ConstraintWeight weight = CW_Invalid;
11762 Value *CallOperandVal = info.CallOperandVal;
11763 // If we don't have a value, we can't do a match,
11764 // but allow it at the lowest weight.
11765 if (CallOperandVal == NULL)
11767 const Type *type = CallOperandVal->getType();
11768 // Look at the constraint type.
11769 switch (*constraint) {
11771 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11782 if (CallOperandVal->getType()->isIntegerTy())
11783 weight = CW_SpecificReg;
11788 if (type->isFloatingPointTy())
11789 weight = CW_SpecificReg;
11792 if (type->isX86_MMXTy() && Subtarget->hasMMX())
11793 weight = CW_SpecificReg;
11797 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11798 weight = CW_Register;
11801 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11802 if (C->getZExtValue() <= 31)
11803 weight = CW_Constant;
11807 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11808 if (C->getZExtValue() <= 63)
11809 weight = CW_Constant;
11813 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11814 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11815 weight = CW_Constant;
11819 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11820 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11821 weight = CW_Constant;
11825 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11826 if (C->getZExtValue() <= 3)
11827 weight = CW_Constant;
11831 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11832 if (C->getZExtValue() <= 0xff)
11833 weight = CW_Constant;
11838 if (dyn_cast<ConstantFP>(CallOperandVal)) {
11839 weight = CW_Constant;
11843 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11844 if ((C->getSExtValue() >= -0x80000000LL) &&
11845 (C->getSExtValue() <= 0x7fffffffLL))
11846 weight = CW_Constant;
11850 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11851 if (C->getZExtValue() <= 0xffffffff)
11852 weight = CW_Constant;
11859 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11860 /// with another that has more specific requirements based on the type of the
11861 /// corresponding operand.
11862 const char *X86TargetLowering::
11863 LowerXConstraint(EVT ConstraintVT) const {
11864 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11865 // 'f' like normal targets.
11866 if (ConstraintVT.isFloatingPoint()) {
11867 if (Subtarget->hasXMMInt())
11869 if (Subtarget->hasXMM())
11873 return TargetLowering::LowerXConstraint(ConstraintVT);
11876 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11877 /// vector. If it is invalid, don't add anything to Ops.
11878 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11880 std::vector<SDValue>&Ops,
11881 SelectionDAG &DAG) const {
11882 SDValue Result(0, 0);
11884 switch (Constraint) {
11887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11888 if (C->getZExtValue() <= 31) {
11889 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11895 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11896 if (C->getZExtValue() <= 63) {
11897 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11904 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11905 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11912 if (C->getZExtValue() <= 255) {
11913 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11919 // 32-bit signed value
11920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11921 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11922 C->getSExtValue())) {
11923 // Widen to 64 bits here to get it sign extended.
11924 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11927 // FIXME gcc accepts some relocatable values here too, but only in certain
11928 // memory models; it's complicated.
11933 // 32-bit unsigned value
11934 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11935 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11936 C->getZExtValue())) {
11937 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11941 // FIXME gcc accepts some relocatable values here too, but only in certain
11942 // memory models; it's complicated.
11946 // Literal immediates are always ok.
11947 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11948 // Widen to 64 bits here to get it sign extended.
11949 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11953 // In any sort of PIC mode addresses need to be computed at runtime by
11954 // adding in a register or some sort of table lookup. These can't
11955 // be used as immediates.
11956 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11959 // If we are in non-pic codegen mode, we allow the address of a global (with
11960 // an optional displacement) to be used with 'i'.
11961 GlobalAddressSDNode *GA = 0;
11962 int64_t Offset = 0;
11964 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11966 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11967 Offset += GA->getOffset();
11969 } else if (Op.getOpcode() == ISD::ADD) {
11970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11971 Offset += C->getZExtValue();
11972 Op = Op.getOperand(0);
11975 } else if (Op.getOpcode() == ISD::SUB) {
11976 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11977 Offset += -C->getZExtValue();
11978 Op = Op.getOperand(0);
11983 // Otherwise, this isn't something we can handle, reject it.
11987 const GlobalValue *GV = GA->getGlobal();
11988 // If we require an extra load to get this address, as in PIC mode, we
11989 // can't accept it.
11990 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11991 getTargetMachine())))
11994 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11995 GA->getValueType(0), Offset);
12000 if (Result.getNode()) {
12001 Ops.push_back(Result);
12004 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12007 std::vector<unsigned> X86TargetLowering::
12008 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12010 if (Constraint.size() == 1) {
12011 // FIXME: not handling fp-stack yet!
12012 switch (Constraint[0]) { // GCC X86 Constraint Letters
12013 default: break; // Unknown constraint letter
12014 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12015 if (Subtarget->is64Bit()) {
12016 if (VT == MVT::i32)
12017 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12018 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12019 X86::R10D,X86::R11D,X86::R12D,
12020 X86::R13D,X86::R14D,X86::R15D,
12021 X86::EBP, X86::ESP, 0);
12022 else if (VT == MVT::i16)
12023 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12024 X86::SI, X86::DI, X86::R8W,X86::R9W,
12025 X86::R10W,X86::R11W,X86::R12W,
12026 X86::R13W,X86::R14W,X86::R15W,
12027 X86::BP, X86::SP, 0);
12028 else if (VT == MVT::i8)
12029 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12030 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12031 X86::R10B,X86::R11B,X86::R12B,
12032 X86::R13B,X86::R14B,X86::R15B,
12033 X86::BPL, X86::SPL, 0);
12035 else if (VT == MVT::i64)
12036 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12037 X86::RSI, X86::RDI, X86::R8, X86::R9,
12038 X86::R10, X86::R11, X86::R12,
12039 X86::R13, X86::R14, X86::R15,
12040 X86::RBP, X86::RSP, 0);
12044 // 32-bit fallthrough
12045 case 'Q': // Q_REGS
12046 if (VT == MVT::i32)
12047 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12048 else if (VT == MVT::i16)
12049 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12050 else if (VT == MVT::i8)
12051 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12052 else if (VT == MVT::i64)
12053 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12058 return std::vector<unsigned>();
12061 std::pair<unsigned, const TargetRegisterClass*>
12062 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12064 // First, see if this is a constraint that directly corresponds to an LLVM
12066 if (Constraint.size() == 1) {
12067 // GCC Constraint Letters
12068 switch (Constraint[0]) {
12070 case 'r': // GENERAL_REGS
12071 case 'l': // INDEX_REGS
12073 return std::make_pair(0U, X86::GR8RegisterClass);
12074 if (VT == MVT::i16)
12075 return std::make_pair(0U, X86::GR16RegisterClass);
12076 if (VT == MVT::i32 || !Subtarget->is64Bit())
12077 return std::make_pair(0U, X86::GR32RegisterClass);
12078 return std::make_pair(0U, X86::GR64RegisterClass);
12079 case 'R': // LEGACY_REGS
12081 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12082 if (VT == MVT::i16)
12083 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12084 if (VT == MVT::i32 || !Subtarget->is64Bit())
12085 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12086 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12087 case 'f': // FP Stack registers.
12088 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12089 // value to the correct fpstack register class.
12090 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12091 return std::make_pair(0U, X86::RFP32RegisterClass);
12092 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12093 return std::make_pair(0U, X86::RFP64RegisterClass);
12094 return std::make_pair(0U, X86::RFP80RegisterClass);
12095 case 'y': // MMX_REGS if MMX allowed.
12096 if (!Subtarget->hasMMX()) break;
12097 return std::make_pair(0U, X86::VR64RegisterClass);
12098 case 'Y': // SSE_REGS if SSE2 allowed
12099 if (!Subtarget->hasXMMInt()) break;
12101 case 'x': // SSE_REGS if SSE1 allowed
12102 if (!Subtarget->hasXMM()) break;
12104 switch (VT.getSimpleVT().SimpleTy) {
12106 // Scalar SSE types.
12109 return std::make_pair(0U, X86::FR32RegisterClass);
12112 return std::make_pair(0U, X86::FR64RegisterClass);
12120 return std::make_pair(0U, X86::VR128RegisterClass);
12126 // Use the default implementation in TargetLowering to convert the register
12127 // constraint into a member of a register class.
12128 std::pair<unsigned, const TargetRegisterClass*> Res;
12129 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12131 // Not found as a standard register?
12132 if (Res.second == 0) {
12133 // Map st(0) -> st(7) -> ST0
12134 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12135 tolower(Constraint[1]) == 's' &&
12136 tolower(Constraint[2]) == 't' &&
12137 Constraint[3] == '(' &&
12138 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12139 Constraint[5] == ')' &&
12140 Constraint[6] == '}') {
12142 Res.first = X86::ST0+Constraint[4]-'0';
12143 Res.second = X86::RFP80RegisterClass;
12147 // GCC allows "st(0)" to be called just plain "st".
12148 if (StringRef("{st}").equals_lower(Constraint)) {
12149 Res.first = X86::ST0;
12150 Res.second = X86::RFP80RegisterClass;
12155 if (StringRef("{flags}").equals_lower(Constraint)) {
12156 Res.first = X86::EFLAGS;
12157 Res.second = X86::CCRRegisterClass;
12161 // 'A' means EAX + EDX.
12162 if (Constraint == "A") {
12163 Res.first = X86::EAX;
12164 Res.second = X86::GR32_ADRegisterClass;
12170 // Otherwise, check to see if this is a register class of the wrong value
12171 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12172 // turn into {ax},{dx}.
12173 if (Res.second->hasType(VT))
12174 return Res; // Correct type already, nothing to do.
12176 // All of the single-register GCC register classes map their values onto
12177 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12178 // really want an 8-bit or 32-bit register, map to the appropriate register
12179 // class and return the appropriate register.
12180 if (Res.second == X86::GR16RegisterClass) {
12181 if (VT == MVT::i8) {
12182 unsigned DestReg = 0;
12183 switch (Res.first) {
12185 case X86::AX: DestReg = X86::AL; break;
12186 case X86::DX: DestReg = X86::DL; break;
12187 case X86::CX: DestReg = X86::CL; break;
12188 case X86::BX: DestReg = X86::BL; break;
12191 Res.first = DestReg;
12192 Res.second = X86::GR8RegisterClass;
12194 } else if (VT == MVT::i32) {
12195 unsigned DestReg = 0;
12196 switch (Res.first) {
12198 case X86::AX: DestReg = X86::EAX; break;
12199 case X86::DX: DestReg = X86::EDX; break;
12200 case X86::CX: DestReg = X86::ECX; break;
12201 case X86::BX: DestReg = X86::EBX; break;
12202 case X86::SI: DestReg = X86::ESI; break;
12203 case X86::DI: DestReg = X86::EDI; break;
12204 case X86::BP: DestReg = X86::EBP; break;
12205 case X86::SP: DestReg = X86::ESP; break;
12208 Res.first = DestReg;
12209 Res.second = X86::GR32RegisterClass;
12211 } else if (VT == MVT::i64) {
12212 unsigned DestReg = 0;
12213 switch (Res.first) {
12215 case X86::AX: DestReg = X86::RAX; break;
12216 case X86::DX: DestReg = X86::RDX; break;
12217 case X86::CX: DestReg = X86::RCX; break;
12218 case X86::BX: DestReg = X86::RBX; break;
12219 case X86::SI: DestReg = X86::RSI; break;
12220 case X86::DI: DestReg = X86::RDI; break;
12221 case X86::BP: DestReg = X86::RBP; break;
12222 case X86::SP: DestReg = X86::RSP; break;
12225 Res.first = DestReg;
12226 Res.second = X86::GR64RegisterClass;
12229 } else if (Res.second == X86::FR32RegisterClass ||
12230 Res.second == X86::FR64RegisterClass ||
12231 Res.second == X86::VR128RegisterClass) {
12232 // Handle references to XMM physical registers that got mapped into the
12233 // wrong class. This can happen with constraints like {xmm0} where the
12234 // target independent register mapper will just pick the first match it can
12235 // find, ignoring the required type.
12236 if (VT == MVT::f32)
12237 Res.second = X86::FR32RegisterClass;
12238 else if (VT == MVT::f64)
12239 Res.second = X86::FR64RegisterClass;
12240 else if (X86::VR128RegisterClass->hasType(VT))
12241 Res.second = X86::VR128RegisterClass;