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 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
119 if (!UseSoftFloat && !NoImplicitFloat && X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
130 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
132 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
133 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
135 if (!UseSoftFloat && !NoImplicitFloat) {
136 // SSE has no i16 to fp conversion, only i32
137 if (X86ScalarSSEf32) {
138 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
139 // f32 and f64 cases are Legal, f80 case is not
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
142 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
143 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
147 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
150 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
151 // are Legal, f80 is custom lowered.
152 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
153 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
155 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
157 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
160 if (X86ScalarSSEf32) {
161 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
162 // f32 and f64 cases are Legal, f80 case is not
163 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
165 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
166 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
169 // Handle FP_TO_UINT by promoting the destination to a larger signed
171 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
172 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
173 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
175 if (Subtarget->is64Bit()) {
176 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
177 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
179 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
180 // Expand FP_TO_UINT into a select.
181 // FIXME: We would like to use a Custom expander here eventually to do
182 // the optimal thing for SSE vs. the default expansion in the legalizer.
183 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
185 // With SSE3 we can use fisttpll to convert to a signed i64.
186 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
189 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
190 if (!X86ScalarSSEf64) {
191 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
192 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
195 // Scalar integer divide and remainder are lowered to use operations that
196 // produce two results, to match the available instructions. This exposes
197 // the two-result form to trivial CSE, which is able to combine x/y and x%y
198 // into a single instruction.
200 // Scalar integer multiply-high is also lowered to use two-result
201 // operations, to match the available instructions. However, plain multiply
202 // (low) operations are left as Legal, as there are single-result
203 // instructions for this in x86. Using the two-result multiply instructions
204 // when both high and low results are needed must be arranged by dagcombine.
205 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
206 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
207 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
208 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
209 setOperationAction(ISD::SREM , MVT::i8 , Expand);
210 setOperationAction(ISD::UREM , MVT::i8 , Expand);
211 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
212 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
213 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
214 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
215 setOperationAction(ISD::SREM , MVT::i16 , Expand);
216 setOperationAction(ISD::UREM , MVT::i16 , Expand);
217 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
218 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
219 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
220 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
221 setOperationAction(ISD::SREM , MVT::i32 , Expand);
222 setOperationAction(ISD::UREM , MVT::i32 , Expand);
223 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
224 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
225 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
226 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
227 setOperationAction(ISD::SREM , MVT::i64 , Expand);
228 setOperationAction(ISD::UREM , MVT::i64 , Expand);
230 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
231 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
232 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
233 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
234 if (Subtarget->is64Bit())
235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
239 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
240 setOperationAction(ISD::FREM , MVT::f32 , Expand);
241 setOperationAction(ISD::FREM , MVT::f64 , Expand);
242 setOperationAction(ISD::FREM , MVT::f80 , Expand);
243 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
245 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
246 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
247 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
248 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
251 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
252 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
253 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
256 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
257 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
260 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
261 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
263 // These should be promoted to a larger select which is supported.
264 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
265 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
266 // X86 wants to expand cmov itself.
267 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
268 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
269 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
270 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
271 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
272 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
274 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
275 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
276 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
277 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
278 if (Subtarget->is64Bit()) {
279 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
280 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
282 // X86 ret instruction may pop stack.
283 setOperationAction(ISD::RET , MVT::Other, Custom);
284 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
287 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
288 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
289 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
290 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
291 if (Subtarget->is64Bit())
292 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
293 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
294 if (Subtarget->is64Bit()) {
295 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
296 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
297 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
298 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
300 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
301 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
302 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
303 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
304 if (Subtarget->is64Bit()) {
305 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
306 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
307 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
310 if (Subtarget->hasSSE1())
311 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
313 if (!Subtarget->hasSSE2())
314 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
316 // Expand certain atomics
317 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
318 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
327 if (!Subtarget->is64Bit()) {
328 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
332 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
333 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
334 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
337 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
338 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
339 // FIXME - use subtarget debug flags
340 if (!Subtarget->isTargetDarwin() &&
341 !Subtarget->isTargetELF() &&
342 !Subtarget->isTargetCygMing()) {
343 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
344 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
347 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
348 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
349 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
350 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
351 if (Subtarget->is64Bit()) {
352 setExceptionPointerRegister(X86::RAX);
353 setExceptionSelectorRegister(X86::RDX);
355 setExceptionPointerRegister(X86::EAX);
356 setExceptionSelectorRegister(X86::EDX);
358 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
359 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
361 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
363 setOperationAction(ISD::TRAP, MVT::Other, Legal);
365 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
366 setOperationAction(ISD::VASTART , MVT::Other, Custom);
367 setOperationAction(ISD::VAEND , MVT::Other, Expand);
368 if (Subtarget->is64Bit()) {
369 setOperationAction(ISD::VAARG , MVT::Other, Custom);
370 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
372 setOperationAction(ISD::VAARG , MVT::Other, Expand);
373 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
376 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
377 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
378 if (Subtarget->is64Bit())
379 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
380 if (Subtarget->isTargetCygMing())
381 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
383 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
385 if (!UseSoftFloat && X86ScalarSSEf64) {
386 // f32 and f64 use SSE.
387 // Set up the FP register classes.
388 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
389 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
391 // Use ANDPD to simulate FABS.
392 setOperationAction(ISD::FABS , MVT::f64, Custom);
393 setOperationAction(ISD::FABS , MVT::f32, Custom);
395 // Use XORP to simulate FNEG.
396 setOperationAction(ISD::FNEG , MVT::f64, Custom);
397 setOperationAction(ISD::FNEG , MVT::f32, Custom);
399 // Use ANDPD and ORPD to simulate FCOPYSIGN.
400 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
401 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
403 // We don't support sin/cos/fmod
404 setOperationAction(ISD::FSIN , MVT::f64, Expand);
405 setOperationAction(ISD::FCOS , MVT::f64, Expand);
406 setOperationAction(ISD::FSIN , MVT::f32, Expand);
407 setOperationAction(ISD::FCOS , MVT::f32, Expand);
409 // Expand FP immediates into loads from the stack, except for the special
411 addLegalFPImmediate(APFloat(+0.0)); // xorpd
412 addLegalFPImmediate(APFloat(+0.0f)); // xorps
414 // Floating truncations from f80 and extensions to f80 go through memory.
415 // If optimizing, we lie about this though and handle it in
416 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
418 setConvertAction(MVT::f32, MVT::f80, Expand);
419 setConvertAction(MVT::f64, MVT::f80, Expand);
420 setConvertAction(MVT::f80, MVT::f32, Expand);
421 setConvertAction(MVT::f80, MVT::f64, Expand);
423 } else if (!UseSoftFloat && X86ScalarSSEf32) {
424 // Use SSE for f32, x87 for f64.
425 // Set up the FP register classes.
426 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
429 // Use ANDPS to simulate FABS.
430 setOperationAction(ISD::FABS , MVT::f32, Custom);
432 // Use XORP to simulate FNEG.
433 setOperationAction(ISD::FNEG , MVT::f32, Custom);
435 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
437 // Use ANDPS and ORPS to simulate FCOPYSIGN.
438 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
441 // We don't support sin/cos/fmod
442 setOperationAction(ISD::FSIN , MVT::f32, Expand);
443 setOperationAction(ISD::FCOS , MVT::f32, Expand);
445 // Special cases we handle for FP constants.
446 addLegalFPImmediate(APFloat(+0.0f)); // xorps
447 addLegalFPImmediate(APFloat(+0.0)); // FLD0
448 addLegalFPImmediate(APFloat(+1.0)); // FLD1
449 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
450 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
452 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
453 // this though and handle it in InstructionSelectPreprocess so that
454 // dagcombine2 can hack on these.
456 setConvertAction(MVT::f32, MVT::f64, Expand);
457 setConvertAction(MVT::f32, MVT::f80, Expand);
458 setConvertAction(MVT::f80, MVT::f32, Expand);
459 setConvertAction(MVT::f64, MVT::f32, Expand);
460 // And x87->x87 truncations also.
461 setConvertAction(MVT::f80, MVT::f64, Expand);
465 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
466 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
468 } else if (!UseSoftFloat) {
469 // f32 and f64 in x87.
470 // Set up the FP register classes.
471 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
472 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
474 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
475 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
476 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
477 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
479 // Floating truncations go through memory. If optimizing, we lie about
480 // this though and handle it in InstructionSelectPreprocess so that
481 // dagcombine2 can hack on these.
483 setConvertAction(MVT::f80, MVT::f32, Expand);
484 setConvertAction(MVT::f64, MVT::f32, Expand);
485 setConvertAction(MVT::f80, MVT::f64, Expand);
489 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
490 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
492 addLegalFPImmediate(APFloat(+0.0)); // FLD0
493 addLegalFPImmediate(APFloat(+1.0)); // FLD1
494 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
495 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
496 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
497 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
498 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
499 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
502 // Long double always uses X87.
504 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
505 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
506 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
509 APFloat TmpFlt(+0.0);
510 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
512 addLegalFPImmediate(TmpFlt); // FLD0
514 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
515 APFloat TmpFlt2(+1.0);
516 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 addLegalFPImmediate(TmpFlt2); // FLD1
519 TmpFlt2.changeSign();
520 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
524 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
525 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
529 // Always use a library call for pow.
530 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
531 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
532 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
534 setOperationAction(ISD::FLOG, MVT::f80, Expand);
535 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
536 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
537 setOperationAction(ISD::FEXP, MVT::f80, Expand);
538 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
540 // First set operation action for all vector types to either promote
541 // (for widening) or expand (for scalarization). Then we will selectively
542 // turn on ones that can be effectively codegen'd.
543 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
544 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
545 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
560 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
590 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
591 // with -msoft-float, disable use of MMX as well.
592 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
593 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
594 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
595 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
596 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
597 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
599 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
600 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
601 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
602 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
604 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
605 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
606 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
607 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
609 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
610 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
612 setOperationAction(ISD::AND, MVT::v8i8, Promote);
613 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
614 setOperationAction(ISD::AND, MVT::v4i16, Promote);
615 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
616 setOperationAction(ISD::AND, MVT::v2i32, Promote);
617 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
618 setOperationAction(ISD::AND, MVT::v1i64, Legal);
620 setOperationAction(ISD::OR, MVT::v8i8, Promote);
621 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
622 setOperationAction(ISD::OR, MVT::v4i16, Promote);
623 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
624 setOperationAction(ISD::OR, MVT::v2i32, Promote);
625 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
626 setOperationAction(ISD::OR, MVT::v1i64, Legal);
628 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
629 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
630 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
631 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
632 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
633 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
634 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
636 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
637 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
638 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
639 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
640 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
641 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
642 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
643 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
644 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
646 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
648 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
650 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
662 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
664 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
665 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
666 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
667 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
668 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
669 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
672 if (!UseSoftFloat && Subtarget->hasSSE1()) {
673 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
675 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
676 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
677 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
678 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
679 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
680 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
681 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
682 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
683 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
684 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
685 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
686 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
689 if (!UseSoftFloat && Subtarget->hasSSE2()) {
690 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
692 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
693 // registers cannot be used even for integer operations.
694 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
695 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
696 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
697 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
699 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
700 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
701 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
702 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
703 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
704 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
705 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
706 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
707 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
708 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
709 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
710 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
711 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
712 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
713 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
714 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
716 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
717 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
718 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
719 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
722 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
723 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
724 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
725 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
727 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
728 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
729 MVT VT = (MVT::SimpleValueType)i;
730 // Do not attempt to custom lower non-power-of-2 vectors
731 if (!isPowerOf2_32(VT.getVectorNumElements()))
733 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
734 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
735 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
738 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
739 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
741 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
742 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
743 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
745 if (Subtarget->is64Bit()) {
746 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
750 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
751 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
752 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
753 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
754 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
755 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
756 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
757 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
758 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
759 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
760 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
761 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
764 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
766 // Custom lower v2i64 and v2f64 selects.
767 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
768 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
769 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
770 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
774 if (Subtarget->hasSSE41()) {
775 // FIXME: Do we need to handle scalar-to-vector here?
776 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
778 // i8 and i16 vectors are custom , because the source register and source
779 // source memory operand types are not the same width. f32 vectors are
780 // custom since the immediate controlling the insert encodes additional
782 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
784 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
788 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792 if (Subtarget->is64Bit()) {
793 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
794 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
798 if (Subtarget->hasSSE42()) {
799 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
802 // We want to custom lower some of our intrinsics.
803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
805 // Add/Sub/Mul with overflow operations are custom lowered.
806 setOperationAction(ISD::SADDO, MVT::i32, Custom);
807 setOperationAction(ISD::SADDO, MVT::i64, Custom);
808 setOperationAction(ISD::UADDO, MVT::i32, Custom);
809 setOperationAction(ISD::UADDO, MVT::i64, Custom);
810 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
811 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
812 setOperationAction(ISD::USUBO, MVT::i32, Custom);
813 setOperationAction(ISD::USUBO, MVT::i64, Custom);
814 setOperationAction(ISD::SMULO, MVT::i32, Custom);
815 setOperationAction(ISD::SMULO, MVT::i64, Custom);
816 setOperationAction(ISD::UMULO, MVT::i32, Custom);
817 setOperationAction(ISD::UMULO, MVT::i64, Custom);
819 if (!Subtarget->is64Bit()) {
820 // These libcalls are not available in 32-bit.
821 setLibcallName(RTLIB::SHL_I128, 0);
822 setLibcallName(RTLIB::SRL_I128, 0);
823 setLibcallName(RTLIB::SRA_I128, 0);
826 // We have target-specific dag combine patterns for the following nodes:
827 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
828 setTargetDAGCombine(ISD::BUILD_VECTOR);
829 setTargetDAGCombine(ISD::SELECT);
830 setTargetDAGCombine(ISD::SHL);
831 setTargetDAGCombine(ISD::SRA);
832 setTargetDAGCombine(ISD::SRL);
833 setTargetDAGCombine(ISD::STORE);
834 if (Subtarget->is64Bit())
835 setTargetDAGCombine(ISD::MUL);
837 computeRegisterProperties();
839 // FIXME: These should be based on subtarget info. Plus, the values should
840 // be smaller when we are in optimizing for size mode.
841 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
842 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
843 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
844 allowUnalignedMemoryAccesses = true; // x86 supports it!
845 setPrefLoopAlignment(16);
849 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
854 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
855 /// the desired ByVal argument alignment.
856 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
859 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
860 if (VTy->getBitWidth() == 128)
862 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
863 unsigned EltAlign = 0;
864 getMaxByValAlign(ATy->getElementType(), EltAlign);
865 if (EltAlign > MaxAlign)
867 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
868 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
869 unsigned EltAlign = 0;
870 getMaxByValAlign(STy->getElementType(i), EltAlign);
871 if (EltAlign > MaxAlign)
880 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
881 /// function arguments in the caller parameter area. For X86, aggregates
882 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
883 /// are at 4-byte boundaries.
884 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
885 if (Subtarget->is64Bit()) {
886 // Max of 8 and alignment of type.
887 unsigned TyAlign = TD->getABITypeAlignment(Ty);
894 if (Subtarget->hasSSE1())
895 getMaxByValAlign(Ty, Align);
899 /// getOptimalMemOpType - Returns the target specific optimal type for load
900 /// and store operations as a result of memset, memcpy, and memmove
901 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
904 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
905 bool isSrcConst, bool isSrcStr) const {
906 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
907 // linux. This is because the stack realignment code can't handle certain
908 // cases like PR2962. This should be removed when PR2962 is fixed.
909 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
910 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
912 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
915 if (Subtarget->is64Bit() && Size >= 8)
920 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
922 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
923 SelectionDAG &DAG) const {
924 if (usesGlobalOffsetTable())
925 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
926 if (!Subtarget->isPICStyleRIPRel())
927 // This doesn't have DebugLoc associated with it, but is not really the
928 // same as a Register.
929 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
934 //===----------------------------------------------------------------------===//
935 // Return Value Calling Convention Implementation
936 //===----------------------------------------------------------------------===//
938 #include "X86GenCallingConv.inc"
940 /// LowerRET - Lower an ISD::RET node.
941 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
942 DebugLoc dl = Op.getDebugLoc();
943 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
945 SmallVector<CCValAssign, 16> RVLocs;
946 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
947 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
948 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
949 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
951 // If this is the first return lowered for this function, add the regs to the
952 // liveout set for the function.
953 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
954 for (unsigned i = 0; i != RVLocs.size(); ++i)
955 if (RVLocs[i].isRegLoc())
956 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
958 SDValue Chain = Op.getOperand(0);
960 // Handle tail call return.
961 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
962 if (Chain.getOpcode() == X86ISD::TAILCALL) {
963 SDValue TailCall = Chain;
964 SDValue TargetAddress = TailCall.getOperand(1);
965 SDValue StackAdjustment = TailCall.getOperand(2);
966 assert(((TargetAddress.getOpcode() == ISD::Register &&
967 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
968 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
969 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
970 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
971 "Expecting an global address, external symbol, or register");
972 assert(StackAdjustment.getOpcode() == ISD::Constant &&
973 "Expecting a const value");
975 SmallVector<SDValue,8> Operands;
976 Operands.push_back(Chain.getOperand(0));
977 Operands.push_back(TargetAddress);
978 Operands.push_back(StackAdjustment);
979 // Copy registers used by the call. Last operand is a flag so it is not
981 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
982 Operands.push_back(Chain.getOperand(i));
984 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
991 SmallVector<SDValue, 6> RetOps;
992 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
993 // Operand #1 = Bytes To Pop
994 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
996 // Copy the result values into the output registers.
997 for (unsigned i = 0; i != RVLocs.size(); ++i) {
998 CCValAssign &VA = RVLocs[i];
999 assert(VA.isRegLoc() && "Can only return in registers!");
1000 SDValue ValToCopy = Op.getOperand(i*2+1);
1002 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1003 // the RET instruction and handled by the FP Stackifier.
1004 if (VA.getLocReg() == X86::ST0 ||
1005 VA.getLocReg() == X86::ST1) {
1006 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1007 // change the value to the FP stack register class.
1008 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1009 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1010 RetOps.push_back(ValToCopy);
1011 // Don't emit a copytoreg.
1015 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1016 // which is returned in RAX / RDX.
1017 if (Subtarget->is64Bit()) {
1018 MVT ValVT = ValToCopy.getValueType();
1019 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1020 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1021 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1022 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1026 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1027 Flag = Chain.getValue(1);
1030 // The x86-64 ABI for returning structs by value requires that we copy
1031 // the sret argument into %rax for the return. We saved the argument into
1032 // a virtual register in the entry block, so now we copy the value out
1034 if (Subtarget->is64Bit() &&
1035 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1036 MachineFunction &MF = DAG.getMachineFunction();
1037 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1038 unsigned Reg = FuncInfo->getSRetReturnReg();
1040 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1041 FuncInfo->setSRetReturnReg(Reg);
1043 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1045 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1046 Flag = Chain.getValue(1);
1049 RetOps[0] = Chain; // Update chain.
1051 // Add the flag if we have it.
1053 RetOps.push_back(Flag);
1055 return DAG.getNode(X86ISD::RET_FLAG, dl,
1056 MVT::Other, &RetOps[0], RetOps.size());
1060 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1061 /// appropriate copies out of appropriate physical registers. This assumes that
1062 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1063 /// being lowered. The returns a SDNode with the same number of values as the
1065 SDNode *X86TargetLowering::
1066 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1067 unsigned CallingConv, SelectionDAG &DAG) {
1069 DebugLoc dl = TheCall->getDebugLoc();
1070 // Assign locations to each value returned by this call.
1071 SmallVector<CCValAssign, 16> RVLocs;
1072 bool isVarArg = TheCall->isVarArg();
1073 bool Is64Bit = Subtarget->is64Bit();
1074 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1075 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1077 SmallVector<SDValue, 8> ResultVals;
1079 // Copy all of the result registers out of their specified physreg.
1080 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1081 CCValAssign &VA = RVLocs[i];
1082 MVT CopyVT = VA.getValVT();
1084 // If this is x86-64, and we disabled SSE, we can't return FP values
1085 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1086 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1087 cerr << "SSE register return with SSE disabled\n";
1091 // If this is a call to a function that returns an fp value on the floating
1092 // point stack, but where we prefer to use the value in xmm registers, copy
1093 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1094 if ((VA.getLocReg() == X86::ST0 ||
1095 VA.getLocReg() == X86::ST1) &&
1096 isScalarFPTypeInSSEReg(VA.getValVT())) {
1101 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1102 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1103 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1104 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1105 MVT::v2i64, InFlag).getValue(1);
1106 Val = Chain.getValue(0);
1107 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1108 Val, DAG.getConstant(0, MVT::i64));
1110 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1111 MVT::i64, InFlag).getValue(1);
1112 Val = Chain.getValue(0);
1114 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1116 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1117 CopyVT, InFlag).getValue(1);
1118 Val = Chain.getValue(0);
1120 InFlag = Chain.getValue(2);
1122 if (CopyVT != VA.getValVT()) {
1123 // Round the F80 the right size, which also moves to the appropriate xmm
1125 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1126 // This truncation won't change the value.
1127 DAG.getIntPtrConstant(1));
1130 ResultVals.push_back(Val);
1133 // Merge everything together with a MERGE_VALUES node.
1134 ResultVals.push_back(Chain);
1135 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1136 &ResultVals[0], ResultVals.size()).getNode();
1140 //===----------------------------------------------------------------------===//
1141 // C & StdCall & Fast Calling Convention implementation
1142 //===----------------------------------------------------------------------===//
1143 // StdCall calling convention seems to be standard for many Windows' API
1144 // routines and around. It differs from C calling convention just a little:
1145 // callee should clean up the stack, not caller. Symbols should be also
1146 // decorated in some fancy way :) It doesn't support any vector arguments.
1147 // For info on fast calling convention see Fast Calling Convention (tail call)
1148 // implementation LowerX86_32FastCCCallTo.
1150 /// AddLiveIn - This helper function adds the specified physical register to the
1151 /// MachineFunction as a live in value. It also creates a corresponding virtual
1152 /// register for it.
1153 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1154 const TargetRegisterClass *RC) {
1155 assert(RC->contains(PReg) && "Not the correct regclass!");
1156 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1157 MF.getRegInfo().addLiveIn(PReg, VReg);
1161 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1163 static bool CallIsStructReturn(CallSDNode *TheCall) {
1164 unsigned NumOps = TheCall->getNumArgs();
1168 return TheCall->getArgFlags(0).isSRet();
1171 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1172 /// return semantics.
1173 static bool ArgsAreStructReturn(SDValue Op) {
1174 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1178 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1181 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1182 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1184 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1188 switch (CallingConv) {
1191 case CallingConv::X86_StdCall:
1192 return !Subtarget->is64Bit();
1193 case CallingConv::X86_FastCall:
1194 return !Subtarget->is64Bit();
1195 case CallingConv::Fast:
1196 return PerformTailCallOpt;
1200 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1201 /// given CallingConvention value.
1202 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1203 if (Subtarget->is64Bit()) {
1204 if (Subtarget->isTargetWin64())
1205 return CC_X86_Win64_C;
1206 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1207 return CC_X86_64_TailCall;
1212 if (CC == CallingConv::X86_FastCall)
1213 return CC_X86_32_FastCall;
1214 else if (CC == CallingConv::Fast)
1215 return CC_X86_32_FastCC;
1220 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1221 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1223 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1224 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1225 if (CC == CallingConv::X86_FastCall)
1227 else if (CC == CallingConv::X86_StdCall)
1233 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1234 /// in a register before calling.
1235 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1236 return !IsTailCall && !Is64Bit &&
1237 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1238 Subtarget->isPICStyleGOT();
1241 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1242 /// address to be loaded in a register.
1244 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1245 return !Is64Bit && IsTailCall &&
1246 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1247 Subtarget->isPICStyleGOT();
1250 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1251 /// by "Src" to address "Dst" with size and alignment information specified by
1252 /// the specific parameter attribute. The copy will be passed as a byval
1253 /// function parameter.
1255 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1256 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1258 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1259 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1260 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1263 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1264 const CCValAssign &VA,
1265 MachineFrameInfo *MFI,
1267 SDValue Root, unsigned i) {
1268 // Create the nodes corresponding to a load from this parameter slot.
1269 ISD::ArgFlagsTy Flags =
1270 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1271 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1272 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1274 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1275 // changed with more analysis.
1276 // In case of tail call optimization mark all arguments mutable. Since they
1277 // could be overwritten by lowering of arguments in case of a tail call.
1278 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1279 VA.getLocMemOffset(), isImmutable);
1280 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1281 if (Flags.isByVal())
1283 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1284 PseudoSourceValue::getFixedStack(FI), 0);
1288 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1289 MachineFunction &MF = DAG.getMachineFunction();
1290 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1291 DebugLoc dl = Op.getDebugLoc();
1293 const Function* Fn = MF.getFunction();
1294 if (Fn->hasExternalLinkage() &&
1295 Subtarget->isTargetCygMing() &&
1296 Fn->getName() == "main")
1297 FuncInfo->setForceFramePointer(true);
1299 // Decorate the function name.
1300 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1302 MachineFrameInfo *MFI = MF.getFrameInfo();
1303 SDValue Root = Op.getOperand(0);
1304 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1305 unsigned CC = MF.getFunction()->getCallingConv();
1306 bool Is64Bit = Subtarget->is64Bit();
1307 bool IsWin64 = Subtarget->isTargetWin64();
1309 assert(!(isVarArg && CC == CallingConv::Fast) &&
1310 "Var args not supported with calling convention fastcc");
1312 // Assign locations to all of the incoming arguments.
1313 SmallVector<CCValAssign, 16> ArgLocs;
1314 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1315 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1317 SmallVector<SDValue, 8> ArgValues;
1318 unsigned LastVal = ~0U;
1319 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1320 CCValAssign &VA = ArgLocs[i];
1321 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1323 assert(VA.getValNo() != LastVal &&
1324 "Don't support value assigned to multiple locs yet");
1325 LastVal = VA.getValNo();
1327 if (VA.isRegLoc()) {
1328 MVT RegVT = VA.getLocVT();
1329 TargetRegisterClass *RC = NULL;
1330 if (RegVT == MVT::i32)
1331 RC = X86::GR32RegisterClass;
1332 else if (Is64Bit && RegVT == MVT::i64)
1333 RC = X86::GR64RegisterClass;
1334 else if (RegVT == MVT::f32)
1335 RC = X86::FR32RegisterClass;
1336 else if (RegVT == MVT::f64)
1337 RC = X86::FR64RegisterClass;
1338 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1339 RC = X86::VR128RegisterClass;
1340 else if (RegVT.isVector()) {
1341 assert(RegVT.getSizeInBits() == 64);
1343 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1345 // Darwin calling convention passes MMX values in either GPRs or
1346 // XMMs in x86-64. Other targets pass them in memory.
1347 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1348 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1351 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1356 assert(0 && "Unknown argument type!");
1359 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1360 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1362 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1363 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1365 if (VA.getLocInfo() == CCValAssign::SExt)
1366 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1367 DAG.getValueType(VA.getValVT()));
1368 else if (VA.getLocInfo() == CCValAssign::ZExt)
1369 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1370 DAG.getValueType(VA.getValVT()));
1372 if (VA.getLocInfo() != CCValAssign::Full)
1373 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1375 // Handle MMX values passed in GPRs.
1376 if (Is64Bit && RegVT != VA.getLocVT()) {
1377 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1378 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1379 else if (RC == X86::VR128RegisterClass) {
1380 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1381 ArgValue, DAG.getConstant(0, MVT::i64));
1382 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1386 ArgValues.push_back(ArgValue);
1388 assert(VA.isMemLoc());
1389 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1393 // The x86-64 ABI for returning structs by value requires that we copy
1394 // the sret argument into %rax for the return. Save the argument into
1395 // a virtual register so that we can access it from the return points.
1396 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1397 MachineFunction &MF = DAG.getMachineFunction();
1398 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1399 unsigned Reg = FuncInfo->getSRetReturnReg();
1401 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1402 FuncInfo->setSRetReturnReg(Reg);
1404 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1405 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1408 unsigned StackSize = CCInfo.getNextStackOffset();
1409 // align stack specially for tail calls
1410 if (PerformTailCallOpt && CC == CallingConv::Fast)
1411 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1413 // If the function takes variable number of arguments, make a frame index for
1414 // the start of the first vararg value... for expansion of llvm.va_start.
1416 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1417 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1420 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1422 // FIXME: We should really autogenerate these arrays
1423 static const unsigned GPR64ArgRegsWin64[] = {
1424 X86::RCX, X86::RDX, X86::R8, X86::R9
1426 static const unsigned XMMArgRegsWin64[] = {
1427 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1429 static const unsigned GPR64ArgRegs64Bit[] = {
1430 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1432 static const unsigned XMMArgRegs64Bit[] = {
1433 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1434 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1436 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1439 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1440 GPR64ArgRegs = GPR64ArgRegsWin64;
1441 XMMArgRegs = XMMArgRegsWin64;
1443 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1444 GPR64ArgRegs = GPR64ArgRegs64Bit;
1445 XMMArgRegs = XMMArgRegs64Bit;
1447 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1449 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1452 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1453 "SSE register cannot be used when SSE is disabled!");
1454 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1455 "SSE register cannot be used when SSE is disabled!");
1456 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1457 // Kernel mode asks for SSE to be disabled, so don't push them
1459 TotalNumXMMRegs = 0;
1461 // For X86-64, if there are vararg parameters that are passed via
1462 // registers, then we must store them to their spots on the stack so they
1463 // may be loaded by deferencing the result of va_next.
1464 VarArgsGPOffset = NumIntRegs * 8;
1465 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1466 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1467 TotalNumXMMRegs * 16, 16);
1469 // Store the integer parameter registers.
1470 SmallVector<SDValue, 8> MemOps;
1471 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1472 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1473 DAG.getIntPtrConstant(VarArgsGPOffset));
1474 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1475 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1476 X86::GR64RegisterClass);
1477 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1479 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1480 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1481 MemOps.push_back(Store);
1482 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1483 DAG.getIntPtrConstant(8));
1486 // Now store the XMM (fp + vector) parameter registers.
1487 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1488 DAG.getIntPtrConstant(VarArgsFPOffset));
1489 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1490 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1491 X86::VR128RegisterClass);
1492 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1494 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1495 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1496 MemOps.push_back(Store);
1497 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1498 DAG.getIntPtrConstant(16));
1500 if (!MemOps.empty())
1501 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1502 &MemOps[0], MemOps.size());
1506 ArgValues.push_back(Root);
1508 // Some CCs need callee pop.
1509 if (IsCalleePop(isVarArg, CC)) {
1510 BytesToPopOnReturn = StackSize; // Callee pops everything.
1511 BytesCallerReserves = 0;
1513 BytesToPopOnReturn = 0; // Callee pops nothing.
1514 // If this is an sret function, the return should pop the hidden pointer.
1515 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1516 BytesToPopOnReturn = 4;
1517 BytesCallerReserves = StackSize;
1521 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1522 if (CC == CallingConv::X86_FastCall)
1523 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1526 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1528 // Return the new list of results.
1529 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1530 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1534 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1535 const SDValue &StackPtr,
1536 const CCValAssign &VA,
1538 SDValue Arg, ISD::ArgFlagsTy Flags) {
1539 DebugLoc dl = TheCall->getDebugLoc();
1540 unsigned LocMemOffset = VA.getLocMemOffset();
1541 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1542 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1543 if (Flags.isByVal()) {
1544 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1546 return DAG.getStore(Chain, dl, Arg, PtrOff,
1547 PseudoSourceValue::getStack(), LocMemOffset);
1550 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1551 /// optimization is performed and it is required.
1553 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1554 SDValue &OutRetAddr,
1560 if (!IsTailCall || FPDiff==0) return Chain;
1562 // Adjust the Return address stack slot.
1563 MVT VT = getPointerTy();
1564 OutRetAddr = getReturnAddressFrameIndex(DAG);
1566 // Load the "old" Return address.
1567 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1568 return SDValue(OutRetAddr.getNode(), 1);
1571 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1572 /// optimization is performed and it is required (FPDiff!=0).
1574 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1575 SDValue Chain, SDValue RetAddrFrIdx,
1576 bool Is64Bit, int FPDiff, DebugLoc dl) {
1577 // Store the return address to the appropriate stack slot.
1578 if (!FPDiff) return Chain;
1579 // Calculate the new stack slot for the return address.
1580 int SlotSize = Is64Bit ? 8 : 4;
1581 int NewReturnAddrFI =
1582 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1583 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1584 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1585 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1586 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1590 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1591 MachineFunction &MF = DAG.getMachineFunction();
1592 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1593 SDValue Chain = TheCall->getChain();
1594 unsigned CC = TheCall->getCallingConv();
1595 bool isVarArg = TheCall->isVarArg();
1596 bool IsTailCall = TheCall->isTailCall() &&
1597 CC == CallingConv::Fast && PerformTailCallOpt;
1598 SDValue Callee = TheCall->getCallee();
1599 bool Is64Bit = Subtarget->is64Bit();
1600 bool IsStructRet = CallIsStructReturn(TheCall);
1601 DebugLoc dl = TheCall->getDebugLoc();
1603 assert(!(isVarArg && CC == CallingConv::Fast) &&
1604 "Var args not supported with calling convention fastcc");
1606 // Analyze operands of the call, assigning locations to each operand.
1607 SmallVector<CCValAssign, 16> ArgLocs;
1608 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1609 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1611 // Get a count of how many bytes are to be pushed on the stack.
1612 unsigned NumBytes = CCInfo.getNextStackOffset();
1613 if (PerformTailCallOpt && CC == CallingConv::Fast)
1614 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1618 // Lower arguments at fp - stackoffset + fpdiff.
1619 unsigned NumBytesCallerPushed =
1620 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1621 FPDiff = NumBytesCallerPushed - NumBytes;
1623 // Set the delta of movement of the returnaddr stackslot.
1624 // But only set if delta is greater than previous delta.
1625 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1626 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1629 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1631 SDValue RetAddrFrIdx;
1632 // Load return adress for tail calls.
1633 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1636 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1637 SmallVector<SDValue, 8> MemOpChains;
1640 // Walk the register/memloc assignments, inserting copies/loads. In the case
1641 // of tail call optimization arguments are handle later.
1642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1643 CCValAssign &VA = ArgLocs[i];
1644 SDValue Arg = TheCall->getArg(i);
1645 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1646 bool isByVal = Flags.isByVal();
1648 // Promote the value if needed.
1649 switch (VA.getLocInfo()) {
1650 default: assert(0 && "Unknown loc info!");
1651 case CCValAssign::Full: break;
1652 case CCValAssign::SExt:
1653 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1655 case CCValAssign::ZExt:
1656 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1658 case CCValAssign::AExt:
1659 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1663 if (VA.isRegLoc()) {
1665 MVT RegVT = VA.getLocVT();
1666 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1667 switch (VA.getLocReg()) {
1670 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1672 // Special case: passing MMX values in GPR registers.
1673 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1676 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1677 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1678 // Special case: passing MMX values in XMM registers.
1679 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1680 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1681 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1682 DAG.getUNDEF(MVT::v2i64), Arg,
1683 getMOVLMask(2, DAG, dl));
1688 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1690 if (!IsTailCall || (IsTailCall && isByVal)) {
1691 assert(VA.isMemLoc());
1692 if (StackPtr.getNode() == 0)
1693 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1695 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1696 Chain, Arg, Flags));
1701 if (!MemOpChains.empty())
1702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1703 &MemOpChains[0], MemOpChains.size());
1705 // Build a sequence of copy-to-reg nodes chained together with token chain
1706 // and flag operands which copy the outgoing args into registers.
1708 // Tail call byval lowering might overwrite argument registers so in case of
1709 // tail call optimization the copies to registers are lowered later.
1711 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1712 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1713 RegsToPass[i].second, InFlag);
1714 InFlag = Chain.getValue(1);
1717 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1719 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1720 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1721 DAG.getNode(X86ISD::GlobalBaseReg,
1722 DebugLoc::getUnknownLoc(),
1725 InFlag = Chain.getValue(1);
1727 // If we are tail calling and generating PIC/GOT style code load the address
1728 // of the callee into ecx. The value in ecx is used as target of the tail
1729 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1730 // calls on PIC/GOT architectures. Normally we would just put the address of
1731 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1732 // restored (since ebx is callee saved) before jumping to the target@PLT.
1733 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1734 // Note: The actual moving to ecx is done further down.
1735 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1736 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1737 !G->getGlobal()->hasProtectedVisibility())
1738 Callee = LowerGlobalAddress(Callee, DAG);
1739 else if (isa<ExternalSymbolSDNode>(Callee))
1740 Callee = LowerExternalSymbol(Callee,DAG);
1743 if (Is64Bit && isVarArg) {
1744 // From AMD64 ABI document:
1745 // For calls that may call functions that use varargs or stdargs
1746 // (prototype-less calls or calls to functions containing ellipsis (...) in
1747 // the declaration) %al is used as hidden argument to specify the number
1748 // of SSE registers used. The contents of %al do not need to match exactly
1749 // the number of registers, but must be an ubound on the number of SSE
1750 // registers used and is in the range 0 - 8 inclusive.
1752 // FIXME: Verify this on Win64
1753 // Count the number of XMM registers allocated.
1754 static const unsigned XMMArgRegs[] = {
1755 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1756 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1758 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1759 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1760 && "SSE registers cannot be used when SSE is disabled");
1762 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1763 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1764 InFlag = Chain.getValue(1);
1768 // For tail calls lower the arguments to the 'real' stack slot.
1770 SmallVector<SDValue, 8> MemOpChains2;
1773 // Do not flag preceeding copytoreg stuff together with the following stuff.
1775 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1776 CCValAssign &VA = ArgLocs[i];
1777 if (!VA.isRegLoc()) {
1778 assert(VA.isMemLoc());
1779 SDValue Arg = TheCall->getArg(i);
1780 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1781 // Create frame index.
1782 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1783 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1784 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1785 FIN = DAG.getFrameIndex(FI, getPointerTy());
1787 if (Flags.isByVal()) {
1788 // Copy relative to framepointer.
1789 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1790 if (StackPtr.getNode() == 0)
1791 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1793 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1795 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1798 // Store relative to framepointer.
1799 MemOpChains2.push_back(
1800 DAG.getStore(Chain, dl, Arg, FIN,
1801 PseudoSourceValue::getFixedStack(FI), 0));
1806 if (!MemOpChains2.empty())
1807 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1808 &MemOpChains2[0], MemOpChains2.size());
1810 // Copy arguments to their registers.
1811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1812 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1813 RegsToPass[i].second, InFlag);
1814 InFlag = Chain.getValue(1);
1818 // Store the return address to the appropriate stack slot.
1819 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1823 // If the callee is a GlobalAddress node (quite common, every direct call is)
1824 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1825 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1826 // We should use extra load for direct calls to dllimported functions in
1828 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1829 getTargetMachine(), true))
1830 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1832 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1833 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1834 } else if (IsTailCall) {
1835 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1837 Chain = DAG.getCopyToReg(Chain, dl,
1838 DAG.getRegister(Opc, getPointerTy()),
1840 Callee = DAG.getRegister(Opc, getPointerTy());
1841 // Add register as live out.
1842 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1845 // Returns a chain & a flag for retval copy to use.
1846 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1847 SmallVector<SDValue, 8> Ops;
1850 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1851 DAG.getIntPtrConstant(0, true), InFlag);
1852 InFlag = Chain.getValue(1);
1854 // Returns a chain & a flag for retval copy to use.
1855 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1859 Ops.push_back(Chain);
1860 Ops.push_back(Callee);
1863 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1865 // Add argument registers to the end of the list so that they are known live
1867 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1868 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1869 RegsToPass[i].second.getValueType()));
1871 // Add an implicit use GOT pointer in EBX.
1872 if (!IsTailCall && !Is64Bit &&
1873 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1874 Subtarget->isPICStyleGOT())
1875 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1877 // Add an implicit use of AL for x86 vararg functions.
1878 if (Is64Bit && isVarArg)
1879 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1881 if (InFlag.getNode())
1882 Ops.push_back(InFlag);
1885 assert(InFlag.getNode() &&
1886 "Flag must be set. Depend on flag being set in LowerRET");
1887 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1888 TheCall->getVTList(), &Ops[0], Ops.size());
1890 return SDValue(Chain.getNode(), Op.getResNo());
1893 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1894 InFlag = Chain.getValue(1);
1896 // Create the CALLSEQ_END node.
1897 unsigned NumBytesForCalleeToPush;
1898 if (IsCalleePop(isVarArg, CC))
1899 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1900 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1901 // If this is is a call to a struct-return function, the callee
1902 // pops the hidden struct pointer, so we have to push it back.
1903 // This is common for Darwin/X86, Linux & Mingw32 targets.
1904 NumBytesForCalleeToPush = 4;
1906 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1908 // Returns a flag for retval copy to use.
1909 Chain = DAG.getCALLSEQ_END(Chain,
1910 DAG.getIntPtrConstant(NumBytes, true),
1911 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1914 InFlag = Chain.getValue(1);
1916 // Handle result values, copying them out of physregs into vregs that we
1918 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1923 //===----------------------------------------------------------------------===//
1924 // Fast Calling Convention (tail call) implementation
1925 //===----------------------------------------------------------------------===//
1927 // Like std call, callee cleans arguments, convention except that ECX is
1928 // reserved for storing the tail called function address. Only 2 registers are
1929 // free for argument passing (inreg). Tail call optimization is performed
1931 // * tailcallopt is enabled
1932 // * caller/callee are fastcc
1933 // On X86_64 architecture with GOT-style position independent code only local
1934 // (within module) calls are supported at the moment.
1935 // To keep the stack aligned according to platform abi the function
1936 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1937 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1938 // If a tail called function callee has more arguments than the caller the
1939 // caller needs to make sure that there is room to move the RETADDR to. This is
1940 // achieved by reserving an area the size of the argument delta right after the
1941 // original REtADDR, but before the saved framepointer or the spilled registers
1942 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1954 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1955 /// for a 16 byte align requirement.
1956 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1957 SelectionDAG& DAG) {
1958 MachineFunction &MF = DAG.getMachineFunction();
1959 const TargetMachine &TM = MF.getTarget();
1960 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1961 unsigned StackAlignment = TFI.getStackAlignment();
1962 uint64_t AlignMask = StackAlignment - 1;
1963 int64_t Offset = StackSize;
1964 uint64_t SlotSize = TD->getPointerSize();
1965 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1966 // Number smaller than 12 so just add the difference.
1967 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1969 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1970 Offset = ((~AlignMask) & Offset) + StackAlignment +
1971 (StackAlignment-SlotSize);
1976 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1977 /// following the call is a return. A function is eligible if caller/callee
1978 /// calling conventions match, currently only fastcc supports tail calls, and
1979 /// the function CALL is immediatly followed by a RET.
1980 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1982 SelectionDAG& DAG) const {
1983 if (!PerformTailCallOpt)
1986 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1987 MachineFunction &MF = DAG.getMachineFunction();
1988 unsigned CallerCC = MF.getFunction()->getCallingConv();
1989 unsigned CalleeCC= TheCall->getCallingConv();
1990 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1991 SDValue Callee = TheCall->getCallee();
1992 // On x86/32Bit PIC/GOT tail calls are supported.
1993 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1994 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1997 // Can only do local tail calls (in same module, hidden or protected) on
1998 // x86_64 PIC/GOT at the moment.
1999 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2000 return G->getGlobal()->hasHiddenVisibility()
2001 || G->getGlobal()->hasProtectedVisibility();
2009 X86TargetLowering::createFastISel(MachineFunction &mf,
2010 MachineModuleInfo *mmo,
2012 DenseMap<const Value *, unsigned> &vm,
2013 DenseMap<const BasicBlock *,
2014 MachineBasicBlock *> &bm,
2015 DenseMap<const AllocaInst *, int> &am
2017 , SmallSet<Instruction*, 8> &cil
2020 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2028 //===----------------------------------------------------------------------===//
2029 // Other Lowering Hooks
2030 //===----------------------------------------------------------------------===//
2033 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2034 MachineFunction &MF = DAG.getMachineFunction();
2035 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2036 int ReturnAddrIndex = FuncInfo->getRAIndex();
2038 if (ReturnAddrIndex == 0) {
2039 // Set up a frame object for the return address.
2040 uint64_t SlotSize = TD->getPointerSize();
2041 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2042 FuncInfo->setRAIndex(ReturnAddrIndex);
2045 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2049 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2050 /// specific condition code, returning the condition code and the LHS/RHS of the
2051 /// comparison to make.
2052 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2053 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2055 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2056 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2057 // X > -1 -> X == 0, jump !sign.
2058 RHS = DAG.getConstant(0, RHS.getValueType());
2059 return X86::COND_NS;
2060 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2061 // X < 0 -> X == 0, jump on sign.
2063 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2065 RHS = DAG.getConstant(0, RHS.getValueType());
2066 return X86::COND_LE;
2070 switch (SetCCOpcode) {
2071 default: assert(0 && "Invalid integer condition!");
2072 case ISD::SETEQ: return X86::COND_E;
2073 case ISD::SETGT: return X86::COND_G;
2074 case ISD::SETGE: return X86::COND_GE;
2075 case ISD::SETLT: return X86::COND_L;
2076 case ISD::SETLE: return X86::COND_LE;
2077 case ISD::SETNE: return X86::COND_NE;
2078 case ISD::SETULT: return X86::COND_B;
2079 case ISD::SETUGT: return X86::COND_A;
2080 case ISD::SETULE: return X86::COND_BE;
2081 case ISD::SETUGE: return X86::COND_AE;
2085 // First determine if it is required or is profitable to flip the operands.
2087 // If LHS is a foldable load, but RHS is not, flip the condition.
2088 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2089 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2090 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2091 std::swap(LHS, RHS);
2094 switch (SetCCOpcode) {
2100 std::swap(LHS, RHS);
2104 // On a floating point condition, the flags are set as follows:
2106 // 0 | 0 | 0 | X > Y
2107 // 0 | 0 | 1 | X < Y
2108 // 1 | 0 | 0 | X == Y
2109 // 1 | 1 | 1 | unordered
2110 switch (SetCCOpcode) {
2111 default: assert(0 && "Condcode should be pre-legalized away");
2113 case ISD::SETEQ: return X86::COND_E;
2114 case ISD::SETOLT: // flipped
2116 case ISD::SETGT: return X86::COND_A;
2117 case ISD::SETOLE: // flipped
2119 case ISD::SETGE: return X86::COND_AE;
2120 case ISD::SETUGT: // flipped
2122 case ISD::SETLT: return X86::COND_B;
2123 case ISD::SETUGE: // flipped
2125 case ISD::SETLE: return X86::COND_BE;
2127 case ISD::SETNE: return X86::COND_NE;
2128 case ISD::SETUO: return X86::COND_P;
2129 case ISD::SETO: return X86::COND_NP;
2133 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2134 /// code. Current x86 isa includes the following FP cmov instructions:
2135 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2136 static bool hasFPCMov(unsigned X86CC) {
2152 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2153 /// true if Op is undef or if its value falls within the specified range (L, H].
2154 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2155 if (Op.getOpcode() == ISD::UNDEF)
2158 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2159 return (Val >= Low && Val < Hi);
2162 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2163 /// true if Op is undef or if its value equal to the specified value.
2164 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2165 if (Op.getOpcode() == ISD::UNDEF)
2167 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2170 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2171 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2172 bool X86::isPSHUFDMask(SDNode *N) {
2173 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2175 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2178 // Check if the value doesn't reference the second vector.
2179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2180 SDValue Arg = N->getOperand(i);
2181 if (Arg.getOpcode() == ISD::UNDEF) continue;
2182 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2183 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2190 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2191 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2192 bool X86::isPSHUFHWMask(SDNode *N) {
2193 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2195 if (N->getNumOperands() != 8)
2198 // Lower quadword copied in order.
2199 for (unsigned i = 0; i != 4; ++i) {
2200 SDValue Arg = N->getOperand(i);
2201 if (Arg.getOpcode() == ISD::UNDEF) continue;
2202 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2203 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2207 // Upper quadword shuffled.
2208 for (unsigned i = 4; i != 8; ++i) {
2209 SDValue Arg = N->getOperand(i);
2210 if (Arg.getOpcode() == ISD::UNDEF) continue;
2211 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2212 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2213 if (Val < 4 || Val > 7)
2220 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2221 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2222 bool X86::isPSHUFLWMask(SDNode *N) {
2223 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2225 if (N->getNumOperands() != 8)
2228 // Upper quadword copied in order.
2229 for (unsigned i = 4; i != 8; ++i)
2230 if (!isUndefOrEqual(N->getOperand(i), i))
2233 // Lower quadword shuffled.
2234 for (unsigned i = 0; i != 4; ++i)
2235 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2241 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2242 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2243 template<class SDOperand>
2244 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2245 if (NumElems != 2 && NumElems != 4) return false;
2247 unsigned Half = NumElems / 2;
2248 for (unsigned i = 0; i < Half; ++i)
2249 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2251 for (unsigned i = Half; i < NumElems; ++i)
2252 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2258 bool X86::isSHUFPMask(SDNode *N) {
2259 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2260 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2263 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2264 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2265 /// half elements to come from vector 1 (which would equal the dest.) and
2266 /// the upper half to come from vector 2.
2267 template<class SDOperand>
2268 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2269 if (NumOps != 2 && NumOps != 4) return false;
2271 unsigned Half = NumOps / 2;
2272 for (unsigned i = 0; i < Half; ++i)
2273 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2275 for (unsigned i = Half; i < NumOps; ++i)
2276 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2281 static bool isCommutedSHUFP(SDNode *N) {
2282 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2283 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2286 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2287 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2288 bool X86::isMOVHLPSMask(SDNode *N) {
2289 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2291 if (N->getNumOperands() != 4)
2294 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2295 return isUndefOrEqual(N->getOperand(0), 6) &&
2296 isUndefOrEqual(N->getOperand(1), 7) &&
2297 isUndefOrEqual(N->getOperand(2), 2) &&
2298 isUndefOrEqual(N->getOperand(3), 3);
2301 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2302 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2304 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2305 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2307 if (N->getNumOperands() != 4)
2310 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2311 return isUndefOrEqual(N->getOperand(0), 2) &&
2312 isUndefOrEqual(N->getOperand(1), 3) &&
2313 isUndefOrEqual(N->getOperand(2), 2) &&
2314 isUndefOrEqual(N->getOperand(3), 3);
2317 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2318 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2319 bool X86::isMOVLPMask(SDNode *N) {
2320 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2322 unsigned NumElems = N->getNumOperands();
2323 if (NumElems != 2 && NumElems != 4)
2326 for (unsigned i = 0; i < NumElems/2; ++i)
2327 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2330 for (unsigned i = NumElems/2; i < NumElems; ++i)
2331 if (!isUndefOrEqual(N->getOperand(i), i))
2337 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2338 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2340 bool X86::isMOVHPMask(SDNode *N) {
2341 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2343 unsigned NumElems = N->getNumOperands();
2344 if (NumElems != 2 && NumElems != 4)
2347 for (unsigned i = 0; i < NumElems/2; ++i)
2348 if (!isUndefOrEqual(N->getOperand(i), i))
2351 for (unsigned i = 0; i < NumElems/2; ++i) {
2352 SDValue Arg = N->getOperand(i + NumElems/2);
2353 if (!isUndefOrEqual(Arg, i + NumElems))
2360 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2361 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2362 template<class SDOperand>
2363 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2364 bool V2IsSplat = false) {
2365 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2368 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2369 SDValue BitI = Elts[i];
2370 SDValue BitI1 = Elts[i+1];
2371 if (!isUndefOrEqual(BitI, j))
2374 if (!isUndefOrEqual(BitI1, NumElts))
2377 if (!isUndefOrEqual(BitI1, j + NumElts))
2385 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2386 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2387 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2390 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2391 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2392 template<class SDOperand>
2393 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2394 bool V2IsSplat = false) {
2395 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2398 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2399 SDValue BitI = Elts[i];
2400 SDValue BitI1 = Elts[i+1];
2401 if (!isUndefOrEqual(BitI, j + NumElts/2))
2404 if (isUndefOrEqual(BitI1, NumElts))
2407 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2415 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2420 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2421 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2423 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2424 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2426 unsigned NumElems = N->getNumOperands();
2427 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2430 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2431 SDValue BitI = N->getOperand(i);
2432 SDValue BitI1 = N->getOperand(i+1);
2434 if (!isUndefOrEqual(BitI, j))
2436 if (!isUndefOrEqual(BitI1, j))
2443 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2444 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2446 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2447 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2449 unsigned NumElems = N->getNumOperands();
2450 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2453 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2454 SDValue BitI = N->getOperand(i);
2455 SDValue BitI1 = N->getOperand(i + 1);
2457 if (!isUndefOrEqual(BitI, j))
2459 if (!isUndefOrEqual(BitI1, j))
2466 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2467 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2468 /// MOVSD, and MOVD, i.e. setting the lowest element.
2469 template<class SDOperand>
2470 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2471 if (NumElts != 2 && NumElts != 4)
2474 if (!isUndefOrEqual(Elts[0], NumElts))
2477 for (unsigned i = 1; i < NumElts; ++i) {
2478 if (!isUndefOrEqual(Elts[i], i))
2485 bool X86::isMOVLMask(SDNode *N) {
2486 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2487 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2490 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2491 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2492 /// element of vector 2 and the other elements to come from vector 1 in order.
2493 template<class SDOperand>
2494 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2495 bool V2IsSplat = false,
2496 bool V2IsUndef = false) {
2497 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2500 if (!isUndefOrEqual(Ops[0], 0))
2503 for (unsigned i = 1; i < NumOps; ++i) {
2504 SDValue Arg = Ops[i];
2505 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2506 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2507 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2514 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2515 bool V2IsUndef = false) {
2516 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2517 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2518 V2IsSplat, V2IsUndef);
2521 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2522 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2523 bool X86::isMOVSHDUPMask(SDNode *N) {
2524 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2526 if (N->getNumOperands() != 4)
2529 // Expect 1, 1, 3, 3
2530 for (unsigned i = 0; i < 2; ++i) {
2531 SDValue Arg = N->getOperand(i);
2532 if (Arg.getOpcode() == ISD::UNDEF) continue;
2533 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2534 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2535 if (Val != 1) return false;
2539 for (unsigned i = 2; i < 4; ++i) {
2540 SDValue Arg = N->getOperand(i);
2541 if (Arg.getOpcode() == ISD::UNDEF) continue;
2542 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2543 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2544 if (Val != 3) return false;
2548 // Don't use movshdup if it can be done with a shufps.
2552 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2553 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2554 bool X86::isMOVSLDUPMask(SDNode *N) {
2555 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2557 if (N->getNumOperands() != 4)
2560 // Expect 0, 0, 2, 2
2561 for (unsigned i = 0; i < 2; ++i) {
2562 SDValue Arg = N->getOperand(i);
2563 if (Arg.getOpcode() == ISD::UNDEF) continue;
2564 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2565 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2566 if (Val != 0) return false;
2570 for (unsigned i = 2; i < 4; ++i) {
2571 SDValue Arg = N->getOperand(i);
2572 if (Arg.getOpcode() == ISD::UNDEF) continue;
2573 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2574 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2575 if (Val != 2) return false;
2579 // Don't use movshdup if it can be done with a shufps.
2583 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2584 /// specifies a identity operation on the LHS or RHS.
2585 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2586 unsigned NumElems = N->getNumOperands();
2587 for (unsigned i = 0; i < NumElems; ++i)
2588 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2593 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2594 /// a splat of a single element.
2595 static bool isSplatMask(SDNode *N) {
2596 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2598 // This is a splat operation if each element of the permute is the same, and
2599 // if the value doesn't reference the second vector.
2600 unsigned NumElems = N->getNumOperands();
2601 SDValue ElementBase;
2603 for (; i != NumElems; ++i) {
2604 SDValue Elt = N->getOperand(i);
2605 if (isa<ConstantSDNode>(Elt)) {
2611 if (!ElementBase.getNode())
2614 for (; i != NumElems; ++i) {
2615 SDValue Arg = N->getOperand(i);
2616 if (Arg.getOpcode() == ISD::UNDEF) continue;
2617 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2618 if (Arg != ElementBase) return false;
2621 // Make sure it is a splat of the first vector operand.
2622 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2625 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2626 /// we want to splat.
2627 static SDValue getSplatMaskEltNo(SDNode *N) {
2628 assert(isSplatMask(N) && "Not a splat mask");
2629 unsigned NumElems = N->getNumOperands();
2630 SDValue ElementBase;
2632 for (; i != NumElems; ++i) {
2633 SDValue Elt = N->getOperand(i);
2634 if (isa<ConstantSDNode>(Elt))
2637 assert(0 && " No splat value found!");
2642 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2643 /// a splat of a single element and it's a 2 or 4 element mask.
2644 bool X86::isSplatMask(SDNode *N) {
2645 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2647 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2648 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2650 return ::isSplatMask(N);
2653 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2654 /// specifies a splat of zero element.
2655 bool X86::isSplatLoMask(SDNode *N) {
2656 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2658 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2659 if (!isUndefOrEqual(N->getOperand(i), 0))
2664 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2665 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2666 bool X86::isMOVDDUPMask(SDNode *N) {
2667 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2669 unsigned e = N->getNumOperands() / 2;
2670 for (unsigned i = 0; i < e; ++i)
2671 if (!isUndefOrEqual(N->getOperand(i), i))
2673 for (unsigned i = 0; i < e; ++i)
2674 if (!isUndefOrEqual(N->getOperand(e+i), i))
2679 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2680 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2682 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2683 unsigned NumOperands = N->getNumOperands();
2684 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2686 for (unsigned i = 0; i < NumOperands; ++i) {
2688 SDValue Arg = N->getOperand(NumOperands-i-1);
2689 if (Arg.getOpcode() != ISD::UNDEF)
2690 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2691 if (Val >= NumOperands) Val -= NumOperands;
2693 if (i != NumOperands - 1)
2700 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2701 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2703 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2705 // 8 nodes, but we only care about the last 4.
2706 for (unsigned i = 7; i >= 4; --i) {
2708 SDValue Arg = N->getOperand(i);
2709 if (Arg.getOpcode() != ISD::UNDEF) {
2710 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2720 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2721 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2723 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2725 // 8 nodes, but we only care about the first 4.
2726 for (int i = 3; i >= 0; --i) {
2728 SDValue Arg = N->getOperand(i);
2729 if (Arg.getOpcode() != ISD::UNDEF)
2730 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2739 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2740 /// values in ther permute mask.
2741 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2742 SDValue &V2, SDValue &Mask,
2743 SelectionDAG &DAG) {
2744 MVT VT = Op.getValueType();
2745 MVT MaskVT = Mask.getValueType();
2746 MVT EltVT = MaskVT.getVectorElementType();
2747 unsigned NumElems = Mask.getNumOperands();
2748 SmallVector<SDValue, 8> MaskVec;
2749 DebugLoc dl = Op.getDebugLoc();
2751 for (unsigned i = 0; i != NumElems; ++i) {
2752 SDValue Arg = Mask.getOperand(i);
2753 if (Arg.getOpcode() == ISD::UNDEF) {
2754 MaskVec.push_back(DAG.getUNDEF(EltVT));
2757 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2758 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2760 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2762 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2766 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2767 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2770 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2771 /// the two vector operands have swapped position.
2773 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2774 MVT MaskVT = Mask.getValueType();
2775 MVT EltVT = MaskVT.getVectorElementType();
2776 unsigned NumElems = Mask.getNumOperands();
2777 SmallVector<SDValue, 8> MaskVec;
2778 for (unsigned i = 0; i != NumElems; ++i) {
2779 SDValue Arg = Mask.getOperand(i);
2780 if (Arg.getOpcode() == ISD::UNDEF) {
2781 MaskVec.push_back(DAG.getUNDEF(EltVT));
2784 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2785 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2787 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2789 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2791 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2795 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2796 /// match movhlps. The lower half elements should come from upper half of
2797 /// V1 (and in order), and the upper half elements should come from the upper
2798 /// half of V2 (and in order).
2799 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2800 unsigned NumElems = Mask->getNumOperands();
2803 for (unsigned i = 0, e = 2; i != e; ++i)
2804 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2806 for (unsigned i = 2; i != 4; ++i)
2807 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2812 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2813 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2815 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2816 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2818 N = N->getOperand(0).getNode();
2819 if (!ISD::isNON_EXTLoad(N))
2822 *LD = cast<LoadSDNode>(N);
2826 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2827 /// match movlp{s|d}. The lower half elements should come from lower half of
2828 /// V1 (and in order), and the upper half elements should come from the upper
2829 /// half of V2 (and in order). And since V1 will become the source of the
2830 /// MOVLP, it must be either a vector load or a scalar load to vector.
2831 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2832 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2834 // Is V2 is a vector load, don't do this transformation. We will try to use
2835 // load folding shufps op.
2836 if (ISD::isNON_EXTLoad(V2))
2839 unsigned NumElems = Mask->getNumOperands();
2840 if (NumElems != 2 && NumElems != 4)
2842 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2843 if (!isUndefOrEqual(Mask->getOperand(i), i))
2845 for (unsigned i = NumElems/2; i != NumElems; ++i)
2846 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2851 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2853 static bool isSplatVector(SDNode *N) {
2854 if (N->getOpcode() != ISD::BUILD_VECTOR)
2857 SDValue SplatValue = N->getOperand(0);
2858 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2859 if (N->getOperand(i) != SplatValue)
2864 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2866 static bool isUndefShuffle(SDNode *N) {
2867 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2870 SDValue V1 = N->getOperand(0);
2871 SDValue V2 = N->getOperand(1);
2872 SDValue Mask = N->getOperand(2);
2873 unsigned NumElems = Mask.getNumOperands();
2874 for (unsigned i = 0; i != NumElems; ++i) {
2875 SDValue Arg = Mask.getOperand(i);
2876 if (Arg.getOpcode() != ISD::UNDEF) {
2877 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2878 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2880 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2887 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2889 static inline bool isZeroNode(SDValue Elt) {
2890 return ((isa<ConstantSDNode>(Elt) &&
2891 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2892 (isa<ConstantFPSDNode>(Elt) &&
2893 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2896 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2897 /// to an zero vector.
2898 static bool isZeroShuffle(SDNode *N) {
2899 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2902 SDValue V1 = N->getOperand(0);
2903 SDValue V2 = N->getOperand(1);
2904 SDValue Mask = N->getOperand(2);
2905 unsigned NumElems = Mask.getNumOperands();
2906 for (unsigned i = 0; i != NumElems; ++i) {
2907 SDValue Arg = Mask.getOperand(i);
2908 if (Arg.getOpcode() == ISD::UNDEF)
2911 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2912 if (Idx < NumElems) {
2913 unsigned Opc = V1.getNode()->getOpcode();
2914 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2916 if (Opc != ISD::BUILD_VECTOR ||
2917 !isZeroNode(V1.getNode()->getOperand(Idx)))
2919 } else if (Idx >= NumElems) {
2920 unsigned Opc = V2.getNode()->getOpcode();
2921 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2923 if (Opc != ISD::BUILD_VECTOR ||
2924 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2931 /// getZeroVector - Returns a vector of specified type with all zero elements.
2933 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2935 assert(VT.isVector() && "Expected a vector type");
2937 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2938 // type. This ensures they get CSE'd.
2940 if (VT.getSizeInBits() == 64) { // MMX
2941 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2942 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2943 } else if (HasSSE2) { // SSE2
2944 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2947 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2948 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2950 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2953 /// getOnesVector - Returns a vector of specified type with all bits set.
2955 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2956 assert(VT.isVector() && "Expected a vector type");
2958 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2959 // type. This ensures they get CSE'd.
2960 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2962 if (VT.getSizeInBits() == 64) // MMX
2963 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2965 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2966 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2970 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2971 /// that point to V2 points to its first element.
2972 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2973 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2975 bool Changed = false;
2976 SmallVector<SDValue, 8> MaskVec;
2977 unsigned NumElems = Mask.getNumOperands();
2978 for (unsigned i = 0; i != NumElems; ++i) {
2979 SDValue Arg = Mask.getOperand(i);
2980 if (Arg.getOpcode() != ISD::UNDEF) {
2981 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2982 if (Val > NumElems) {
2983 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2987 MaskVec.push_back(Arg);
2991 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getDebugLoc(),
2992 Mask.getValueType(),
2993 &MaskVec[0], MaskVec.size());
2997 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2998 /// operation of specified width.
2999 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
3000 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3001 MVT BaseVT = MaskVT.getVectorElementType();
3003 SmallVector<SDValue, 8> MaskVec;
3004 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
3005 for (unsigned i = 1; i != NumElems; ++i)
3006 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3007 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3008 &MaskVec[0], MaskVec.size());
3011 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
3012 /// of specified width.
3013 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
3015 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3016 MVT BaseVT = MaskVT.getVectorElementType();
3017 SmallVector<SDValue, 8> MaskVec;
3018 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3019 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3020 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3022 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3023 &MaskVec[0], MaskVec.size());
3026 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3027 /// of specified width.
3028 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3030 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3031 MVT BaseVT = MaskVT.getVectorElementType();
3032 unsigned Half = NumElems/2;
3033 SmallVector<SDValue, 8> MaskVec;
3034 for (unsigned i = 0; i != Half; ++i) {
3035 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3036 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3038 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3039 &MaskVec[0], MaskVec.size());
3042 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3043 /// element #0 of a vector with the specified index, leaving the rest of the
3044 /// elements in place.
3045 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3046 SelectionDAG &DAG, DebugLoc dl) {
3047 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3048 MVT BaseVT = MaskVT.getVectorElementType();
3049 SmallVector<SDValue, 8> MaskVec;
3050 // Element #0 of the result gets the elt we are replacing.
3051 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3052 for (unsigned i = 1; i != NumElems; ++i)
3053 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3054 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3055 &MaskVec[0], MaskVec.size());
3058 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3059 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3060 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3061 MVT VT = Op.getValueType();
3064 SDValue V1 = Op.getOperand(0);
3065 SDValue Mask = Op.getOperand(2);
3066 unsigned MaskNumElems = Mask.getNumOperands();
3067 unsigned NumElems = MaskNumElems;
3068 DebugLoc dl = Op.getDebugLoc();
3069 // Special handling of v4f32 -> v4i32.
3070 if (VT != MVT::v4f32) {
3071 // Find which element we want to splat.
3072 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3073 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3074 // unpack elements to the correct location
3075 while (NumElems > 4) {
3076 if (EltNo < NumElems/2) {
3077 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3079 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3080 EltNo -= NumElems/2;
3082 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3085 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3086 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3089 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3090 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3091 DAG.getUNDEF(PVT), Mask);
3092 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3095 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3096 /// load that's promoted to vector, or a load bitcasted.
3097 static bool isVectorLoad(SDValue Op) {
3098 assert(Op.getValueType().isVector() && "Expected a vector type");
3099 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3100 Op.getOpcode() == ISD::BIT_CONVERT) {
3101 return isa<LoadSDNode>(Op.getOperand(0));
3103 return isa<LoadSDNode>(Op);
3107 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3109 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3110 SelectionDAG &DAG, bool HasSSE3) {
3111 // If we have sse3 and shuffle has more than one use or input is a load, then
3112 // use movddup. Otherwise, use movlhps.
3113 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3114 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3115 MVT VT = Op.getValueType();
3118 DebugLoc dl = Op.getDebugLoc();
3119 unsigned NumElems = PVT.getVectorNumElements();
3120 if (NumElems == 2) {
3121 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3122 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3124 assert(NumElems == 4);
3125 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3126 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3127 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3128 Cst0, Cst1, Cst0, Cst1);
3131 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3132 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3133 DAG.getUNDEF(PVT), Mask);
3134 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3137 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3138 /// vector of zero or undef vector. This produces a shuffle where the low
3139 /// element of V2 is swizzled into the zero/undef vector, landing at element
3140 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3141 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3142 bool isZero, bool HasSSE2,
3143 SelectionDAG &DAG) {
3144 DebugLoc dl = V2.getDebugLoc();
3145 MVT VT = V2.getValueType();
3147 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getUNDEF(VT);
3148 unsigned NumElems = V2.getValueType().getVectorNumElements();
3149 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3150 MVT EVT = MaskVT.getVectorElementType();
3151 SmallVector<SDValue, 16> MaskVec;
3152 for (unsigned i = 0; i != NumElems; ++i)
3153 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3154 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3156 MaskVec.push_back(DAG.getConstant(i, EVT));
3157 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3158 &MaskVec[0], MaskVec.size());
3159 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3162 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3163 /// a shuffle that is zero.
3165 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3166 unsigned NumElems, bool Low,
3167 SelectionDAG &DAG) {
3168 unsigned NumZeros = 0;
3169 for (unsigned i = 0; i < NumElems; ++i) {
3170 unsigned Index = Low ? i : NumElems-i-1;
3171 SDValue Idx = Mask.getOperand(Index);
3172 if (Idx.getOpcode() == ISD::UNDEF) {
3176 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3177 if (Elt.getNode() && isZeroNode(Elt))
3185 /// isVectorShift - Returns true if the shuffle can be implemented as a
3186 /// logical left or right shift of a vector.
3187 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3188 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3189 unsigned NumElems = Mask.getNumOperands();
3192 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3195 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3200 bool SeenV1 = false;
3201 bool SeenV2 = false;
3202 for (unsigned i = NumZeros; i < NumElems; ++i) {
3203 unsigned Val = isLeft ? (i - NumZeros) : i;
3204 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3205 if (Idx.getOpcode() == ISD::UNDEF)
3207 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3208 if (Index < NumElems)
3217 if (SeenV1 && SeenV2)
3220 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3226 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3228 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3229 unsigned NumNonZero, unsigned NumZero,
3230 SelectionDAG &DAG, TargetLowering &TLI) {
3234 DebugLoc dl = Op.getDebugLoc();
3237 for (unsigned i = 0; i < 16; ++i) {
3238 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3239 if (ThisIsNonZero && First) {
3241 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3243 V = DAG.getUNDEF(MVT::v8i16);
3248 SDValue ThisElt(0, 0), LastElt(0, 0);
3249 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3250 if (LastIsNonZero) {
3251 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3252 MVT::i16, Op.getOperand(i-1));
3254 if (ThisIsNonZero) {
3255 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3256 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3257 ThisElt, DAG.getConstant(8, MVT::i8));
3259 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3263 if (ThisElt.getNode())
3264 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3265 DAG.getIntPtrConstant(i/2));
3269 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3272 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3274 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3275 unsigned NumNonZero, unsigned NumZero,
3276 SelectionDAG &DAG, TargetLowering &TLI) {
3280 DebugLoc dl = Op.getDebugLoc();
3283 for (unsigned i = 0; i < 8; ++i) {
3284 bool isNonZero = (NonZeros & (1 << i)) != 0;
3288 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3290 V = DAG.getUNDEF(MVT::v8i16);
3293 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3294 MVT::v8i16, V, Op.getOperand(i),
3295 DAG.getIntPtrConstant(i));
3302 /// getVShift - Return a vector logical shift node.
3304 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3305 unsigned NumBits, SelectionDAG &DAG,
3306 const TargetLowering &TLI, DebugLoc dl) {
3307 bool isMMX = VT.getSizeInBits() == 64;
3308 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3309 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3310 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3311 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3312 DAG.getNode(Opc, dl, ShVT, SrcOp,
3313 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3317 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3318 DebugLoc dl = Op.getDebugLoc();
3319 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3320 if (ISD::isBuildVectorAllZeros(Op.getNode())
3321 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3322 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3323 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3324 // eliminated on x86-32 hosts.
3325 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3328 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3329 return getOnesVector(Op.getValueType(), DAG, dl);
3330 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3333 MVT VT = Op.getValueType();
3334 MVT EVT = VT.getVectorElementType();
3335 unsigned EVTBits = EVT.getSizeInBits();
3337 unsigned NumElems = Op.getNumOperands();
3338 unsigned NumZero = 0;
3339 unsigned NumNonZero = 0;
3340 unsigned NonZeros = 0;
3341 bool IsAllConstants = true;
3342 SmallSet<SDValue, 8> Values;
3343 for (unsigned i = 0; i < NumElems; ++i) {
3344 SDValue Elt = Op.getOperand(i);
3345 if (Elt.getOpcode() == ISD::UNDEF)
3348 if (Elt.getOpcode() != ISD::Constant &&
3349 Elt.getOpcode() != ISD::ConstantFP)
3350 IsAllConstants = false;
3351 if (isZeroNode(Elt))
3354 NonZeros |= (1 << i);
3359 if (NumNonZero == 0) {
3360 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3361 return DAG.getUNDEF(VT);
3364 // Special case for single non-zero, non-undef, element.
3365 if (NumNonZero == 1 && NumElems <= 4) {
3366 unsigned Idx = CountTrailingZeros_32(NonZeros);
3367 SDValue Item = Op.getOperand(Idx);
3369 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3370 // the value are obviously zero, truncate the value to i32 and do the
3371 // insertion that way. Only do this if the value is non-constant or if the
3372 // value is a constant being inserted into element 0. It is cheaper to do
3373 // a constant pool load than it is to do a movd + shuffle.
3374 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3375 (!IsAllConstants || Idx == 0)) {
3376 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3377 // Handle MMX and SSE both.
3378 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3379 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3381 // Truncate the value (which may itself be a constant) to i32, and
3382 // convert it to a vector with movd (S2V+shuffle to zero extend).
3383 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3384 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3385 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3386 Subtarget->hasSSE2(), DAG);
3388 // Now we have our 32-bit value zero extended in the low element of
3389 // a vector. If Idx != 0, swizzle it into place.
3392 Item, DAG.getUNDEF(Item.getValueType()),
3393 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3395 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3397 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3401 // If we have a constant or non-constant insertion into the low element of
3402 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3403 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3404 // depending on what the source datatype is. Because we can only get here
3405 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3407 // Don't do this for i64 values on x86-32.
3408 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3409 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3410 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3411 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3412 Subtarget->hasSSE2(), DAG);
3415 // Is it a vector logical left shift?
3416 if (NumElems == 2 && Idx == 1 &&
3417 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3418 unsigned NumBits = VT.getSizeInBits();
3419 return getVShift(true, VT,
3420 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3421 VT, Op.getOperand(1)),
3422 NumBits/2, DAG, *this, dl);
3425 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3428 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3429 // is a non-constant being inserted into an element other than the low one,
3430 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3431 // movd/movss) to move this into the low element, then shuffle it into
3433 if (EVTBits == 32) {
3434 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3436 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3437 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3438 Subtarget->hasSSE2(), DAG);
3439 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3440 MVT MaskEVT = MaskVT.getVectorElementType();
3441 SmallVector<SDValue, 8> MaskVec;
3442 for (unsigned i = 0; i < NumElems; i++)
3443 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3444 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3445 &MaskVec[0], MaskVec.size());
3446 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3447 DAG.getUNDEF(VT), Mask);
3451 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3452 if (Values.size() == 1)
3455 // A vector full of immediates; various special cases are already
3456 // handled, so this is best done with a single constant-pool load.
3460 // Let legalizer expand 2-wide build_vectors.
3461 if (EVTBits == 64) {
3462 if (NumNonZero == 1) {
3463 // One half is zero or undef.
3464 unsigned Idx = CountTrailingZeros_32(NonZeros);
3465 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3466 Op.getOperand(Idx));
3467 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3468 Subtarget->hasSSE2(), DAG);
3473 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3474 if (EVTBits == 8 && NumElems == 16) {
3475 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3477 if (V.getNode()) return V;
3480 if (EVTBits == 16 && NumElems == 8) {
3481 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3483 if (V.getNode()) return V;
3486 // If element VT is == 32 bits, turn it into a number of shuffles.
3487 SmallVector<SDValue, 8> V;
3489 if (NumElems == 4 && NumZero > 0) {
3490 for (unsigned i = 0; i < 4; ++i) {
3491 bool isZero = !(NonZeros & (1 << i));
3493 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3495 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3498 for (unsigned i = 0; i < 2; ++i) {
3499 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3502 V[i] = V[i*2]; // Must be a zero vector.
3505 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3506 getMOVLMask(NumElems, DAG, dl));
3509 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3510 getMOVLMask(NumElems, DAG, dl));
3513 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3514 getUnpacklMask(NumElems, DAG, dl));
3519 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3520 MVT EVT = MaskVT.getVectorElementType();
3521 SmallVector<SDValue, 8> MaskVec;
3522 bool Reverse = (NonZeros & 0x3) == 2;
3523 for (unsigned i = 0; i < 2; ++i)
3525 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3527 MaskVec.push_back(DAG.getConstant(i, EVT));
3528 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3529 for (unsigned i = 0; i < 2; ++i)
3531 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3533 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3534 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3535 &MaskVec[0], MaskVec.size());
3536 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3539 if (Values.size() > 2) {
3540 // Expand into a number of unpckl*.
3542 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3543 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3544 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3545 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3546 for (unsigned i = 0; i < NumElems; ++i)
3547 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3549 while (NumElems != 0) {
3550 for (unsigned i = 0; i < NumElems; ++i)
3551 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3561 // v8i16 shuffles - Prefer shuffles in the following order:
3562 // 1. [all] pshuflw, pshufhw, optional move
3563 // 2. [ssse3] 1 x pshufb
3564 // 3. [ssse3] 2 x pshufb + 1 x por
3565 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3567 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3568 SDValue PermMask, SelectionDAG &DAG,
3569 X86TargetLowering &TLI, DebugLoc dl) {
3570 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3571 PermMask.getNode()->op_end());
3572 SmallVector<int, 8> MaskVals;
3574 // Determine if more than 1 of the words in each of the low and high quadwords
3575 // of the result come from the same quadword of one of the two inputs. Undef
3576 // mask values count as coming from any quadword, for better codegen.
3577 SmallVector<unsigned, 4> LoQuad(4);
3578 SmallVector<unsigned, 4> HiQuad(4);
3579 BitVector InputQuads(4);
3580 for (unsigned i = 0; i < 8; ++i) {
3581 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3582 SDValue Elt = MaskElts[i];
3583 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3584 cast<ConstantSDNode>(Elt)->getZExtValue();
3585 MaskVals.push_back(EltIdx);
3594 InputQuads.set(EltIdx / 4);
3597 int BestLoQuad = -1;
3598 unsigned MaxQuad = 1;
3599 for (unsigned i = 0; i < 4; ++i) {
3600 if (LoQuad[i] > MaxQuad) {
3602 MaxQuad = LoQuad[i];
3606 int BestHiQuad = -1;
3608 for (unsigned i = 0; i < 4; ++i) {
3609 if (HiQuad[i] > MaxQuad) {
3611 MaxQuad = HiQuad[i];
3615 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3616 // of the two input vectors, shuffle them into one input vector so only a
3617 // single pshufb instruction is necessary. If There are more than 2 input
3618 // quads, disable the next transformation since it does not help SSSE3.
3619 bool V1Used = InputQuads[0] || InputQuads[1];
3620 bool V2Used = InputQuads[2] || InputQuads[3];
3621 if (TLI.getSubtarget()->hasSSSE3()) {
3622 if (InputQuads.count() == 2 && V1Used && V2Used) {
3623 BestLoQuad = InputQuads.find_first();
3624 BestHiQuad = InputQuads.find_next(BestLoQuad);
3626 if (InputQuads.count() > 2) {
3632 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3633 // the shuffle mask. If a quad is scored as -1, that means that it contains
3634 // words from all 4 input quadwords.
3636 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3637 SmallVector<SDValue,8> MaskV;
3638 MaskV.push_back(DAG.getConstant(BestLoQuad < 0 ? 0 : BestLoQuad, MVT::i64));
3639 MaskV.push_back(DAG.getConstant(BestHiQuad < 0 ? 1 : BestHiQuad, MVT::i64));
3640 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, &MaskV[0], 2);
3642 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3643 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3644 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3645 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3647 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3648 // source words for the shuffle, to aid later transformations.
3649 bool AllWordsInNewV = true;
3650 bool InOrder[2] = { true, true };
3651 for (unsigned i = 0; i != 8; ++i) {
3652 int idx = MaskVals[i];
3654 InOrder[i/4] = false;
3655 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3657 AllWordsInNewV = false;
3661 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3662 if (AllWordsInNewV) {
3663 for (int i = 0; i != 8; ++i) {
3664 int idx = MaskVals[i];
3667 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3668 if ((idx != i) && idx < 4)
3670 if ((idx != i) && idx > 3)
3679 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3680 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3681 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3683 for (unsigned i = 0; i != 8; ++i)
3684 MaskV.push_back((MaskVals[i] < 0) ? DAG.getUNDEF(MVT::i16)
3685 : DAG.getConstant(MaskVals[i],
3687 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3688 DAG.getUNDEF(MVT::v8i16),
3689 DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i16,
3694 // If we have SSSE3, and all words of the result are from 1 input vector,
3695 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3696 // is present, fall back to case 4.
3697 if (TLI.getSubtarget()->hasSSSE3()) {
3698 SmallVector<SDValue,16> pshufbMask;
3700 // If we have elements from both input vectors, set the high bit of the
3701 // shuffle mask element to zero out elements that come from V2 in the V1
3702 // mask, and elements that come from V1 in the V2 mask, so that the two
3703 // results can be OR'd together.
3704 bool TwoInputs = V1Used && V2Used;
3705 for (unsigned i = 0; i != 8; ++i) {
3706 int EltIdx = MaskVals[i] * 2;
3707 if (TwoInputs && (EltIdx >= 16)) {
3708 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3709 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3712 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3713 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3715 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3716 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3717 DAG.getNode(ISD::BUILD_VECTOR, dl,
3718 MVT::v16i8, &pshufbMask[0], 16));
3720 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3722 // Calculate the shuffle mask for the second input, shuffle it, and
3723 // OR it with the first shuffled input.
3725 for (unsigned i = 0; i != 8; ++i) {
3726 int EltIdx = MaskVals[i] * 2;
3728 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3729 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3732 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3733 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3735 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3736 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3737 DAG.getNode(ISD::BUILD_VECTOR, dl,
3738 MVT::v16i8, &pshufbMask[0], 16));
3739 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3740 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3743 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3744 // and update MaskVals with new element order.
3745 BitVector InOrder(8);
3746 if (BestLoQuad >= 0) {
3747 SmallVector<SDValue, 8> MaskV;
3748 for (int i = 0; i != 4; ++i) {
3749 int idx = MaskVals[i];
3751 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3753 } else if ((idx / 4) == BestLoQuad) {
3754 MaskV.push_back(DAG.getConstant(idx & 3, MVT::i16));
3757 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3760 for (unsigned i = 4; i != 8; ++i)
3761 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3762 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3763 DAG.getUNDEF(MVT::v8i16),
3764 DAG.getNode(ISD::BUILD_VECTOR, dl,
3765 MVT::v8i16, &MaskV[0], 8));
3768 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3769 // and update MaskVals with the new element order.
3770 if (BestHiQuad >= 0) {
3771 SmallVector<SDValue, 8> MaskV;
3772 for (unsigned i = 0; i != 4; ++i)
3773 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3774 for (unsigned i = 4; i != 8; ++i) {
3775 int idx = MaskVals[i];
3777 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3779 } else if ((idx / 4) == BestHiQuad) {
3780 MaskV.push_back(DAG.getConstant((idx & 3) + 4, MVT::i16));
3783 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3786 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3787 DAG.getUNDEF(MVT::v8i16),
3788 DAG.getNode(ISD::BUILD_VECTOR, dl,
3789 MVT::v8i16, &MaskV[0], 8));
3792 // In case BestHi & BestLo were both -1, which means each quadword has a word
3793 // from each of the four input quadwords, calculate the InOrder bitvector now
3794 // before falling through to the insert/extract cleanup.
3795 if (BestLoQuad == -1 && BestHiQuad == -1) {
3797 for (int i = 0; i != 8; ++i)
3798 if (MaskVals[i] < 0 || MaskVals[i] == i)
3802 // The other elements are put in the right place using pextrw and pinsrw.
3803 for (unsigned i = 0; i != 8; ++i) {
3806 int EltIdx = MaskVals[i];
3809 SDValue ExtOp = (EltIdx < 8)
3810 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3811 DAG.getIntPtrConstant(EltIdx))
3812 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3813 DAG.getIntPtrConstant(EltIdx - 8));
3814 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3815 DAG.getIntPtrConstant(i));
3820 // v16i8 shuffles - Prefer shuffles in the following order:
3821 // 1. [ssse3] 1 x pshufb
3822 // 2. [ssse3] 2 x pshufb + 1 x por
3823 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3825 SDValue LowerVECTOR_SHUFFLEv16i8(SDValue V1, SDValue V2,
3826 SDValue PermMask, SelectionDAG &DAG,
3827 X86TargetLowering &TLI, DebugLoc dl) {
3828 SmallVector<SDValue, 16> MaskElts(PermMask.getNode()->op_begin(),
3829 PermMask.getNode()->op_end());
3830 SmallVector<int, 16> MaskVals;
3832 // If we have SSSE3, case 1 is generated when all result bytes come from
3833 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3834 // present, fall back to case 3.
3835 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3838 for (unsigned i = 0; i < 16; ++i) {
3839 SDValue Elt = MaskElts[i];
3840 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3841 cast<ConstantSDNode>(Elt)->getZExtValue();
3842 MaskVals.push_back(EltIdx);
3851 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3852 if (TLI.getSubtarget()->hasSSSE3()) {
3853 SmallVector<SDValue,16> pshufbMask;
3855 // If all result elements are from one input vector, then only translate
3856 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3858 // Otherwise, we have elements from both input vectors, and must zero out
3859 // elements that come from V2 in the first mask, and V1 in the second mask
3860 // so that we can OR them together.
3861 bool TwoInputs = !(V1Only || V2Only);
3862 for (unsigned i = 0; i != 16; ++i) {
3863 int EltIdx = MaskVals[i];
3864 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3865 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3868 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3870 // If all the elements are from V2, assign it to V1 and return after
3871 // building the first pshufb.
3874 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3875 DAG.getNode(ISD::BUILD_VECTOR, dl,
3876 MVT::v16i8, &pshufbMask[0], 16));
3880 // Calculate the shuffle mask for the second input, shuffle it, and
3881 // OR it with the first shuffled input.
3883 for (unsigned i = 0; i != 16; ++i) {
3884 int EltIdx = MaskVals[i];
3886 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3889 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3891 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3892 DAG.getNode(ISD::BUILD_VECTOR, dl,
3893 MVT::v16i8, &pshufbMask[0], 16));
3894 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3897 // No SSSE3 - Calculate in place words and then fix all out of place words
3898 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3899 // the 16 different words that comprise the two doublequadword input vectors.
3900 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3901 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3902 SDValue NewV = V2Only ? V2 : V1;
3903 for (int i = 0; i != 8; ++i) {
3904 int Elt0 = MaskVals[i*2];
3905 int Elt1 = MaskVals[i*2+1];
3907 // This word of the result is all undef, skip it.
3908 if (Elt0 < 0 && Elt1 < 0)
3911 // This word of the result is already in the correct place, skip it.
3912 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3914 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3917 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3918 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3921 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3922 // using a single extract together, load it and store it.
3923 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3924 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3925 DAG.getIntPtrConstant(Elt1 / 2));
3926 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3927 DAG.getIntPtrConstant(i));
3931 // If Elt1 is defined, extract it from the appropriate source. If the
3932 // source byte is not also odd, shift the extracted word left 8 bits
3933 // otherwise clear the bottom 8 bits if we need to do an or.
3935 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3936 DAG.getIntPtrConstant(Elt1 / 2));
3937 if ((Elt1 & 1) == 0)
3938 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3939 DAG.getConstant(8, TLI.getShiftAmountTy()));
3941 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3942 DAG.getConstant(0xFF00, MVT::i16));
3944 // If Elt0 is defined, extract it from the appropriate source. If the
3945 // source byte is not also even, shift the extracted word right 8 bits. If
3946 // Elt1 was also defined, OR the extracted values together before
3947 // inserting them in the result.
3949 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3950 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3951 if ((Elt0 & 1) != 0)
3952 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3953 DAG.getConstant(8, TLI.getShiftAmountTy()));
3955 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3956 DAG.getConstant(0x00FF, MVT::i16));
3957 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3960 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3961 DAG.getIntPtrConstant(i));
3963 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3966 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3967 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3968 /// done when every pair / quad of shuffle mask elements point to elements in
3969 /// the right sequence. e.g.
3970 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3972 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3974 SDValue PermMask, SelectionDAG &DAG,
3975 TargetLowering &TLI, DebugLoc dl) {
3976 unsigned NumElems = PermMask.getNumOperands();
3977 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3978 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3979 MVT MaskEltVT = MaskVT.getVectorElementType();
3981 switch (VT.getSimpleVT()) {
3982 default: assert(false && "Unexpected!");
3983 case MVT::v4f32: NewVT = MVT::v2f64; break;
3984 case MVT::v4i32: NewVT = MVT::v2i64; break;
3985 case MVT::v8i16: NewVT = MVT::v4i32; break;
3986 case MVT::v16i8: NewVT = MVT::v4i32; break;
3989 if (NewWidth == 2) {
3995 unsigned Scale = NumElems / NewWidth;
3996 SmallVector<SDValue, 8> MaskVec;
3997 for (unsigned i = 0; i < NumElems; i += Scale) {
3998 unsigned StartIdx = ~0U;
3999 for (unsigned j = 0; j < Scale; ++j) {
4000 SDValue Elt = PermMask.getOperand(i+j);
4001 if (Elt.getOpcode() == ISD::UNDEF)
4003 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
4004 if (StartIdx == ~0U)
4005 StartIdx = EltIdx - (EltIdx % Scale);
4006 if (EltIdx != StartIdx + j)
4009 if (StartIdx == ~0U)
4010 MaskVec.push_back(DAG.getUNDEF(MaskEltVT));
4012 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
4015 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4016 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4017 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
4018 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4019 &MaskVec[0], MaskVec.size()));
4022 /// getVZextMovL - Return a zero-extending vector move low node.
4024 static SDValue getVZextMovL(MVT VT, MVT OpVT,
4025 SDValue SrcOp, SelectionDAG &DAG,
4026 const X86Subtarget *Subtarget, DebugLoc dl) {
4027 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4028 LoadSDNode *LD = NULL;
4029 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4030 LD = dyn_cast<LoadSDNode>(SrcOp);
4032 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4034 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4035 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
4036 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4037 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4038 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
4040 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4041 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4042 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4043 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4051 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4052 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4053 DAG.getNode(ISD::BIT_CONVERT, dl,
4057 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4060 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
4061 SDValue PermMask, MVT VT, SelectionDAG &DAG,
4063 MVT MaskVT = PermMask.getValueType();
4064 MVT MaskEVT = MaskVT.getVectorElementType();
4065 SmallVector<std::pair<int, int>, 8> Locs;
4067 SmallVector<SDValue, 8> Mask1(4, DAG.getUNDEF(MaskEVT));
4070 for (unsigned i = 0; i != 4; ++i) {
4071 SDValue Elt = PermMask.getOperand(i);
4072 if (Elt.getOpcode() == ISD::UNDEF) {
4073 Locs[i] = std::make_pair(-1, -1);
4075 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4076 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
4078 Locs[i] = std::make_pair(0, NumLo);
4082 Locs[i] = std::make_pair(1, NumHi);
4084 Mask1[2+NumHi] = Elt;
4090 if (NumLo <= 2 && NumHi <= 2) {
4091 // If no more than two elements come from either vector. This can be
4092 // implemented with two shuffles. First shuffle gather the elements.
4093 // The second shuffle, which takes the first shuffle as both of its
4094 // vector operands, put the elements into the right order.
4095 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4096 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4097 &Mask1[0], Mask1.size()));
4099 SmallVector<SDValue, 8> Mask2(4, DAG.getUNDEF(MaskEVT));
4100 for (unsigned i = 0; i != 4; ++i) {
4101 if (Locs[i].first == -1)
4104 unsigned Idx = (i < 2) ? 0 : 4;
4105 Idx += Locs[i].first * 2 + Locs[i].second;
4106 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
4110 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
4111 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4112 &Mask2[0], Mask2.size()));
4113 } else if (NumLo == 3 || NumHi == 3) {
4114 // Otherwise, we must have three elements from one vector, call it X, and
4115 // one element from the other, call it Y. First, use a shufps to build an
4116 // intermediate vector with the one element from Y and the element from X
4117 // that will be in the same half in the final destination (the indexes don't
4118 // matter). Then, use a shufps to build the final vector, taking the half
4119 // containing the element from Y from the intermediate, and the other half
4122 // Normalize it so the 3 elements come from V1.
4123 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
4127 // Find the element from V2.
4129 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4130 SDValue Elt = PermMask.getOperand(HiIndex);
4131 if (Elt.getOpcode() == ISD::UNDEF)
4133 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4138 Mask1[0] = PermMask.getOperand(HiIndex);
4139 Mask1[1] = DAG.getUNDEF(MaskEVT);
4140 Mask1[2] = PermMask.getOperand(HiIndex^1);
4141 Mask1[3] = DAG.getUNDEF(MaskEVT);
4142 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4143 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &Mask1[0], 4));
4146 Mask1[0] = PermMask.getOperand(0);
4147 Mask1[1] = PermMask.getOperand(1);
4148 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
4149 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
4150 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4151 DAG.getNode(ISD::BUILD_VECTOR, dl,
4152 MaskVT, &Mask1[0], 4));
4154 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
4155 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
4156 Mask1[2] = PermMask.getOperand(2);
4157 Mask1[3] = PermMask.getOperand(3);
4158 if (Mask1[2].getOpcode() != ISD::UNDEF)
4160 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
4162 if (Mask1[3].getOpcode() != ISD::UNDEF)
4164 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
4166 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
4167 DAG.getNode(ISD::BUILD_VECTOR, dl,
4168 MaskVT, &Mask1[0], 4));
4172 // Break it into (shuffle shuffle_hi, shuffle_lo).
4174 SmallVector<SDValue,8> LoMask(4, DAG.getUNDEF(MaskEVT));
4175 SmallVector<SDValue,8> HiMask(4, DAG.getUNDEF(MaskEVT));
4176 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4177 unsigned MaskIdx = 0;
4180 for (unsigned i = 0; i != 4; ++i) {
4187 SDValue Elt = PermMask.getOperand(i);
4188 if (Elt.getOpcode() == ISD::UNDEF) {
4189 Locs[i] = std::make_pair(-1, -1);
4190 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4191 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4192 (*MaskPtr)[LoIdx] = Elt;
4195 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4196 (*MaskPtr)[HiIdx] = Elt;
4201 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4202 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4203 &LoMask[0], LoMask.size()));
4204 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4205 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4206 &HiMask[0], HiMask.size()));
4207 SmallVector<SDValue, 8> MaskOps;
4208 for (unsigned i = 0; i != 4; ++i) {
4209 if (Locs[i].first == -1) {
4210 MaskOps.push_back(DAG.getUNDEF(MaskEVT));
4212 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4213 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4216 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4217 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4218 &MaskOps[0], MaskOps.size()));
4222 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4223 SDValue V1 = Op.getOperand(0);
4224 SDValue V2 = Op.getOperand(1);
4225 SDValue PermMask = Op.getOperand(2);
4226 MVT VT = Op.getValueType();
4227 DebugLoc dl = Op.getDebugLoc();
4228 unsigned NumElems = PermMask.getNumOperands();
4229 bool isMMX = VT.getSizeInBits() == 64;
4230 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4231 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4232 bool V1IsSplat = false;
4233 bool V2IsSplat = false;
4235 // FIXME: Check for legal shuffle and return?
4237 if (isUndefShuffle(Op.getNode()))
4238 return DAG.getUNDEF(VT);
4240 if (isZeroShuffle(Op.getNode()))
4241 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4243 if (isIdentityMask(PermMask.getNode()))
4245 else if (isIdentityMask(PermMask.getNode(), true))
4248 // Canonicalize movddup shuffles.
4249 if (V2IsUndef && Subtarget->hasSSE2() &&
4250 VT.getSizeInBits() == 128 &&
4251 X86::isMOVDDUPMask(PermMask.getNode()))
4252 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4254 if (isSplatMask(PermMask.getNode())) {
4255 if (isMMX || NumElems < 4) return Op;
4256 // Promote it to a v4{if}32 splat.
4257 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4260 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4262 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4263 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4265 if (NewOp.getNode())
4266 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4267 LowerVECTOR_SHUFFLE(NewOp, DAG));
4268 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4269 // FIXME: Figure out a cleaner way to do this.
4270 // Try to make use of movq to zero out the top part.
4271 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4272 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4274 if (NewOp.getNode()) {
4275 SDValue NewV1 = NewOp.getOperand(0);
4276 SDValue NewV2 = NewOp.getOperand(1);
4277 SDValue NewMask = NewOp.getOperand(2);
4278 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4279 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4280 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4284 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4285 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4287 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4288 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4289 DAG, Subtarget, dl);
4293 // Check if this can be converted into a logical shift.
4294 bool isLeft = false;
4297 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4298 if (isShift && ShVal.hasOneUse()) {
4299 // If the shifted value has multiple uses, it may be cheaper to use
4300 // v_set0 + movlhps or movhlps, etc.
4301 MVT EVT = VT.getVectorElementType();
4302 ShAmt *= EVT.getSizeInBits();
4303 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4306 if (X86::isMOVLMask(PermMask.getNode())) {
4309 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4310 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4315 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4316 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4317 X86::isMOVHLPSMask(PermMask.getNode()) ||
4318 X86::isMOVHPMask(PermMask.getNode()) ||
4319 X86::isMOVLPMask(PermMask.getNode())))
4322 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4323 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4324 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4327 // No better options. Use a vshl / vsrl.
4328 MVT EVT = VT.getVectorElementType();
4329 ShAmt *= EVT.getSizeInBits();
4330 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4333 bool Commuted = false;
4334 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4335 // 1,1,1,1 -> v8i16 though.
4336 V1IsSplat = isSplatVector(V1.getNode());
4337 V2IsSplat = isSplatVector(V2.getNode());
4339 // Canonicalize the splat or undef, if present, to be on the RHS.
4340 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4341 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4342 std::swap(V1IsSplat, V2IsSplat);
4343 std::swap(V1IsUndef, V2IsUndef);
4347 // FIXME: Figure out a cleaner way to do this.
4348 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4349 if (V2IsUndef) return V1;
4350 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4352 // V2 is a splat, so the mask may be malformed. That is, it may point
4353 // to any V2 element. The instruction selectior won't like this. Get
4354 // a corrected mask and commute to form a proper MOVS{S|D}.
4355 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4356 if (NewMask.getNode() != PermMask.getNode())
4357 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4362 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4363 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4364 X86::isUNPCKLMask(PermMask.getNode()) ||
4365 X86::isUNPCKHMask(PermMask.getNode()))
4369 // Normalize mask so all entries that point to V2 points to its first
4370 // element then try to match unpck{h|l} again. If match, return a
4371 // new vector_shuffle with the corrected mask.
4372 SDValue NewMask = NormalizeMask(PermMask, DAG);
4373 if (NewMask.getNode() != PermMask.getNode()) {
4374 if (X86::isUNPCKLMask(NewMask.getNode(), true)) {
4375 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4376 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4377 } else if (X86::isUNPCKHMask(NewMask.getNode(), true)) {
4378 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4379 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4384 // Normalize the node to match x86 shuffle ops if needed
4385 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4386 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4389 // Commute is back and try unpck* again.
4390 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4391 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4392 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4393 X86::isUNPCKLMask(PermMask.getNode()) ||
4394 X86::isUNPCKHMask(PermMask.getNode()))
4398 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4399 // Try PSHUF* first, then SHUFP*.
4400 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4401 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4402 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4403 if (V2.getOpcode() != ISD::UNDEF)
4404 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4405 DAG.getUNDEF(VT), PermMask);
4410 if (Subtarget->hasSSE2() &&
4411 (X86::isPSHUFDMask(PermMask.getNode()) ||
4412 X86::isPSHUFHWMask(PermMask.getNode()) ||
4413 X86::isPSHUFLWMask(PermMask.getNode()))) {
4415 if (VT == MVT::v4f32) {
4417 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4418 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4419 DAG.getUNDEF(RVT), PermMask);
4420 } else if (V2.getOpcode() != ISD::UNDEF)
4421 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4422 DAG.getUNDEF(RVT), PermMask);
4424 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4428 // Binary or unary shufps.
4429 if (X86::isSHUFPMask(PermMask.getNode()) ||
4430 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4434 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4435 if (VT == MVT::v8i16) {
4436 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4437 if (NewOp.getNode())
4441 if (VT == MVT::v16i8) {
4442 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(V1, V2, PermMask, DAG, *this, dl);
4443 if (NewOp.getNode())
4447 // Handle all 4 wide cases with a number of shuffles except for MMX.
4448 if (NumElems == 4 && !isMMX)
4449 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4455 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4456 SelectionDAG &DAG) {
4457 MVT VT = Op.getValueType();
4458 DebugLoc dl = Op.getDebugLoc();
4459 if (VT.getSizeInBits() == 8) {
4460 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4461 Op.getOperand(0), Op.getOperand(1));
4462 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4463 DAG.getValueType(VT));
4464 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4465 } else if (VT.getSizeInBits() == 16) {
4466 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4467 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4469 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4470 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4471 DAG.getNode(ISD::BIT_CONVERT, dl,
4475 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4476 Op.getOperand(0), Op.getOperand(1));
4477 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4478 DAG.getValueType(VT));
4479 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4480 } else if (VT == MVT::f32) {
4481 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4482 // the result back to FR32 register. It's only worth matching if the
4483 // result has a single use which is a store or a bitcast to i32. And in
4484 // the case of a store, it's not worth it if the index is a constant 0,
4485 // because a MOVSSmr can be used instead, which is smaller and faster.
4486 if (!Op.hasOneUse())
4488 SDNode *User = *Op.getNode()->use_begin();
4489 if ((User->getOpcode() != ISD::STORE ||
4490 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4491 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4492 (User->getOpcode() != ISD::BIT_CONVERT ||
4493 User->getValueType(0) != MVT::i32))
4495 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4496 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4499 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4500 } else if (VT == MVT::i32) {
4501 // ExtractPS works with constant index.
4502 if (isa<ConstantSDNode>(Op.getOperand(1)))
4510 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4511 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4514 if (Subtarget->hasSSE41()) {
4515 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4520 MVT VT = Op.getValueType();
4521 DebugLoc dl = Op.getDebugLoc();
4522 // TODO: handle v16i8.
4523 if (VT.getSizeInBits() == 16) {
4524 SDValue Vec = Op.getOperand(0);
4525 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4527 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4528 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4529 DAG.getNode(ISD::BIT_CONVERT, dl,
4532 // Transform it so it match pextrw which produces a 32-bit result.
4533 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4534 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4535 Op.getOperand(0), Op.getOperand(1));
4536 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4537 DAG.getValueType(VT));
4538 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4539 } else if (VT.getSizeInBits() == 32) {
4540 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4543 // SHUFPS the element to the lowest double word, then movss.
4544 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4545 SmallVector<SDValue, 8> IdxVec;
4547 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4549 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4551 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4553 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4554 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4555 &IdxVec[0], IdxVec.size());
4556 SDValue Vec = Op.getOperand(0);
4557 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4558 Vec, DAG.getUNDEF(Vec.getValueType()), Mask);
4559 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4560 DAG.getIntPtrConstant(0));
4561 } else if (VT.getSizeInBits() == 64) {
4562 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4563 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4564 // to match extract_elt for f64.
4565 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4569 // UNPCKHPD the element to the lowest double word, then movsd.
4570 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4571 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4572 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4573 SmallVector<SDValue, 8> IdxVec;
4574 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4576 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4577 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4578 &IdxVec[0], IdxVec.size());
4579 SDValue Vec = Op.getOperand(0);
4580 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4581 Vec, DAG.getUNDEF(Vec.getValueType()),
4583 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4584 DAG.getIntPtrConstant(0));
4591 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4592 MVT VT = Op.getValueType();
4593 MVT EVT = VT.getVectorElementType();
4594 DebugLoc dl = Op.getDebugLoc();
4596 SDValue N0 = Op.getOperand(0);
4597 SDValue N1 = Op.getOperand(1);
4598 SDValue N2 = Op.getOperand(2);
4600 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4601 isa<ConstantSDNode>(N2)) {
4602 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4604 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4606 if (N1.getValueType() != MVT::i32)
4607 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4608 if (N2.getValueType() != MVT::i32)
4609 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4610 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4611 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4612 // Bits [7:6] of the constant are the source select. This will always be
4613 // zero here. The DAG Combiner may combine an extract_elt index into these
4614 // bits. For example (insert (extract, 3), 2) could be matched by putting
4615 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4616 // Bits [5:4] of the constant are the destination select. This is the
4617 // value of the incoming immediate.
4618 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4619 // combine either bitwise AND or insert of float 0.0 to set these bits.
4620 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4621 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4622 } else if (EVT == MVT::i32) {
4623 // InsertPS works with constant index.
4624 if (isa<ConstantSDNode>(N2))
4631 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4632 MVT VT = Op.getValueType();
4633 MVT EVT = VT.getVectorElementType();
4635 if (Subtarget->hasSSE41())
4636 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4641 DebugLoc dl = Op.getDebugLoc();
4642 SDValue N0 = Op.getOperand(0);
4643 SDValue N1 = Op.getOperand(1);
4644 SDValue N2 = Op.getOperand(2);
4646 if (EVT.getSizeInBits() == 16) {
4647 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4648 // as its second argument.
4649 if (N1.getValueType() != MVT::i32)
4650 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4651 if (N2.getValueType() != MVT::i32)
4652 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4653 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4659 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4660 DebugLoc dl = Op.getDebugLoc();
4661 if (Op.getValueType() == MVT::v2f32)
4662 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4663 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4664 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4665 Op.getOperand(0))));
4667 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4668 MVT VT = MVT::v2i32;
4669 switch (Op.getValueType().getSimpleVT()) {
4676 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4677 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4680 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4681 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4682 // one of the above mentioned nodes. It has to be wrapped because otherwise
4683 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4684 // be used to form addressing mode. These wrapped nodes will be selected
4687 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4688 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4689 // FIXME there isn't really any debug info here, should come from the parent
4690 DebugLoc dl = CP->getDebugLoc();
4691 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4692 CP->getAlignment());
4693 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4694 // With PIC, the address is actually $g + Offset.
4695 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4696 !Subtarget->isPICStyleRIPRel()) {
4697 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4698 DAG.getNode(X86ISD::GlobalBaseReg,
4699 DebugLoc::getUnknownLoc(),
4708 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4710 SelectionDAG &DAG) const {
4711 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4712 bool ExtraLoadRequired =
4713 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4715 // Create the TargetGlobalAddress node, folding in the constant
4716 // offset if it is legal.
4718 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4719 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4722 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4723 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4725 // With PIC, the address is actually $g + Offset.
4726 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4727 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4728 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4732 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4733 // load the value at address GV, not the value of GV itself. This means that
4734 // the GlobalAddress must be in the base or index register of the address, not
4735 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4736 // The same applies for external symbols during PIC codegen
4737 if (ExtraLoadRequired)
4738 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4739 PseudoSourceValue::getGOT(), 0);
4741 // If there was a non-zero offset that we didn't fold, create an explicit
4744 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4745 DAG.getConstant(Offset, getPointerTy()));
4751 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4752 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4753 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4754 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4757 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4759 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4762 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4763 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4764 DAG.getNode(X86ISD::GlobalBaseReg,
4765 DebugLoc::getUnknownLoc(),
4767 InFlag = Chain.getValue(1);
4769 // emit leal symbol@TLSGD(,%ebx,1), %eax
4770 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4771 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4772 GA->getValueType(0),
4774 SDValue Ops[] = { Chain, TGA, InFlag };
4775 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4776 InFlag = Result.getValue(2);
4777 Chain = Result.getValue(1);
4779 // call ___tls_get_addr. This function receives its argument in
4780 // the register EAX.
4781 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4782 InFlag = Chain.getValue(1);
4784 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4785 SDValue Ops1[] = { Chain,
4786 DAG.getTargetExternalSymbol("___tls_get_addr",
4788 DAG.getRegister(X86::EAX, PtrVT),
4789 DAG.getRegister(X86::EBX, PtrVT),
4791 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 5);
4792 InFlag = Chain.getValue(1);
4794 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4797 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4799 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4801 SDValue InFlag, Chain;
4802 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4804 // emit leaq symbol@TLSGD(%rip), %rdi
4805 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4806 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4807 GA->getValueType(0),
4809 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4810 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4811 Chain = Result.getValue(1);
4812 InFlag = Result.getValue(2);
4814 // call __tls_get_addr. This function receives its argument in
4815 // the register RDI.
4816 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4817 InFlag = Chain.getValue(1);
4819 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4820 SDValue Ops1[] = { Chain,
4821 DAG.getTargetExternalSymbol("__tls_get_addr",
4823 DAG.getRegister(X86::RDI, PtrVT),
4825 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 4);
4826 InFlag = Chain.getValue(1);
4828 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4831 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4832 // "local exec" model.
4833 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4834 const MVT PtrVT, TLSModel::Model model) {
4835 DebugLoc dl = GA->getDebugLoc();
4836 // Get the Thread Pointer
4837 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4838 DebugLoc::getUnknownLoc(), PtrVT,
4839 DAG.getRegister(X86::GS, MVT::i32));
4841 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4844 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4846 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4847 GA->getValueType(0),
4849 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4851 if (model == TLSModel::InitialExec)
4852 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4853 PseudoSourceValue::getGOT(), 0);
4855 // The address of the thread local variable is the add of the thread
4856 // pointer with the offset of the variable.
4857 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4861 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4862 // TODO: implement the "local dynamic" model
4863 // TODO: implement the "initial exec"model for pic executables
4864 assert(Subtarget->isTargetELF() &&
4865 "TLS not implemented for non-ELF targets");
4866 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4867 GlobalValue *GV = GA->getGlobal();
4868 TLSModel::Model model =
4869 getTLSModel (GV, getTargetMachine().getRelocationModel());
4870 if (Subtarget->is64Bit()) {
4872 case TLSModel::GeneralDynamic:
4873 case TLSModel::LocalDynamic: // not implemented
4874 case TLSModel::InitialExec: // not implemented
4875 case TLSModel::LocalExec: // not implemented
4876 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4880 case TLSModel::GeneralDynamic:
4881 case TLSModel::LocalDynamic: // not implemented
4882 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4884 case TLSModel::InitialExec:
4885 case TLSModel::LocalExec:
4886 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model);
4889 assert(0 && "Unreachable");
4894 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4895 // FIXME there isn't really any debug info here
4896 DebugLoc dl = Op.getDebugLoc();
4897 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4898 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4899 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4900 // With PIC, the address is actually $g + Offset.
4901 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4902 !Subtarget->isPICStyleRIPRel()) {
4903 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4904 DAG.getNode(X86ISD::GlobalBaseReg,
4905 DebugLoc::getUnknownLoc(),
4913 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4914 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4915 // FIXME there isn't really any debug into here
4916 DebugLoc dl = JT->getDebugLoc();
4917 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4918 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4919 // With PIC, the address is actually $g + Offset.
4920 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4921 !Subtarget->isPICStyleRIPRel()) {
4922 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4923 DAG.getNode(X86ISD::GlobalBaseReg,
4924 DebugLoc::getUnknownLoc(),
4932 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4933 /// take a 2 x i32 value to shift plus a shift amount.
4934 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4935 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4936 MVT VT = Op.getValueType();
4937 unsigned VTBits = VT.getSizeInBits();
4938 DebugLoc dl = Op.getDebugLoc();
4939 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4940 SDValue ShOpLo = Op.getOperand(0);
4941 SDValue ShOpHi = Op.getOperand(1);
4942 SDValue ShAmt = Op.getOperand(2);
4943 SDValue Tmp1 = isSRA ?
4944 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4945 DAG.getConstant(VTBits - 1, MVT::i8)) :
4946 DAG.getConstant(0, VT);
4949 if (Op.getOpcode() == ISD::SHL_PARTS) {
4950 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4951 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4953 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4954 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4957 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4958 DAG.getConstant(VTBits, MVT::i8));
4959 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4960 AndNode, DAG.getConstant(0, MVT::i8));
4963 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4964 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4965 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4967 if (Op.getOpcode() == ISD::SHL_PARTS) {
4968 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4969 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4971 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4972 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4975 SDValue Ops[2] = { Lo, Hi };
4976 return DAG.getMergeValues(Ops, 2, dl);
4979 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4980 MVT SrcVT = Op.getOperand(0).getValueType();
4981 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4982 "Unknown SINT_TO_FP to lower!");
4984 // These are really Legal; caller falls through into that case.
4985 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4987 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4988 Subtarget->is64Bit())
4991 DebugLoc dl = Op.getDebugLoc();
4992 unsigned Size = SrcVT.getSizeInBits()/8;
4993 MachineFunction &MF = DAG.getMachineFunction();
4994 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4995 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4996 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4998 PseudoSourceValue::getFixedStack(SSFI), 0);
5002 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5004 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5006 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5007 SmallVector<SDValue, 8> Ops;
5008 Ops.push_back(Chain);
5009 Ops.push_back(StackSlot);
5010 Ops.push_back(DAG.getValueType(SrcVT));
5011 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5012 Tys, &Ops[0], Ops.size());
5015 Chain = Result.getValue(1);
5016 SDValue InFlag = Result.getValue(2);
5018 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5019 // shouldn't be necessary except that RFP cannot be live across
5020 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5021 MachineFunction &MF = DAG.getMachineFunction();
5022 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
5023 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5024 Tys = DAG.getVTList(MVT::Other);
5025 SmallVector<SDValue, 8> Ops;
5026 Ops.push_back(Chain);
5027 Ops.push_back(Result);
5028 Ops.push_back(StackSlot);
5029 Ops.push_back(DAG.getValueType(Op.getValueType()));
5030 Ops.push_back(InFlag);
5031 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5032 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5033 PseudoSourceValue::getFixedStack(SSFI), 0);
5039 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5040 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5041 // This algorithm is not obvious. Here it is in C code, more or less:
5043 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5044 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5045 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5047 // Copy ints to xmm registers.
5048 __m128i xh = _mm_cvtsi32_si128( hi );
5049 __m128i xl = _mm_cvtsi32_si128( lo );
5051 // Combine into low half of a single xmm register.
5052 __m128i x = _mm_unpacklo_epi32( xh, xl );
5056 // Merge in appropriate exponents to give the integer bits the right
5058 x = _mm_unpacklo_epi32( x, exp );
5060 // Subtract away the biases to deal with the IEEE-754 double precision
5062 d = _mm_sub_pd( (__m128d) x, bias );
5064 // All conversions up to here are exact. The correctly rounded result is
5065 // calculated using the current rounding mode using the following
5067 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5068 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5069 // store doesn't really need to be here (except
5070 // maybe to zero the other double)
5075 DebugLoc dl = Op.getDebugLoc();
5077 // Build some magic constants.
5078 std::vector<Constant*> CV0;
5079 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
5080 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
5081 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5082 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5083 Constant *C0 = ConstantVector::get(CV0);
5084 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5086 std::vector<Constant*> CV1;
5087 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
5088 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
5089 Constant *C1 = ConstantVector::get(CV1);
5090 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5092 SmallVector<SDValue, 4> MaskVec;
5093 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
5094 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
5095 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
5096 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
5097 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
5098 &MaskVec[0], MaskVec.size());
5099 SmallVector<SDValue, 4> MaskVec2;
5100 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
5101 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
5102 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
5103 &MaskVec2[0], MaskVec2.size());
5105 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5106 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5108 DAG.getIntPtrConstant(1)));
5109 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5110 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5112 DAG.getIntPtrConstant(0)));
5113 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5114 XR1, XR2, UnpcklMask);
5115 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5116 PseudoSourceValue::getConstantPool(), 0,
5118 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5119 Unpck1, CLod0, UnpcklMask);
5120 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5121 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5122 PseudoSourceValue::getConstantPool(), 0,
5124 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5126 // Add the halves; easiest way is to swap them into another reg first.
5127 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
5128 Sub, Sub, ShufMask);
5129 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5131 DAG.getIntPtrConstant(0));
5134 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5135 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5136 DebugLoc dl = Op.getDebugLoc();
5137 // FP constant to bias correct the final result.
5138 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5141 // Load the 32-bit value into an XMM register.
5142 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5143 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5145 DAG.getIntPtrConstant(0)));
5147 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5148 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5149 DAG.getIntPtrConstant(0));
5151 // Or the load with the bias.
5152 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5153 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5154 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5156 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5157 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5158 MVT::v2f64, Bias)));
5159 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5160 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5161 DAG.getIntPtrConstant(0));
5163 // Subtract the bias.
5164 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5166 // Handle final rounding.
5167 MVT DestVT = Op.getValueType();
5169 if (DestVT.bitsLT(MVT::f64)) {
5170 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5171 DAG.getIntPtrConstant(0));
5172 } else if (DestVT.bitsGT(MVT::f64)) {
5173 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5176 // Handle final rounding.
5180 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5181 SDValue N0 = Op.getOperand(0);
5182 DebugLoc dl = Op.getDebugLoc();
5184 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5185 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5186 // the optimization here.
5187 if (DAG.SignBitIsZero(N0))
5188 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5190 MVT SrcVT = N0.getValueType();
5191 if (SrcVT == MVT::i64) {
5192 // We only handle SSE2 f64 target here; caller can handle the rest.
5193 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5196 return LowerUINT_TO_FP_i64(Op, DAG);
5197 } else if (SrcVT == MVT::i32) {
5198 return LowerUINT_TO_FP_i32(Op, DAG);
5201 assert(0 && "Unknown UINT_TO_FP to lower!");
5205 std::pair<SDValue,SDValue> X86TargetLowering::
5206 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
5207 DebugLoc dl = Op.getDebugLoc();
5208 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5209 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5210 "Unknown FP_TO_SINT to lower!");
5212 // These are really Legal.
5213 if (Op.getValueType() == MVT::i32 &&
5214 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5215 return std::make_pair(SDValue(), SDValue());
5216 if (Subtarget->is64Bit() &&
5217 Op.getValueType() == MVT::i64 &&
5218 Op.getOperand(0).getValueType() != MVT::f80)
5219 return std::make_pair(SDValue(), SDValue());
5221 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5223 MachineFunction &MF = DAG.getMachineFunction();
5224 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5225 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5226 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5228 switch (Op.getValueType().getSimpleVT()) {
5229 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5230 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5231 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5232 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5235 SDValue Chain = DAG.getEntryNode();
5236 SDValue Value = Op.getOperand(0);
5237 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5238 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5239 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5240 PseudoSourceValue::getFixedStack(SSFI), 0);
5241 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5243 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5245 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5246 Chain = Value.getValue(1);
5247 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5248 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5251 // Build the FP_TO_INT*_IN_MEM
5252 SDValue Ops[] = { Chain, Value, StackSlot };
5253 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5255 return std::make_pair(FIST, StackSlot);
5258 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5259 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5260 SDValue FIST = Vals.first, StackSlot = Vals.second;
5261 if (FIST.getNode() == 0) return SDValue();
5264 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5265 FIST, StackSlot, NULL, 0);
5268 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5269 DebugLoc dl = Op.getDebugLoc();
5270 MVT VT = Op.getValueType();
5273 EltVT = VT.getVectorElementType();
5274 std::vector<Constant*> CV;
5275 if (EltVT == MVT::f64) {
5276 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5280 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5286 Constant *C = ConstantVector::get(CV);
5287 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5288 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5289 PseudoSourceValue::getConstantPool(), 0,
5291 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5294 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5295 DebugLoc dl = Op.getDebugLoc();
5296 MVT VT = Op.getValueType();
5298 unsigned EltNum = 1;
5299 if (VT.isVector()) {
5300 EltVT = VT.getVectorElementType();
5301 EltNum = VT.getVectorNumElements();
5303 std::vector<Constant*> CV;
5304 if (EltVT == MVT::f64) {
5305 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5309 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5315 Constant *C = ConstantVector::get(CV);
5316 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5317 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5318 PseudoSourceValue::getConstantPool(), 0,
5320 if (VT.isVector()) {
5321 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5322 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5323 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5325 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5327 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5331 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5332 SDValue Op0 = Op.getOperand(0);
5333 SDValue Op1 = Op.getOperand(1);
5334 DebugLoc dl = Op.getDebugLoc();
5335 MVT VT = Op.getValueType();
5336 MVT SrcVT = Op1.getValueType();
5338 // If second operand is smaller, extend it first.
5339 if (SrcVT.bitsLT(VT)) {
5340 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5343 // And if it is bigger, shrink it first.
5344 if (SrcVT.bitsGT(VT)) {
5345 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5349 // At this point the operands and the result should have the same
5350 // type, and that won't be f80 since that is not custom lowered.
5352 // First get the sign bit of second operand.
5353 std::vector<Constant*> CV;
5354 if (SrcVT == MVT::f64) {
5355 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5356 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5358 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5359 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5360 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5361 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5363 Constant *C = ConstantVector::get(CV);
5364 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5365 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5366 PseudoSourceValue::getConstantPool(), 0,
5368 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5370 // Shift sign bit right or left if the two operands have different types.
5371 if (SrcVT.bitsGT(VT)) {
5372 // Op0 is MVT::f32, Op1 is MVT::f64.
5373 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5374 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5375 DAG.getConstant(32, MVT::i32));
5376 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5377 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5378 DAG.getIntPtrConstant(0));
5381 // Clear first operand sign bit.
5383 if (VT == MVT::f64) {
5384 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5385 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5387 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5388 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5389 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5390 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5392 C = ConstantVector::get(CV);
5393 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5394 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5395 PseudoSourceValue::getConstantPool(), 0,
5397 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5399 // Or the value with the sign bit.
5400 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5403 /// Emit nodes that will be selected as "test Op0,Op0", or something
5405 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5406 SelectionDAG &DAG) {
5407 DebugLoc dl = Op.getDebugLoc();
5409 // CF and OF aren't always set the way we want. Determine which
5410 // of these we need.
5411 bool NeedCF = false;
5412 bool NeedOF = false;
5414 case X86::COND_A: case X86::COND_AE:
5415 case X86::COND_B: case X86::COND_BE:
5418 case X86::COND_G: case X86::COND_GE:
5419 case X86::COND_L: case X86::COND_LE:
5420 case X86::COND_O: case X86::COND_NO:
5426 // See if we can use the EFLAGS value from the operand instead of
5427 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5428 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5429 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5430 unsigned Opcode = 0;
5431 unsigned NumOperands = 0;
5432 switch (Op.getNode()->getOpcode()) {
5434 // Due to an isel shortcoming, be conservative if this add is likely to
5435 // be selected as part of a load-modify-store instruction. When the root
5436 // node in a match is a store, isel doesn't know how to remap non-chain
5437 // non-flag uses of other nodes in the match, such as the ADD in this
5438 // case. This leads to the ADD being left around and reselected, with
5439 // the result being two adds in the output.
5440 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5441 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5442 if (UI->getOpcode() == ISD::STORE)
5444 if (ConstantSDNode *C =
5445 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5446 // An add of one will be selected as an INC.
5447 if (C->getAPIntValue() == 1) {
5448 Opcode = X86ISD::INC;
5452 // An add of negative one (subtract of one) will be selected as a DEC.
5453 if (C->getAPIntValue().isAllOnesValue()) {
5454 Opcode = X86ISD::DEC;
5459 // Otherwise use a regular EFLAGS-setting add.
5460 Opcode = X86ISD::ADD;
5464 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5465 // likely to be selected as part of a load-modify-store instruction.
5466 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5467 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5468 if (UI->getOpcode() == ISD::STORE)
5470 // Otherwise use a regular EFLAGS-setting sub.
5471 Opcode = X86ISD::SUB;
5478 return SDValue(Op.getNode(), 1);
5484 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::i32);
5485 SmallVector<SDValue, 4> Ops;
5486 for (unsigned i = 0; i != NumOperands; ++i)
5487 Ops.push_back(Op.getOperand(i));
5488 SDValue New = DAG.getNode(Opcode, dl, VTs, 2, &Ops[0], NumOperands);
5489 DAG.ReplaceAllUsesWith(Op, New);
5490 return SDValue(New.getNode(), 1);
5494 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5495 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5496 DAG.getConstant(0, Op.getValueType()));
5499 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5501 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5502 SelectionDAG &DAG) {
5503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5504 if (C->getAPIntValue() == 0)
5505 return EmitTest(Op0, X86CC, DAG);
5507 DebugLoc dl = Op0.getDebugLoc();
5508 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5511 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5512 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5513 SDValue Op0 = Op.getOperand(0);
5514 SDValue Op1 = Op.getOperand(1);
5515 DebugLoc dl = Op.getDebugLoc();
5516 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5518 // Lower (X & (1 << N)) == 0 to BT(X, N).
5519 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5520 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5521 if (Op0.getOpcode() == ISD::AND &&
5523 Op1.getOpcode() == ISD::Constant &&
5524 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5525 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5527 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5528 if (ConstantSDNode *Op010C =
5529 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5530 if (Op010C->getZExtValue() == 1) {
5531 LHS = Op0.getOperand(0);
5532 RHS = Op0.getOperand(1).getOperand(1);
5534 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5535 if (ConstantSDNode *Op000C =
5536 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5537 if (Op000C->getZExtValue() == 1) {
5538 LHS = Op0.getOperand(1);
5539 RHS = Op0.getOperand(0).getOperand(1);
5541 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5542 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5543 SDValue AndLHS = Op0.getOperand(0);
5544 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5545 LHS = AndLHS.getOperand(0);
5546 RHS = AndLHS.getOperand(1);
5550 if (LHS.getNode()) {
5551 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5552 // instruction. Since the shift amount is in-range-or-undefined, we know
5553 // that doing a bittest on the i16 value is ok. We extend to i32 because
5554 // the encoding for the i16 version is larger than the i32 version.
5555 if (LHS.getValueType() == MVT::i8)
5556 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5558 // If the operand types disagree, extend the shift amount to match. Since
5559 // BT ignores high bits (like shifts) we can use anyextend.
5560 if (LHS.getValueType() != RHS.getValueType())
5561 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5563 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5564 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5565 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5566 DAG.getConstant(Cond, MVT::i8), BT);
5570 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5571 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5573 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5574 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5575 DAG.getConstant(X86CC, MVT::i8), Cond);
5578 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5580 SDValue Op0 = Op.getOperand(0);
5581 SDValue Op1 = Op.getOperand(1);
5582 SDValue CC = Op.getOperand(2);
5583 MVT VT = Op.getValueType();
5584 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5585 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5586 DebugLoc dl = Op.getDebugLoc();
5590 MVT VT0 = Op0.getValueType();
5591 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5592 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5595 switch (SetCCOpcode) {
5598 case ISD::SETEQ: SSECC = 0; break;
5600 case ISD::SETGT: Swap = true; // Fallthrough
5602 case ISD::SETOLT: SSECC = 1; break;
5604 case ISD::SETGE: Swap = true; // Fallthrough
5606 case ISD::SETOLE: SSECC = 2; break;
5607 case ISD::SETUO: SSECC = 3; break;
5609 case ISD::SETNE: SSECC = 4; break;
5610 case ISD::SETULE: Swap = true;
5611 case ISD::SETUGE: SSECC = 5; break;
5612 case ISD::SETULT: Swap = true;
5613 case ISD::SETUGT: SSECC = 6; break;
5614 case ISD::SETO: SSECC = 7; break;
5617 std::swap(Op0, Op1);
5619 // In the two special cases we can't handle, emit two comparisons.
5621 if (SetCCOpcode == ISD::SETUEQ) {
5623 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5624 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5625 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5627 else if (SetCCOpcode == ISD::SETONE) {
5629 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5630 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5631 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5633 assert(0 && "Illegal FP comparison");
5635 // Handle all other FP comparisons here.
5636 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5639 // We are handling one of the integer comparisons here. Since SSE only has
5640 // GT and EQ comparisons for integer, swapping operands and multiple
5641 // operations may be required for some comparisons.
5642 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5643 bool Swap = false, Invert = false, FlipSigns = false;
5645 switch (VT.getSimpleVT()) {
5647 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5648 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5649 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5650 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5653 switch (SetCCOpcode) {
5655 case ISD::SETNE: Invert = true;
5656 case ISD::SETEQ: Opc = EQOpc; break;
5657 case ISD::SETLT: Swap = true;
5658 case ISD::SETGT: Opc = GTOpc; break;
5659 case ISD::SETGE: Swap = true;
5660 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5661 case ISD::SETULT: Swap = true;
5662 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5663 case ISD::SETUGE: Swap = true;
5664 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5667 std::swap(Op0, Op1);
5669 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5670 // bits of the inputs before performing those operations.
5672 MVT EltVT = VT.getVectorElementType();
5673 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5675 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5676 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5678 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5679 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5682 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5684 // If the logical-not of the result is required, perform that now.
5686 Result = DAG.getNOT(dl, Result, VT);
5691 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5692 static bool isX86LogicalCmp(SDValue Op) {
5693 unsigned Opc = Op.getNode()->getOpcode();
5694 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5696 if (Op.getResNo() == 1 &&
5697 (Opc == X86ISD::ADD ||
5698 Opc == X86ISD::SUB ||
5699 Opc == X86ISD::SMUL ||
5700 Opc == X86ISD::UMUL ||
5701 Opc == X86ISD::INC ||
5702 Opc == X86ISD::DEC))
5708 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5709 bool addTest = true;
5710 SDValue Cond = Op.getOperand(0);
5711 DebugLoc dl = Op.getDebugLoc();
5714 if (Cond.getOpcode() == ISD::SETCC)
5715 Cond = LowerSETCC(Cond, DAG);
5717 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5718 // setting operand in place of the X86ISD::SETCC.
5719 if (Cond.getOpcode() == X86ISD::SETCC) {
5720 CC = Cond.getOperand(0);
5722 SDValue Cmp = Cond.getOperand(1);
5723 unsigned Opc = Cmp.getOpcode();
5724 MVT VT = Op.getValueType();
5726 bool IllegalFPCMov = false;
5727 if (VT.isFloatingPoint() && !VT.isVector() &&
5728 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5729 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5731 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5732 Opc == X86ISD::BT) { // FIXME
5739 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5740 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5743 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5745 SmallVector<SDValue, 4> Ops;
5746 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5747 // condition is true.
5748 Ops.push_back(Op.getOperand(2));
5749 Ops.push_back(Op.getOperand(1));
5751 Ops.push_back(Cond);
5752 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5755 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5756 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5757 // from the AND / OR.
5758 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5759 Opc = Op.getOpcode();
5760 if (Opc != ISD::OR && Opc != ISD::AND)
5762 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5763 Op.getOperand(0).hasOneUse() &&
5764 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5765 Op.getOperand(1).hasOneUse());
5768 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5769 // 1 and that the SETCC node has a single use.
5770 static bool isXor1OfSetCC(SDValue Op) {
5771 if (Op.getOpcode() != ISD::XOR)
5773 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5774 if (N1C && N1C->getAPIntValue() == 1) {
5775 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5776 Op.getOperand(0).hasOneUse();
5781 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5782 bool addTest = true;
5783 SDValue Chain = Op.getOperand(0);
5784 SDValue Cond = Op.getOperand(1);
5785 SDValue Dest = Op.getOperand(2);
5786 DebugLoc dl = Op.getDebugLoc();
5789 if (Cond.getOpcode() == ISD::SETCC)
5790 Cond = LowerSETCC(Cond, DAG);
5792 // FIXME: LowerXALUO doesn't handle these!!
5793 else if (Cond.getOpcode() == X86ISD::ADD ||
5794 Cond.getOpcode() == X86ISD::SUB ||
5795 Cond.getOpcode() == X86ISD::SMUL ||
5796 Cond.getOpcode() == X86ISD::UMUL)
5797 Cond = LowerXALUO(Cond, DAG);
5800 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5801 // setting operand in place of the X86ISD::SETCC.
5802 if (Cond.getOpcode() == X86ISD::SETCC) {
5803 CC = Cond.getOperand(0);
5805 SDValue Cmp = Cond.getOperand(1);
5806 unsigned Opc = Cmp.getOpcode();
5807 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5808 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5812 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5816 // These can only come from an arithmetic instruction with overflow,
5817 // e.g. SADDO, UADDO.
5818 Cond = Cond.getNode()->getOperand(1);
5825 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5826 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5827 if (CondOpc == ISD::OR) {
5828 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5829 // two branches instead of an explicit OR instruction with a
5831 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5832 isX86LogicalCmp(Cmp)) {
5833 CC = Cond.getOperand(0).getOperand(0);
5834 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5835 Chain, Dest, CC, Cmp);
5836 CC = Cond.getOperand(1).getOperand(0);
5840 } else { // ISD::AND
5841 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5842 // two branches instead of an explicit AND instruction with a
5843 // separate test. However, we only do this if this block doesn't
5844 // have a fall-through edge, because this requires an explicit
5845 // jmp when the condition is false.
5846 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5847 isX86LogicalCmp(Cmp) &&
5848 Op.getNode()->hasOneUse()) {
5849 X86::CondCode CCode =
5850 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5851 CCode = X86::GetOppositeBranchCondition(CCode);
5852 CC = DAG.getConstant(CCode, MVT::i8);
5853 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5854 // Look for an unconditional branch following this conditional branch.
5855 // We need this because we need to reverse the successors in order
5856 // to implement FCMP_OEQ.
5857 if (User.getOpcode() == ISD::BR) {
5858 SDValue FalseBB = User.getOperand(1);
5860 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5861 assert(NewBR == User);
5864 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5865 Chain, Dest, CC, Cmp);
5866 X86::CondCode CCode =
5867 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5868 CCode = X86::GetOppositeBranchCondition(CCode);
5869 CC = DAG.getConstant(CCode, MVT::i8);
5875 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5876 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5877 // It should be transformed during dag combiner except when the condition
5878 // is set by a arithmetics with overflow node.
5879 X86::CondCode CCode =
5880 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5881 CCode = X86::GetOppositeBranchCondition(CCode);
5882 CC = DAG.getConstant(CCode, MVT::i8);
5883 Cond = Cond.getOperand(0).getOperand(1);
5889 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5890 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5892 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5893 Chain, Dest, CC, Cond);
5897 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5898 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5899 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5900 // that the guard pages used by the OS virtual memory manager are allocated in
5901 // correct sequence.
5903 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5904 SelectionDAG &DAG) {
5905 assert(Subtarget->isTargetCygMing() &&
5906 "This should be used only on Cygwin/Mingw targets");
5907 DebugLoc dl = Op.getDebugLoc();
5910 SDValue Chain = Op.getOperand(0);
5911 SDValue Size = Op.getOperand(1);
5912 // FIXME: Ensure alignment here
5916 MVT IntPtr = getPointerTy();
5917 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5919 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5921 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5922 Flag = Chain.getValue(1);
5924 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5925 SDValue Ops[] = { Chain,
5926 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5927 DAG.getRegister(X86::EAX, IntPtr),
5928 DAG.getRegister(X86StackPtr, SPTy),
5930 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5931 Flag = Chain.getValue(1);
5933 Chain = DAG.getCALLSEQ_END(Chain,
5934 DAG.getIntPtrConstant(0, true),
5935 DAG.getIntPtrConstant(0, true),
5938 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5940 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5941 return DAG.getMergeValues(Ops1, 2, dl);
5945 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5947 SDValue Dst, SDValue Src,
5948 SDValue Size, unsigned Align,
5950 uint64_t DstSVOff) {
5951 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5953 // If not DWORD aligned or size is more than the threshold, call the library.
5954 // The libc version is likely to be faster for these cases. It can use the
5955 // address value and run time information about the CPU.
5956 if ((Align & 3) != 0 ||
5958 ConstantSize->getZExtValue() >
5959 getSubtarget()->getMaxInlineSizeThreshold()) {
5960 SDValue InFlag(0, 0);
5962 // Check to see if there is a specialized entry-point for memory zeroing.
5963 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5965 if (const char *bzeroEntry = V &&
5966 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5967 MVT IntPtr = getPointerTy();
5968 const Type *IntPtrTy = TD->getIntPtrType();
5969 TargetLowering::ArgListTy Args;
5970 TargetLowering::ArgListEntry Entry;
5972 Entry.Ty = IntPtrTy;
5973 Args.push_back(Entry);
5975 Args.push_back(Entry);
5976 std::pair<SDValue,SDValue> CallResult =
5977 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5978 CallingConv::C, false,
5979 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5980 return CallResult.second;
5983 // Otherwise have the target-independent code call memset.
5987 uint64_t SizeVal = ConstantSize->getZExtValue();
5988 SDValue InFlag(0, 0);
5991 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5992 unsigned BytesLeft = 0;
5993 bool TwoRepStos = false;
5996 uint64_t Val = ValC->getZExtValue() & 255;
5998 // If the value is a constant, then we can potentially use larger sets.
5999 switch (Align & 3) {
6000 case 2: // WORD aligned
6003 Val = (Val << 8) | Val;
6005 case 0: // DWORD aligned
6008 Val = (Val << 8) | Val;
6009 Val = (Val << 16) | Val;
6010 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6013 Val = (Val << 32) | Val;
6016 default: // Byte aligned
6019 Count = DAG.getIntPtrConstant(SizeVal);
6023 if (AVT.bitsGT(MVT::i8)) {
6024 unsigned UBytes = AVT.getSizeInBits() / 8;
6025 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6026 BytesLeft = SizeVal % UBytes;
6029 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6031 InFlag = Chain.getValue(1);
6034 Count = DAG.getIntPtrConstant(SizeVal);
6035 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6036 InFlag = Chain.getValue(1);
6039 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6042 InFlag = Chain.getValue(1);
6043 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6046 InFlag = Chain.getValue(1);
6048 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6049 SmallVector<SDValue, 8> Ops;
6050 Ops.push_back(Chain);
6051 Ops.push_back(DAG.getValueType(AVT));
6052 Ops.push_back(InFlag);
6053 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6056 InFlag = Chain.getValue(1);
6058 MVT CVT = Count.getValueType();
6059 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6060 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6061 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6064 InFlag = Chain.getValue(1);
6065 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6067 Ops.push_back(Chain);
6068 Ops.push_back(DAG.getValueType(MVT::i8));
6069 Ops.push_back(InFlag);
6070 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6071 } else if (BytesLeft) {
6072 // Handle the last 1 - 7 bytes.
6073 unsigned Offset = SizeVal - BytesLeft;
6074 MVT AddrVT = Dst.getValueType();
6075 MVT SizeVT = Size.getValueType();
6077 Chain = DAG.getMemset(Chain, dl,
6078 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6079 DAG.getConstant(Offset, AddrVT)),
6081 DAG.getConstant(BytesLeft, SizeVT),
6082 Align, DstSV, DstSVOff + Offset);
6085 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6090 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6091 SDValue Chain, SDValue Dst, SDValue Src,
6092 SDValue Size, unsigned Align,
6094 const Value *DstSV, uint64_t DstSVOff,
6095 const Value *SrcSV, uint64_t SrcSVOff) {
6096 // This requires the copy size to be a constant, preferrably
6097 // within a subtarget-specific limit.
6098 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6101 uint64_t SizeVal = ConstantSize->getZExtValue();
6102 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6105 /// If not DWORD aligned, call the library.
6106 if ((Align & 3) != 0)
6111 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6114 unsigned UBytes = AVT.getSizeInBits() / 8;
6115 unsigned CountVal = SizeVal / UBytes;
6116 SDValue Count = DAG.getIntPtrConstant(CountVal);
6117 unsigned BytesLeft = SizeVal % UBytes;
6119 SDValue InFlag(0, 0);
6120 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6123 InFlag = Chain.getValue(1);
6124 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6127 InFlag = Chain.getValue(1);
6128 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6131 InFlag = Chain.getValue(1);
6133 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6134 SmallVector<SDValue, 8> Ops;
6135 Ops.push_back(Chain);
6136 Ops.push_back(DAG.getValueType(AVT));
6137 Ops.push_back(InFlag);
6138 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6140 SmallVector<SDValue, 4> Results;
6141 Results.push_back(RepMovs);
6143 // Handle the last 1 - 7 bytes.
6144 unsigned Offset = SizeVal - BytesLeft;
6145 MVT DstVT = Dst.getValueType();
6146 MVT SrcVT = Src.getValueType();
6147 MVT SizeVT = Size.getValueType();
6148 Results.push_back(DAG.getMemcpy(Chain, dl,
6149 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6150 DAG.getConstant(Offset, DstVT)),
6151 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6152 DAG.getConstant(Offset, SrcVT)),
6153 DAG.getConstant(BytesLeft, SizeVT),
6154 Align, AlwaysInline,
6155 DstSV, DstSVOff + Offset,
6156 SrcSV, SrcSVOff + Offset));
6159 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6160 &Results[0], Results.size());
6163 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6164 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6165 DebugLoc dl = Op.getDebugLoc();
6167 if (!Subtarget->is64Bit()) {
6168 // vastart just stores the address of the VarArgsFrameIndex slot into the
6169 // memory location argument.
6170 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6171 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6175 // gp_offset (0 - 6 * 8)
6176 // fp_offset (48 - 48 + 8 * 16)
6177 // overflow_arg_area (point to parameters coming in memory).
6179 SmallVector<SDValue, 8> MemOps;
6180 SDValue FIN = Op.getOperand(1);
6182 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6183 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6185 MemOps.push_back(Store);
6188 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6189 FIN, DAG.getIntPtrConstant(4));
6190 Store = DAG.getStore(Op.getOperand(0), dl,
6191 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6193 MemOps.push_back(Store);
6195 // Store ptr to overflow_arg_area
6196 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6197 FIN, DAG.getIntPtrConstant(4));
6198 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6199 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6200 MemOps.push_back(Store);
6202 // Store ptr to reg_save_area.
6203 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6204 FIN, DAG.getIntPtrConstant(8));
6205 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6206 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6207 MemOps.push_back(Store);
6208 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6209 &MemOps[0], MemOps.size());
6212 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6213 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6214 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6215 SDValue Chain = Op.getOperand(0);
6216 SDValue SrcPtr = Op.getOperand(1);
6217 SDValue SrcSV = Op.getOperand(2);
6219 assert(0 && "VAArgInst is not yet implemented for x86-64!");
6224 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6225 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6226 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6227 SDValue Chain = Op.getOperand(0);
6228 SDValue DstPtr = Op.getOperand(1);
6229 SDValue SrcPtr = Op.getOperand(2);
6230 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6231 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6232 DebugLoc dl = Op.getDebugLoc();
6234 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6235 DAG.getIntPtrConstant(24), 8, false,
6236 DstSV, 0, SrcSV, 0);
6240 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6241 DebugLoc dl = Op.getDebugLoc();
6242 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6244 default: return SDValue(); // Don't custom lower most intrinsics.
6245 // Comparison intrinsics.
6246 case Intrinsic::x86_sse_comieq_ss:
6247 case Intrinsic::x86_sse_comilt_ss:
6248 case Intrinsic::x86_sse_comile_ss:
6249 case Intrinsic::x86_sse_comigt_ss:
6250 case Intrinsic::x86_sse_comige_ss:
6251 case Intrinsic::x86_sse_comineq_ss:
6252 case Intrinsic::x86_sse_ucomieq_ss:
6253 case Intrinsic::x86_sse_ucomilt_ss:
6254 case Intrinsic::x86_sse_ucomile_ss:
6255 case Intrinsic::x86_sse_ucomigt_ss:
6256 case Intrinsic::x86_sse_ucomige_ss:
6257 case Intrinsic::x86_sse_ucomineq_ss:
6258 case Intrinsic::x86_sse2_comieq_sd:
6259 case Intrinsic::x86_sse2_comilt_sd:
6260 case Intrinsic::x86_sse2_comile_sd:
6261 case Intrinsic::x86_sse2_comigt_sd:
6262 case Intrinsic::x86_sse2_comige_sd:
6263 case Intrinsic::x86_sse2_comineq_sd:
6264 case Intrinsic::x86_sse2_ucomieq_sd:
6265 case Intrinsic::x86_sse2_ucomilt_sd:
6266 case Intrinsic::x86_sse2_ucomile_sd:
6267 case Intrinsic::x86_sse2_ucomigt_sd:
6268 case Intrinsic::x86_sse2_ucomige_sd:
6269 case Intrinsic::x86_sse2_ucomineq_sd: {
6271 ISD::CondCode CC = ISD::SETCC_INVALID;
6274 case Intrinsic::x86_sse_comieq_ss:
6275 case Intrinsic::x86_sse2_comieq_sd:
6279 case Intrinsic::x86_sse_comilt_ss:
6280 case Intrinsic::x86_sse2_comilt_sd:
6284 case Intrinsic::x86_sse_comile_ss:
6285 case Intrinsic::x86_sse2_comile_sd:
6289 case Intrinsic::x86_sse_comigt_ss:
6290 case Intrinsic::x86_sse2_comigt_sd:
6294 case Intrinsic::x86_sse_comige_ss:
6295 case Intrinsic::x86_sse2_comige_sd:
6299 case Intrinsic::x86_sse_comineq_ss:
6300 case Intrinsic::x86_sse2_comineq_sd:
6304 case Intrinsic::x86_sse_ucomieq_ss:
6305 case Intrinsic::x86_sse2_ucomieq_sd:
6306 Opc = X86ISD::UCOMI;
6309 case Intrinsic::x86_sse_ucomilt_ss:
6310 case Intrinsic::x86_sse2_ucomilt_sd:
6311 Opc = X86ISD::UCOMI;
6314 case Intrinsic::x86_sse_ucomile_ss:
6315 case Intrinsic::x86_sse2_ucomile_sd:
6316 Opc = X86ISD::UCOMI;
6319 case Intrinsic::x86_sse_ucomigt_ss:
6320 case Intrinsic::x86_sse2_ucomigt_sd:
6321 Opc = X86ISD::UCOMI;
6324 case Intrinsic::x86_sse_ucomige_ss:
6325 case Intrinsic::x86_sse2_ucomige_sd:
6326 Opc = X86ISD::UCOMI;
6329 case Intrinsic::x86_sse_ucomineq_ss:
6330 case Intrinsic::x86_sse2_ucomineq_sd:
6331 Opc = X86ISD::UCOMI;
6336 SDValue LHS = Op.getOperand(1);
6337 SDValue RHS = Op.getOperand(2);
6338 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6339 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6340 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6341 DAG.getConstant(X86CC, MVT::i8), Cond);
6342 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6345 // Fix vector shift instructions where the last operand is a non-immediate
6347 case Intrinsic::x86_sse2_pslli_w:
6348 case Intrinsic::x86_sse2_pslli_d:
6349 case Intrinsic::x86_sse2_pslli_q:
6350 case Intrinsic::x86_sse2_psrli_w:
6351 case Intrinsic::x86_sse2_psrli_d:
6352 case Intrinsic::x86_sse2_psrli_q:
6353 case Intrinsic::x86_sse2_psrai_w:
6354 case Intrinsic::x86_sse2_psrai_d:
6355 case Intrinsic::x86_mmx_pslli_w:
6356 case Intrinsic::x86_mmx_pslli_d:
6357 case Intrinsic::x86_mmx_pslli_q:
6358 case Intrinsic::x86_mmx_psrli_w:
6359 case Intrinsic::x86_mmx_psrli_d:
6360 case Intrinsic::x86_mmx_psrli_q:
6361 case Intrinsic::x86_mmx_psrai_w:
6362 case Intrinsic::x86_mmx_psrai_d: {
6363 SDValue ShAmt = Op.getOperand(2);
6364 if (isa<ConstantSDNode>(ShAmt))
6367 unsigned NewIntNo = 0;
6368 MVT ShAmtVT = MVT::v4i32;
6370 case Intrinsic::x86_sse2_pslli_w:
6371 NewIntNo = Intrinsic::x86_sse2_psll_w;
6373 case Intrinsic::x86_sse2_pslli_d:
6374 NewIntNo = Intrinsic::x86_sse2_psll_d;
6376 case Intrinsic::x86_sse2_pslli_q:
6377 NewIntNo = Intrinsic::x86_sse2_psll_q;
6379 case Intrinsic::x86_sse2_psrli_w:
6380 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6382 case Intrinsic::x86_sse2_psrli_d:
6383 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6385 case Intrinsic::x86_sse2_psrli_q:
6386 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6388 case Intrinsic::x86_sse2_psrai_w:
6389 NewIntNo = Intrinsic::x86_sse2_psra_w;
6391 case Intrinsic::x86_sse2_psrai_d:
6392 NewIntNo = Intrinsic::x86_sse2_psra_d;
6395 ShAmtVT = MVT::v2i32;
6397 case Intrinsic::x86_mmx_pslli_w:
6398 NewIntNo = Intrinsic::x86_mmx_psll_w;
6400 case Intrinsic::x86_mmx_pslli_d:
6401 NewIntNo = Intrinsic::x86_mmx_psll_d;
6403 case Intrinsic::x86_mmx_pslli_q:
6404 NewIntNo = Intrinsic::x86_mmx_psll_q;
6406 case Intrinsic::x86_mmx_psrli_w:
6407 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6409 case Intrinsic::x86_mmx_psrli_d:
6410 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6412 case Intrinsic::x86_mmx_psrli_q:
6413 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6415 case Intrinsic::x86_mmx_psrai_w:
6416 NewIntNo = Intrinsic::x86_mmx_psra_w;
6418 case Intrinsic::x86_mmx_psrai_d:
6419 NewIntNo = Intrinsic::x86_mmx_psra_d;
6421 default: abort(); // Can't reach here.
6426 MVT VT = Op.getValueType();
6427 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6428 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6429 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6430 DAG.getConstant(NewIntNo, MVT::i32),
6431 Op.getOperand(1), ShAmt);
6436 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6437 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6438 DebugLoc dl = Op.getDebugLoc();
6441 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6443 DAG.getConstant(TD->getPointerSize(),
6444 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6445 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6446 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6451 // Just load the return address.
6452 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6453 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6454 RetAddrFI, NULL, 0);
6457 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6458 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6459 MFI->setFrameAddressIsTaken(true);
6460 MVT VT = Op.getValueType();
6461 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6462 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6463 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6464 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6466 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6470 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6471 SelectionDAG &DAG) {
6472 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6475 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6477 MachineFunction &MF = DAG.getMachineFunction();
6478 SDValue Chain = Op.getOperand(0);
6479 SDValue Offset = Op.getOperand(1);
6480 SDValue Handler = Op.getOperand(2);
6481 DebugLoc dl = Op.getDebugLoc();
6483 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6485 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6487 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6488 DAG.getIntPtrConstant(-TD->getPointerSize()));
6489 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6490 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6491 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6492 MF.getRegInfo().addLiveOut(StoreAddrReg);
6494 return DAG.getNode(X86ISD::EH_RETURN, dl,
6496 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6499 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6500 SelectionDAG &DAG) {
6501 SDValue Root = Op.getOperand(0);
6502 SDValue Trmp = Op.getOperand(1); // trampoline
6503 SDValue FPtr = Op.getOperand(2); // nested function
6504 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6505 DebugLoc dl = Op.getDebugLoc();
6507 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6509 const X86InstrInfo *TII =
6510 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6512 if (Subtarget->is64Bit()) {
6513 SDValue OutChains[6];
6515 // Large code-model.
6517 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6518 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6520 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6521 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6523 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6525 // Load the pointer to the nested function into R11.
6526 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6527 SDValue Addr = Trmp;
6528 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6531 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6532 DAG.getConstant(2, MVT::i64));
6533 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6535 // Load the 'nest' parameter value into R10.
6536 // R10 is specified in X86CallingConv.td
6537 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6538 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6539 DAG.getConstant(10, MVT::i64));
6540 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6541 Addr, TrmpAddr, 10);
6543 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6544 DAG.getConstant(12, MVT::i64));
6545 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6547 // Jump to the nested function.
6548 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6549 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6550 DAG.getConstant(20, MVT::i64));
6551 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6552 Addr, TrmpAddr, 20);
6554 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6555 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6556 DAG.getConstant(22, MVT::i64));
6557 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6561 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6562 return DAG.getMergeValues(Ops, 2, dl);
6564 const Function *Func =
6565 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6566 unsigned CC = Func->getCallingConv();
6571 assert(0 && "Unsupported calling convention");
6572 case CallingConv::C:
6573 case CallingConv::X86_StdCall: {
6574 // Pass 'nest' parameter in ECX.
6575 // Must be kept in sync with X86CallingConv.td
6578 // Check that ECX wasn't needed by an 'inreg' parameter.
6579 const FunctionType *FTy = Func->getFunctionType();
6580 const AttrListPtr &Attrs = Func->getAttributes();
6582 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6583 unsigned InRegCount = 0;
6586 for (FunctionType::param_iterator I = FTy->param_begin(),
6587 E = FTy->param_end(); I != E; ++I, ++Idx)
6588 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6589 // FIXME: should only count parameters that are lowered to integers.
6590 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6592 if (InRegCount > 2) {
6593 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6599 case CallingConv::X86_FastCall:
6600 case CallingConv::Fast:
6601 // Pass 'nest' parameter in EAX.
6602 // Must be kept in sync with X86CallingConv.td
6607 SDValue OutChains[4];
6610 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6611 DAG.getConstant(10, MVT::i32));
6612 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6614 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6615 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6616 OutChains[0] = DAG.getStore(Root, dl,
6617 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6621 DAG.getConstant(1, MVT::i32));
6622 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6624 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6625 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6626 DAG.getConstant(5, MVT::i32));
6627 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6628 TrmpAddr, 5, false, 1);
6630 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6631 DAG.getConstant(6, MVT::i32));
6632 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6635 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6636 return DAG.getMergeValues(Ops, 2, dl);
6640 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6642 The rounding mode is in bits 11:10 of FPSR, and has the following
6649 FLT_ROUNDS, on the other hand, expects the following:
6656 To perform the conversion, we do:
6657 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6660 MachineFunction &MF = DAG.getMachineFunction();
6661 const TargetMachine &TM = MF.getTarget();
6662 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6663 unsigned StackAlignment = TFI.getStackAlignment();
6664 MVT VT = Op.getValueType();
6665 DebugLoc dl = Op.getDebugLoc();
6667 // Save FP Control Word to stack slot
6668 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6669 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6671 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6672 DAG.getEntryNode(), StackSlot);
6674 // Load FP Control Word from stack slot
6675 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6677 // Transform as necessary
6679 DAG.getNode(ISD::SRL, dl, MVT::i16,
6680 DAG.getNode(ISD::AND, dl, MVT::i16,
6681 CWD, DAG.getConstant(0x800, MVT::i16)),
6682 DAG.getConstant(11, MVT::i8));
6684 DAG.getNode(ISD::SRL, dl, MVT::i16,
6685 DAG.getNode(ISD::AND, dl, MVT::i16,
6686 CWD, DAG.getConstant(0x400, MVT::i16)),
6687 DAG.getConstant(9, MVT::i8));
6690 DAG.getNode(ISD::AND, dl, MVT::i16,
6691 DAG.getNode(ISD::ADD, dl, MVT::i16,
6692 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6693 DAG.getConstant(1, MVT::i16)),
6694 DAG.getConstant(3, MVT::i16));
6697 return DAG.getNode((VT.getSizeInBits() < 16 ?
6698 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6701 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6702 MVT VT = Op.getValueType();
6704 unsigned NumBits = VT.getSizeInBits();
6705 DebugLoc dl = Op.getDebugLoc();
6707 Op = Op.getOperand(0);
6708 if (VT == MVT::i8) {
6709 // Zero extend to i32 since there is not an i8 bsr.
6711 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6714 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6715 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6716 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6718 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6719 SmallVector<SDValue, 4> Ops;
6721 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6722 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6723 Ops.push_back(Op.getValue(1));
6724 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6726 // Finally xor with NumBits-1.
6727 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6730 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6734 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6735 MVT VT = Op.getValueType();
6737 unsigned NumBits = VT.getSizeInBits();
6738 DebugLoc dl = Op.getDebugLoc();
6740 Op = Op.getOperand(0);
6741 if (VT == MVT::i8) {
6743 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6746 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6747 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6748 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6750 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6751 SmallVector<SDValue, 4> Ops;
6753 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6754 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6755 Ops.push_back(Op.getValue(1));
6756 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6759 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6763 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6764 MVT VT = Op.getValueType();
6765 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6766 DebugLoc dl = Op.getDebugLoc();
6768 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6769 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6770 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6771 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6772 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6774 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6775 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6776 // return AloBlo + AloBhi + AhiBlo;
6778 SDValue A = Op.getOperand(0);
6779 SDValue B = Op.getOperand(1);
6781 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6782 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6783 A, DAG.getConstant(32, MVT::i32));
6784 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6785 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6786 B, DAG.getConstant(32, MVT::i32));
6787 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6788 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6790 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6791 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6793 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6794 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6796 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6797 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6798 AloBhi, DAG.getConstant(32, MVT::i32));
6799 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6800 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6801 AhiBlo, DAG.getConstant(32, MVT::i32));
6802 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6803 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6808 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6809 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6810 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6811 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6812 // has only one use.
6813 SDNode *N = Op.getNode();
6814 SDValue LHS = N->getOperand(0);
6815 SDValue RHS = N->getOperand(1);
6816 unsigned BaseOp = 0;
6818 DebugLoc dl = Op.getDebugLoc();
6820 switch (Op.getOpcode()) {
6821 default: assert(0 && "Unknown ovf instruction!");
6823 // A subtract of one will be selected as a INC. Note that INC doesn't
6824 // set CF, so we can't do this for UADDO.
6825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6826 if (C->getAPIntValue() == 1) {
6827 BaseOp = X86ISD::INC;
6831 BaseOp = X86ISD::ADD;
6835 BaseOp = X86ISD::ADD;
6839 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6840 // set CF, so we can't do this for USUBO.
6841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6842 if (C->getAPIntValue() == 1) {
6843 BaseOp = X86ISD::DEC;
6847 BaseOp = X86ISD::SUB;
6851 BaseOp = X86ISD::SUB;
6855 BaseOp = X86ISD::SMUL;
6859 BaseOp = X86ISD::UMUL;
6864 // Also sets EFLAGS.
6865 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6866 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6869 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6870 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6872 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6876 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6877 MVT T = Op.getValueType();
6878 DebugLoc dl = Op.getDebugLoc();
6881 switch(T.getSimpleVT()) {
6883 assert(false && "Invalid value type!");
6884 case MVT::i8: Reg = X86::AL; size = 1; break;
6885 case MVT::i16: Reg = X86::AX; size = 2; break;
6886 case MVT::i32: Reg = X86::EAX; size = 4; break;
6888 assert(Subtarget->is64Bit() && "Node not type legal!");
6889 Reg = X86::RAX; size = 8;
6892 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6893 Op.getOperand(2), SDValue());
6894 SDValue Ops[] = { cpIn.getValue(0),
6897 DAG.getTargetConstant(size, MVT::i8),
6899 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6900 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6902 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6906 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6907 SelectionDAG &DAG) {
6908 assert(Subtarget->is64Bit() && "Result not type legalized?");
6909 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6910 SDValue TheChain = Op.getOperand(0);
6911 DebugLoc dl = Op.getDebugLoc();
6912 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6913 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6914 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6916 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6917 DAG.getConstant(32, MVT::i8));
6919 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6922 return DAG.getMergeValues(Ops, 2, dl);
6925 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6926 SDNode *Node = Op.getNode();
6927 DebugLoc dl = Node->getDebugLoc();
6928 MVT T = Node->getValueType(0);
6929 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6930 DAG.getConstant(0, T), Node->getOperand(2));
6931 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6932 cast<AtomicSDNode>(Node)->getMemoryVT(),
6933 Node->getOperand(0),
6934 Node->getOperand(1), negOp,
6935 cast<AtomicSDNode>(Node)->getSrcValue(),
6936 cast<AtomicSDNode>(Node)->getAlignment());
6939 /// LowerOperation - Provide custom lowering hooks for some operations.
6941 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6942 switch (Op.getOpcode()) {
6943 default: assert(0 && "Should not custom lower this!");
6944 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6945 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6946 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6947 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6948 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6949 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6950 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6951 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6952 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6953 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6954 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6955 case ISD::SHL_PARTS:
6956 case ISD::SRA_PARTS:
6957 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6958 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6959 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6960 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6961 case ISD::FABS: return LowerFABS(Op, DAG);
6962 case ISD::FNEG: return LowerFNEG(Op, DAG);
6963 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6964 case ISD::SETCC: return LowerSETCC(Op, DAG);
6965 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6966 case ISD::SELECT: return LowerSELECT(Op, DAG);
6967 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6968 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6969 case ISD::CALL: return LowerCALL(Op, DAG);
6970 case ISD::RET: return LowerRET(Op, DAG);
6971 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6972 case ISD::VASTART: return LowerVASTART(Op, DAG);
6973 case ISD::VAARG: return LowerVAARG(Op, DAG);
6974 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6975 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6976 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6977 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6978 case ISD::FRAME_TO_ARGS_OFFSET:
6979 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6980 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6981 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6982 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6983 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6984 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6985 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6986 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6992 case ISD::UMULO: return LowerXALUO(Op, DAG);
6993 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6997 void X86TargetLowering::
6998 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6999 SelectionDAG &DAG, unsigned NewOp) {
7000 MVT T = Node->getValueType(0);
7001 DebugLoc dl = Node->getDebugLoc();
7002 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7004 SDValue Chain = Node->getOperand(0);
7005 SDValue In1 = Node->getOperand(1);
7006 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7007 Node->getOperand(2), DAG.getIntPtrConstant(0));
7008 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7009 Node->getOperand(2), DAG.getIntPtrConstant(1));
7010 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
7011 // have a MemOperand. Pass the info through as a normal operand.
7012 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
7013 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
7014 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7015 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
7016 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7017 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7018 Results.push_back(Result.getValue(2));
7021 /// ReplaceNodeResults - Replace a node with an illegal result type
7022 /// with a new node built out of custom code.
7023 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7024 SmallVectorImpl<SDValue>&Results,
7025 SelectionDAG &DAG) {
7026 DebugLoc dl = N->getDebugLoc();
7027 switch (N->getOpcode()) {
7029 assert(false && "Do not know how to custom type legalize this operation!");
7031 case ISD::FP_TO_SINT: {
7032 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
7033 SDValue FIST = Vals.first, StackSlot = Vals.second;
7034 if (FIST.getNode() != 0) {
7035 MVT VT = N->getValueType(0);
7036 // Return a load from the stack slot.
7037 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7041 case ISD::READCYCLECOUNTER: {
7042 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7043 SDValue TheChain = N->getOperand(0);
7044 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7045 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7047 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7049 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7050 SDValue Ops[] = { eax, edx };
7051 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7052 Results.push_back(edx.getValue(1));
7055 case ISD::ATOMIC_CMP_SWAP: {
7056 MVT T = N->getValueType(0);
7057 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7058 SDValue cpInL, cpInH;
7059 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7060 DAG.getConstant(0, MVT::i32));
7061 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7062 DAG.getConstant(1, MVT::i32));
7063 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7064 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7066 SDValue swapInL, swapInH;
7067 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7068 DAG.getConstant(0, MVT::i32));
7069 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7070 DAG.getConstant(1, MVT::i32));
7071 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7073 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7074 swapInL.getValue(1));
7075 SDValue Ops[] = { swapInH.getValue(0),
7077 swapInH.getValue(1) };
7078 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7079 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7080 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7081 MVT::i32, Result.getValue(1));
7082 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7083 MVT::i32, cpOutL.getValue(2));
7084 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7085 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7086 Results.push_back(cpOutH.getValue(1));
7089 case ISD::ATOMIC_LOAD_ADD:
7090 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7092 case ISD::ATOMIC_LOAD_AND:
7093 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7095 case ISD::ATOMIC_LOAD_NAND:
7096 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7098 case ISD::ATOMIC_LOAD_OR:
7099 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7101 case ISD::ATOMIC_LOAD_SUB:
7102 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7104 case ISD::ATOMIC_LOAD_XOR:
7105 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7107 case ISD::ATOMIC_SWAP:
7108 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7113 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7115 default: return NULL;
7116 case X86ISD::BSF: return "X86ISD::BSF";
7117 case X86ISD::BSR: return "X86ISD::BSR";
7118 case X86ISD::SHLD: return "X86ISD::SHLD";
7119 case X86ISD::SHRD: return "X86ISD::SHRD";
7120 case X86ISD::FAND: return "X86ISD::FAND";
7121 case X86ISD::FOR: return "X86ISD::FOR";
7122 case X86ISD::FXOR: return "X86ISD::FXOR";
7123 case X86ISD::FSRL: return "X86ISD::FSRL";
7124 case X86ISD::FILD: return "X86ISD::FILD";
7125 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7126 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7127 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7128 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7129 case X86ISD::FLD: return "X86ISD::FLD";
7130 case X86ISD::FST: return "X86ISD::FST";
7131 case X86ISD::CALL: return "X86ISD::CALL";
7132 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
7133 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7134 case X86ISD::BT: return "X86ISD::BT";
7135 case X86ISD::CMP: return "X86ISD::CMP";
7136 case X86ISD::COMI: return "X86ISD::COMI";
7137 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7138 case X86ISD::SETCC: return "X86ISD::SETCC";
7139 case X86ISD::CMOV: return "X86ISD::CMOV";
7140 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7141 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7142 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7143 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7144 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7145 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7146 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7147 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7148 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7149 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7150 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7151 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7152 case X86ISD::FMAX: return "X86ISD::FMAX";
7153 case X86ISD::FMIN: return "X86ISD::FMIN";
7154 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7155 case X86ISD::FRCP: return "X86ISD::FRCP";
7156 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7157 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7158 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7159 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7160 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7161 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7162 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7163 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7164 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7165 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7166 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7167 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7168 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7169 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7170 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7171 case X86ISD::VSHL: return "X86ISD::VSHL";
7172 case X86ISD::VSRL: return "X86ISD::VSRL";
7173 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7174 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7175 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7176 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7177 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7178 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7179 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7180 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7181 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7182 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7183 case X86ISD::ADD: return "X86ISD::ADD";
7184 case X86ISD::SUB: return "X86ISD::SUB";
7185 case X86ISD::SMUL: return "X86ISD::SMUL";
7186 case X86ISD::UMUL: return "X86ISD::UMUL";
7187 case X86ISD::INC: return "X86ISD::INC";
7188 case X86ISD::DEC: return "X86ISD::DEC";
7189 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7193 // isLegalAddressingMode - Return true if the addressing mode represented
7194 // by AM is legal for this target, for a load/store of the specified type.
7195 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7196 const Type *Ty) const {
7197 // X86 supports extremely general addressing modes.
7199 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7200 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7204 // We can only fold this if we don't need an extra load.
7205 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
7207 // If BaseGV requires a register, we cannot also have a BaseReg.
7208 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
7212 // X86-64 only supports addr of globals in small code model.
7213 if (Subtarget->is64Bit()) {
7214 if (getTargetMachine().getCodeModel() != CodeModel::Small)
7216 // If lower 4G is not available, then we must use rip-relative addressing.
7217 if (AM.BaseOffs || AM.Scale > 1)
7228 // These scales always work.
7233 // These scales are formed with basereg+scalereg. Only accept if there is
7238 default: // Other stuff never works.
7246 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7247 if (!Ty1->isInteger() || !Ty2->isInteger())
7249 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7250 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7251 if (NumBits1 <= NumBits2)
7253 return Subtarget->is64Bit() || NumBits1 < 64;
7256 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7257 if (!VT1.isInteger() || !VT2.isInteger())
7259 unsigned NumBits1 = VT1.getSizeInBits();
7260 unsigned NumBits2 = VT2.getSizeInBits();
7261 if (NumBits1 <= NumBits2)
7263 return Subtarget->is64Bit() || NumBits1 < 64;
7266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7269 /// are assumed to be legal.
7271 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
7272 // Only do shuffles on 128-bit vector types for now.
7273 // FIXME: pshufb, blends
7274 if (VT.getSizeInBits() == 64) return false;
7275 return (Mask.getNode()->getNumOperands() <= 4 ||
7276 isIdentityMask(Mask.getNode()) ||
7277 isIdentityMask(Mask.getNode(), true) ||
7278 isSplatMask(Mask.getNode()) ||
7279 X86::isPSHUFHWMask(Mask.getNode()) ||
7280 X86::isPSHUFLWMask(Mask.getNode()) ||
7281 X86::isUNPCKLMask(Mask.getNode()) ||
7282 X86::isUNPCKHMask(Mask.getNode()) ||
7283 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
7284 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
7288 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
7289 MVT EVT, SelectionDAG &DAG) const {
7290 unsigned NumElts = BVOps.size();
7291 // Only do shuffles on 128-bit vector types for now.
7292 if (EVT.getSizeInBits() * NumElts == 64) return false;
7293 if (NumElts == 2) return true;
7295 return (isMOVLMask(&BVOps[0], 4) ||
7296 isCommutedMOVL(&BVOps[0], 4, true) ||
7297 isSHUFPMask(&BVOps[0], 4) ||
7298 isCommutedSHUFP(&BVOps[0], 4));
7303 //===----------------------------------------------------------------------===//
7304 // X86 Scheduler Hooks
7305 //===----------------------------------------------------------------------===//
7307 // private utility function
7309 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7310 MachineBasicBlock *MBB,
7318 TargetRegisterClass *RC,
7319 bool invSrc) const {
7320 // For the atomic bitwise operator, we generate
7323 // ld t1 = [bitinstr.addr]
7324 // op t2 = t1, [bitinstr.val]
7326 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7328 // fallthrough -->nextMBB
7329 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7330 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7331 MachineFunction::iterator MBBIter = MBB;
7334 /// First build the CFG
7335 MachineFunction *F = MBB->getParent();
7336 MachineBasicBlock *thisMBB = MBB;
7337 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7338 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7339 F->insert(MBBIter, newMBB);
7340 F->insert(MBBIter, nextMBB);
7342 // Move all successors to thisMBB to nextMBB
7343 nextMBB->transferSuccessors(thisMBB);
7345 // Update thisMBB to fall through to newMBB
7346 thisMBB->addSuccessor(newMBB);
7348 // newMBB jumps to itself and fall through to nextMBB
7349 newMBB->addSuccessor(nextMBB);
7350 newMBB->addSuccessor(newMBB);
7352 // Insert instructions into newMBB based on incoming instruction
7353 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7354 "unexpected number of operands");
7355 DebugLoc dl = bInstr->getDebugLoc();
7356 MachineOperand& destOper = bInstr->getOperand(0);
7357 MachineOperand* argOpers[2 + X86AddrNumOperands];
7358 int numArgs = bInstr->getNumOperands() - 1;
7359 for (int i=0; i < numArgs; ++i)
7360 argOpers[i] = &bInstr->getOperand(i+1);
7362 // x86 address has 4 operands: base, index, scale, and displacement
7363 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7364 int valArgIndx = lastAddrIndx + 1;
7366 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7367 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7368 for (int i=0; i <= lastAddrIndx; ++i)
7369 (*MIB).addOperand(*argOpers[i]);
7371 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7373 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7378 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7379 assert((argOpers[valArgIndx]->isReg() ||
7380 argOpers[valArgIndx]->isImm()) &&
7382 if (argOpers[valArgIndx]->isReg())
7383 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7385 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7387 (*MIB).addOperand(*argOpers[valArgIndx]);
7389 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7392 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7393 for (int i=0; i <= lastAddrIndx; ++i)
7394 (*MIB).addOperand(*argOpers[i]);
7396 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7397 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7399 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7403 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7405 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7409 // private utility function: 64 bit atomics on 32 bit host.
7411 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7412 MachineBasicBlock *MBB,
7417 bool invSrc) const {
7418 // For the atomic bitwise operator, we generate
7419 // thisMBB (instructions are in pairs, except cmpxchg8b)
7420 // ld t1,t2 = [bitinstr.addr]
7422 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7423 // op t5, t6 <- out1, out2, [bitinstr.val]
7424 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7425 // mov ECX, EBX <- t5, t6
7426 // mov EAX, EDX <- t1, t2
7427 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7428 // mov t3, t4 <- EAX, EDX
7430 // result in out1, out2
7431 // fallthrough -->nextMBB
7433 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7434 const unsigned LoadOpc = X86::MOV32rm;
7435 const unsigned copyOpc = X86::MOV32rr;
7436 const unsigned NotOpc = X86::NOT32r;
7437 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7438 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7439 MachineFunction::iterator MBBIter = MBB;
7442 /// First build the CFG
7443 MachineFunction *F = MBB->getParent();
7444 MachineBasicBlock *thisMBB = MBB;
7445 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7446 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7447 F->insert(MBBIter, newMBB);
7448 F->insert(MBBIter, nextMBB);
7450 // Move all successors to thisMBB to nextMBB
7451 nextMBB->transferSuccessors(thisMBB);
7453 // Update thisMBB to fall through to newMBB
7454 thisMBB->addSuccessor(newMBB);
7456 // newMBB jumps to itself and fall through to nextMBB
7457 newMBB->addSuccessor(nextMBB);
7458 newMBB->addSuccessor(newMBB);
7460 DebugLoc dl = bInstr->getDebugLoc();
7461 // Insert instructions into newMBB based on incoming instruction
7462 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7463 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7464 "unexpected number of operands");
7465 MachineOperand& dest1Oper = bInstr->getOperand(0);
7466 MachineOperand& dest2Oper = bInstr->getOperand(1);
7467 MachineOperand* argOpers[2 + X86AddrNumOperands];
7468 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7469 argOpers[i] = &bInstr->getOperand(i+2);
7471 // x86 address has 4 operands: base, index, scale, and displacement
7472 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7474 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7475 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7476 for (int i=0; i <= lastAddrIndx; ++i)
7477 (*MIB).addOperand(*argOpers[i]);
7478 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7479 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7480 // add 4 to displacement.
7481 for (int i=0; i <= lastAddrIndx-2; ++i)
7482 (*MIB).addOperand(*argOpers[i]);
7483 MachineOperand newOp3 = *(argOpers[3]);
7485 newOp3.setImm(newOp3.getImm()+4);
7487 newOp3.setOffset(newOp3.getOffset()+4);
7488 (*MIB).addOperand(newOp3);
7489 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7491 // t3/4 are defined later, at the bottom of the loop
7492 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7493 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7494 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7495 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7496 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7497 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7499 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7500 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7502 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7503 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7509 int valArgIndx = lastAddrIndx + 1;
7510 assert((argOpers[valArgIndx]->isReg() ||
7511 argOpers[valArgIndx]->isImm()) &&
7513 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7514 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7515 if (argOpers[valArgIndx]->isReg())
7516 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7518 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7519 if (regOpcL != X86::MOV32rr)
7521 (*MIB).addOperand(*argOpers[valArgIndx]);
7522 assert(argOpers[valArgIndx + 1]->isReg() ==
7523 argOpers[valArgIndx]->isReg());
7524 assert(argOpers[valArgIndx + 1]->isImm() ==
7525 argOpers[valArgIndx]->isImm());
7526 if (argOpers[valArgIndx + 1]->isReg())
7527 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7529 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7530 if (regOpcH != X86::MOV32rr)
7532 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7534 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7536 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7539 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7541 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7544 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7545 for (int i=0; i <= lastAddrIndx; ++i)
7546 (*MIB).addOperand(*argOpers[i]);
7548 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7549 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7551 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7552 MIB.addReg(X86::EAX);
7553 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7554 MIB.addReg(X86::EDX);
7557 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7559 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7563 // private utility function
7565 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7566 MachineBasicBlock *MBB,
7567 unsigned cmovOpc) const {
7568 // For the atomic min/max operator, we generate
7571 // ld t1 = [min/max.addr]
7572 // mov t2 = [min/max.val]
7574 // cmov[cond] t2 = t1
7576 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7578 // fallthrough -->nextMBB
7580 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7581 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7582 MachineFunction::iterator MBBIter = MBB;
7585 /// First build the CFG
7586 MachineFunction *F = MBB->getParent();
7587 MachineBasicBlock *thisMBB = MBB;
7588 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7589 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7590 F->insert(MBBIter, newMBB);
7591 F->insert(MBBIter, nextMBB);
7593 // Move all successors to thisMBB to nextMBB
7594 nextMBB->transferSuccessors(thisMBB);
7596 // Update thisMBB to fall through to newMBB
7597 thisMBB->addSuccessor(newMBB);
7599 // newMBB jumps to newMBB and fall through to nextMBB
7600 newMBB->addSuccessor(nextMBB);
7601 newMBB->addSuccessor(newMBB);
7603 DebugLoc dl = mInstr->getDebugLoc();
7604 // Insert instructions into newMBB based on incoming instruction
7605 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7606 "unexpected number of operands");
7607 MachineOperand& destOper = mInstr->getOperand(0);
7608 MachineOperand* argOpers[2 + X86AddrNumOperands];
7609 int numArgs = mInstr->getNumOperands() - 1;
7610 for (int i=0; i < numArgs; ++i)
7611 argOpers[i] = &mInstr->getOperand(i+1);
7613 // x86 address has 4 operands: base, index, scale, and displacement
7614 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7615 int valArgIndx = lastAddrIndx + 1;
7617 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7618 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7619 for (int i=0; i <= lastAddrIndx; ++i)
7620 (*MIB).addOperand(*argOpers[i]);
7622 // We only support register and immediate values
7623 assert((argOpers[valArgIndx]->isReg() ||
7624 argOpers[valArgIndx]->isImm()) &&
7627 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7628 if (argOpers[valArgIndx]->isReg())
7629 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7631 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7632 (*MIB).addOperand(*argOpers[valArgIndx]);
7634 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7637 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7642 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7643 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7647 // Cmp and exchange if none has modified the memory location
7648 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7649 for (int i=0; i <= lastAddrIndx; ++i)
7650 (*MIB).addOperand(*argOpers[i]);
7652 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7653 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7655 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7656 MIB.addReg(X86::EAX);
7659 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7661 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7667 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7668 MachineBasicBlock *BB) const {
7669 DebugLoc dl = MI->getDebugLoc();
7670 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7671 switch (MI->getOpcode()) {
7672 default: assert(false && "Unexpected instr type to insert");
7673 case X86::CMOV_V1I64:
7674 case X86::CMOV_FR32:
7675 case X86::CMOV_FR64:
7676 case X86::CMOV_V4F32:
7677 case X86::CMOV_V2F64:
7678 case X86::CMOV_V2I64: {
7679 // To "insert" a SELECT_CC instruction, we actually have to insert the
7680 // diamond control-flow pattern. The incoming instruction knows the
7681 // destination vreg to set, the condition code register to branch on, the
7682 // true/false values to select between, and a branch opcode to use.
7683 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7684 MachineFunction::iterator It = BB;
7690 // cmpTY ccX, r1, r2
7692 // fallthrough --> copy0MBB
7693 MachineBasicBlock *thisMBB = BB;
7694 MachineFunction *F = BB->getParent();
7695 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7696 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7698 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7699 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7700 F->insert(It, copy0MBB);
7701 F->insert(It, sinkMBB);
7702 // Update machine-CFG edges by transferring all successors of the current
7703 // block to the new block which will contain the Phi node for the select.
7704 sinkMBB->transferSuccessors(BB);
7706 // Add the true and fallthrough blocks as its successors.
7707 BB->addSuccessor(copy0MBB);
7708 BB->addSuccessor(sinkMBB);
7711 // %FalseValue = ...
7712 // # fallthrough to sinkMBB
7715 // Update machine-CFG edges
7716 BB->addSuccessor(sinkMBB);
7719 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7722 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7723 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7724 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7726 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7730 case X86::FP32_TO_INT16_IN_MEM:
7731 case X86::FP32_TO_INT32_IN_MEM:
7732 case X86::FP32_TO_INT64_IN_MEM:
7733 case X86::FP64_TO_INT16_IN_MEM:
7734 case X86::FP64_TO_INT32_IN_MEM:
7735 case X86::FP64_TO_INT64_IN_MEM:
7736 case X86::FP80_TO_INT16_IN_MEM:
7737 case X86::FP80_TO_INT32_IN_MEM:
7738 case X86::FP80_TO_INT64_IN_MEM: {
7739 // Change the floating point control register to use "round towards zero"
7740 // mode when truncating to an integer value.
7741 MachineFunction *F = BB->getParent();
7742 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7743 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7745 // Load the old value of the high byte of the control word...
7747 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7748 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7751 // Set the high part to be round to zero...
7752 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7755 // Reload the modified control word now...
7756 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7758 // Restore the memory image of control word to original value
7759 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7762 // Get the X86 opcode to use.
7764 switch (MI->getOpcode()) {
7765 default: assert(0 && "illegal opcode!");
7766 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7767 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7768 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7769 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7770 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7771 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7772 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7773 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7774 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7778 MachineOperand &Op = MI->getOperand(0);
7780 AM.BaseType = X86AddressMode::RegBase;
7781 AM.Base.Reg = Op.getReg();
7783 AM.BaseType = X86AddressMode::FrameIndexBase;
7784 AM.Base.FrameIndex = Op.getIndex();
7786 Op = MI->getOperand(1);
7788 AM.Scale = Op.getImm();
7789 Op = MI->getOperand(2);
7791 AM.IndexReg = Op.getImm();
7792 Op = MI->getOperand(3);
7793 if (Op.isGlobal()) {
7794 AM.GV = Op.getGlobal();
7796 AM.Disp = Op.getImm();
7798 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7799 .addReg(MI->getOperand(4).getReg());
7801 // Reload the original control word now.
7802 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7804 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7807 case X86::ATOMAND32:
7808 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7809 X86::AND32ri, X86::MOV32rm,
7810 X86::LCMPXCHG32, X86::MOV32rr,
7811 X86::NOT32r, X86::EAX,
7812 X86::GR32RegisterClass);
7814 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7815 X86::OR32ri, X86::MOV32rm,
7816 X86::LCMPXCHG32, X86::MOV32rr,
7817 X86::NOT32r, X86::EAX,
7818 X86::GR32RegisterClass);
7819 case X86::ATOMXOR32:
7820 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7821 X86::XOR32ri, X86::MOV32rm,
7822 X86::LCMPXCHG32, X86::MOV32rr,
7823 X86::NOT32r, X86::EAX,
7824 X86::GR32RegisterClass);
7825 case X86::ATOMNAND32:
7826 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7827 X86::AND32ri, X86::MOV32rm,
7828 X86::LCMPXCHG32, X86::MOV32rr,
7829 X86::NOT32r, X86::EAX,
7830 X86::GR32RegisterClass, true);
7831 case X86::ATOMMIN32:
7832 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7833 case X86::ATOMMAX32:
7834 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7835 case X86::ATOMUMIN32:
7836 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7837 case X86::ATOMUMAX32:
7838 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7840 case X86::ATOMAND16:
7841 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7842 X86::AND16ri, X86::MOV16rm,
7843 X86::LCMPXCHG16, X86::MOV16rr,
7844 X86::NOT16r, X86::AX,
7845 X86::GR16RegisterClass);
7847 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7848 X86::OR16ri, X86::MOV16rm,
7849 X86::LCMPXCHG16, X86::MOV16rr,
7850 X86::NOT16r, X86::AX,
7851 X86::GR16RegisterClass);
7852 case X86::ATOMXOR16:
7853 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7854 X86::XOR16ri, X86::MOV16rm,
7855 X86::LCMPXCHG16, X86::MOV16rr,
7856 X86::NOT16r, X86::AX,
7857 X86::GR16RegisterClass);
7858 case X86::ATOMNAND16:
7859 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7860 X86::AND16ri, X86::MOV16rm,
7861 X86::LCMPXCHG16, X86::MOV16rr,
7862 X86::NOT16r, X86::AX,
7863 X86::GR16RegisterClass, true);
7864 case X86::ATOMMIN16:
7865 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7866 case X86::ATOMMAX16:
7867 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7868 case X86::ATOMUMIN16:
7869 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7870 case X86::ATOMUMAX16:
7871 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7874 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7875 X86::AND8ri, X86::MOV8rm,
7876 X86::LCMPXCHG8, X86::MOV8rr,
7877 X86::NOT8r, X86::AL,
7878 X86::GR8RegisterClass);
7880 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7881 X86::OR8ri, X86::MOV8rm,
7882 X86::LCMPXCHG8, X86::MOV8rr,
7883 X86::NOT8r, X86::AL,
7884 X86::GR8RegisterClass);
7886 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7887 X86::XOR8ri, X86::MOV8rm,
7888 X86::LCMPXCHG8, X86::MOV8rr,
7889 X86::NOT8r, X86::AL,
7890 X86::GR8RegisterClass);
7891 case X86::ATOMNAND8:
7892 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7893 X86::AND8ri, X86::MOV8rm,
7894 X86::LCMPXCHG8, X86::MOV8rr,
7895 X86::NOT8r, X86::AL,
7896 X86::GR8RegisterClass, true);
7897 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7898 // This group is for 64-bit host.
7899 case X86::ATOMAND64:
7900 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7901 X86::AND64ri32, X86::MOV64rm,
7902 X86::LCMPXCHG64, X86::MOV64rr,
7903 X86::NOT64r, X86::RAX,
7904 X86::GR64RegisterClass);
7906 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7907 X86::OR64ri32, X86::MOV64rm,
7908 X86::LCMPXCHG64, X86::MOV64rr,
7909 X86::NOT64r, X86::RAX,
7910 X86::GR64RegisterClass);
7911 case X86::ATOMXOR64:
7912 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7913 X86::XOR64ri32, X86::MOV64rm,
7914 X86::LCMPXCHG64, X86::MOV64rr,
7915 X86::NOT64r, X86::RAX,
7916 X86::GR64RegisterClass);
7917 case X86::ATOMNAND64:
7918 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7919 X86::AND64ri32, X86::MOV64rm,
7920 X86::LCMPXCHG64, X86::MOV64rr,
7921 X86::NOT64r, X86::RAX,
7922 X86::GR64RegisterClass, true);
7923 case X86::ATOMMIN64:
7924 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7925 case X86::ATOMMAX64:
7926 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7927 case X86::ATOMUMIN64:
7928 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7929 case X86::ATOMUMAX64:
7930 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7932 // This group does 64-bit operations on a 32-bit host.
7933 case X86::ATOMAND6432:
7934 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7935 X86::AND32rr, X86::AND32rr,
7936 X86::AND32ri, X86::AND32ri,
7938 case X86::ATOMOR6432:
7939 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7940 X86::OR32rr, X86::OR32rr,
7941 X86::OR32ri, X86::OR32ri,
7943 case X86::ATOMXOR6432:
7944 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7945 X86::XOR32rr, X86::XOR32rr,
7946 X86::XOR32ri, X86::XOR32ri,
7948 case X86::ATOMNAND6432:
7949 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7950 X86::AND32rr, X86::AND32rr,
7951 X86::AND32ri, X86::AND32ri,
7953 case X86::ATOMADD6432:
7954 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7955 X86::ADD32rr, X86::ADC32rr,
7956 X86::ADD32ri, X86::ADC32ri,
7958 case X86::ATOMSUB6432:
7959 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7960 X86::SUB32rr, X86::SBB32rr,
7961 X86::SUB32ri, X86::SBB32ri,
7963 case X86::ATOMSWAP6432:
7964 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7965 X86::MOV32rr, X86::MOV32rr,
7966 X86::MOV32ri, X86::MOV32ri,
7971 //===----------------------------------------------------------------------===//
7972 // X86 Optimization Hooks
7973 //===----------------------------------------------------------------------===//
7975 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7979 const SelectionDAG &DAG,
7980 unsigned Depth) const {
7981 unsigned Opc = Op.getOpcode();
7982 assert((Opc >= ISD::BUILTIN_OP_END ||
7983 Opc == ISD::INTRINSIC_WO_CHAIN ||
7984 Opc == ISD::INTRINSIC_W_CHAIN ||
7985 Opc == ISD::INTRINSIC_VOID) &&
7986 "Should use MaskedValueIsZero if you don't know whether Op"
7987 " is a target node!");
7989 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7998 // These nodes' second result is a boolean.
7999 if (Op.getResNo() == 0)
8003 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8004 Mask.getBitWidth() - 1);
8009 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8010 /// node is a GlobalAddress + offset.
8011 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8012 GlobalValue* &GA, int64_t &Offset) const{
8013 if (N->getOpcode() == X86ISD::Wrapper) {
8014 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8015 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8016 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8020 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8023 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8024 const TargetLowering &TLI) {
8027 if (TLI.isGAPlusOffset(Base, GV, Offset))
8028 return (GV->getAlignment() >= N && (Offset % N) == 0);
8029 // DAG combine handles the stack object case.
8033 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
8034 unsigned NumElems, MVT EVT,
8036 SelectionDAG &DAG, MachineFrameInfo *MFI,
8037 const TargetLowering &TLI) {
8039 for (unsigned i = 0; i < NumElems; ++i) {
8040 SDValue Idx = PermMask.getOperand(i);
8041 if (Idx.getOpcode() == ISD::UNDEF) {
8047 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8048 if (!Elt.getNode() ||
8049 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8052 Base = Elt.getNode();
8053 if (Base->getOpcode() == ISD::UNDEF)
8057 if (Elt.getOpcode() == ISD::UNDEF)
8060 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
8061 EVT.getSizeInBits()/8, i, MFI))
8067 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8068 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8069 /// if the load addresses are consecutive, non-overlapping, and in the right
8070 /// order. In the case of v2i64, it will see if it can rewrite the
8071 /// shuffle to be an appropriate build vector so it can take advantage of
8072 // performBuildVectorCombine.
8073 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8074 const TargetLowering &TLI) {
8075 DebugLoc dl = N->getDebugLoc();
8076 MVT VT = N->getValueType(0);
8077 MVT EVT = VT.getVectorElementType();
8078 SDValue PermMask = N->getOperand(2);
8079 unsigned NumElems = PermMask.getNumOperands();
8081 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
8082 // where the upper half is 0, it is advantageous to rewrite it as a build
8083 // vector of (0, val) so it can use movq.
8084 if (VT == MVT::v2i64) {
8086 In[0] = N->getOperand(0);
8087 In[1] = N->getOperand(1);
8088 unsigned Idx0 =cast<ConstantSDNode>(PermMask.getOperand(0))->getZExtValue();
8089 unsigned Idx1 =cast<ConstantSDNode>(PermMask.getOperand(1))->getZExtValue();
8090 if (In[0].getValueType().getVectorNumElements() == NumElems &&
8091 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
8092 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
8093 ConstantSDNode* InsertVecIdx =
8094 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
8096 InsertVecIdx->getZExtValue() == (Idx0 % 2) &&
8097 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
8098 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
8099 In[Idx0/2].getOperand(1),
8100 In[Idx1/2].getOperand(Idx1 % 2));
8105 // Try to combine a vector_shuffle into a 128-bit load.
8106 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8107 SDNode *Base = NULL;
8108 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
8112 LoadSDNode *LD = cast<LoadSDNode>(Base);
8113 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
8114 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8115 LD->getSrcValue(), LD->getSrcValueOffset(),
8117 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8118 LD->getSrcValue(), LD->getSrcValueOffset(),
8119 LD->isVolatile(), LD->getAlignment());
8122 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
8123 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
8124 TargetLowering::DAGCombinerInfo &DCI,
8125 const X86Subtarget *Subtarget,
8126 const TargetLowering &TLI) {
8127 unsigned NumOps = N->getNumOperands();
8128 DebugLoc dl = N->getDebugLoc();
8130 // Ignore single operand BUILD_VECTOR.
8134 MVT VT = N->getValueType(0);
8135 MVT EVT = VT.getVectorElementType();
8136 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
8137 // We are looking for load i64 and zero extend. We want to transform
8138 // it before legalizer has a chance to expand it. Also look for i64
8139 // BUILD_PAIR bit casted to f64.
8141 // This must be an insertion into a zero vector.
8142 SDValue HighElt = N->getOperand(1);
8143 if (!isZeroNode(HighElt))
8146 // Value must be a load.
8147 SDNode *Base = N->getOperand(0).getNode();
8148 if (!isa<LoadSDNode>(Base)) {
8149 if (Base->getOpcode() != ISD::BIT_CONVERT)
8151 Base = Base->getOperand(0).getNode();
8152 if (!isa<LoadSDNode>(Base))
8156 // Transform it into VZEXT_LOAD addr.
8157 LoadSDNode *LD = cast<LoadSDNode>(Base);
8159 // Load must not be an extload.
8160 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
8163 // Load type should legal type so we don't have to legalize it.
8164 if (!TLI.isTypeLegal(VT))
8167 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8168 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8169 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8170 TargetLowering::TargetLoweringOpt TLO(DAG);
8171 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
8172 DCI.CommitTargetLoweringOpt(TLO);
8176 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8177 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8178 const X86Subtarget *Subtarget) {
8179 DebugLoc DL = N->getDebugLoc();
8180 SDValue Cond = N->getOperand(0);
8181 // Get the LHS/RHS of the select.
8182 SDValue LHS = N->getOperand(1);
8183 SDValue RHS = N->getOperand(2);
8185 // If we have SSE[12] support, try to form min/max nodes.
8186 if (Subtarget->hasSSE2() &&
8187 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8188 Cond.getOpcode() == ISD::SETCC) {
8189 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8191 unsigned Opcode = 0;
8192 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8195 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8198 if (!UnsafeFPMath) break;
8200 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
8202 Opcode = X86ISD::FMIN;
8205 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8208 if (!UnsafeFPMath) break;
8210 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8212 Opcode = X86ISD::FMAX;
8215 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8218 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8221 if (!UnsafeFPMath) break;
8223 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8225 Opcode = X86ISD::FMIN;
8228 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8231 if (!UnsafeFPMath) break;
8233 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8235 Opcode = X86ISD::FMAX;
8241 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8244 // If this is a select between two integer constants, try to do some
8246 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8247 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8248 // Don't do this for crazy integer types.
8249 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8250 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8251 // so that TrueC (the true value) is larger than FalseC.
8252 bool NeedsCondInvert = false;
8254 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8255 // Efficiently invertible.
8256 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8257 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8258 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8259 NeedsCondInvert = true;
8260 std::swap(TrueC, FalseC);
8263 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8264 if (FalseC->getAPIntValue() == 0 &&
8265 TrueC->getAPIntValue().isPowerOf2()) {
8266 if (NeedsCondInvert) // Invert the condition if needed.
8267 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8268 DAG.getConstant(1, Cond.getValueType()));
8270 // Zero extend the condition if needed.
8271 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8273 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8274 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8275 DAG.getConstant(ShAmt, MVT::i8));
8278 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8279 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8280 if (NeedsCondInvert) // Invert the condition if needed.
8281 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8282 DAG.getConstant(1, Cond.getValueType()));
8284 // Zero extend the condition if needed.
8285 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8286 FalseC->getValueType(0), Cond);
8287 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8288 SDValue(FalseC, 0));
8291 // Optimize cases that will turn into an LEA instruction. This requires
8292 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8293 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8294 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8295 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8297 bool isFastMultiplier = false;
8299 switch ((unsigned char)Diff) {
8301 case 1: // result = add base, cond
8302 case 2: // result = lea base( , cond*2)
8303 case 3: // result = lea base(cond, cond*2)
8304 case 4: // result = lea base( , cond*4)
8305 case 5: // result = lea base(cond, cond*4)
8306 case 8: // result = lea base( , cond*8)
8307 case 9: // result = lea base(cond, cond*8)
8308 isFastMultiplier = true;
8313 if (isFastMultiplier) {
8314 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8315 if (NeedsCondInvert) // Invert the condition if needed.
8316 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8317 DAG.getConstant(1, Cond.getValueType()));
8319 // Zero extend the condition if needed.
8320 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8322 // Scale the condition by the difference.
8324 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8325 DAG.getConstant(Diff, Cond.getValueType()));
8327 // Add the base if non-zero.
8328 if (FalseC->getAPIntValue() != 0)
8329 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8330 SDValue(FalseC, 0));
8340 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8341 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8342 TargetLowering::DAGCombinerInfo &DCI) {
8343 DebugLoc DL = N->getDebugLoc();
8345 // If the flag operand isn't dead, don't touch this CMOV.
8346 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8349 // If this is a select between two integer constants, try to do some
8350 // optimizations. Note that the operands are ordered the opposite of SELECT
8352 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8353 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8354 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8355 // larger than FalseC (the false value).
8356 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8358 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8359 CC = X86::GetOppositeBranchCondition(CC);
8360 std::swap(TrueC, FalseC);
8363 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8364 // This is efficient for any integer data type (including i8/i16) and
8366 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8367 SDValue Cond = N->getOperand(3);
8368 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8369 DAG.getConstant(CC, MVT::i8), Cond);
8371 // Zero extend the condition if needed.
8372 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8374 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8375 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8376 DAG.getConstant(ShAmt, MVT::i8));
8377 if (N->getNumValues() == 2) // Dead flag value?
8378 return DCI.CombineTo(N, Cond, SDValue());
8382 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8383 // for any integer data type, including i8/i16.
8384 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8385 SDValue Cond = N->getOperand(3);
8386 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8387 DAG.getConstant(CC, MVT::i8), Cond);
8389 // Zero extend the condition if needed.
8390 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8391 FalseC->getValueType(0), Cond);
8392 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8393 SDValue(FalseC, 0));
8395 if (N->getNumValues() == 2) // Dead flag value?
8396 return DCI.CombineTo(N, Cond, SDValue());
8400 // Optimize cases that will turn into an LEA instruction. This requires
8401 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8402 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8403 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8404 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8406 bool isFastMultiplier = false;
8408 switch ((unsigned char)Diff) {
8410 case 1: // result = add base, cond
8411 case 2: // result = lea base( , cond*2)
8412 case 3: // result = lea base(cond, cond*2)
8413 case 4: // result = lea base( , cond*4)
8414 case 5: // result = lea base(cond, cond*4)
8415 case 8: // result = lea base( , cond*8)
8416 case 9: // result = lea base(cond, cond*8)
8417 isFastMultiplier = true;
8422 if (isFastMultiplier) {
8423 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8424 SDValue Cond = N->getOperand(3);
8425 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8426 DAG.getConstant(CC, MVT::i8), Cond);
8427 // Zero extend the condition if needed.
8428 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8430 // Scale the condition by the difference.
8432 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8433 DAG.getConstant(Diff, Cond.getValueType()));
8435 // Add the base if non-zero.
8436 if (FalseC->getAPIntValue() != 0)
8437 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8438 SDValue(FalseC, 0));
8439 if (N->getNumValues() == 2) // Dead flag value?
8440 return DCI.CombineTo(N, Cond, SDValue());
8450 /// PerformMulCombine - Optimize a single multiply with constant into two
8451 /// in order to implement it with two cheaper instructions, e.g.
8452 /// LEA + SHL, LEA + LEA.
8453 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8454 TargetLowering::DAGCombinerInfo &DCI) {
8455 if (DAG.getMachineFunction().
8456 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8459 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8462 MVT VT = N->getValueType(0);
8466 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8469 uint64_t MulAmt = C->getZExtValue();
8470 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8473 uint64_t MulAmt1 = 0;
8474 uint64_t MulAmt2 = 0;
8475 if ((MulAmt % 9) == 0) {
8477 MulAmt2 = MulAmt / 9;
8478 } else if ((MulAmt % 5) == 0) {
8480 MulAmt2 = MulAmt / 5;
8481 } else if ((MulAmt % 3) == 0) {
8483 MulAmt2 = MulAmt / 3;
8486 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8487 DebugLoc DL = N->getDebugLoc();
8489 if (isPowerOf2_64(MulAmt2) &&
8490 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8491 // If second multiplifer is pow2, issue it first. We want the multiply by
8492 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8494 std::swap(MulAmt1, MulAmt2);
8497 if (isPowerOf2_64(MulAmt1))
8498 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8499 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8501 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8502 DAG.getConstant(MulAmt1, VT));
8504 if (isPowerOf2_64(MulAmt2))
8505 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8506 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8508 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8509 DAG.getConstant(MulAmt2, VT));
8511 // Do not add new nodes to DAG combiner worklist.
8512 DCI.CombineTo(N, NewMul, false);
8518 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8520 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8521 const X86Subtarget *Subtarget) {
8522 // On X86 with SSE2 support, we can transform this to a vector shift if
8523 // all elements are shifted by the same amount. We can't do this in legalize
8524 // because the a constant vector is typically transformed to a constant pool
8525 // so we have no knowledge of the shift amount.
8526 if (!Subtarget->hasSSE2())
8529 MVT VT = N->getValueType(0);
8530 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8533 SDValue ShAmtOp = N->getOperand(1);
8534 MVT EltVT = VT.getVectorElementType();
8535 DebugLoc DL = N->getDebugLoc();
8537 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8538 unsigned NumElts = VT.getVectorNumElements();
8540 for (; i != NumElts; ++i) {
8541 SDValue Arg = ShAmtOp.getOperand(i);
8542 if (Arg.getOpcode() == ISD::UNDEF) continue;
8546 for (; i != NumElts; ++i) {
8547 SDValue Arg = ShAmtOp.getOperand(i);
8548 if (Arg.getOpcode() == ISD::UNDEF) continue;
8549 if (Arg != BaseShAmt) {
8553 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8554 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
8555 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8556 DAG.getIntPtrConstant(0));
8560 if (EltVT.bitsGT(MVT::i32))
8561 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8562 else if (EltVT.bitsLT(MVT::i32))
8563 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8565 // The shift amount is identical so we can do a vector shift.
8566 SDValue ValOp = N->getOperand(0);
8567 switch (N->getOpcode()) {
8569 assert(0 && "Unknown shift opcode!");
8572 if (VT == MVT::v2i64)
8573 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8574 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8576 if (VT == MVT::v4i32)
8577 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8578 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8580 if (VT == MVT::v8i16)
8581 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8582 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8586 if (VT == MVT::v4i32)
8587 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8588 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8590 if (VT == MVT::v8i16)
8591 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8592 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8596 if (VT == MVT::v2i64)
8597 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8598 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8600 if (VT == MVT::v4i32)
8601 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8602 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8604 if (VT == MVT::v8i16)
8605 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8606 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8613 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8614 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8615 const X86Subtarget *Subtarget) {
8616 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8617 // the FP state in cases where an emms may be missing.
8618 // A preferable solution to the general problem is to figure out the right
8619 // places to insert EMMS. This qualifies as a quick hack.
8621 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8622 StoreSDNode *St = cast<StoreSDNode>(N);
8623 MVT VT = St->getValue().getValueType();
8624 if (VT.getSizeInBits() != 64)
8627 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8628 if ((VT.isVector() ||
8629 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8630 isa<LoadSDNode>(St->getValue()) &&
8631 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8632 St->getChain().hasOneUse() && !St->isVolatile()) {
8633 SDNode* LdVal = St->getValue().getNode();
8635 int TokenFactorIndex = -1;
8636 SmallVector<SDValue, 8> Ops;
8637 SDNode* ChainVal = St->getChain().getNode();
8638 // Must be a store of a load. We currently handle two cases: the load
8639 // is a direct child, and it's under an intervening TokenFactor. It is
8640 // possible to dig deeper under nested TokenFactors.
8641 if (ChainVal == LdVal)
8642 Ld = cast<LoadSDNode>(St->getChain());
8643 else if (St->getValue().hasOneUse() &&
8644 ChainVal->getOpcode() == ISD::TokenFactor) {
8645 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8646 if (ChainVal->getOperand(i).getNode() == LdVal) {
8647 TokenFactorIndex = i;
8648 Ld = cast<LoadSDNode>(St->getValue());
8650 Ops.push_back(ChainVal->getOperand(i));
8654 if (!Ld || !ISD::isNormalLoad(Ld))
8657 // If this is not the MMX case, i.e. we are just turning i64 load/store
8658 // into f64 load/store, avoid the transformation if there are multiple
8659 // uses of the loaded value.
8660 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8663 DebugLoc LdDL = Ld->getDebugLoc();
8664 DebugLoc StDL = N->getDebugLoc();
8665 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8666 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8668 if (Subtarget->is64Bit() || F64IsLegal) {
8669 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8670 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8671 Ld->getBasePtr(), Ld->getSrcValue(),
8672 Ld->getSrcValueOffset(), Ld->isVolatile(),
8673 Ld->getAlignment());
8674 SDValue NewChain = NewLd.getValue(1);
8675 if (TokenFactorIndex != -1) {
8676 Ops.push_back(NewChain);
8677 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8680 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8681 St->getSrcValue(), St->getSrcValueOffset(),
8682 St->isVolatile(), St->getAlignment());
8685 // Otherwise, lower to two pairs of 32-bit loads / stores.
8686 SDValue LoAddr = Ld->getBasePtr();
8687 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8688 DAG.getConstant(4, MVT::i32));
8690 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8691 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8692 Ld->isVolatile(), Ld->getAlignment());
8693 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8694 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8696 MinAlign(Ld->getAlignment(), 4));
8698 SDValue NewChain = LoLd.getValue(1);
8699 if (TokenFactorIndex != -1) {
8700 Ops.push_back(LoLd);
8701 Ops.push_back(HiLd);
8702 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8706 LoAddr = St->getBasePtr();
8707 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8708 DAG.getConstant(4, MVT::i32));
8710 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8711 St->getSrcValue(), St->getSrcValueOffset(),
8712 St->isVolatile(), St->getAlignment());
8713 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8715 St->getSrcValueOffset() + 4,
8717 MinAlign(St->getAlignment(), 4));
8718 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8723 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8724 /// X86ISD::FXOR nodes.
8725 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8726 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8727 // F[X]OR(0.0, x) -> x
8728 // F[X]OR(x, 0.0) -> x
8729 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8730 if (C->getValueAPF().isPosZero())
8731 return N->getOperand(1);
8732 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8733 if (C->getValueAPF().isPosZero())
8734 return N->getOperand(0);
8738 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8739 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8740 // FAND(0.0, x) -> 0.0
8741 // FAND(x, 0.0) -> 0.0
8742 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8743 if (C->getValueAPF().isPosZero())
8744 return N->getOperand(0);
8745 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8746 if (C->getValueAPF().isPosZero())
8747 return N->getOperand(1);
8751 static SDValue PerformBTCombine(SDNode *N,
8753 TargetLowering::DAGCombinerInfo &DCI) {
8754 // BT ignores high bits in the bit index operand.
8755 SDValue Op1 = N->getOperand(1);
8756 if (Op1.hasOneUse()) {
8757 unsigned BitWidth = Op1.getValueSizeInBits();
8758 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8759 APInt KnownZero, KnownOne;
8760 TargetLowering::TargetLoweringOpt TLO(DAG);
8761 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8762 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8763 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8764 DCI.CommitTargetLoweringOpt(TLO);
8769 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8770 DAGCombinerInfo &DCI) const {
8771 SelectionDAG &DAG = DCI.DAG;
8772 switch (N->getOpcode()) {
8774 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8775 case ISD::BUILD_VECTOR:
8776 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8777 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8778 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8779 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8782 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8783 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8785 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8786 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8787 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8793 //===----------------------------------------------------------------------===//
8794 // X86 Inline Assembly Support
8795 //===----------------------------------------------------------------------===//
8797 /// getConstraintType - Given a constraint letter, return the type of
8798 /// constraint it is for this target.
8799 X86TargetLowering::ConstraintType
8800 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8801 if (Constraint.size() == 1) {
8802 switch (Constraint[0]) {
8814 return C_RegisterClass;
8822 return TargetLowering::getConstraintType(Constraint);
8825 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8826 /// with another that has more specific requirements based on the type of the
8827 /// corresponding operand.
8828 const char *X86TargetLowering::
8829 LowerXConstraint(MVT ConstraintVT) const {
8830 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8831 // 'f' like normal targets.
8832 if (ConstraintVT.isFloatingPoint()) {
8833 if (Subtarget->hasSSE2())
8835 if (Subtarget->hasSSE1())
8839 return TargetLowering::LowerXConstraint(ConstraintVT);
8842 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8843 /// vector. If it is invalid, don't add anything to Ops.
8844 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8847 std::vector<SDValue>&Ops,
8848 SelectionDAG &DAG) const {
8849 SDValue Result(0, 0);
8851 switch (Constraint) {
8854 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8855 if (C->getZExtValue() <= 31) {
8856 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8863 if (C->getZExtValue() <= 63) {
8864 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8871 if (C->getZExtValue() <= 255) {
8872 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8878 // 32-bit signed value
8879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8880 const ConstantInt *CI = C->getConstantIntValue();
8881 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8882 // Widen to 64 bits here to get it sign extended.
8883 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8886 // FIXME gcc accepts some relocatable values here too, but only in certain
8887 // memory models; it's complicated.
8892 // 32-bit unsigned value
8893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8894 const ConstantInt *CI = C->getConstantIntValue();
8895 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8896 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8900 // FIXME gcc accepts some relocatable values here too, but only in certain
8901 // memory models; it's complicated.
8905 // Literal immediates are always ok.
8906 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8907 // Widen to 64 bits here to get it sign extended.
8908 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8912 // If we are in non-pic codegen mode, we allow the address of a global (with
8913 // an optional displacement) to be used with 'i'.
8914 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8917 // Match either (GA) or (GA+C)
8919 Offset = GA->getOffset();
8920 } else if (Op.getOpcode() == ISD::ADD) {
8921 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8922 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8924 Offset = GA->getOffset()+C->getZExtValue();
8926 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8927 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8929 Offset = GA->getOffset()+C->getZExtValue();
8937 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(),
8940 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8946 // Otherwise, not valid for this mode.
8951 if (Result.getNode()) {
8952 Ops.push_back(Result);
8955 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8959 std::vector<unsigned> X86TargetLowering::
8960 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8962 if (Constraint.size() == 1) {
8963 // FIXME: not handling fp-stack yet!
8964 switch (Constraint[0]) { // GCC X86 Constraint Letters
8965 default: break; // Unknown constraint letter
8966 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8969 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8970 else if (VT == MVT::i16)
8971 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8972 else if (VT == MVT::i8)
8973 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8974 else if (VT == MVT::i64)
8975 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8980 return std::vector<unsigned>();
8983 std::pair<unsigned, const TargetRegisterClass*>
8984 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8986 // First, see if this is a constraint that directly corresponds to an LLVM
8988 if (Constraint.size() == 1) {
8989 // GCC Constraint Letters
8990 switch (Constraint[0]) {
8992 case 'r': // GENERAL_REGS
8993 case 'R': // LEGACY_REGS
8994 case 'l': // INDEX_REGS
8996 return std::make_pair(0U, X86::GR8RegisterClass);
8998 return std::make_pair(0U, X86::GR16RegisterClass);
8999 if (VT == MVT::i32 || !Subtarget->is64Bit())
9000 return std::make_pair(0U, X86::GR32RegisterClass);
9001 return std::make_pair(0U, X86::GR64RegisterClass);
9002 case 'f': // FP Stack registers.
9003 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9004 // value to the correct fpstack register class.
9005 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9006 return std::make_pair(0U, X86::RFP32RegisterClass);
9007 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9008 return std::make_pair(0U, X86::RFP64RegisterClass);
9009 return std::make_pair(0U, X86::RFP80RegisterClass);
9010 case 'y': // MMX_REGS if MMX allowed.
9011 if (!Subtarget->hasMMX()) break;
9012 return std::make_pair(0U, X86::VR64RegisterClass);
9013 case 'Y': // SSE_REGS if SSE2 allowed
9014 if (!Subtarget->hasSSE2()) break;
9016 case 'x': // SSE_REGS if SSE1 allowed
9017 if (!Subtarget->hasSSE1()) break;
9019 switch (VT.getSimpleVT()) {
9021 // Scalar SSE types.
9024 return std::make_pair(0U, X86::FR32RegisterClass);
9027 return std::make_pair(0U, X86::FR64RegisterClass);
9035 return std::make_pair(0U, X86::VR128RegisterClass);
9041 // Use the default implementation in TargetLowering to convert the register
9042 // constraint into a member of a register class.
9043 std::pair<unsigned, const TargetRegisterClass*> Res;
9044 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9046 // Not found as a standard register?
9047 if (Res.second == 0) {
9048 // GCC calls "st(0)" just plain "st".
9049 if (StringsEqualNoCase("{st}", Constraint)) {
9050 Res.first = X86::ST0;
9051 Res.second = X86::RFP80RegisterClass;
9053 // 'A' means EAX + EDX.
9054 if (Constraint == "A") {
9055 Res.first = X86::EAX;
9056 Res.second = X86::GRADRegisterClass;
9061 // Otherwise, check to see if this is a register class of the wrong value
9062 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9063 // turn into {ax},{dx}.
9064 if (Res.second->hasType(VT))
9065 return Res; // Correct type already, nothing to do.
9067 // All of the single-register GCC register classes map their values onto
9068 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9069 // really want an 8-bit or 32-bit register, map to the appropriate register
9070 // class and return the appropriate register.
9071 if (Res.second == X86::GR16RegisterClass) {
9072 if (VT == MVT::i8) {
9073 unsigned DestReg = 0;
9074 switch (Res.first) {
9076 case X86::AX: DestReg = X86::AL; break;
9077 case X86::DX: DestReg = X86::DL; break;
9078 case X86::CX: DestReg = X86::CL; break;
9079 case X86::BX: DestReg = X86::BL; break;
9082 Res.first = DestReg;
9083 Res.second = Res.second = X86::GR8RegisterClass;
9085 } else if (VT == MVT::i32) {
9086 unsigned DestReg = 0;
9087 switch (Res.first) {
9089 case X86::AX: DestReg = X86::EAX; break;
9090 case X86::DX: DestReg = X86::EDX; break;
9091 case X86::CX: DestReg = X86::ECX; break;
9092 case X86::BX: DestReg = X86::EBX; break;
9093 case X86::SI: DestReg = X86::ESI; break;
9094 case X86::DI: DestReg = X86::EDI; break;
9095 case X86::BP: DestReg = X86::EBP; break;
9096 case X86::SP: DestReg = X86::ESP; break;
9099 Res.first = DestReg;
9100 Res.second = Res.second = X86::GR32RegisterClass;
9102 } else if (VT == MVT::i64) {
9103 unsigned DestReg = 0;
9104 switch (Res.first) {
9106 case X86::AX: DestReg = X86::RAX; break;
9107 case X86::DX: DestReg = X86::RDX; break;
9108 case X86::CX: DestReg = X86::RCX; break;
9109 case X86::BX: DestReg = X86::RBX; break;
9110 case X86::SI: DestReg = X86::RSI; break;
9111 case X86::DI: DestReg = X86::RDI; break;
9112 case X86::BP: DestReg = X86::RBP; break;
9113 case X86::SP: DestReg = X86::RSP; break;
9116 Res.first = DestReg;
9117 Res.second = Res.second = X86::GR64RegisterClass;
9120 } else if (Res.second == X86::FR32RegisterClass ||
9121 Res.second == X86::FR64RegisterClass ||
9122 Res.second == X86::VR128RegisterClass) {
9123 // Handle references to XMM physical registers that got mapped into the
9124 // wrong class. This can happen with constraints like {xmm0} where the
9125 // target independent register mapper will just pick the first match it can
9126 // find, ignoring the required type.
9128 Res.second = X86::FR32RegisterClass;
9129 else if (VT == MVT::f64)
9130 Res.second = X86::FR64RegisterClass;
9131 else if (X86::VR128RegisterClass->hasType(VT))
9132 Res.second = X86::VR128RegisterClass;
9138 //===----------------------------------------------------------------------===//
9139 // X86 Widen vector type
9140 //===----------------------------------------------------------------------===//
9142 /// getWidenVectorType: given a vector type, returns the type to widen
9143 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9144 /// If there is no vector type that we want to widen to, returns MVT::Other
9145 /// When and where to widen is target dependent based on the cost of
9146 /// scalarizing vs using the wider vector type.
9148 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9149 assert(VT.isVector());
9150 if (isTypeLegal(VT))
9153 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9154 // type based on element type. This would speed up our search (though
9155 // it may not be worth it since the size of the list is relatively
9157 MVT EltVT = VT.getVectorElementType();
9158 unsigned NElts = VT.getVectorNumElements();
9160 // On X86, it make sense to widen any vector wider than 1
9164 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9165 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9166 MVT SVT = (MVT::SimpleValueType)nVT;
9168 if (isTypeLegal(SVT) &&
9169 SVT.getVectorElementType() == EltVT &&
9170 SVT.getVectorNumElements() > NElts)