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 ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER,
4838 DebugLoc::getUnknownLoc(), PtrVT);
4839 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4841 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4842 GA->getValueType(0),
4844 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4846 if (model == TLSModel::InitialExec)
4847 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4848 PseudoSourceValue::getGOT(), 0);
4850 // The address of the thread local variable is the add of the thread
4851 // pointer with the offset of the variable.
4852 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4856 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4857 // TODO: implement the "local dynamic" model
4858 // TODO: implement the "initial exec"model for pic executables
4859 assert(Subtarget->isTargetELF() &&
4860 "TLS not implemented for non-ELF targets");
4861 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4862 GlobalValue *GV = GA->getGlobal();
4863 TLSModel::Model model =
4864 getTLSModel (GV, getTargetMachine().getRelocationModel());
4865 if (Subtarget->is64Bit()) {
4867 case TLSModel::GeneralDynamic:
4868 case TLSModel::LocalDynamic: // not implemented
4869 case TLSModel::InitialExec: // not implemented
4870 case TLSModel::LocalExec: // not implemented
4871 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4875 case TLSModel::GeneralDynamic:
4876 case TLSModel::LocalDynamic: // not implemented
4877 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4879 case TLSModel::InitialExec:
4880 case TLSModel::LocalExec:
4881 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model);
4884 assert(0 && "Unreachable");
4889 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4890 // FIXME there isn't really any debug info here
4891 DebugLoc dl = Op.getDebugLoc();
4892 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4893 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4894 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4895 // With PIC, the address is actually $g + Offset.
4896 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4897 !Subtarget->isPICStyleRIPRel()) {
4898 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4899 DAG.getNode(X86ISD::GlobalBaseReg,
4900 DebugLoc::getUnknownLoc(),
4908 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4909 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4910 // FIXME there isn't really any debug into here
4911 DebugLoc dl = JT->getDebugLoc();
4912 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4913 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4914 // With PIC, the address is actually $g + Offset.
4915 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4916 !Subtarget->isPICStyleRIPRel()) {
4917 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4918 DAG.getNode(X86ISD::GlobalBaseReg,
4919 DebugLoc::getUnknownLoc(),
4927 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4928 /// take a 2 x i32 value to shift plus a shift amount.
4929 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4930 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4931 MVT VT = Op.getValueType();
4932 unsigned VTBits = VT.getSizeInBits();
4933 DebugLoc dl = Op.getDebugLoc();
4934 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4935 SDValue ShOpLo = Op.getOperand(0);
4936 SDValue ShOpHi = Op.getOperand(1);
4937 SDValue ShAmt = Op.getOperand(2);
4938 SDValue Tmp1 = isSRA ?
4939 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4940 DAG.getConstant(VTBits - 1, MVT::i8)) :
4941 DAG.getConstant(0, VT);
4944 if (Op.getOpcode() == ISD::SHL_PARTS) {
4945 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4946 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4948 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4949 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4952 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4953 DAG.getConstant(VTBits, MVT::i8));
4954 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4955 AndNode, DAG.getConstant(0, MVT::i8));
4958 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4959 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4960 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4962 if (Op.getOpcode() == ISD::SHL_PARTS) {
4963 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4964 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4966 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4967 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4970 SDValue Ops[2] = { Lo, Hi };
4971 return DAG.getMergeValues(Ops, 2, dl);
4974 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4975 MVT SrcVT = Op.getOperand(0).getValueType();
4976 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4977 "Unknown SINT_TO_FP to lower!");
4979 // These are really Legal; caller falls through into that case.
4980 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4982 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4983 Subtarget->is64Bit())
4986 DebugLoc dl = Op.getDebugLoc();
4987 unsigned Size = SrcVT.getSizeInBits()/8;
4988 MachineFunction &MF = DAG.getMachineFunction();
4989 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4990 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4991 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4993 PseudoSourceValue::getFixedStack(SSFI), 0);
4997 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4999 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5001 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5002 SmallVector<SDValue, 8> Ops;
5003 Ops.push_back(Chain);
5004 Ops.push_back(StackSlot);
5005 Ops.push_back(DAG.getValueType(SrcVT));
5006 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5007 Tys, &Ops[0], Ops.size());
5010 Chain = Result.getValue(1);
5011 SDValue InFlag = Result.getValue(2);
5013 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5014 // shouldn't be necessary except that RFP cannot be live across
5015 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5016 MachineFunction &MF = DAG.getMachineFunction();
5017 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
5018 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5019 Tys = DAG.getVTList(MVT::Other);
5020 SmallVector<SDValue, 8> Ops;
5021 Ops.push_back(Chain);
5022 Ops.push_back(Result);
5023 Ops.push_back(StackSlot);
5024 Ops.push_back(DAG.getValueType(Op.getValueType()));
5025 Ops.push_back(InFlag);
5026 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5027 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5028 PseudoSourceValue::getFixedStack(SSFI), 0);
5034 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5035 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5036 // This algorithm is not obvious. Here it is in C code, more or less:
5038 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5039 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5040 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5042 // Copy ints to xmm registers.
5043 __m128i xh = _mm_cvtsi32_si128( hi );
5044 __m128i xl = _mm_cvtsi32_si128( lo );
5046 // Combine into low half of a single xmm register.
5047 __m128i x = _mm_unpacklo_epi32( xh, xl );
5051 // Merge in appropriate exponents to give the integer bits the right
5053 x = _mm_unpacklo_epi32( x, exp );
5055 // Subtract away the biases to deal with the IEEE-754 double precision
5057 d = _mm_sub_pd( (__m128d) x, bias );
5059 // All conversions up to here are exact. The correctly rounded result is
5060 // calculated using the current rounding mode using the following
5062 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5063 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5064 // store doesn't really need to be here (except
5065 // maybe to zero the other double)
5070 DebugLoc dl = Op.getDebugLoc();
5072 // Build some magic constants.
5073 std::vector<Constant*> CV0;
5074 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
5075 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
5076 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5077 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5078 Constant *C0 = ConstantVector::get(CV0);
5079 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5081 std::vector<Constant*> CV1;
5082 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
5083 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
5084 Constant *C1 = ConstantVector::get(CV1);
5085 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5087 SmallVector<SDValue, 4> MaskVec;
5088 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
5089 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
5090 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
5091 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
5092 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
5093 &MaskVec[0], MaskVec.size());
5094 SmallVector<SDValue, 4> MaskVec2;
5095 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
5096 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
5097 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
5098 &MaskVec2[0], MaskVec2.size());
5100 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5101 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5103 DAG.getIntPtrConstant(1)));
5104 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5105 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5107 DAG.getIntPtrConstant(0)));
5108 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5109 XR1, XR2, UnpcklMask);
5110 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5111 PseudoSourceValue::getConstantPool(), 0,
5113 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5114 Unpck1, CLod0, UnpcklMask);
5115 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5116 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5117 PseudoSourceValue::getConstantPool(), 0,
5119 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5121 // Add the halves; easiest way is to swap them into another reg first.
5122 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
5123 Sub, Sub, ShufMask);
5124 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5125 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5126 DAG.getIntPtrConstant(0));
5129 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5130 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5131 DebugLoc dl = Op.getDebugLoc();
5132 // FP constant to bias correct the final result.
5133 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5136 // Load the 32-bit value into an XMM register.
5137 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5138 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5140 DAG.getIntPtrConstant(0)));
5142 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5143 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5144 DAG.getIntPtrConstant(0));
5146 // Or the load with the bias.
5147 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5148 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5149 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5151 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5152 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5153 MVT::v2f64, Bias)));
5154 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5155 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5156 DAG.getIntPtrConstant(0));
5158 // Subtract the bias.
5159 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5161 // Handle final rounding.
5162 MVT DestVT = Op.getValueType();
5164 if (DestVT.bitsLT(MVT::f64)) {
5165 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5166 DAG.getIntPtrConstant(0));
5167 } else if (DestVT.bitsGT(MVT::f64)) {
5168 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5171 // Handle final rounding.
5175 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5176 SDValue N0 = Op.getOperand(0);
5177 DebugLoc dl = Op.getDebugLoc();
5179 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5180 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5181 // the optimization here.
5182 if (DAG.SignBitIsZero(N0))
5183 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5185 MVT SrcVT = N0.getValueType();
5186 if (SrcVT == MVT::i64) {
5187 // We only handle SSE2 f64 target here; caller can handle the rest.
5188 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5191 return LowerUINT_TO_FP_i64(Op, DAG);
5192 } else if (SrcVT == MVT::i32) {
5193 return LowerUINT_TO_FP_i32(Op, DAG);
5196 assert(0 && "Unknown UINT_TO_FP to lower!");
5200 std::pair<SDValue,SDValue> X86TargetLowering::
5201 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
5202 DebugLoc dl = Op.getDebugLoc();
5203 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5204 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5205 "Unknown FP_TO_SINT to lower!");
5207 // These are really Legal.
5208 if (Op.getValueType() == MVT::i32 &&
5209 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5210 return std::make_pair(SDValue(), SDValue());
5211 if (Subtarget->is64Bit() &&
5212 Op.getValueType() == MVT::i64 &&
5213 Op.getOperand(0).getValueType() != MVT::f80)
5214 return std::make_pair(SDValue(), SDValue());
5216 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5218 MachineFunction &MF = DAG.getMachineFunction();
5219 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5220 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5221 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5223 switch (Op.getValueType().getSimpleVT()) {
5224 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5225 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5226 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5227 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5230 SDValue Chain = DAG.getEntryNode();
5231 SDValue Value = Op.getOperand(0);
5232 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5233 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5234 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5235 PseudoSourceValue::getFixedStack(SSFI), 0);
5236 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5238 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5240 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5241 Chain = Value.getValue(1);
5242 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5243 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5246 // Build the FP_TO_INT*_IN_MEM
5247 SDValue Ops[] = { Chain, Value, StackSlot };
5248 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5250 return std::make_pair(FIST, StackSlot);
5253 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5254 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5255 SDValue FIST = Vals.first, StackSlot = Vals.second;
5256 if (FIST.getNode() == 0) return SDValue();
5259 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5260 FIST, StackSlot, NULL, 0);
5263 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5264 DebugLoc dl = Op.getDebugLoc();
5265 MVT VT = Op.getValueType();
5268 EltVT = VT.getVectorElementType();
5269 std::vector<Constant*> CV;
5270 if (EltVT == MVT::f64) {
5271 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5275 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5281 Constant *C = ConstantVector::get(CV);
5282 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5283 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5284 PseudoSourceValue::getConstantPool(), 0,
5286 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5289 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5290 DebugLoc dl = Op.getDebugLoc();
5291 MVT VT = Op.getValueType();
5293 unsigned EltNum = 1;
5294 if (VT.isVector()) {
5295 EltVT = VT.getVectorElementType();
5296 EltNum = VT.getVectorNumElements();
5298 std::vector<Constant*> CV;
5299 if (EltVT == MVT::f64) {
5300 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5304 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5310 Constant *C = ConstantVector::get(CV);
5311 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5312 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5313 PseudoSourceValue::getConstantPool(), 0,
5315 if (VT.isVector()) {
5316 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5317 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5318 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5320 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5322 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5326 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5327 SDValue Op0 = Op.getOperand(0);
5328 SDValue Op1 = Op.getOperand(1);
5329 DebugLoc dl = Op.getDebugLoc();
5330 MVT VT = Op.getValueType();
5331 MVT SrcVT = Op1.getValueType();
5333 // If second operand is smaller, extend it first.
5334 if (SrcVT.bitsLT(VT)) {
5335 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5338 // And if it is bigger, shrink it first.
5339 if (SrcVT.bitsGT(VT)) {
5340 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5344 // At this point the operands and the result should have the same
5345 // type, and that won't be f80 since that is not custom lowered.
5347 // First get the sign bit of second operand.
5348 std::vector<Constant*> CV;
5349 if (SrcVT == MVT::f64) {
5350 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5351 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5353 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5354 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5355 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5356 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5358 Constant *C = ConstantVector::get(CV);
5359 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5360 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5361 PseudoSourceValue::getConstantPool(), 0,
5363 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5365 // Shift sign bit right or left if the two operands have different types.
5366 if (SrcVT.bitsGT(VT)) {
5367 // Op0 is MVT::f32, Op1 is MVT::f64.
5368 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5369 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5370 DAG.getConstant(32, MVT::i32));
5371 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5372 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5373 DAG.getIntPtrConstant(0));
5376 // Clear first operand sign bit.
5378 if (VT == MVT::f64) {
5379 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5380 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5382 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5383 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5384 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5385 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5387 C = ConstantVector::get(CV);
5388 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5389 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5390 PseudoSourceValue::getConstantPool(), 0,
5392 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5394 // Or the value with the sign bit.
5395 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5398 /// Emit nodes that will be selected as "test Op0,Op0", or something
5400 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5401 SelectionDAG &DAG) {
5402 DebugLoc dl = Op.getDebugLoc();
5404 // CF and OF aren't always set the way we want. Determine which
5405 // of these we need.
5406 bool NeedCF = false;
5407 bool NeedOF = false;
5409 case X86::COND_A: case X86::COND_AE:
5410 case X86::COND_B: case X86::COND_BE:
5413 case X86::COND_G: case X86::COND_GE:
5414 case X86::COND_L: case X86::COND_LE:
5415 case X86::COND_O: case X86::COND_NO:
5421 // See if we can use the EFLAGS value from the operand instead of
5422 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5423 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5424 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5425 unsigned Opcode = 0;
5426 unsigned NumOperands = 0;
5427 switch (Op.getNode()->getOpcode()) {
5429 // Due to an isel shortcoming, be conservative if this add is likely to
5430 // be selected as part of a load-modify-store instruction. When the root
5431 // node in a match is a store, isel doesn't know how to remap non-chain
5432 // non-flag uses of other nodes in the match, such as the ADD in this
5433 // case. This leads to the ADD being left around and reselected, with
5434 // the result being two adds in the output.
5435 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5436 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5437 if (UI->getOpcode() == ISD::STORE)
5439 if (ConstantSDNode *C =
5440 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5441 // An add of one will be selected as an INC.
5442 if (C->getAPIntValue() == 1) {
5443 Opcode = X86ISD::INC;
5447 // An add of negative one (subtract of one) will be selected as a DEC.
5448 if (C->getAPIntValue().isAllOnesValue()) {
5449 Opcode = X86ISD::DEC;
5454 // Otherwise use a regular EFLAGS-setting add.
5455 Opcode = X86ISD::ADD;
5459 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5460 // likely to be selected as part of a load-modify-store instruction.
5461 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5462 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5463 if (UI->getOpcode() == ISD::STORE)
5465 // Otherwise use a regular EFLAGS-setting sub.
5466 Opcode = X86ISD::SUB;
5473 return SDValue(Op.getNode(), 1);
5479 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::i32);
5480 SmallVector<SDValue, 4> Ops;
5481 for (unsigned i = 0; i != NumOperands; ++i)
5482 Ops.push_back(Op.getOperand(i));
5483 SDValue New = DAG.getNode(Opcode, dl, VTs, 2, &Ops[0], NumOperands);
5484 DAG.ReplaceAllUsesWith(Op, New);
5485 return SDValue(New.getNode(), 1);
5489 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5490 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5491 DAG.getConstant(0, Op.getValueType()));
5494 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5496 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5497 SelectionDAG &DAG) {
5498 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5499 if (C->getAPIntValue() == 0)
5500 return EmitTest(Op0, X86CC, DAG);
5502 DebugLoc dl = Op0.getDebugLoc();
5503 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5506 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5507 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5508 SDValue Op0 = Op.getOperand(0);
5509 SDValue Op1 = Op.getOperand(1);
5510 DebugLoc dl = Op.getDebugLoc();
5511 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5513 // Lower (X & (1 << N)) == 0 to BT(X, N).
5514 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5515 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5516 if (Op0.getOpcode() == ISD::AND &&
5518 Op1.getOpcode() == ISD::Constant &&
5519 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5520 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5522 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5523 if (ConstantSDNode *Op010C =
5524 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5525 if (Op010C->getZExtValue() == 1) {
5526 LHS = Op0.getOperand(0);
5527 RHS = Op0.getOperand(1).getOperand(1);
5529 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5530 if (ConstantSDNode *Op000C =
5531 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5532 if (Op000C->getZExtValue() == 1) {
5533 LHS = Op0.getOperand(1);
5534 RHS = Op0.getOperand(0).getOperand(1);
5536 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5537 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5538 SDValue AndLHS = Op0.getOperand(0);
5539 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5540 LHS = AndLHS.getOperand(0);
5541 RHS = AndLHS.getOperand(1);
5545 if (LHS.getNode()) {
5546 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5547 // instruction. Since the shift amount is in-range-or-undefined, we know
5548 // that doing a bittest on the i16 value is ok. We extend to i32 because
5549 // the encoding for the i16 version is larger than the i32 version.
5550 if (LHS.getValueType() == MVT::i8)
5551 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5553 // If the operand types disagree, extend the shift amount to match. Since
5554 // BT ignores high bits (like shifts) we can use anyextend.
5555 if (LHS.getValueType() != RHS.getValueType())
5556 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5558 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5559 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5560 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5561 DAG.getConstant(Cond, MVT::i8), BT);
5565 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5566 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5568 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5569 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5570 DAG.getConstant(X86CC, MVT::i8), Cond);
5573 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5575 SDValue Op0 = Op.getOperand(0);
5576 SDValue Op1 = Op.getOperand(1);
5577 SDValue CC = Op.getOperand(2);
5578 MVT VT = Op.getValueType();
5579 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5580 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5581 DebugLoc dl = Op.getDebugLoc();
5585 MVT VT0 = Op0.getValueType();
5586 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5587 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5590 switch (SetCCOpcode) {
5593 case ISD::SETEQ: SSECC = 0; break;
5595 case ISD::SETGT: Swap = true; // Fallthrough
5597 case ISD::SETOLT: SSECC = 1; break;
5599 case ISD::SETGE: Swap = true; // Fallthrough
5601 case ISD::SETOLE: SSECC = 2; break;
5602 case ISD::SETUO: SSECC = 3; break;
5604 case ISD::SETNE: SSECC = 4; break;
5605 case ISD::SETULE: Swap = true;
5606 case ISD::SETUGE: SSECC = 5; break;
5607 case ISD::SETULT: Swap = true;
5608 case ISD::SETUGT: SSECC = 6; break;
5609 case ISD::SETO: SSECC = 7; break;
5612 std::swap(Op0, Op1);
5614 // In the two special cases we can't handle, emit two comparisons.
5616 if (SetCCOpcode == ISD::SETUEQ) {
5618 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5619 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5620 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5622 else if (SetCCOpcode == ISD::SETONE) {
5624 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5625 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5626 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5628 assert(0 && "Illegal FP comparison");
5630 // Handle all other FP comparisons here.
5631 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5634 // We are handling one of the integer comparisons here. Since SSE only has
5635 // GT and EQ comparisons for integer, swapping operands and multiple
5636 // operations may be required for some comparisons.
5637 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5638 bool Swap = false, Invert = false, FlipSigns = false;
5640 switch (VT.getSimpleVT()) {
5642 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5643 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5644 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5645 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5648 switch (SetCCOpcode) {
5650 case ISD::SETNE: Invert = true;
5651 case ISD::SETEQ: Opc = EQOpc; break;
5652 case ISD::SETLT: Swap = true;
5653 case ISD::SETGT: Opc = GTOpc; break;
5654 case ISD::SETGE: Swap = true;
5655 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5656 case ISD::SETULT: Swap = true;
5657 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5658 case ISD::SETUGE: Swap = true;
5659 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5662 std::swap(Op0, Op1);
5664 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5665 // bits of the inputs before performing those operations.
5667 MVT EltVT = VT.getVectorElementType();
5668 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5670 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5671 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5673 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5674 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5677 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5679 // If the logical-not of the result is required, perform that now.
5681 Result = DAG.getNOT(dl, Result, VT);
5686 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5687 static bool isX86LogicalCmp(SDValue Op) {
5688 unsigned Opc = Op.getNode()->getOpcode();
5689 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5691 if (Op.getResNo() == 1 &&
5692 (Opc == X86ISD::ADD ||
5693 Opc == X86ISD::SUB ||
5694 Opc == X86ISD::SMUL ||
5695 Opc == X86ISD::UMUL ||
5696 Opc == X86ISD::INC ||
5697 Opc == X86ISD::DEC))
5703 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5704 bool addTest = true;
5705 SDValue Cond = Op.getOperand(0);
5706 DebugLoc dl = Op.getDebugLoc();
5709 if (Cond.getOpcode() == ISD::SETCC)
5710 Cond = LowerSETCC(Cond, DAG);
5712 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5713 // setting operand in place of the X86ISD::SETCC.
5714 if (Cond.getOpcode() == X86ISD::SETCC) {
5715 CC = Cond.getOperand(0);
5717 SDValue Cmp = Cond.getOperand(1);
5718 unsigned Opc = Cmp.getOpcode();
5719 MVT VT = Op.getValueType();
5721 bool IllegalFPCMov = false;
5722 if (VT.isFloatingPoint() && !VT.isVector() &&
5723 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5724 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5726 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5727 Opc == X86ISD::BT) { // FIXME
5734 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5735 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5738 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5740 SmallVector<SDValue, 4> Ops;
5741 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5742 // condition is true.
5743 Ops.push_back(Op.getOperand(2));
5744 Ops.push_back(Op.getOperand(1));
5746 Ops.push_back(Cond);
5747 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5750 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5751 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5752 // from the AND / OR.
5753 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5754 Opc = Op.getOpcode();
5755 if (Opc != ISD::OR && Opc != ISD::AND)
5757 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5758 Op.getOperand(0).hasOneUse() &&
5759 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5760 Op.getOperand(1).hasOneUse());
5763 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5764 // 1 and that the SETCC node has a single use.
5765 static bool isXor1OfSetCC(SDValue Op) {
5766 if (Op.getOpcode() != ISD::XOR)
5768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5769 if (N1C && N1C->getAPIntValue() == 1) {
5770 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5771 Op.getOperand(0).hasOneUse();
5776 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5777 bool addTest = true;
5778 SDValue Chain = Op.getOperand(0);
5779 SDValue Cond = Op.getOperand(1);
5780 SDValue Dest = Op.getOperand(2);
5781 DebugLoc dl = Op.getDebugLoc();
5784 if (Cond.getOpcode() == ISD::SETCC)
5785 Cond = LowerSETCC(Cond, DAG);
5787 // FIXME: LowerXALUO doesn't handle these!!
5788 else if (Cond.getOpcode() == X86ISD::ADD ||
5789 Cond.getOpcode() == X86ISD::SUB ||
5790 Cond.getOpcode() == X86ISD::SMUL ||
5791 Cond.getOpcode() == X86ISD::UMUL)
5792 Cond = LowerXALUO(Cond, DAG);
5795 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5796 // setting operand in place of the X86ISD::SETCC.
5797 if (Cond.getOpcode() == X86ISD::SETCC) {
5798 CC = Cond.getOperand(0);
5800 SDValue Cmp = Cond.getOperand(1);
5801 unsigned Opc = Cmp.getOpcode();
5802 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5803 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5807 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5811 // These can only come from an arithmetic instruction with overflow,
5812 // e.g. SADDO, UADDO.
5813 Cond = Cond.getNode()->getOperand(1);
5820 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5821 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5822 if (CondOpc == ISD::OR) {
5823 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5824 // two branches instead of an explicit OR instruction with a
5826 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5827 isX86LogicalCmp(Cmp)) {
5828 CC = Cond.getOperand(0).getOperand(0);
5829 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5830 Chain, Dest, CC, Cmp);
5831 CC = Cond.getOperand(1).getOperand(0);
5835 } else { // ISD::AND
5836 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5837 // two branches instead of an explicit AND instruction with a
5838 // separate test. However, we only do this if this block doesn't
5839 // have a fall-through edge, because this requires an explicit
5840 // jmp when the condition is false.
5841 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5842 isX86LogicalCmp(Cmp) &&
5843 Op.getNode()->hasOneUse()) {
5844 X86::CondCode CCode =
5845 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5846 CCode = X86::GetOppositeBranchCondition(CCode);
5847 CC = DAG.getConstant(CCode, MVT::i8);
5848 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5849 // Look for an unconditional branch following this conditional branch.
5850 // We need this because we need to reverse the successors in order
5851 // to implement FCMP_OEQ.
5852 if (User.getOpcode() == ISD::BR) {
5853 SDValue FalseBB = User.getOperand(1);
5855 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5856 assert(NewBR == User);
5859 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5860 Chain, Dest, CC, Cmp);
5861 X86::CondCode CCode =
5862 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5863 CCode = X86::GetOppositeBranchCondition(CCode);
5864 CC = DAG.getConstant(CCode, MVT::i8);
5870 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5871 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5872 // It should be transformed during dag combiner except when the condition
5873 // is set by a arithmetics with overflow node.
5874 X86::CondCode CCode =
5875 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5876 CCode = X86::GetOppositeBranchCondition(CCode);
5877 CC = DAG.getConstant(CCode, MVT::i8);
5878 Cond = Cond.getOperand(0).getOperand(1);
5884 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5885 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5887 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5888 Chain, Dest, CC, Cond);
5892 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5893 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5894 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5895 // that the guard pages used by the OS virtual memory manager are allocated in
5896 // correct sequence.
5898 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5899 SelectionDAG &DAG) {
5900 assert(Subtarget->isTargetCygMing() &&
5901 "This should be used only on Cygwin/Mingw targets");
5902 DebugLoc dl = Op.getDebugLoc();
5905 SDValue Chain = Op.getOperand(0);
5906 SDValue Size = Op.getOperand(1);
5907 // FIXME: Ensure alignment here
5911 MVT IntPtr = getPointerTy();
5912 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5914 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5916 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5917 Flag = Chain.getValue(1);
5919 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5920 SDValue Ops[] = { Chain,
5921 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5922 DAG.getRegister(X86::EAX, IntPtr),
5923 DAG.getRegister(X86StackPtr, SPTy),
5925 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5926 Flag = Chain.getValue(1);
5928 Chain = DAG.getCALLSEQ_END(Chain,
5929 DAG.getIntPtrConstant(0, true),
5930 DAG.getIntPtrConstant(0, true),
5933 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5935 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5936 return DAG.getMergeValues(Ops1, 2, dl);
5940 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5942 SDValue Dst, SDValue Src,
5943 SDValue Size, unsigned Align,
5945 uint64_t DstSVOff) {
5946 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5948 // If not DWORD aligned or size is more than the threshold, call the library.
5949 // The libc version is likely to be faster for these cases. It can use the
5950 // address value and run time information about the CPU.
5951 if ((Align & 3) != 0 ||
5953 ConstantSize->getZExtValue() >
5954 getSubtarget()->getMaxInlineSizeThreshold()) {
5955 SDValue InFlag(0, 0);
5957 // Check to see if there is a specialized entry-point for memory zeroing.
5958 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5960 if (const char *bzeroEntry = V &&
5961 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5962 MVT IntPtr = getPointerTy();
5963 const Type *IntPtrTy = TD->getIntPtrType();
5964 TargetLowering::ArgListTy Args;
5965 TargetLowering::ArgListEntry Entry;
5967 Entry.Ty = IntPtrTy;
5968 Args.push_back(Entry);
5970 Args.push_back(Entry);
5971 std::pair<SDValue,SDValue> CallResult =
5972 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5973 CallingConv::C, false,
5974 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5975 return CallResult.second;
5978 // Otherwise have the target-independent code call memset.
5982 uint64_t SizeVal = ConstantSize->getZExtValue();
5983 SDValue InFlag(0, 0);
5986 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5987 unsigned BytesLeft = 0;
5988 bool TwoRepStos = false;
5991 uint64_t Val = ValC->getZExtValue() & 255;
5993 // If the value is a constant, then we can potentially use larger sets.
5994 switch (Align & 3) {
5995 case 2: // WORD aligned
5998 Val = (Val << 8) | Val;
6000 case 0: // DWORD aligned
6003 Val = (Val << 8) | Val;
6004 Val = (Val << 16) | Val;
6005 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6008 Val = (Val << 32) | Val;
6011 default: // Byte aligned
6014 Count = DAG.getIntPtrConstant(SizeVal);
6018 if (AVT.bitsGT(MVT::i8)) {
6019 unsigned UBytes = AVT.getSizeInBits() / 8;
6020 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6021 BytesLeft = SizeVal % UBytes;
6024 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6026 InFlag = Chain.getValue(1);
6029 Count = DAG.getIntPtrConstant(SizeVal);
6030 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6031 InFlag = Chain.getValue(1);
6034 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6037 InFlag = Chain.getValue(1);
6038 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6041 InFlag = Chain.getValue(1);
6043 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6044 SmallVector<SDValue, 8> Ops;
6045 Ops.push_back(Chain);
6046 Ops.push_back(DAG.getValueType(AVT));
6047 Ops.push_back(InFlag);
6048 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6051 InFlag = Chain.getValue(1);
6053 MVT CVT = Count.getValueType();
6054 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6055 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6056 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6059 InFlag = Chain.getValue(1);
6060 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6062 Ops.push_back(Chain);
6063 Ops.push_back(DAG.getValueType(MVT::i8));
6064 Ops.push_back(InFlag);
6065 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6066 } else if (BytesLeft) {
6067 // Handle the last 1 - 7 bytes.
6068 unsigned Offset = SizeVal - BytesLeft;
6069 MVT AddrVT = Dst.getValueType();
6070 MVT SizeVT = Size.getValueType();
6072 Chain = DAG.getMemset(Chain, dl,
6073 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6074 DAG.getConstant(Offset, AddrVT)),
6076 DAG.getConstant(BytesLeft, SizeVT),
6077 Align, DstSV, DstSVOff + Offset);
6080 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6085 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6086 SDValue Chain, SDValue Dst, SDValue Src,
6087 SDValue Size, unsigned Align,
6089 const Value *DstSV, uint64_t DstSVOff,
6090 const Value *SrcSV, uint64_t SrcSVOff) {
6091 // This requires the copy size to be a constant, preferrably
6092 // within a subtarget-specific limit.
6093 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6096 uint64_t SizeVal = ConstantSize->getZExtValue();
6097 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6100 /// If not DWORD aligned, call the library.
6101 if ((Align & 3) != 0)
6106 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6109 unsigned UBytes = AVT.getSizeInBits() / 8;
6110 unsigned CountVal = SizeVal / UBytes;
6111 SDValue Count = DAG.getIntPtrConstant(CountVal);
6112 unsigned BytesLeft = SizeVal % UBytes;
6114 SDValue InFlag(0, 0);
6115 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6118 InFlag = Chain.getValue(1);
6119 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6122 InFlag = Chain.getValue(1);
6123 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6126 InFlag = Chain.getValue(1);
6128 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6129 SmallVector<SDValue, 8> Ops;
6130 Ops.push_back(Chain);
6131 Ops.push_back(DAG.getValueType(AVT));
6132 Ops.push_back(InFlag);
6133 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6135 SmallVector<SDValue, 4> Results;
6136 Results.push_back(RepMovs);
6138 // Handle the last 1 - 7 bytes.
6139 unsigned Offset = SizeVal - BytesLeft;
6140 MVT DstVT = Dst.getValueType();
6141 MVT SrcVT = Src.getValueType();
6142 MVT SizeVT = Size.getValueType();
6143 Results.push_back(DAG.getMemcpy(Chain, dl,
6144 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6145 DAG.getConstant(Offset, DstVT)),
6146 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6147 DAG.getConstant(Offset, SrcVT)),
6148 DAG.getConstant(BytesLeft, SizeVT),
6149 Align, AlwaysInline,
6150 DstSV, DstSVOff + Offset,
6151 SrcSV, SrcSVOff + Offset));
6154 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6155 &Results[0], Results.size());
6158 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6159 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6160 DebugLoc dl = Op.getDebugLoc();
6162 if (!Subtarget->is64Bit()) {
6163 // vastart just stores the address of the VarArgsFrameIndex slot into the
6164 // memory location argument.
6165 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6166 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6170 // gp_offset (0 - 6 * 8)
6171 // fp_offset (48 - 48 + 8 * 16)
6172 // overflow_arg_area (point to parameters coming in memory).
6174 SmallVector<SDValue, 8> MemOps;
6175 SDValue FIN = Op.getOperand(1);
6177 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6178 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6180 MemOps.push_back(Store);
6183 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6184 FIN, DAG.getIntPtrConstant(4));
6185 Store = DAG.getStore(Op.getOperand(0), dl,
6186 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6188 MemOps.push_back(Store);
6190 // Store ptr to overflow_arg_area
6191 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6192 FIN, DAG.getIntPtrConstant(4));
6193 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6194 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6195 MemOps.push_back(Store);
6197 // Store ptr to reg_save_area.
6198 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6199 FIN, DAG.getIntPtrConstant(8));
6200 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6201 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6202 MemOps.push_back(Store);
6203 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6204 &MemOps[0], MemOps.size());
6207 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6208 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6209 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6210 SDValue Chain = Op.getOperand(0);
6211 SDValue SrcPtr = Op.getOperand(1);
6212 SDValue SrcSV = Op.getOperand(2);
6214 assert(0 && "VAArgInst is not yet implemented for x86-64!");
6219 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6220 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6221 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6222 SDValue Chain = Op.getOperand(0);
6223 SDValue DstPtr = Op.getOperand(1);
6224 SDValue SrcPtr = Op.getOperand(2);
6225 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6226 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6227 DebugLoc dl = Op.getDebugLoc();
6229 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6230 DAG.getIntPtrConstant(24), 8, false,
6231 DstSV, 0, SrcSV, 0);
6235 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6236 DebugLoc dl = Op.getDebugLoc();
6237 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6239 default: return SDValue(); // Don't custom lower most intrinsics.
6240 // Comparison intrinsics.
6241 case Intrinsic::x86_sse_comieq_ss:
6242 case Intrinsic::x86_sse_comilt_ss:
6243 case Intrinsic::x86_sse_comile_ss:
6244 case Intrinsic::x86_sse_comigt_ss:
6245 case Intrinsic::x86_sse_comige_ss:
6246 case Intrinsic::x86_sse_comineq_ss:
6247 case Intrinsic::x86_sse_ucomieq_ss:
6248 case Intrinsic::x86_sse_ucomilt_ss:
6249 case Intrinsic::x86_sse_ucomile_ss:
6250 case Intrinsic::x86_sse_ucomigt_ss:
6251 case Intrinsic::x86_sse_ucomige_ss:
6252 case Intrinsic::x86_sse_ucomineq_ss:
6253 case Intrinsic::x86_sse2_comieq_sd:
6254 case Intrinsic::x86_sse2_comilt_sd:
6255 case Intrinsic::x86_sse2_comile_sd:
6256 case Intrinsic::x86_sse2_comigt_sd:
6257 case Intrinsic::x86_sse2_comige_sd:
6258 case Intrinsic::x86_sse2_comineq_sd:
6259 case Intrinsic::x86_sse2_ucomieq_sd:
6260 case Intrinsic::x86_sse2_ucomilt_sd:
6261 case Intrinsic::x86_sse2_ucomile_sd:
6262 case Intrinsic::x86_sse2_ucomigt_sd:
6263 case Intrinsic::x86_sse2_ucomige_sd:
6264 case Intrinsic::x86_sse2_ucomineq_sd: {
6266 ISD::CondCode CC = ISD::SETCC_INVALID;
6269 case Intrinsic::x86_sse_comieq_ss:
6270 case Intrinsic::x86_sse2_comieq_sd:
6274 case Intrinsic::x86_sse_comilt_ss:
6275 case Intrinsic::x86_sse2_comilt_sd:
6279 case Intrinsic::x86_sse_comile_ss:
6280 case Intrinsic::x86_sse2_comile_sd:
6284 case Intrinsic::x86_sse_comigt_ss:
6285 case Intrinsic::x86_sse2_comigt_sd:
6289 case Intrinsic::x86_sse_comige_ss:
6290 case Intrinsic::x86_sse2_comige_sd:
6294 case Intrinsic::x86_sse_comineq_ss:
6295 case Intrinsic::x86_sse2_comineq_sd:
6299 case Intrinsic::x86_sse_ucomieq_ss:
6300 case Intrinsic::x86_sse2_ucomieq_sd:
6301 Opc = X86ISD::UCOMI;
6304 case Intrinsic::x86_sse_ucomilt_ss:
6305 case Intrinsic::x86_sse2_ucomilt_sd:
6306 Opc = X86ISD::UCOMI;
6309 case Intrinsic::x86_sse_ucomile_ss:
6310 case Intrinsic::x86_sse2_ucomile_sd:
6311 Opc = X86ISD::UCOMI;
6314 case Intrinsic::x86_sse_ucomigt_ss:
6315 case Intrinsic::x86_sse2_ucomigt_sd:
6316 Opc = X86ISD::UCOMI;
6319 case Intrinsic::x86_sse_ucomige_ss:
6320 case Intrinsic::x86_sse2_ucomige_sd:
6321 Opc = X86ISD::UCOMI;
6324 case Intrinsic::x86_sse_ucomineq_ss:
6325 case Intrinsic::x86_sse2_ucomineq_sd:
6326 Opc = X86ISD::UCOMI;
6331 SDValue LHS = Op.getOperand(1);
6332 SDValue RHS = Op.getOperand(2);
6333 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6334 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6335 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6336 DAG.getConstant(X86CC, MVT::i8), Cond);
6337 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6340 // Fix vector shift instructions where the last operand is a non-immediate
6342 case Intrinsic::x86_sse2_pslli_w:
6343 case Intrinsic::x86_sse2_pslli_d:
6344 case Intrinsic::x86_sse2_pslli_q:
6345 case Intrinsic::x86_sse2_psrli_w:
6346 case Intrinsic::x86_sse2_psrli_d:
6347 case Intrinsic::x86_sse2_psrli_q:
6348 case Intrinsic::x86_sse2_psrai_w:
6349 case Intrinsic::x86_sse2_psrai_d:
6350 case Intrinsic::x86_mmx_pslli_w:
6351 case Intrinsic::x86_mmx_pslli_d:
6352 case Intrinsic::x86_mmx_pslli_q:
6353 case Intrinsic::x86_mmx_psrli_w:
6354 case Intrinsic::x86_mmx_psrli_d:
6355 case Intrinsic::x86_mmx_psrli_q:
6356 case Intrinsic::x86_mmx_psrai_w:
6357 case Intrinsic::x86_mmx_psrai_d: {
6358 SDValue ShAmt = Op.getOperand(2);
6359 if (isa<ConstantSDNode>(ShAmt))
6362 unsigned NewIntNo = 0;
6363 MVT ShAmtVT = MVT::v4i32;
6365 case Intrinsic::x86_sse2_pslli_w:
6366 NewIntNo = Intrinsic::x86_sse2_psll_w;
6368 case Intrinsic::x86_sse2_pslli_d:
6369 NewIntNo = Intrinsic::x86_sse2_psll_d;
6371 case Intrinsic::x86_sse2_pslli_q:
6372 NewIntNo = Intrinsic::x86_sse2_psll_q;
6374 case Intrinsic::x86_sse2_psrli_w:
6375 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6377 case Intrinsic::x86_sse2_psrli_d:
6378 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6380 case Intrinsic::x86_sse2_psrli_q:
6381 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6383 case Intrinsic::x86_sse2_psrai_w:
6384 NewIntNo = Intrinsic::x86_sse2_psra_w;
6386 case Intrinsic::x86_sse2_psrai_d:
6387 NewIntNo = Intrinsic::x86_sse2_psra_d;
6390 ShAmtVT = MVT::v2i32;
6392 case Intrinsic::x86_mmx_pslli_w:
6393 NewIntNo = Intrinsic::x86_mmx_psll_w;
6395 case Intrinsic::x86_mmx_pslli_d:
6396 NewIntNo = Intrinsic::x86_mmx_psll_d;
6398 case Intrinsic::x86_mmx_pslli_q:
6399 NewIntNo = Intrinsic::x86_mmx_psll_q;
6401 case Intrinsic::x86_mmx_psrli_w:
6402 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6404 case Intrinsic::x86_mmx_psrli_d:
6405 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6407 case Intrinsic::x86_mmx_psrli_q:
6408 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6410 case Intrinsic::x86_mmx_psrai_w:
6411 NewIntNo = Intrinsic::x86_mmx_psra_w;
6413 case Intrinsic::x86_mmx_psrai_d:
6414 NewIntNo = Intrinsic::x86_mmx_psra_d;
6416 default: abort(); // Can't reach here.
6421 MVT VT = Op.getValueType();
6422 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6423 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6424 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6425 DAG.getConstant(NewIntNo, MVT::i32),
6426 Op.getOperand(1), ShAmt);
6431 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6432 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6433 DebugLoc dl = Op.getDebugLoc();
6436 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6438 DAG.getConstant(TD->getPointerSize(),
6439 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6440 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6441 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6446 // Just load the return address.
6447 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6448 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6449 RetAddrFI, NULL, 0);
6452 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6453 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6454 MFI->setFrameAddressIsTaken(true);
6455 MVT VT = Op.getValueType();
6456 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6457 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6458 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6459 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6461 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6465 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6466 SelectionDAG &DAG) {
6467 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6470 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6472 MachineFunction &MF = DAG.getMachineFunction();
6473 SDValue Chain = Op.getOperand(0);
6474 SDValue Offset = Op.getOperand(1);
6475 SDValue Handler = Op.getOperand(2);
6476 DebugLoc dl = Op.getDebugLoc();
6478 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6480 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6482 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6483 DAG.getIntPtrConstant(-TD->getPointerSize()));
6484 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6485 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6486 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6487 MF.getRegInfo().addLiveOut(StoreAddrReg);
6489 return DAG.getNode(X86ISD::EH_RETURN, dl,
6491 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6494 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6495 SelectionDAG &DAG) {
6496 SDValue Root = Op.getOperand(0);
6497 SDValue Trmp = Op.getOperand(1); // trampoline
6498 SDValue FPtr = Op.getOperand(2); // nested function
6499 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6500 DebugLoc dl = Op.getDebugLoc();
6502 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6504 const X86InstrInfo *TII =
6505 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6507 if (Subtarget->is64Bit()) {
6508 SDValue OutChains[6];
6510 // Large code-model.
6512 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6513 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6515 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6516 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6518 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6520 // Load the pointer to the nested function into R11.
6521 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6522 SDValue Addr = Trmp;
6523 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6526 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6527 DAG.getConstant(2, MVT::i64));
6528 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6530 // Load the 'nest' parameter value into R10.
6531 // R10 is specified in X86CallingConv.td
6532 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6533 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6534 DAG.getConstant(10, MVT::i64));
6535 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6536 Addr, TrmpAddr, 10);
6538 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6539 DAG.getConstant(12, MVT::i64));
6540 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6542 // Jump to the nested function.
6543 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6545 DAG.getConstant(20, MVT::i64));
6546 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6547 Addr, TrmpAddr, 20);
6549 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6551 DAG.getConstant(22, MVT::i64));
6552 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6556 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6557 return DAG.getMergeValues(Ops, 2, dl);
6559 const Function *Func =
6560 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6561 unsigned CC = Func->getCallingConv();
6566 assert(0 && "Unsupported calling convention");
6567 case CallingConv::C:
6568 case CallingConv::X86_StdCall: {
6569 // Pass 'nest' parameter in ECX.
6570 // Must be kept in sync with X86CallingConv.td
6573 // Check that ECX wasn't needed by an 'inreg' parameter.
6574 const FunctionType *FTy = Func->getFunctionType();
6575 const AttrListPtr &Attrs = Func->getAttributes();
6577 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6578 unsigned InRegCount = 0;
6581 for (FunctionType::param_iterator I = FTy->param_begin(),
6582 E = FTy->param_end(); I != E; ++I, ++Idx)
6583 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6584 // FIXME: should only count parameters that are lowered to integers.
6585 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6587 if (InRegCount > 2) {
6588 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6594 case CallingConv::X86_FastCall:
6595 case CallingConv::Fast:
6596 // Pass 'nest' parameter in EAX.
6597 // Must be kept in sync with X86CallingConv.td
6602 SDValue OutChains[4];
6605 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6606 DAG.getConstant(10, MVT::i32));
6607 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6609 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6610 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6611 OutChains[0] = DAG.getStore(Root, dl,
6612 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6615 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6616 DAG.getConstant(1, MVT::i32));
6617 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6619 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6621 DAG.getConstant(5, MVT::i32));
6622 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6623 TrmpAddr, 5, false, 1);
6625 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6626 DAG.getConstant(6, MVT::i32));
6627 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6630 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6631 return DAG.getMergeValues(Ops, 2, dl);
6635 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6637 The rounding mode is in bits 11:10 of FPSR, and has the following
6644 FLT_ROUNDS, on the other hand, expects the following:
6651 To perform the conversion, we do:
6652 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6655 MachineFunction &MF = DAG.getMachineFunction();
6656 const TargetMachine &TM = MF.getTarget();
6657 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6658 unsigned StackAlignment = TFI.getStackAlignment();
6659 MVT VT = Op.getValueType();
6660 DebugLoc dl = Op.getDebugLoc();
6662 // Save FP Control Word to stack slot
6663 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6664 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6666 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6667 DAG.getEntryNode(), StackSlot);
6669 // Load FP Control Word from stack slot
6670 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6672 // Transform as necessary
6674 DAG.getNode(ISD::SRL, dl, MVT::i16,
6675 DAG.getNode(ISD::AND, dl, MVT::i16,
6676 CWD, DAG.getConstant(0x800, MVT::i16)),
6677 DAG.getConstant(11, MVT::i8));
6679 DAG.getNode(ISD::SRL, dl, MVT::i16,
6680 DAG.getNode(ISD::AND, dl, MVT::i16,
6681 CWD, DAG.getConstant(0x400, MVT::i16)),
6682 DAG.getConstant(9, MVT::i8));
6685 DAG.getNode(ISD::AND, dl, MVT::i16,
6686 DAG.getNode(ISD::ADD, dl, MVT::i16,
6687 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6688 DAG.getConstant(1, MVT::i16)),
6689 DAG.getConstant(3, MVT::i16));
6692 return DAG.getNode((VT.getSizeInBits() < 16 ?
6693 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6696 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6697 MVT VT = Op.getValueType();
6699 unsigned NumBits = VT.getSizeInBits();
6700 DebugLoc dl = Op.getDebugLoc();
6702 Op = Op.getOperand(0);
6703 if (VT == MVT::i8) {
6704 // Zero extend to i32 since there is not an i8 bsr.
6706 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6709 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6710 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6711 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6713 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6714 SmallVector<SDValue, 4> Ops;
6716 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6717 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6718 Ops.push_back(Op.getValue(1));
6719 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6721 // Finally xor with NumBits-1.
6722 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6725 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6729 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6730 MVT VT = Op.getValueType();
6732 unsigned NumBits = VT.getSizeInBits();
6733 DebugLoc dl = Op.getDebugLoc();
6735 Op = Op.getOperand(0);
6736 if (VT == MVT::i8) {
6738 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6741 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6742 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6743 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6745 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6746 SmallVector<SDValue, 4> Ops;
6748 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6749 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6750 Ops.push_back(Op.getValue(1));
6751 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6754 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6758 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6759 MVT VT = Op.getValueType();
6760 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6761 DebugLoc dl = Op.getDebugLoc();
6763 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6764 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6765 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6766 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6767 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6769 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6770 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6771 // return AloBlo + AloBhi + AhiBlo;
6773 SDValue A = Op.getOperand(0);
6774 SDValue B = Op.getOperand(1);
6776 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6777 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6778 A, DAG.getConstant(32, MVT::i32));
6779 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6780 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6781 B, DAG.getConstant(32, MVT::i32));
6782 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6783 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6785 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6786 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6788 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6789 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6791 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6792 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6793 AloBhi, DAG.getConstant(32, MVT::i32));
6794 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6795 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6796 AhiBlo, DAG.getConstant(32, MVT::i32));
6797 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6798 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6803 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6804 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6805 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6806 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6807 // has only one use.
6808 SDNode *N = Op.getNode();
6809 SDValue LHS = N->getOperand(0);
6810 SDValue RHS = N->getOperand(1);
6811 unsigned BaseOp = 0;
6813 DebugLoc dl = Op.getDebugLoc();
6815 switch (Op.getOpcode()) {
6816 default: assert(0 && "Unknown ovf instruction!");
6818 // A subtract of one will be selected as a INC. Note that INC doesn't
6819 // set CF, so we can't do this for UADDO.
6820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6821 if (C->getAPIntValue() == 1) {
6822 BaseOp = X86ISD::INC;
6826 BaseOp = X86ISD::ADD;
6830 BaseOp = X86ISD::ADD;
6834 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6835 // set CF, so we can't do this for USUBO.
6836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6837 if (C->getAPIntValue() == 1) {
6838 BaseOp = X86ISD::DEC;
6842 BaseOp = X86ISD::SUB;
6846 BaseOp = X86ISD::SUB;
6850 BaseOp = X86ISD::SMUL;
6854 BaseOp = X86ISD::UMUL;
6859 // Also sets EFLAGS.
6860 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6861 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6864 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6865 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6867 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6871 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6872 MVT T = Op.getValueType();
6873 DebugLoc dl = Op.getDebugLoc();
6876 switch(T.getSimpleVT()) {
6878 assert(false && "Invalid value type!");
6879 case MVT::i8: Reg = X86::AL; size = 1; break;
6880 case MVT::i16: Reg = X86::AX; size = 2; break;
6881 case MVT::i32: Reg = X86::EAX; size = 4; break;
6883 assert(Subtarget->is64Bit() && "Node not type legal!");
6884 Reg = X86::RAX; size = 8;
6887 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6888 Op.getOperand(2), SDValue());
6889 SDValue Ops[] = { cpIn.getValue(0),
6892 DAG.getTargetConstant(size, MVT::i8),
6894 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6895 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6897 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6901 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6902 SelectionDAG &DAG) {
6903 assert(Subtarget->is64Bit() && "Result not type legalized?");
6904 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6905 SDValue TheChain = Op.getOperand(0);
6906 DebugLoc dl = Op.getDebugLoc();
6907 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6908 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6909 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6911 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6912 DAG.getConstant(32, MVT::i8));
6914 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6917 return DAG.getMergeValues(Ops, 2, dl);
6920 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6921 SDNode *Node = Op.getNode();
6922 DebugLoc dl = Node->getDebugLoc();
6923 MVT T = Node->getValueType(0);
6924 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6925 DAG.getConstant(0, T), Node->getOperand(2));
6926 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6927 cast<AtomicSDNode>(Node)->getMemoryVT(),
6928 Node->getOperand(0),
6929 Node->getOperand(1), negOp,
6930 cast<AtomicSDNode>(Node)->getSrcValue(),
6931 cast<AtomicSDNode>(Node)->getAlignment());
6934 /// LowerOperation - Provide custom lowering hooks for some operations.
6936 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6937 switch (Op.getOpcode()) {
6938 default: assert(0 && "Should not custom lower this!");
6939 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6940 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6941 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6942 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6943 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6944 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6945 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6946 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6947 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6948 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6949 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6950 case ISD::SHL_PARTS:
6951 case ISD::SRA_PARTS:
6952 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6953 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6954 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6955 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6956 case ISD::FABS: return LowerFABS(Op, DAG);
6957 case ISD::FNEG: return LowerFNEG(Op, DAG);
6958 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6959 case ISD::SETCC: return LowerSETCC(Op, DAG);
6960 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6961 case ISD::SELECT: return LowerSELECT(Op, DAG);
6962 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6963 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6964 case ISD::CALL: return LowerCALL(Op, DAG);
6965 case ISD::RET: return LowerRET(Op, DAG);
6966 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6967 case ISD::VASTART: return LowerVASTART(Op, DAG);
6968 case ISD::VAARG: return LowerVAARG(Op, DAG);
6969 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6970 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6971 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6972 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6973 case ISD::FRAME_TO_ARGS_OFFSET:
6974 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6975 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6976 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6977 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6978 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6979 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6980 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6981 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6987 case ISD::UMULO: return LowerXALUO(Op, DAG);
6988 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6992 void X86TargetLowering::
6993 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6994 SelectionDAG &DAG, unsigned NewOp) {
6995 MVT T = Node->getValueType(0);
6996 DebugLoc dl = Node->getDebugLoc();
6997 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6999 SDValue Chain = Node->getOperand(0);
7000 SDValue In1 = Node->getOperand(1);
7001 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7002 Node->getOperand(2), DAG.getIntPtrConstant(0));
7003 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7004 Node->getOperand(2), DAG.getIntPtrConstant(1));
7005 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
7006 // have a MemOperand. Pass the info through as a normal operand.
7007 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
7008 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
7009 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7010 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
7011 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7012 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7013 Results.push_back(Result.getValue(2));
7016 /// ReplaceNodeResults - Replace a node with an illegal result type
7017 /// with a new node built out of custom code.
7018 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7019 SmallVectorImpl<SDValue>&Results,
7020 SelectionDAG &DAG) {
7021 DebugLoc dl = N->getDebugLoc();
7022 switch (N->getOpcode()) {
7024 assert(false && "Do not know how to custom type legalize this operation!");
7026 case ISD::FP_TO_SINT: {
7027 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
7028 SDValue FIST = Vals.first, StackSlot = Vals.second;
7029 if (FIST.getNode() != 0) {
7030 MVT VT = N->getValueType(0);
7031 // Return a load from the stack slot.
7032 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7036 case ISD::READCYCLECOUNTER: {
7037 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7038 SDValue TheChain = N->getOperand(0);
7039 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7040 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7042 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7044 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7045 SDValue Ops[] = { eax, edx };
7046 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7047 Results.push_back(edx.getValue(1));
7050 case ISD::ATOMIC_CMP_SWAP: {
7051 MVT T = N->getValueType(0);
7052 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7053 SDValue cpInL, cpInH;
7054 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7055 DAG.getConstant(0, MVT::i32));
7056 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7057 DAG.getConstant(1, MVT::i32));
7058 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7059 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7061 SDValue swapInL, swapInH;
7062 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7063 DAG.getConstant(0, MVT::i32));
7064 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7065 DAG.getConstant(1, MVT::i32));
7066 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7068 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7069 swapInL.getValue(1));
7070 SDValue Ops[] = { swapInH.getValue(0),
7072 swapInH.getValue(1) };
7073 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7074 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7075 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7076 MVT::i32, Result.getValue(1));
7077 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7078 MVT::i32, cpOutL.getValue(2));
7079 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7080 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7081 Results.push_back(cpOutH.getValue(1));
7084 case ISD::ATOMIC_LOAD_ADD:
7085 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7087 case ISD::ATOMIC_LOAD_AND:
7088 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7090 case ISD::ATOMIC_LOAD_NAND:
7091 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7093 case ISD::ATOMIC_LOAD_OR:
7094 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7096 case ISD::ATOMIC_LOAD_SUB:
7097 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7099 case ISD::ATOMIC_LOAD_XOR:
7100 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7102 case ISD::ATOMIC_SWAP:
7103 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7108 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7110 default: return NULL;
7111 case X86ISD::BSF: return "X86ISD::BSF";
7112 case X86ISD::BSR: return "X86ISD::BSR";
7113 case X86ISD::SHLD: return "X86ISD::SHLD";
7114 case X86ISD::SHRD: return "X86ISD::SHRD";
7115 case X86ISD::FAND: return "X86ISD::FAND";
7116 case X86ISD::FOR: return "X86ISD::FOR";
7117 case X86ISD::FXOR: return "X86ISD::FXOR";
7118 case X86ISD::FSRL: return "X86ISD::FSRL";
7119 case X86ISD::FILD: return "X86ISD::FILD";
7120 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7121 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7122 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7123 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7124 case X86ISD::FLD: return "X86ISD::FLD";
7125 case X86ISD::FST: return "X86ISD::FST";
7126 case X86ISD::CALL: return "X86ISD::CALL";
7127 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
7128 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7129 case X86ISD::BT: return "X86ISD::BT";
7130 case X86ISD::CMP: return "X86ISD::CMP";
7131 case X86ISD::COMI: return "X86ISD::COMI";
7132 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7133 case X86ISD::SETCC: return "X86ISD::SETCC";
7134 case X86ISD::CMOV: return "X86ISD::CMOV";
7135 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7136 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7137 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7138 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7139 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7140 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7141 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7142 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7143 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7144 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7145 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7146 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7147 case X86ISD::FMAX: return "X86ISD::FMAX";
7148 case X86ISD::FMIN: return "X86ISD::FMIN";
7149 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7150 case X86ISD::FRCP: return "X86ISD::FRCP";
7151 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7152 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
7153 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7154 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7155 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7156 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7157 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7158 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7159 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7160 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7161 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7162 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7163 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7164 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7165 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7166 case X86ISD::VSHL: return "X86ISD::VSHL";
7167 case X86ISD::VSRL: return "X86ISD::VSRL";
7168 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7169 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7170 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7171 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7172 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7173 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7174 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7175 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7176 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7177 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7178 case X86ISD::ADD: return "X86ISD::ADD";
7179 case X86ISD::SUB: return "X86ISD::SUB";
7180 case X86ISD::SMUL: return "X86ISD::SMUL";
7181 case X86ISD::UMUL: return "X86ISD::UMUL";
7182 case X86ISD::INC: return "X86ISD::INC";
7183 case X86ISD::DEC: return "X86ISD::DEC";
7184 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7188 // isLegalAddressingMode - Return true if the addressing mode represented
7189 // by AM is legal for this target, for a load/store of the specified type.
7190 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7191 const Type *Ty) const {
7192 // X86 supports extremely general addressing modes.
7194 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7195 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7199 // We can only fold this if we don't need an extra load.
7200 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
7202 // If BaseGV requires a register, we cannot also have a BaseReg.
7203 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
7207 // X86-64 only supports addr of globals in small code model.
7208 if (Subtarget->is64Bit()) {
7209 if (getTargetMachine().getCodeModel() != CodeModel::Small)
7211 // If lower 4G is not available, then we must use rip-relative addressing.
7212 if (AM.BaseOffs || AM.Scale > 1)
7223 // These scales always work.
7228 // These scales are formed with basereg+scalereg. Only accept if there is
7233 default: // Other stuff never works.
7241 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7242 if (!Ty1->isInteger() || !Ty2->isInteger())
7244 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7245 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7246 if (NumBits1 <= NumBits2)
7248 return Subtarget->is64Bit() || NumBits1 < 64;
7251 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7252 if (!VT1.isInteger() || !VT2.isInteger())
7254 unsigned NumBits1 = VT1.getSizeInBits();
7255 unsigned NumBits2 = VT2.getSizeInBits();
7256 if (NumBits1 <= NumBits2)
7258 return Subtarget->is64Bit() || NumBits1 < 64;
7261 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7262 // x86-64 has implicitly zero-extends 32-bit results in 64-bit registers.
7263 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
7266 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
7267 // x86-64 has implicitly zero-extends 32-bit results in 64-bit registers.
7268 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7271 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7272 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7273 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7274 /// are assumed to be legal.
7276 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
7277 // Only do shuffles on 128-bit vector types for now.
7278 // FIXME: pshufb, blends
7279 if (VT.getSizeInBits() == 64) return false;
7280 return (Mask.getNode()->getNumOperands() <= 4 ||
7281 isIdentityMask(Mask.getNode()) ||
7282 isIdentityMask(Mask.getNode(), true) ||
7283 isSplatMask(Mask.getNode()) ||
7284 X86::isPSHUFHWMask(Mask.getNode()) ||
7285 X86::isPSHUFLWMask(Mask.getNode()) ||
7286 X86::isUNPCKLMask(Mask.getNode()) ||
7287 X86::isUNPCKHMask(Mask.getNode()) ||
7288 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
7289 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
7293 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
7294 MVT EVT, SelectionDAG &DAG) const {
7295 unsigned NumElts = BVOps.size();
7296 // Only do shuffles on 128-bit vector types for now.
7297 if (EVT.getSizeInBits() * NumElts == 64) return false;
7298 if (NumElts == 2) return true;
7300 return (isMOVLMask(&BVOps[0], 4) ||
7301 isCommutedMOVL(&BVOps[0], 4, true) ||
7302 isSHUFPMask(&BVOps[0], 4) ||
7303 isCommutedSHUFP(&BVOps[0], 4));
7308 //===----------------------------------------------------------------------===//
7309 // X86 Scheduler Hooks
7310 //===----------------------------------------------------------------------===//
7312 // private utility function
7314 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7315 MachineBasicBlock *MBB,
7323 TargetRegisterClass *RC,
7324 bool invSrc) const {
7325 // For the atomic bitwise operator, we generate
7328 // ld t1 = [bitinstr.addr]
7329 // op t2 = t1, [bitinstr.val]
7331 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7333 // fallthrough -->nextMBB
7334 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7335 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7336 MachineFunction::iterator MBBIter = MBB;
7339 /// First build the CFG
7340 MachineFunction *F = MBB->getParent();
7341 MachineBasicBlock *thisMBB = MBB;
7342 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7343 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7344 F->insert(MBBIter, newMBB);
7345 F->insert(MBBIter, nextMBB);
7347 // Move all successors to thisMBB to nextMBB
7348 nextMBB->transferSuccessors(thisMBB);
7350 // Update thisMBB to fall through to newMBB
7351 thisMBB->addSuccessor(newMBB);
7353 // newMBB jumps to itself and fall through to nextMBB
7354 newMBB->addSuccessor(nextMBB);
7355 newMBB->addSuccessor(newMBB);
7357 // Insert instructions into newMBB based on incoming instruction
7358 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7359 "unexpected number of operands");
7360 DebugLoc dl = bInstr->getDebugLoc();
7361 MachineOperand& destOper = bInstr->getOperand(0);
7362 MachineOperand* argOpers[2 + X86AddrNumOperands];
7363 int numArgs = bInstr->getNumOperands() - 1;
7364 for (int i=0; i < numArgs; ++i)
7365 argOpers[i] = &bInstr->getOperand(i+1);
7367 // x86 address has 4 operands: base, index, scale, and displacement
7368 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7369 int valArgIndx = lastAddrIndx + 1;
7371 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7372 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7373 for (int i=0; i <= lastAddrIndx; ++i)
7374 (*MIB).addOperand(*argOpers[i]);
7376 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7378 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7383 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7384 assert((argOpers[valArgIndx]->isReg() ||
7385 argOpers[valArgIndx]->isImm()) &&
7387 if (argOpers[valArgIndx]->isReg())
7388 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7390 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7392 (*MIB).addOperand(*argOpers[valArgIndx]);
7394 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7397 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7398 for (int i=0; i <= lastAddrIndx; ++i)
7399 (*MIB).addOperand(*argOpers[i]);
7401 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7402 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7404 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7408 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7410 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7414 // private utility function: 64 bit atomics on 32 bit host.
7416 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7417 MachineBasicBlock *MBB,
7422 bool invSrc) const {
7423 // For the atomic bitwise operator, we generate
7424 // thisMBB (instructions are in pairs, except cmpxchg8b)
7425 // ld t1,t2 = [bitinstr.addr]
7427 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7428 // op t5, t6 <- out1, out2, [bitinstr.val]
7429 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7430 // mov ECX, EBX <- t5, t6
7431 // mov EAX, EDX <- t1, t2
7432 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7433 // mov t3, t4 <- EAX, EDX
7435 // result in out1, out2
7436 // fallthrough -->nextMBB
7438 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7439 const unsigned LoadOpc = X86::MOV32rm;
7440 const unsigned copyOpc = X86::MOV32rr;
7441 const unsigned NotOpc = X86::NOT32r;
7442 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7443 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7444 MachineFunction::iterator MBBIter = MBB;
7447 /// First build the CFG
7448 MachineFunction *F = MBB->getParent();
7449 MachineBasicBlock *thisMBB = MBB;
7450 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7451 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7452 F->insert(MBBIter, newMBB);
7453 F->insert(MBBIter, nextMBB);
7455 // Move all successors to thisMBB to nextMBB
7456 nextMBB->transferSuccessors(thisMBB);
7458 // Update thisMBB to fall through to newMBB
7459 thisMBB->addSuccessor(newMBB);
7461 // newMBB jumps to itself and fall through to nextMBB
7462 newMBB->addSuccessor(nextMBB);
7463 newMBB->addSuccessor(newMBB);
7465 DebugLoc dl = bInstr->getDebugLoc();
7466 // Insert instructions into newMBB based on incoming instruction
7467 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7468 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7469 "unexpected number of operands");
7470 MachineOperand& dest1Oper = bInstr->getOperand(0);
7471 MachineOperand& dest2Oper = bInstr->getOperand(1);
7472 MachineOperand* argOpers[2 + X86AddrNumOperands];
7473 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7474 argOpers[i] = &bInstr->getOperand(i+2);
7476 // x86 address has 4 operands: base, index, scale, and displacement
7477 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7479 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7480 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7481 for (int i=0; i <= lastAddrIndx; ++i)
7482 (*MIB).addOperand(*argOpers[i]);
7483 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7484 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7485 // add 4 to displacement.
7486 for (int i=0; i <= lastAddrIndx-1; ++i)
7487 (*MIB).addOperand(*argOpers[i]);
7488 MachineOperand newOp3 = *(argOpers[3]);
7490 newOp3.setImm(newOp3.getImm()+4);
7492 newOp3.setOffset(newOp3.getOffset()+4);
7493 (*MIB).addOperand(newOp3);
7495 // t3/4 are defined later, at the bottom of the loop
7496 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7497 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7498 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7499 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7500 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7501 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7503 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7504 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7506 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7507 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7513 int valArgIndx = lastAddrIndx + 1;
7514 assert((argOpers[valArgIndx]->isReg() ||
7515 argOpers[valArgIndx]->isImm()) &&
7517 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7518 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7519 if (argOpers[valArgIndx]->isReg())
7520 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7522 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7523 if (regOpcL != X86::MOV32rr)
7525 (*MIB).addOperand(*argOpers[valArgIndx]);
7526 assert(argOpers[valArgIndx + 1]->isReg() ==
7527 argOpers[valArgIndx]->isReg());
7528 assert(argOpers[valArgIndx + 1]->isImm() ==
7529 argOpers[valArgIndx]->isImm());
7530 if (argOpers[valArgIndx + 1]->isReg())
7531 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7533 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7534 if (regOpcH != X86::MOV32rr)
7536 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7538 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7540 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7543 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7545 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7548 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7549 for (int i=0; i <= lastAddrIndx; ++i)
7550 (*MIB).addOperand(*argOpers[i]);
7552 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7553 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7555 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7556 MIB.addReg(X86::EAX);
7557 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7558 MIB.addReg(X86::EDX);
7561 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7563 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7567 // private utility function
7569 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7570 MachineBasicBlock *MBB,
7571 unsigned cmovOpc) const {
7572 // For the atomic min/max operator, we generate
7575 // ld t1 = [min/max.addr]
7576 // mov t2 = [min/max.val]
7578 // cmov[cond] t2 = t1
7580 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7582 // fallthrough -->nextMBB
7584 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7585 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7586 MachineFunction::iterator MBBIter = MBB;
7589 /// First build the CFG
7590 MachineFunction *F = MBB->getParent();
7591 MachineBasicBlock *thisMBB = MBB;
7592 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7593 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7594 F->insert(MBBIter, newMBB);
7595 F->insert(MBBIter, nextMBB);
7597 // Move all successors to thisMBB to nextMBB
7598 nextMBB->transferSuccessors(thisMBB);
7600 // Update thisMBB to fall through to newMBB
7601 thisMBB->addSuccessor(newMBB);
7603 // newMBB jumps to newMBB and fall through to nextMBB
7604 newMBB->addSuccessor(nextMBB);
7605 newMBB->addSuccessor(newMBB);
7607 DebugLoc dl = mInstr->getDebugLoc();
7608 // Insert instructions into newMBB based on incoming instruction
7609 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7610 "unexpected number of operands");
7611 MachineOperand& destOper = mInstr->getOperand(0);
7612 MachineOperand* argOpers[2 + X86AddrNumOperands];
7613 int numArgs = mInstr->getNumOperands() - 1;
7614 for (int i=0; i < numArgs; ++i)
7615 argOpers[i] = &mInstr->getOperand(i+1);
7617 // x86 address has 4 operands: base, index, scale, and displacement
7618 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7619 int valArgIndx = lastAddrIndx + 1;
7621 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7622 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7623 for (int i=0; i <= lastAddrIndx; ++i)
7624 (*MIB).addOperand(*argOpers[i]);
7626 // We only support register and immediate values
7627 assert((argOpers[valArgIndx]->isReg() ||
7628 argOpers[valArgIndx]->isImm()) &&
7631 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7632 if (argOpers[valArgIndx]->isReg())
7633 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7635 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7636 (*MIB).addOperand(*argOpers[valArgIndx]);
7638 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7641 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7646 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7647 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7651 // Cmp and exchange if none has modified the memory location
7652 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7653 for (int i=0; i <= lastAddrIndx; ++i)
7654 (*MIB).addOperand(*argOpers[i]);
7656 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7657 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7659 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7660 MIB.addReg(X86::EAX);
7663 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7665 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7671 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7672 MachineBasicBlock *BB) const {
7673 DebugLoc dl = MI->getDebugLoc();
7674 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7675 switch (MI->getOpcode()) {
7676 default: assert(false && "Unexpected instr type to insert");
7677 case X86::CMOV_V1I64:
7678 case X86::CMOV_FR32:
7679 case X86::CMOV_FR64:
7680 case X86::CMOV_V4F32:
7681 case X86::CMOV_V2F64:
7682 case X86::CMOV_V2I64: {
7683 // To "insert" a SELECT_CC instruction, we actually have to insert the
7684 // diamond control-flow pattern. The incoming instruction knows the
7685 // destination vreg to set, the condition code register to branch on, the
7686 // true/false values to select between, and a branch opcode to use.
7687 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7688 MachineFunction::iterator It = BB;
7694 // cmpTY ccX, r1, r2
7696 // fallthrough --> copy0MBB
7697 MachineBasicBlock *thisMBB = BB;
7698 MachineFunction *F = BB->getParent();
7699 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7700 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7702 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7703 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7704 F->insert(It, copy0MBB);
7705 F->insert(It, sinkMBB);
7706 // Update machine-CFG edges by transferring all successors of the current
7707 // block to the new block which will contain the Phi node for the select.
7708 sinkMBB->transferSuccessors(BB);
7710 // Add the true and fallthrough blocks as its successors.
7711 BB->addSuccessor(copy0MBB);
7712 BB->addSuccessor(sinkMBB);
7715 // %FalseValue = ...
7716 // # fallthrough to sinkMBB
7719 // Update machine-CFG edges
7720 BB->addSuccessor(sinkMBB);
7723 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7726 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7727 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7728 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7730 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7734 case X86::FP32_TO_INT16_IN_MEM:
7735 case X86::FP32_TO_INT32_IN_MEM:
7736 case X86::FP32_TO_INT64_IN_MEM:
7737 case X86::FP64_TO_INT16_IN_MEM:
7738 case X86::FP64_TO_INT32_IN_MEM:
7739 case X86::FP64_TO_INT64_IN_MEM:
7740 case X86::FP80_TO_INT16_IN_MEM:
7741 case X86::FP80_TO_INT32_IN_MEM:
7742 case X86::FP80_TO_INT64_IN_MEM: {
7743 // Change the floating point control register to use "round towards zero"
7744 // mode when truncating to an integer value.
7745 MachineFunction *F = BB->getParent();
7746 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7747 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7749 // Load the old value of the high byte of the control word...
7751 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7752 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7755 // Set the high part to be round to zero...
7756 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7759 // Reload the modified control word now...
7760 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7762 // Restore the memory image of control word to original value
7763 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7766 // Get the X86 opcode to use.
7768 switch (MI->getOpcode()) {
7769 default: assert(0 && "illegal opcode!");
7770 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7771 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7772 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7773 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7774 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7775 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7776 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7777 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7778 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7782 MachineOperand &Op = MI->getOperand(0);
7784 AM.BaseType = X86AddressMode::RegBase;
7785 AM.Base.Reg = Op.getReg();
7787 AM.BaseType = X86AddressMode::FrameIndexBase;
7788 AM.Base.FrameIndex = Op.getIndex();
7790 Op = MI->getOperand(1);
7792 AM.Scale = Op.getImm();
7793 Op = MI->getOperand(2);
7795 AM.IndexReg = Op.getImm();
7796 Op = MI->getOperand(3);
7797 if (Op.isGlobal()) {
7798 AM.GV = Op.getGlobal();
7800 AM.Disp = Op.getImm();
7802 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7803 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7805 // Reload the original control word now.
7806 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7808 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7811 case X86::ATOMAND32:
7812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7813 X86::AND32ri, X86::MOV32rm,
7814 X86::LCMPXCHG32, X86::MOV32rr,
7815 X86::NOT32r, X86::EAX,
7816 X86::GR32RegisterClass);
7818 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7819 X86::OR32ri, X86::MOV32rm,
7820 X86::LCMPXCHG32, X86::MOV32rr,
7821 X86::NOT32r, X86::EAX,
7822 X86::GR32RegisterClass);
7823 case X86::ATOMXOR32:
7824 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7825 X86::XOR32ri, X86::MOV32rm,
7826 X86::LCMPXCHG32, X86::MOV32rr,
7827 X86::NOT32r, X86::EAX,
7828 X86::GR32RegisterClass);
7829 case X86::ATOMNAND32:
7830 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7831 X86::AND32ri, X86::MOV32rm,
7832 X86::LCMPXCHG32, X86::MOV32rr,
7833 X86::NOT32r, X86::EAX,
7834 X86::GR32RegisterClass, true);
7835 case X86::ATOMMIN32:
7836 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7837 case X86::ATOMMAX32:
7838 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7839 case X86::ATOMUMIN32:
7840 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7841 case X86::ATOMUMAX32:
7842 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7844 case X86::ATOMAND16:
7845 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7846 X86::AND16ri, X86::MOV16rm,
7847 X86::LCMPXCHG16, X86::MOV16rr,
7848 X86::NOT16r, X86::AX,
7849 X86::GR16RegisterClass);
7851 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7852 X86::OR16ri, X86::MOV16rm,
7853 X86::LCMPXCHG16, X86::MOV16rr,
7854 X86::NOT16r, X86::AX,
7855 X86::GR16RegisterClass);
7856 case X86::ATOMXOR16:
7857 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7858 X86::XOR16ri, X86::MOV16rm,
7859 X86::LCMPXCHG16, X86::MOV16rr,
7860 X86::NOT16r, X86::AX,
7861 X86::GR16RegisterClass);
7862 case X86::ATOMNAND16:
7863 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7864 X86::AND16ri, X86::MOV16rm,
7865 X86::LCMPXCHG16, X86::MOV16rr,
7866 X86::NOT16r, X86::AX,
7867 X86::GR16RegisterClass, true);
7868 case X86::ATOMMIN16:
7869 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7870 case X86::ATOMMAX16:
7871 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7872 case X86::ATOMUMIN16:
7873 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7874 case X86::ATOMUMAX16:
7875 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7878 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7879 X86::AND8ri, X86::MOV8rm,
7880 X86::LCMPXCHG8, X86::MOV8rr,
7881 X86::NOT8r, X86::AL,
7882 X86::GR8RegisterClass);
7884 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7885 X86::OR8ri, X86::MOV8rm,
7886 X86::LCMPXCHG8, X86::MOV8rr,
7887 X86::NOT8r, X86::AL,
7888 X86::GR8RegisterClass);
7890 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7891 X86::XOR8ri, X86::MOV8rm,
7892 X86::LCMPXCHG8, X86::MOV8rr,
7893 X86::NOT8r, X86::AL,
7894 X86::GR8RegisterClass);
7895 case X86::ATOMNAND8:
7896 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7897 X86::AND8ri, X86::MOV8rm,
7898 X86::LCMPXCHG8, X86::MOV8rr,
7899 X86::NOT8r, X86::AL,
7900 X86::GR8RegisterClass, true);
7901 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7902 // This group is for 64-bit host.
7903 case X86::ATOMAND64:
7904 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7905 X86::AND64ri32, X86::MOV64rm,
7906 X86::LCMPXCHG64, X86::MOV64rr,
7907 X86::NOT64r, X86::RAX,
7908 X86::GR64RegisterClass);
7910 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7911 X86::OR64ri32, X86::MOV64rm,
7912 X86::LCMPXCHG64, X86::MOV64rr,
7913 X86::NOT64r, X86::RAX,
7914 X86::GR64RegisterClass);
7915 case X86::ATOMXOR64:
7916 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7917 X86::XOR64ri32, X86::MOV64rm,
7918 X86::LCMPXCHG64, X86::MOV64rr,
7919 X86::NOT64r, X86::RAX,
7920 X86::GR64RegisterClass);
7921 case X86::ATOMNAND64:
7922 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7923 X86::AND64ri32, X86::MOV64rm,
7924 X86::LCMPXCHG64, X86::MOV64rr,
7925 X86::NOT64r, X86::RAX,
7926 X86::GR64RegisterClass, true);
7927 case X86::ATOMMIN64:
7928 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7929 case X86::ATOMMAX64:
7930 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7931 case X86::ATOMUMIN64:
7932 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7933 case X86::ATOMUMAX64:
7934 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7936 // This group does 64-bit operations on a 32-bit host.
7937 case X86::ATOMAND6432:
7938 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7939 X86::AND32rr, X86::AND32rr,
7940 X86::AND32ri, X86::AND32ri,
7942 case X86::ATOMOR6432:
7943 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7944 X86::OR32rr, X86::OR32rr,
7945 X86::OR32ri, X86::OR32ri,
7947 case X86::ATOMXOR6432:
7948 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7949 X86::XOR32rr, X86::XOR32rr,
7950 X86::XOR32ri, X86::XOR32ri,
7952 case X86::ATOMNAND6432:
7953 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7954 X86::AND32rr, X86::AND32rr,
7955 X86::AND32ri, X86::AND32ri,
7957 case X86::ATOMADD6432:
7958 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7959 X86::ADD32rr, X86::ADC32rr,
7960 X86::ADD32ri, X86::ADC32ri,
7962 case X86::ATOMSUB6432:
7963 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7964 X86::SUB32rr, X86::SBB32rr,
7965 X86::SUB32ri, X86::SBB32ri,
7967 case X86::ATOMSWAP6432:
7968 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7969 X86::MOV32rr, X86::MOV32rr,
7970 X86::MOV32ri, X86::MOV32ri,
7975 //===----------------------------------------------------------------------===//
7976 // X86 Optimization Hooks
7977 //===----------------------------------------------------------------------===//
7979 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7983 const SelectionDAG &DAG,
7984 unsigned Depth) const {
7985 unsigned Opc = Op.getOpcode();
7986 assert((Opc >= ISD::BUILTIN_OP_END ||
7987 Opc == ISD::INTRINSIC_WO_CHAIN ||
7988 Opc == ISD::INTRINSIC_W_CHAIN ||
7989 Opc == ISD::INTRINSIC_VOID) &&
7990 "Should use MaskedValueIsZero if you don't know whether Op"
7991 " is a target node!");
7993 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8002 // These nodes' second result is a boolean.
8003 if (Op.getResNo() == 0)
8007 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8008 Mask.getBitWidth() - 1);
8013 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8014 /// node is a GlobalAddress + offset.
8015 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8016 GlobalValue* &GA, int64_t &Offset) const{
8017 if (N->getOpcode() == X86ISD::Wrapper) {
8018 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8019 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8020 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8024 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8027 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8028 const TargetLowering &TLI) {
8031 if (TLI.isGAPlusOffset(Base, GV, Offset))
8032 return (GV->getAlignment() >= N && (Offset % N) == 0);
8033 // DAG combine handles the stack object case.
8037 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
8038 unsigned NumElems, MVT EVT,
8040 SelectionDAG &DAG, MachineFrameInfo *MFI,
8041 const TargetLowering &TLI) {
8043 for (unsigned i = 0; i < NumElems; ++i) {
8044 SDValue Idx = PermMask.getOperand(i);
8045 if (Idx.getOpcode() == ISD::UNDEF) {
8051 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8052 if (!Elt.getNode() ||
8053 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8056 Base = Elt.getNode();
8057 if (Base->getOpcode() == ISD::UNDEF)
8061 if (Elt.getOpcode() == ISD::UNDEF)
8064 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
8065 EVT.getSizeInBits()/8, i, MFI))
8071 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8072 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8073 /// if the load addresses are consecutive, non-overlapping, and in the right
8074 /// order. In the case of v2i64, it will see if it can rewrite the
8075 /// shuffle to be an appropriate build vector so it can take advantage of
8076 // performBuildVectorCombine.
8077 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8078 const TargetLowering &TLI) {
8079 DebugLoc dl = N->getDebugLoc();
8080 MVT VT = N->getValueType(0);
8081 MVT EVT = VT.getVectorElementType();
8082 SDValue PermMask = N->getOperand(2);
8083 unsigned NumElems = PermMask.getNumOperands();
8085 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
8086 // where the upper half is 0, it is advantageous to rewrite it as a build
8087 // vector of (0, val) so it can use movq.
8088 if (VT == MVT::v2i64) {
8090 In[0] = N->getOperand(0);
8091 In[1] = N->getOperand(1);
8092 unsigned Idx0 =cast<ConstantSDNode>(PermMask.getOperand(0))->getZExtValue();
8093 unsigned Idx1 =cast<ConstantSDNode>(PermMask.getOperand(1))->getZExtValue();
8094 if (In[0].getValueType().getVectorNumElements() == NumElems &&
8095 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
8096 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
8097 ConstantSDNode* InsertVecIdx =
8098 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
8100 InsertVecIdx->getZExtValue() == (Idx0 % 2) &&
8101 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
8102 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
8103 In[Idx0/2].getOperand(1),
8104 In[Idx1/2].getOperand(Idx1 % 2));
8109 // Try to combine a vector_shuffle into a 128-bit load.
8110 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8111 SDNode *Base = NULL;
8112 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
8116 LoadSDNode *LD = cast<LoadSDNode>(Base);
8117 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
8118 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8119 LD->getSrcValue(), LD->getSrcValueOffset(),
8121 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8122 LD->getSrcValue(), LD->getSrcValueOffset(),
8123 LD->isVolatile(), LD->getAlignment());
8126 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
8127 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
8128 TargetLowering::DAGCombinerInfo &DCI,
8129 const X86Subtarget *Subtarget,
8130 const TargetLowering &TLI) {
8131 unsigned NumOps = N->getNumOperands();
8132 DebugLoc dl = N->getDebugLoc();
8134 // Ignore single operand BUILD_VECTOR.
8138 MVT VT = N->getValueType(0);
8139 MVT EVT = VT.getVectorElementType();
8140 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
8141 // We are looking for load i64 and zero extend. We want to transform
8142 // it before legalizer has a chance to expand it. Also look for i64
8143 // BUILD_PAIR bit casted to f64.
8145 // This must be an insertion into a zero vector.
8146 SDValue HighElt = N->getOperand(1);
8147 if (!isZeroNode(HighElt))
8150 // Value must be a load.
8151 SDNode *Base = N->getOperand(0).getNode();
8152 if (!isa<LoadSDNode>(Base)) {
8153 if (Base->getOpcode() != ISD::BIT_CONVERT)
8155 Base = Base->getOperand(0).getNode();
8156 if (!isa<LoadSDNode>(Base))
8160 // Transform it into VZEXT_LOAD addr.
8161 LoadSDNode *LD = cast<LoadSDNode>(Base);
8163 // Load must not be an extload.
8164 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
8167 // Load type should legal type so we don't have to legalize it.
8168 if (!TLI.isTypeLegal(VT))
8171 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8172 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8173 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8174 TargetLowering::TargetLoweringOpt TLO(DAG);
8175 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
8176 DCI.CommitTargetLoweringOpt(TLO);
8180 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8181 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8182 const X86Subtarget *Subtarget) {
8183 DebugLoc DL = N->getDebugLoc();
8184 SDValue Cond = N->getOperand(0);
8185 // Get the LHS/RHS of the select.
8186 SDValue LHS = N->getOperand(1);
8187 SDValue RHS = N->getOperand(2);
8189 // If we have SSE[12] support, try to form min/max nodes.
8190 if (Subtarget->hasSSE2() &&
8191 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8192 Cond.getOpcode() == ISD::SETCC) {
8193 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8195 unsigned Opcode = 0;
8196 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8199 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8202 if (!UnsafeFPMath) break;
8204 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
8206 Opcode = X86ISD::FMIN;
8209 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8212 if (!UnsafeFPMath) break;
8214 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8216 Opcode = X86ISD::FMAX;
8219 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8222 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8225 if (!UnsafeFPMath) break;
8227 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8229 Opcode = X86ISD::FMIN;
8232 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8235 if (!UnsafeFPMath) break;
8237 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8239 Opcode = X86ISD::FMAX;
8245 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8248 // If this is a select between two integer constants, try to do some
8250 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8251 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8252 // Don't do this for crazy integer types.
8253 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8254 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8255 // so that TrueC (the true value) is larger than FalseC.
8256 bool NeedsCondInvert = false;
8258 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8259 // Efficiently invertible.
8260 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8261 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8262 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8263 NeedsCondInvert = true;
8264 std::swap(TrueC, FalseC);
8267 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8268 if (FalseC->getAPIntValue() == 0 &&
8269 TrueC->getAPIntValue().isPowerOf2()) {
8270 if (NeedsCondInvert) // Invert the condition if needed.
8271 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8272 DAG.getConstant(1, Cond.getValueType()));
8274 // Zero extend the condition if needed.
8275 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8277 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8278 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8279 DAG.getConstant(ShAmt, MVT::i8));
8282 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8283 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8284 if (NeedsCondInvert) // Invert the condition if needed.
8285 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8286 DAG.getConstant(1, Cond.getValueType()));
8288 // Zero extend the condition if needed.
8289 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8290 FalseC->getValueType(0), Cond);
8291 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8292 SDValue(FalseC, 0));
8295 // Optimize cases that will turn into an LEA instruction. This requires
8296 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8297 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8298 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8299 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8301 bool isFastMultiplier = false;
8303 switch ((unsigned char)Diff) {
8305 case 1: // result = add base, cond
8306 case 2: // result = lea base( , cond*2)
8307 case 3: // result = lea base(cond, cond*2)
8308 case 4: // result = lea base( , cond*4)
8309 case 5: // result = lea base(cond, cond*4)
8310 case 8: // result = lea base( , cond*8)
8311 case 9: // result = lea base(cond, cond*8)
8312 isFastMultiplier = true;
8317 if (isFastMultiplier) {
8318 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8319 if (NeedsCondInvert) // Invert the condition if needed.
8320 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8321 DAG.getConstant(1, Cond.getValueType()));
8323 // Zero extend the condition if needed.
8324 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8326 // Scale the condition by the difference.
8328 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8329 DAG.getConstant(Diff, Cond.getValueType()));
8331 // Add the base if non-zero.
8332 if (FalseC->getAPIntValue() != 0)
8333 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8334 SDValue(FalseC, 0));
8344 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8345 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8346 TargetLowering::DAGCombinerInfo &DCI) {
8347 DebugLoc DL = N->getDebugLoc();
8349 // If the flag operand isn't dead, don't touch this CMOV.
8350 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8353 // If this is a select between two integer constants, try to do some
8354 // optimizations. Note that the operands are ordered the opposite of SELECT
8356 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8357 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8358 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8359 // larger than FalseC (the false value).
8360 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8362 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8363 CC = X86::GetOppositeBranchCondition(CC);
8364 std::swap(TrueC, FalseC);
8367 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8368 // This is efficient for any integer data type (including i8/i16) and
8370 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8371 SDValue Cond = N->getOperand(3);
8372 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8373 DAG.getConstant(CC, MVT::i8), Cond);
8375 // Zero extend the condition if needed.
8376 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8378 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8379 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8380 DAG.getConstant(ShAmt, MVT::i8));
8381 if (N->getNumValues() == 2) // Dead flag value?
8382 return DCI.CombineTo(N, Cond, SDValue());
8386 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8387 // for any integer data type, including i8/i16.
8388 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8389 SDValue Cond = N->getOperand(3);
8390 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8391 DAG.getConstant(CC, MVT::i8), Cond);
8393 // Zero extend the condition if needed.
8394 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8395 FalseC->getValueType(0), Cond);
8396 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8397 SDValue(FalseC, 0));
8399 if (N->getNumValues() == 2) // Dead flag value?
8400 return DCI.CombineTo(N, Cond, SDValue());
8404 // Optimize cases that will turn into an LEA instruction. This requires
8405 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8406 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8407 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8408 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8410 bool isFastMultiplier = false;
8412 switch ((unsigned char)Diff) {
8414 case 1: // result = add base, cond
8415 case 2: // result = lea base( , cond*2)
8416 case 3: // result = lea base(cond, cond*2)
8417 case 4: // result = lea base( , cond*4)
8418 case 5: // result = lea base(cond, cond*4)
8419 case 8: // result = lea base( , cond*8)
8420 case 9: // result = lea base(cond, cond*8)
8421 isFastMultiplier = true;
8426 if (isFastMultiplier) {
8427 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8428 SDValue Cond = N->getOperand(3);
8429 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8430 DAG.getConstant(CC, MVT::i8), Cond);
8431 // Zero extend the condition if needed.
8432 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8434 // Scale the condition by the difference.
8436 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8437 DAG.getConstant(Diff, Cond.getValueType()));
8439 // Add the base if non-zero.
8440 if (FalseC->getAPIntValue() != 0)
8441 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8442 SDValue(FalseC, 0));
8443 if (N->getNumValues() == 2) // Dead flag value?
8444 return DCI.CombineTo(N, Cond, SDValue());
8454 /// PerformMulCombine - Optimize a single multiply with constant into two
8455 /// in order to implement it with two cheaper instructions, e.g.
8456 /// LEA + SHL, LEA + LEA.
8457 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8458 TargetLowering::DAGCombinerInfo &DCI) {
8459 if (DAG.getMachineFunction().
8460 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8463 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8466 MVT VT = N->getValueType(0);
8470 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8473 uint64_t MulAmt = C->getZExtValue();
8474 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8477 uint64_t MulAmt1 = 0;
8478 uint64_t MulAmt2 = 0;
8479 if ((MulAmt % 9) == 0) {
8481 MulAmt2 = MulAmt / 9;
8482 } else if ((MulAmt % 5) == 0) {
8484 MulAmt2 = MulAmt / 5;
8485 } else if ((MulAmt % 3) == 0) {
8487 MulAmt2 = MulAmt / 3;
8490 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8491 DebugLoc DL = N->getDebugLoc();
8493 if (isPowerOf2_64(MulAmt2) &&
8494 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8495 // If second multiplifer is pow2, issue it first. We want the multiply by
8496 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8498 std::swap(MulAmt1, MulAmt2);
8501 if (isPowerOf2_64(MulAmt1))
8502 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8503 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8505 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8506 DAG.getConstant(MulAmt1, VT));
8508 if (isPowerOf2_64(MulAmt2))
8509 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8510 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8512 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8513 DAG.getConstant(MulAmt2, VT));
8515 // Do not add new nodes to DAG combiner worklist.
8516 DCI.CombineTo(N, NewMul, false);
8522 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8524 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8525 const X86Subtarget *Subtarget) {
8526 // On X86 with SSE2 support, we can transform this to a vector shift if
8527 // all elements are shifted by the same amount. We can't do this in legalize
8528 // because the a constant vector is typically transformed to a constant pool
8529 // so we have no knowledge of the shift amount.
8530 if (!Subtarget->hasSSE2())
8533 MVT VT = N->getValueType(0);
8534 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8537 SDValue ShAmtOp = N->getOperand(1);
8538 MVT EltVT = VT.getVectorElementType();
8539 DebugLoc DL = N->getDebugLoc();
8541 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8542 unsigned NumElts = VT.getVectorNumElements();
8544 for (; i != NumElts; ++i) {
8545 SDValue Arg = ShAmtOp.getOperand(i);
8546 if (Arg.getOpcode() == ISD::UNDEF) continue;
8550 for (; i != NumElts; ++i) {
8551 SDValue Arg = ShAmtOp.getOperand(i);
8552 if (Arg.getOpcode() == ISD::UNDEF) continue;
8553 if (Arg != BaseShAmt) {
8557 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8558 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
8559 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8560 DAG.getIntPtrConstant(0));
8564 if (EltVT.bitsGT(MVT::i32))
8565 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8566 else if (EltVT.bitsLT(MVT::i32))
8567 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8569 // The shift amount is identical so we can do a vector shift.
8570 SDValue ValOp = N->getOperand(0);
8571 switch (N->getOpcode()) {
8573 assert(0 && "Unknown shift opcode!");
8576 if (VT == MVT::v2i64)
8577 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8578 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8580 if (VT == MVT::v4i32)
8581 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8582 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8584 if (VT == MVT::v8i16)
8585 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8586 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8590 if (VT == MVT::v4i32)
8591 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8592 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8594 if (VT == MVT::v8i16)
8595 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8596 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8600 if (VT == MVT::v2i64)
8601 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8602 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8604 if (VT == MVT::v4i32)
8605 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8606 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8608 if (VT == MVT::v8i16)
8609 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8610 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8617 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8618 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8619 const X86Subtarget *Subtarget) {
8620 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8621 // the FP state in cases where an emms may be missing.
8622 // A preferable solution to the general problem is to figure out the right
8623 // places to insert EMMS. This qualifies as a quick hack.
8625 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8626 StoreSDNode *St = cast<StoreSDNode>(N);
8627 MVT VT = St->getValue().getValueType();
8628 if (VT.getSizeInBits() != 64)
8631 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8632 if ((VT.isVector() ||
8633 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8634 isa<LoadSDNode>(St->getValue()) &&
8635 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8636 St->getChain().hasOneUse() && !St->isVolatile()) {
8637 SDNode* LdVal = St->getValue().getNode();
8639 int TokenFactorIndex = -1;
8640 SmallVector<SDValue, 8> Ops;
8641 SDNode* ChainVal = St->getChain().getNode();
8642 // Must be a store of a load. We currently handle two cases: the load
8643 // is a direct child, and it's under an intervening TokenFactor. It is
8644 // possible to dig deeper under nested TokenFactors.
8645 if (ChainVal == LdVal)
8646 Ld = cast<LoadSDNode>(St->getChain());
8647 else if (St->getValue().hasOneUse() &&
8648 ChainVal->getOpcode() == ISD::TokenFactor) {
8649 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8650 if (ChainVal->getOperand(i).getNode() == LdVal) {
8651 TokenFactorIndex = i;
8652 Ld = cast<LoadSDNode>(St->getValue());
8654 Ops.push_back(ChainVal->getOperand(i));
8658 if (!Ld || !ISD::isNormalLoad(Ld))
8661 // If this is not the MMX case, i.e. we are just turning i64 load/store
8662 // into f64 load/store, avoid the transformation if there are multiple
8663 // uses of the loaded value.
8664 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8667 DebugLoc LdDL = Ld->getDebugLoc();
8668 DebugLoc StDL = N->getDebugLoc();
8669 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8670 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8672 if (Subtarget->is64Bit() || F64IsLegal) {
8673 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8674 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8675 Ld->getBasePtr(), Ld->getSrcValue(),
8676 Ld->getSrcValueOffset(), Ld->isVolatile(),
8677 Ld->getAlignment());
8678 SDValue NewChain = NewLd.getValue(1);
8679 if (TokenFactorIndex != -1) {
8680 Ops.push_back(NewChain);
8681 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8684 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8685 St->getSrcValue(), St->getSrcValueOffset(),
8686 St->isVolatile(), St->getAlignment());
8689 // Otherwise, lower to two pairs of 32-bit loads / stores.
8690 SDValue LoAddr = Ld->getBasePtr();
8691 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8692 DAG.getConstant(4, MVT::i32));
8694 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8695 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8696 Ld->isVolatile(), Ld->getAlignment());
8697 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8698 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8700 MinAlign(Ld->getAlignment(), 4));
8702 SDValue NewChain = LoLd.getValue(1);
8703 if (TokenFactorIndex != -1) {
8704 Ops.push_back(LoLd);
8705 Ops.push_back(HiLd);
8706 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8710 LoAddr = St->getBasePtr();
8711 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8712 DAG.getConstant(4, MVT::i32));
8714 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8715 St->getSrcValue(), St->getSrcValueOffset(),
8716 St->isVolatile(), St->getAlignment());
8717 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8719 St->getSrcValueOffset() + 4,
8721 MinAlign(St->getAlignment(), 4));
8722 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8727 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8728 /// X86ISD::FXOR nodes.
8729 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8730 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8731 // F[X]OR(0.0, x) -> x
8732 // F[X]OR(x, 0.0) -> x
8733 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8734 if (C->getValueAPF().isPosZero())
8735 return N->getOperand(1);
8736 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8737 if (C->getValueAPF().isPosZero())
8738 return N->getOperand(0);
8742 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8743 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8744 // FAND(0.0, x) -> 0.0
8745 // FAND(x, 0.0) -> 0.0
8746 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8747 if (C->getValueAPF().isPosZero())
8748 return N->getOperand(0);
8749 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8750 if (C->getValueAPF().isPosZero())
8751 return N->getOperand(1);
8755 static SDValue PerformBTCombine(SDNode *N,
8757 TargetLowering::DAGCombinerInfo &DCI) {
8758 // BT ignores high bits in the bit index operand.
8759 SDValue Op1 = N->getOperand(1);
8760 if (Op1.hasOneUse()) {
8761 unsigned BitWidth = Op1.getValueSizeInBits();
8762 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8763 APInt KnownZero, KnownOne;
8764 TargetLowering::TargetLoweringOpt TLO(DAG);
8765 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8766 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8767 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8768 DCI.CommitTargetLoweringOpt(TLO);
8773 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8774 DAGCombinerInfo &DCI) const {
8775 SelectionDAG &DAG = DCI.DAG;
8776 switch (N->getOpcode()) {
8778 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8779 case ISD::BUILD_VECTOR:
8780 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8781 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8782 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8783 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8786 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8787 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8789 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8790 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8791 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8797 //===----------------------------------------------------------------------===//
8798 // X86 Inline Assembly Support
8799 //===----------------------------------------------------------------------===//
8801 /// getConstraintType - Given a constraint letter, return the type of
8802 /// constraint it is for this target.
8803 X86TargetLowering::ConstraintType
8804 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8805 if (Constraint.size() == 1) {
8806 switch (Constraint[0]) {
8818 return C_RegisterClass;
8826 return TargetLowering::getConstraintType(Constraint);
8829 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8830 /// with another that has more specific requirements based on the type of the
8831 /// corresponding operand.
8832 const char *X86TargetLowering::
8833 LowerXConstraint(MVT ConstraintVT) const {
8834 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8835 // 'f' like normal targets.
8836 if (ConstraintVT.isFloatingPoint()) {
8837 if (Subtarget->hasSSE2())
8839 if (Subtarget->hasSSE1())
8843 return TargetLowering::LowerXConstraint(ConstraintVT);
8846 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8847 /// vector. If it is invalid, don't add anything to Ops.
8848 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8851 std::vector<SDValue>&Ops,
8852 SelectionDAG &DAG) const {
8853 SDValue Result(0, 0);
8855 switch (Constraint) {
8858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8859 if (C->getZExtValue() <= 31) {
8860 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8867 if (C->getZExtValue() <= 63) {
8868 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8875 if (C->getZExtValue() <= 255) {
8876 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8882 // 32-bit signed value
8883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8884 const ConstantInt *CI = C->getConstantIntValue();
8885 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8886 // Widen to 64 bits here to get it sign extended.
8887 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8890 // FIXME gcc accepts some relocatable values here too, but only in certain
8891 // memory models; it's complicated.
8896 // 32-bit unsigned value
8897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8898 const ConstantInt *CI = C->getConstantIntValue();
8899 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8900 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8904 // FIXME gcc accepts some relocatable values here too, but only in certain
8905 // memory models; it's complicated.
8909 // Literal immediates are always ok.
8910 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8911 // Widen to 64 bits here to get it sign extended.
8912 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8916 // If we are in non-pic codegen mode, we allow the address of a global (with
8917 // an optional displacement) to be used with 'i'.
8918 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8921 // Match either (GA) or (GA+C)
8923 Offset = GA->getOffset();
8924 } else if (Op.getOpcode() == ISD::ADD) {
8925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8926 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8928 Offset = GA->getOffset()+C->getZExtValue();
8930 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8931 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8933 Offset = GA->getOffset()+C->getZExtValue();
8941 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(),
8944 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8950 // Otherwise, not valid for this mode.
8955 if (Result.getNode()) {
8956 Ops.push_back(Result);
8959 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8963 std::vector<unsigned> X86TargetLowering::
8964 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8966 if (Constraint.size() == 1) {
8967 // FIXME: not handling fp-stack yet!
8968 switch (Constraint[0]) { // GCC X86 Constraint Letters
8969 default: break; // Unknown constraint letter
8970 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8973 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8974 else if (VT == MVT::i16)
8975 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8976 else if (VT == MVT::i8)
8977 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8978 else if (VT == MVT::i64)
8979 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8984 return std::vector<unsigned>();
8987 std::pair<unsigned, const TargetRegisterClass*>
8988 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8990 // First, see if this is a constraint that directly corresponds to an LLVM
8992 if (Constraint.size() == 1) {
8993 // GCC Constraint Letters
8994 switch (Constraint[0]) {
8996 case 'r': // GENERAL_REGS
8997 case 'R': // LEGACY_REGS
8998 case 'l': // INDEX_REGS
9000 return std::make_pair(0U, X86::GR8RegisterClass);
9002 return std::make_pair(0U, X86::GR16RegisterClass);
9003 if (VT == MVT::i32 || !Subtarget->is64Bit())
9004 return std::make_pair(0U, X86::GR32RegisterClass);
9005 return std::make_pair(0U, X86::GR64RegisterClass);
9006 case 'f': // FP Stack registers.
9007 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9008 // value to the correct fpstack register class.
9009 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9010 return std::make_pair(0U, X86::RFP32RegisterClass);
9011 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9012 return std::make_pair(0U, X86::RFP64RegisterClass);
9013 return std::make_pair(0U, X86::RFP80RegisterClass);
9014 case 'y': // MMX_REGS if MMX allowed.
9015 if (!Subtarget->hasMMX()) break;
9016 return std::make_pair(0U, X86::VR64RegisterClass);
9017 case 'Y': // SSE_REGS if SSE2 allowed
9018 if (!Subtarget->hasSSE2()) break;
9020 case 'x': // SSE_REGS if SSE1 allowed
9021 if (!Subtarget->hasSSE1()) break;
9023 switch (VT.getSimpleVT()) {
9025 // Scalar SSE types.
9028 return std::make_pair(0U, X86::FR32RegisterClass);
9031 return std::make_pair(0U, X86::FR64RegisterClass);
9039 return std::make_pair(0U, X86::VR128RegisterClass);
9045 // Use the default implementation in TargetLowering to convert the register
9046 // constraint into a member of a register class.
9047 std::pair<unsigned, const TargetRegisterClass*> Res;
9048 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9050 // Not found as a standard register?
9051 if (Res.second == 0) {
9052 // GCC calls "st(0)" just plain "st".
9053 if (StringsEqualNoCase("{st}", Constraint)) {
9054 Res.first = X86::ST0;
9055 Res.second = X86::RFP80RegisterClass;
9057 // 'A' means EAX + EDX.
9058 if (Constraint == "A") {
9059 Res.first = X86::EAX;
9060 Res.second = X86::GRADRegisterClass;
9065 // Otherwise, check to see if this is a register class of the wrong value
9066 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9067 // turn into {ax},{dx}.
9068 if (Res.second->hasType(VT))
9069 return Res; // Correct type already, nothing to do.
9071 // All of the single-register GCC register classes map their values onto
9072 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9073 // really want an 8-bit or 32-bit register, map to the appropriate register
9074 // class and return the appropriate register.
9075 if (Res.second == X86::GR16RegisterClass) {
9076 if (VT == MVT::i8) {
9077 unsigned DestReg = 0;
9078 switch (Res.first) {
9080 case X86::AX: DestReg = X86::AL; break;
9081 case X86::DX: DestReg = X86::DL; break;
9082 case X86::CX: DestReg = X86::CL; break;
9083 case X86::BX: DestReg = X86::BL; break;
9086 Res.first = DestReg;
9087 Res.second = Res.second = X86::GR8RegisterClass;
9089 } else if (VT == MVT::i32) {
9090 unsigned DestReg = 0;
9091 switch (Res.first) {
9093 case X86::AX: DestReg = X86::EAX; break;
9094 case X86::DX: DestReg = X86::EDX; break;
9095 case X86::CX: DestReg = X86::ECX; break;
9096 case X86::BX: DestReg = X86::EBX; break;
9097 case X86::SI: DestReg = X86::ESI; break;
9098 case X86::DI: DestReg = X86::EDI; break;
9099 case X86::BP: DestReg = X86::EBP; break;
9100 case X86::SP: DestReg = X86::ESP; break;
9103 Res.first = DestReg;
9104 Res.second = Res.second = X86::GR32RegisterClass;
9106 } else if (VT == MVT::i64) {
9107 unsigned DestReg = 0;
9108 switch (Res.first) {
9110 case X86::AX: DestReg = X86::RAX; break;
9111 case X86::DX: DestReg = X86::RDX; break;
9112 case X86::CX: DestReg = X86::RCX; break;
9113 case X86::BX: DestReg = X86::RBX; break;
9114 case X86::SI: DestReg = X86::RSI; break;
9115 case X86::DI: DestReg = X86::RDI; break;
9116 case X86::BP: DestReg = X86::RBP; break;
9117 case X86::SP: DestReg = X86::RSP; break;
9120 Res.first = DestReg;
9121 Res.second = Res.second = X86::GR64RegisterClass;
9124 } else if (Res.second == X86::FR32RegisterClass ||
9125 Res.second == X86::FR64RegisterClass ||
9126 Res.second == X86::VR128RegisterClass) {
9127 // Handle references to XMM physical registers that got mapped into the
9128 // wrong class. This can happen with constraints like {xmm0} where the
9129 // target independent register mapper will just pick the first match it can
9130 // find, ignoring the required type.
9132 Res.second = X86::FR32RegisterClass;
9133 else if (VT == MVT::f64)
9134 Res.second = X86::FR64RegisterClass;
9135 else if (X86::VR128RegisterClass->hasType(VT))
9136 Res.second = X86::VR128RegisterClass;
9142 //===----------------------------------------------------------------------===//
9143 // X86 Widen vector type
9144 //===----------------------------------------------------------------------===//
9146 /// getWidenVectorType: given a vector type, returns the type to widen
9147 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9148 /// If there is no vector type that we want to widen to, returns MVT::Other
9149 /// When and where to widen is target dependent based on the cost of
9150 /// scalarizing vs using the wider vector type.
9152 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9153 assert(VT.isVector());
9154 if (isTypeLegal(VT))
9157 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9158 // type based on element type. This would speed up our search (though
9159 // it may not be worth it since the size of the list is relatively
9161 MVT EltVT = VT.getVectorElementType();
9162 unsigned NElts = VT.getVectorNumElements();
9164 // On X86, it make sense to widen any vector wider than 1
9168 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9169 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9170 MVT SVT = (MVT::SimpleValueType)nVT;
9172 if (isTypeLegal(SVT) &&
9173 SVT.getVectorElementType() == EltVT &&
9174 SVT.getVectorNumElements() > NElts)