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 getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
51 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
52 : TargetLowering(TM) {
53 Subtarget = &TM.getSubtarget<X86Subtarget>();
54 X86ScalarSSEf64 = Subtarget->hasSSE2();
55 X86ScalarSSEf32 = Subtarget->hasSSE1();
56 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
58 RegInfo = TM.getRegisterInfo();
61 // Set up the TargetLowering object.
63 // X86 is weird, it always uses i8 for shift amounts and setcc results.
64 setShiftAmountType(MVT::i8);
65 setBooleanContents(ZeroOrOneBooleanContent);
66 setSchedulingPreference(SchedulingForRegPressure);
67 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
68 setStackPointerRegisterToSaveRestore(X86StackPtr);
70 if (Subtarget->isTargetDarwin()) {
71 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
72 setUseUnderscoreSetJmp(false);
73 setUseUnderscoreLongJmp(false);
74 } else if (Subtarget->isTargetMingw()) {
75 // MS runtime is weird: it exports _setjmp, but longjmp!
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(false);
79 setUseUnderscoreSetJmp(true);
80 setUseUnderscoreLongJmp(true);
83 // Set up the register classes.
84 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
85 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
86 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
87 if (Subtarget->is64Bit())
88 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
92 // We don't accept any truncstore of integer registers.
93 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
94 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
96 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
97 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
98 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
100 // SETOEQ and SETUNE require checking two conditions.
101 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
104 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
108 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
110 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
111 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
114 if (Subtarget->is64Bit()) {
115 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 } else if (!UseSoftFloat) {
118 if (X86ScalarSSEf64) {
119 // We have an impenetrably clever algorithm for ui64->double only.
120 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
122 // We have an algorithm for SSE2, and we turn this into a 64-bit
123 // FILD for other targets.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
127 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
129 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
130 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
132 if (!UseSoftFloat && !NoImplicitFloat) {
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
144 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
147 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
148 // are Legal, f80 is custom lowered.
149 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
150 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
152 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
154 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
155 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
157 if (X86ScalarSSEf32) {
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
159 // f32 and f64 cases are Legal, f80 case is not
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
163 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
166 // Handle FP_TO_UINT by promoting the destination to a larger signed
168 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
169 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
172 if (Subtarget->is64Bit()) {
173 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
174 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
175 } else if (!UseSoftFloat) {
176 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
177 // Expand FP_TO_UINT into a select.
178 // FIXME: We would like to use a Custom expander here eventually to do
179 // the optimal thing for SSE vs. the default expansion in the legalizer.
180 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
182 // With SSE3 we can use fisttpll to convert to a signed i64; without
183 // SSE, we're stuck with a fistpll.
184 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
187 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
188 if (!X86ScalarSSEf64) {
189 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
190 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
193 // Scalar integer divide and remainder are lowered to use operations that
194 // produce two results, to match the available instructions. This exposes
195 // the two-result form to trivial CSE, which is able to combine x/y and x%y
196 // into a single instruction.
198 // Scalar integer multiply-high is also lowered to use two-result
199 // operations, to match the available instructions. However, plain multiply
200 // (low) operations are left as Legal, as there are single-result
201 // instructions for this in x86. Using the two-result multiply instructions
202 // when both high and low results are needed must be arranged by dagcombine.
203 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
205 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
206 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
207 setOperationAction(ISD::SREM , MVT::i8 , Expand);
208 setOperationAction(ISD::UREM , MVT::i8 , Expand);
209 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
211 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
212 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
213 setOperationAction(ISD::SREM , MVT::i16 , Expand);
214 setOperationAction(ISD::UREM , MVT::i16 , Expand);
215 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
217 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
218 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
219 setOperationAction(ISD::SREM , MVT::i32 , Expand);
220 setOperationAction(ISD::UREM , MVT::i32 , Expand);
221 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
222 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
223 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
224 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
225 setOperationAction(ISD::SREM , MVT::i64 , Expand);
226 setOperationAction(ISD::UREM , MVT::i64 , Expand);
228 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
229 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
230 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
231 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
232 if (Subtarget->is64Bit())
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
237 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
238 setOperationAction(ISD::FREM , MVT::f32 , Expand);
239 setOperationAction(ISD::FREM , MVT::f64 , Expand);
240 setOperationAction(ISD::FREM , MVT::f80 , Expand);
241 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
249 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
250 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
251 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
254 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
255 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
258 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
259 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
261 // These should be promoted to a larger select which is supported.
262 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
263 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
264 // X86 wants to expand cmov itself.
265 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
266 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
267 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
268 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
269 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
270 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
271 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
272 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
273 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
274 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
275 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
276 if (Subtarget->is64Bit()) {
277 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
278 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
280 // X86 ret instruction may pop stack.
281 setOperationAction(ISD::RET , MVT::Other, Custom);
282 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
285 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
286 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
287 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
288 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
289 if (Subtarget->is64Bit())
290 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
291 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
292 if (Subtarget->is64Bit()) {
293 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
294 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
295 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
296 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
298 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
299 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
300 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
301 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
302 if (Subtarget->is64Bit()) {
303 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
304 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
305 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
308 if (Subtarget->hasSSE1())
309 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
311 if (!Subtarget->hasSSE2())
312 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
314 // Expand certain atomics
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
325 if (!Subtarget->is64Bit()) {
326 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
332 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
335 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
336 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
337 // FIXME - use subtarget debug flags
338 if (!Subtarget->isTargetDarwin() &&
339 !Subtarget->isTargetELF() &&
340 !Subtarget->isTargetCygMing()) {
341 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
342 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
345 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
346 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
347 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
348 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
349 if (Subtarget->is64Bit()) {
350 setExceptionPointerRegister(X86::RAX);
351 setExceptionSelectorRegister(X86::RDX);
353 setExceptionPointerRegister(X86::EAX);
354 setExceptionSelectorRegister(X86::EDX);
356 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
357 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
359 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
361 setOperationAction(ISD::TRAP, MVT::Other, Legal);
363 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
364 setOperationAction(ISD::VASTART , MVT::Other, Custom);
365 setOperationAction(ISD::VAEND , MVT::Other, Expand);
366 if (Subtarget->is64Bit()) {
367 setOperationAction(ISD::VAARG , MVT::Other, Custom);
368 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
370 setOperationAction(ISD::VAARG , MVT::Other, Expand);
371 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
374 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
375 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
376 if (Subtarget->is64Bit())
377 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
378 if (Subtarget->isTargetCygMing())
379 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
381 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
383 if (!UseSoftFloat && X86ScalarSSEf64) {
384 // f32 and f64 use SSE.
385 // Set up the FP register classes.
386 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
387 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
389 // Use ANDPD to simulate FABS.
390 setOperationAction(ISD::FABS , MVT::f64, Custom);
391 setOperationAction(ISD::FABS , MVT::f32, Custom);
393 // Use XORP to simulate FNEG.
394 setOperationAction(ISD::FNEG , MVT::f64, Custom);
395 setOperationAction(ISD::FNEG , MVT::f32, Custom);
397 // Use ANDPD and ORPD to simulate FCOPYSIGN.
398 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
399 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
401 // We don't support sin/cos/fmod
402 setOperationAction(ISD::FSIN , MVT::f64, Expand);
403 setOperationAction(ISD::FCOS , MVT::f64, Expand);
404 setOperationAction(ISD::FSIN , MVT::f32, Expand);
405 setOperationAction(ISD::FCOS , MVT::f32, Expand);
407 // Expand FP immediates into loads from the stack, except for the special
409 addLegalFPImmediate(APFloat(+0.0)); // xorpd
410 addLegalFPImmediate(APFloat(+0.0f)); // xorps
411 } else if (!UseSoftFloat && X86ScalarSSEf32) {
412 // Use SSE for f32, x87 for f64.
413 // Set up the FP register classes.
414 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
415 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
417 // Use ANDPS to simulate FABS.
418 setOperationAction(ISD::FABS , MVT::f32, Custom);
420 // Use XORP to simulate FNEG.
421 setOperationAction(ISD::FNEG , MVT::f32, Custom);
423 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
425 // Use ANDPS and ORPS to simulate FCOPYSIGN.
426 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
427 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
429 // We don't support sin/cos/fmod
430 setOperationAction(ISD::FSIN , MVT::f32, Expand);
431 setOperationAction(ISD::FCOS , MVT::f32, Expand);
433 // Special cases we handle for FP constants.
434 addLegalFPImmediate(APFloat(+0.0f)); // xorps
435 addLegalFPImmediate(APFloat(+0.0)); // FLD0
436 addLegalFPImmediate(APFloat(+1.0)); // FLD1
437 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
438 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
441 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
442 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
444 } else if (!UseSoftFloat) {
445 // f32 and f64 in x87.
446 // Set up the FP register classes.
447 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
448 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
450 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
451 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
452 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
453 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
456 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
457 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
459 addLegalFPImmediate(APFloat(+0.0)); // FLD0
460 addLegalFPImmediate(APFloat(+1.0)); // FLD1
461 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
462 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
463 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
464 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
465 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
466 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
469 // Long double always uses X87.
471 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
472 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
473 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
476 APFloat TmpFlt(+0.0);
477 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
479 addLegalFPImmediate(TmpFlt); // FLD0
481 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
482 APFloat TmpFlt2(+1.0);
483 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
485 addLegalFPImmediate(TmpFlt2); // FLD1
486 TmpFlt2.changeSign();
487 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
491 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
492 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
496 // Always use a library call for pow.
497 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
498 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
499 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
501 setOperationAction(ISD::FLOG, MVT::f80, Expand);
502 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
503 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
504 setOperationAction(ISD::FEXP, MVT::f80, Expand);
505 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
507 // First set operation action for all vector types to either promote
508 // (for widening) or expand (for scalarization). Then we will selectively
509 // turn on ones that can be effectively codegen'd.
510 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
511 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
512 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
527 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
528 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
558 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
559 // with -msoft-float, disable use of MMX as well.
560 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
561 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
562 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
563 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
564 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
565 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
567 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
568 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
569 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
570 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
572 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
573 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
574 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
575 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
577 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
578 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
580 setOperationAction(ISD::AND, MVT::v8i8, Promote);
581 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
582 setOperationAction(ISD::AND, MVT::v4i16, Promote);
583 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
584 setOperationAction(ISD::AND, MVT::v2i32, Promote);
585 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
586 setOperationAction(ISD::AND, MVT::v1i64, Legal);
588 setOperationAction(ISD::OR, MVT::v8i8, Promote);
589 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
590 setOperationAction(ISD::OR, MVT::v4i16, Promote);
591 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
592 setOperationAction(ISD::OR, MVT::v2i32, Promote);
593 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
594 setOperationAction(ISD::OR, MVT::v1i64, Legal);
596 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
597 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
598 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
599 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
600 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
601 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
602 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
604 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
605 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
606 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
607 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
608 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
609 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
610 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
611 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
612 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
616 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
622 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
623 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
625 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
626 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
627 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
630 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
632 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
633 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
634 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
635 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
636 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
637 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
640 if (!UseSoftFloat && Subtarget->hasSSE1()) {
641 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
643 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
644 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
645 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
646 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
647 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
648 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
649 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
650 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
651 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
652 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
653 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
654 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
657 if (!UseSoftFloat && Subtarget->hasSSE2()) {
658 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
660 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
661 // registers cannot be used even for integer operations.
662 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
663 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
664 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
665 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
667 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
668 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
669 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
670 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
671 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
672 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
673 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
674 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
675 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
676 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
677 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
678 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
679 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
680 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
681 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
682 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
684 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
685 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
686 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
689 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
690 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
691 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
695 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
696 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
697 MVT VT = (MVT::SimpleValueType)i;
698 // Do not attempt to custom lower non-power-of-2 vectors
699 if (!isPowerOf2_32(VT.getVectorNumElements()))
701 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
702 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
706 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
707 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
708 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
709 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
710 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
713 if (Subtarget->is64Bit()) {
714 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
718 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
719 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
720 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
721 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
722 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
723 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
724 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
725 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
726 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
727 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
728 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
729 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
732 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
734 // Custom lower v2i64 and v2f64 selects.
735 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
736 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
737 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
738 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
742 if (Subtarget->hasSSE41()) {
743 // FIXME: Do we need to handle scalar-to-vector here?
744 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
746 // i8 and i16 vectors are custom , because the source register and source
747 // source memory operand types are not the same width. f32 vectors are
748 // custom since the immediate controlling the insert encodes additional
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
756 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
757 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
758 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
760 if (Subtarget->is64Bit()) {
761 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
766 if (Subtarget->hasSSE42()) {
767 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
770 // We want to custom lower some of our intrinsics.
771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
773 // Add/Sub/Mul with overflow operations are custom lowered.
774 setOperationAction(ISD::SADDO, MVT::i32, Custom);
775 setOperationAction(ISD::SADDO, MVT::i64, Custom);
776 setOperationAction(ISD::UADDO, MVT::i32, Custom);
777 setOperationAction(ISD::UADDO, MVT::i64, Custom);
778 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
779 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
780 setOperationAction(ISD::USUBO, MVT::i32, Custom);
781 setOperationAction(ISD::USUBO, MVT::i64, Custom);
782 setOperationAction(ISD::SMULO, MVT::i32, Custom);
783 setOperationAction(ISD::SMULO, MVT::i64, Custom);
784 setOperationAction(ISD::UMULO, MVT::i32, Custom);
785 setOperationAction(ISD::UMULO, MVT::i64, Custom);
787 if (!Subtarget->is64Bit()) {
788 // These libcalls are not available in 32-bit.
789 setLibcallName(RTLIB::SHL_I128, 0);
790 setLibcallName(RTLIB::SRL_I128, 0);
791 setLibcallName(RTLIB::SRA_I128, 0);
794 // We have target-specific dag combine patterns for the following nodes:
795 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
796 setTargetDAGCombine(ISD::BUILD_VECTOR);
797 setTargetDAGCombine(ISD::SELECT);
798 setTargetDAGCombine(ISD::SHL);
799 setTargetDAGCombine(ISD::SRA);
800 setTargetDAGCombine(ISD::SRL);
801 setTargetDAGCombine(ISD::STORE);
802 if (Subtarget->is64Bit())
803 setTargetDAGCombine(ISD::MUL);
805 computeRegisterProperties();
807 // FIXME: These should be based on subtarget info. Plus, the values should
808 // be smaller when we are in optimizing for size mode.
809 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
810 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
811 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
812 allowUnalignedMemoryAccesses = true; // x86 supports it!
813 setPrefLoopAlignment(16);
814 benefitFromCodePlacementOpt = true;
818 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
823 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
824 /// the desired ByVal argument alignment.
825 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
828 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
829 if (VTy->getBitWidth() == 128)
831 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
832 unsigned EltAlign = 0;
833 getMaxByValAlign(ATy->getElementType(), EltAlign);
834 if (EltAlign > MaxAlign)
836 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
837 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
838 unsigned EltAlign = 0;
839 getMaxByValAlign(STy->getElementType(i), EltAlign);
840 if (EltAlign > MaxAlign)
849 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
850 /// function arguments in the caller parameter area. For X86, aggregates
851 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
852 /// are at 4-byte boundaries.
853 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
854 if (Subtarget->is64Bit()) {
855 // Max of 8 and alignment of type.
856 unsigned TyAlign = TD->getABITypeAlignment(Ty);
863 if (Subtarget->hasSSE1())
864 getMaxByValAlign(Ty, Align);
868 /// getOptimalMemOpType - Returns the target specific optimal type for load
869 /// and store operations as a result of memset, memcpy, and memmove
870 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
873 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
874 bool isSrcConst, bool isSrcStr) const {
875 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
876 // linux. This is because the stack realignment code can't handle certain
877 // cases like PR2962. This should be removed when PR2962 is fixed.
878 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
879 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
881 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
884 if (Subtarget->is64Bit() && Size >= 8)
889 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
891 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
892 SelectionDAG &DAG) const {
893 if (usesGlobalOffsetTable())
894 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
895 if (!Subtarget->isPICStyleRIPRel())
896 // This doesn't have DebugLoc associated with it, but is not really the
897 // same as a Register.
898 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
903 //===----------------------------------------------------------------------===//
904 // Return Value Calling Convention Implementation
905 //===----------------------------------------------------------------------===//
907 #include "X86GenCallingConv.inc"
909 /// LowerRET - Lower an ISD::RET node.
910 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
911 DebugLoc dl = Op.getDebugLoc();
912 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
914 SmallVector<CCValAssign, 16> RVLocs;
915 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
916 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
917 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
918 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
920 // If this is the first return lowered for this function, add the regs to the
921 // liveout set for the function.
922 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
923 for (unsigned i = 0; i != RVLocs.size(); ++i)
924 if (RVLocs[i].isRegLoc())
925 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
927 SDValue Chain = Op.getOperand(0);
929 // Handle tail call return.
930 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
931 if (Chain.getOpcode() == X86ISD::TAILCALL) {
932 SDValue TailCall = Chain;
933 SDValue TargetAddress = TailCall.getOperand(1);
934 SDValue StackAdjustment = TailCall.getOperand(2);
935 assert(((TargetAddress.getOpcode() == ISD::Register &&
936 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
937 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
938 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
939 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
940 "Expecting an global address, external symbol, or register");
941 assert(StackAdjustment.getOpcode() == ISD::Constant &&
942 "Expecting a const value");
944 SmallVector<SDValue,8> Operands;
945 Operands.push_back(Chain.getOperand(0));
946 Operands.push_back(TargetAddress);
947 Operands.push_back(StackAdjustment);
948 // Copy registers used by the call. Last operand is a flag so it is not
950 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
951 Operands.push_back(Chain.getOperand(i));
953 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
960 SmallVector<SDValue, 6> RetOps;
961 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
962 // Operand #1 = Bytes To Pop
963 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
965 // Copy the result values into the output registers.
966 for (unsigned i = 0; i != RVLocs.size(); ++i) {
967 CCValAssign &VA = RVLocs[i];
968 assert(VA.isRegLoc() && "Can only return in registers!");
969 SDValue ValToCopy = Op.getOperand(i*2+1);
971 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
972 // the RET instruction and handled by the FP Stackifier.
973 if (VA.getLocReg() == X86::ST0 ||
974 VA.getLocReg() == X86::ST1) {
975 // If this is a copy from an xmm register to ST(0), use an FPExtend to
976 // change the value to the FP stack register class.
977 if (isScalarFPTypeInSSEReg(VA.getValVT()))
978 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
979 RetOps.push_back(ValToCopy);
980 // Don't emit a copytoreg.
984 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
985 // which is returned in RAX / RDX.
986 if (Subtarget->is64Bit()) {
987 MVT ValVT = ValToCopy.getValueType();
988 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
989 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
990 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
991 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
995 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
996 Flag = Chain.getValue(1);
999 // The x86-64 ABI for returning structs by value requires that we copy
1000 // the sret argument into %rax for the return. We saved the argument into
1001 // a virtual register in the entry block, so now we copy the value out
1003 if (Subtarget->is64Bit() &&
1004 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1005 MachineFunction &MF = DAG.getMachineFunction();
1006 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1007 unsigned Reg = FuncInfo->getSRetReturnReg();
1009 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1010 FuncInfo->setSRetReturnReg(Reg);
1012 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1014 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1015 Flag = Chain.getValue(1);
1018 RetOps[0] = Chain; // Update chain.
1020 // Add the flag if we have it.
1022 RetOps.push_back(Flag);
1024 return DAG.getNode(X86ISD::RET_FLAG, dl,
1025 MVT::Other, &RetOps[0], RetOps.size());
1029 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1030 /// appropriate copies out of appropriate physical registers. This assumes that
1031 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1032 /// being lowered. The returns a SDNode with the same number of values as the
1034 SDNode *X86TargetLowering::
1035 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1036 unsigned CallingConv, SelectionDAG &DAG) {
1038 DebugLoc dl = TheCall->getDebugLoc();
1039 // Assign locations to each value returned by this call.
1040 SmallVector<CCValAssign, 16> RVLocs;
1041 bool isVarArg = TheCall->isVarArg();
1042 bool Is64Bit = Subtarget->is64Bit();
1043 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1044 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1046 SmallVector<SDValue, 8> ResultVals;
1048 // Copy all of the result registers out of their specified physreg.
1049 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1050 CCValAssign &VA = RVLocs[i];
1051 MVT CopyVT = VA.getValVT();
1053 // If this is x86-64, and we disabled SSE, we can't return FP values
1054 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1055 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1056 cerr << "SSE register return with SSE disabled\n";
1060 // If this is a call to a function that returns an fp value on the floating
1061 // point stack, but where we prefer to use the value in xmm registers, copy
1062 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1063 if ((VA.getLocReg() == X86::ST0 ||
1064 VA.getLocReg() == X86::ST1) &&
1065 isScalarFPTypeInSSEReg(VA.getValVT())) {
1070 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1071 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1072 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1073 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1074 MVT::v2i64, InFlag).getValue(1);
1075 Val = Chain.getValue(0);
1076 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1077 Val, DAG.getConstant(0, MVT::i64));
1079 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1080 MVT::i64, InFlag).getValue(1);
1081 Val = Chain.getValue(0);
1083 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1085 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1086 CopyVT, InFlag).getValue(1);
1087 Val = Chain.getValue(0);
1089 InFlag = Chain.getValue(2);
1091 if (CopyVT != VA.getValVT()) {
1092 // Round the F80 the right size, which also moves to the appropriate xmm
1094 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1095 // This truncation won't change the value.
1096 DAG.getIntPtrConstant(1));
1099 ResultVals.push_back(Val);
1102 // Merge everything together with a MERGE_VALUES node.
1103 ResultVals.push_back(Chain);
1104 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1105 &ResultVals[0], ResultVals.size()).getNode();
1109 //===----------------------------------------------------------------------===//
1110 // C & StdCall & Fast Calling Convention implementation
1111 //===----------------------------------------------------------------------===//
1112 // StdCall calling convention seems to be standard for many Windows' API
1113 // routines and around. It differs from C calling convention just a little:
1114 // callee should clean up the stack, not caller. Symbols should be also
1115 // decorated in some fancy way :) It doesn't support any vector arguments.
1116 // For info on fast calling convention see Fast Calling Convention (tail call)
1117 // implementation LowerX86_32FastCCCallTo.
1119 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1121 static bool CallIsStructReturn(CallSDNode *TheCall) {
1122 unsigned NumOps = TheCall->getNumArgs();
1126 return TheCall->getArgFlags(0).isSRet();
1129 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1130 /// return semantics.
1131 static bool ArgsAreStructReturn(SDValue Op) {
1132 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1136 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1139 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1140 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1142 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1146 switch (CallingConv) {
1149 case CallingConv::X86_StdCall:
1150 return !Subtarget->is64Bit();
1151 case CallingConv::X86_FastCall:
1152 return !Subtarget->is64Bit();
1153 case CallingConv::Fast:
1154 return PerformTailCallOpt;
1158 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1159 /// given CallingConvention value.
1160 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1161 if (Subtarget->is64Bit()) {
1162 if (Subtarget->isTargetWin64())
1163 return CC_X86_Win64_C;
1164 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1165 return CC_X86_64_TailCall;
1170 if (CC == CallingConv::X86_FastCall)
1171 return CC_X86_32_FastCall;
1172 else if (CC == CallingConv::Fast)
1173 return CC_X86_32_FastCC;
1178 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1179 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1181 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1182 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1183 if (CC == CallingConv::X86_FastCall)
1185 else if (CC == CallingConv::X86_StdCall)
1191 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1192 /// in a register before calling.
1193 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1194 return !IsTailCall && !Is64Bit &&
1195 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1196 Subtarget->isPICStyleGOT();
1199 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1200 /// address to be loaded in a register.
1202 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1203 return !Is64Bit && IsTailCall &&
1204 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205 Subtarget->isPICStyleGOT();
1208 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1209 /// by "Src" to address "Dst" with size and alignment information specified by
1210 /// the specific parameter attribute. The copy will be passed as a byval
1211 /// function parameter.
1213 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1214 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1216 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1217 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1218 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1221 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1222 const CCValAssign &VA,
1223 MachineFrameInfo *MFI,
1225 SDValue Root, unsigned i) {
1226 // Create the nodes corresponding to a load from this parameter slot.
1227 ISD::ArgFlagsTy Flags =
1228 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1229 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1230 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1232 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1233 // changed with more analysis.
1234 // In case of tail call optimization mark all arguments mutable. Since they
1235 // could be overwritten by lowering of arguments in case of a tail call.
1236 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1237 VA.getLocMemOffset(), isImmutable);
1238 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1239 if (Flags.isByVal())
1241 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1242 PseudoSourceValue::getFixedStack(FI), 0);
1246 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1247 MachineFunction &MF = DAG.getMachineFunction();
1248 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1249 DebugLoc dl = Op.getDebugLoc();
1251 const Function* Fn = MF.getFunction();
1252 if (Fn->hasExternalLinkage() &&
1253 Subtarget->isTargetCygMing() &&
1254 Fn->getName() == "main")
1255 FuncInfo->setForceFramePointer(true);
1257 // Decorate the function name.
1258 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1260 MachineFrameInfo *MFI = MF.getFrameInfo();
1261 SDValue Root = Op.getOperand(0);
1262 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1263 unsigned CC = MF.getFunction()->getCallingConv();
1264 bool Is64Bit = Subtarget->is64Bit();
1265 bool IsWin64 = Subtarget->isTargetWin64();
1267 assert(!(isVarArg && CC == CallingConv::Fast) &&
1268 "Var args not supported with calling convention fastcc");
1270 // Assign locations to all of the incoming arguments.
1271 SmallVector<CCValAssign, 16> ArgLocs;
1272 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1273 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1275 SmallVector<SDValue, 8> ArgValues;
1276 unsigned LastVal = ~0U;
1277 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1278 CCValAssign &VA = ArgLocs[i];
1279 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1281 assert(VA.getValNo() != LastVal &&
1282 "Don't support value assigned to multiple locs yet");
1283 LastVal = VA.getValNo();
1285 if (VA.isRegLoc()) {
1286 MVT RegVT = VA.getLocVT();
1287 TargetRegisterClass *RC = NULL;
1288 if (RegVT == MVT::i32)
1289 RC = X86::GR32RegisterClass;
1290 else if (Is64Bit && RegVT == MVT::i64)
1291 RC = X86::GR64RegisterClass;
1292 else if (RegVT == MVT::f32)
1293 RC = X86::FR32RegisterClass;
1294 else if (RegVT == MVT::f64)
1295 RC = X86::FR64RegisterClass;
1296 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1297 RC = X86::VR128RegisterClass;
1298 else if (RegVT.isVector()) {
1299 assert(RegVT.getSizeInBits() == 64);
1301 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1303 // Darwin calling convention passes MMX values in either GPRs or
1304 // XMMs in x86-64. Other targets pass them in memory.
1305 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1306 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1309 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1314 assert(0 && "Unknown argument type!");
1317 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1318 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1320 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1321 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1323 if (VA.getLocInfo() == CCValAssign::SExt)
1324 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1325 DAG.getValueType(VA.getValVT()));
1326 else if (VA.getLocInfo() == CCValAssign::ZExt)
1327 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1328 DAG.getValueType(VA.getValVT()));
1330 if (VA.getLocInfo() != CCValAssign::Full)
1331 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1333 // Handle MMX values passed in GPRs.
1334 if (Is64Bit && RegVT != VA.getLocVT()) {
1335 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1336 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1337 else if (RC == X86::VR128RegisterClass) {
1338 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1339 ArgValue, DAG.getConstant(0, MVT::i64));
1340 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1344 ArgValues.push_back(ArgValue);
1346 assert(VA.isMemLoc());
1347 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1351 // The x86-64 ABI for returning structs by value requires that we copy
1352 // the sret argument into %rax for the return. Save the argument into
1353 // a virtual register so that we can access it from the return points.
1354 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1355 MachineFunction &MF = DAG.getMachineFunction();
1356 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1357 unsigned Reg = FuncInfo->getSRetReturnReg();
1359 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1360 FuncInfo->setSRetReturnReg(Reg);
1362 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1363 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1366 unsigned StackSize = CCInfo.getNextStackOffset();
1367 // align stack specially for tail calls
1368 if (PerformTailCallOpt && CC == CallingConv::Fast)
1369 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1371 // If the function takes variable number of arguments, make a frame index for
1372 // the start of the first vararg value... for expansion of llvm.va_start.
1374 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1375 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1378 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1380 // FIXME: We should really autogenerate these arrays
1381 static const unsigned GPR64ArgRegsWin64[] = {
1382 X86::RCX, X86::RDX, X86::R8, X86::R9
1384 static const unsigned XMMArgRegsWin64[] = {
1385 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1387 static const unsigned GPR64ArgRegs64Bit[] = {
1388 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1390 static const unsigned XMMArgRegs64Bit[] = {
1391 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1392 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1394 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1397 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1398 GPR64ArgRegs = GPR64ArgRegsWin64;
1399 XMMArgRegs = XMMArgRegsWin64;
1401 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1402 GPR64ArgRegs = GPR64ArgRegs64Bit;
1403 XMMArgRegs = XMMArgRegs64Bit;
1405 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1407 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1410 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1411 "SSE register cannot be used when SSE is disabled!");
1412 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1413 "SSE register cannot be used when SSE is disabled!");
1414 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1415 // Kernel mode asks for SSE to be disabled, so don't push them
1417 TotalNumXMMRegs = 0;
1419 // For X86-64, if there are vararg parameters that are passed via
1420 // registers, then we must store them to their spots on the stack so they
1421 // may be loaded by deferencing the result of va_next.
1422 VarArgsGPOffset = NumIntRegs * 8;
1423 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1424 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1425 TotalNumXMMRegs * 16, 16);
1427 // Store the integer parameter registers.
1428 SmallVector<SDValue, 8> MemOps;
1429 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1430 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1431 DAG.getIntPtrConstant(VarArgsGPOffset));
1432 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1433 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1434 X86::GR64RegisterClass);
1435 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1437 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1438 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1439 MemOps.push_back(Store);
1440 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1441 DAG.getIntPtrConstant(8));
1444 // Now store the XMM (fp + vector) parameter registers.
1445 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1446 DAG.getIntPtrConstant(VarArgsFPOffset));
1447 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1448 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1449 X86::VR128RegisterClass);
1450 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1452 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1453 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1454 MemOps.push_back(Store);
1455 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1456 DAG.getIntPtrConstant(16));
1458 if (!MemOps.empty())
1459 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1460 &MemOps[0], MemOps.size());
1464 ArgValues.push_back(Root);
1466 // Some CCs need callee pop.
1467 if (IsCalleePop(isVarArg, CC)) {
1468 BytesToPopOnReturn = StackSize; // Callee pops everything.
1469 BytesCallerReserves = 0;
1471 BytesToPopOnReturn = 0; // Callee pops nothing.
1472 // If this is an sret function, the return should pop the hidden pointer.
1473 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1474 BytesToPopOnReturn = 4;
1475 BytesCallerReserves = StackSize;
1479 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1480 if (CC == CallingConv::X86_FastCall)
1481 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1484 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1486 // Return the new list of results.
1487 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1488 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1492 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1493 const SDValue &StackPtr,
1494 const CCValAssign &VA,
1496 SDValue Arg, ISD::ArgFlagsTy Flags) {
1497 DebugLoc dl = TheCall->getDebugLoc();
1498 unsigned LocMemOffset = VA.getLocMemOffset();
1499 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1500 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1501 if (Flags.isByVal()) {
1502 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1504 return DAG.getStore(Chain, dl, Arg, PtrOff,
1505 PseudoSourceValue::getStack(), LocMemOffset);
1508 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1509 /// optimization is performed and it is required.
1511 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1512 SDValue &OutRetAddr,
1518 if (!IsTailCall || FPDiff==0) return Chain;
1520 // Adjust the Return address stack slot.
1521 MVT VT = getPointerTy();
1522 OutRetAddr = getReturnAddressFrameIndex(DAG);
1524 // Load the "old" Return address.
1525 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1526 return SDValue(OutRetAddr.getNode(), 1);
1529 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1530 /// optimization is performed and it is required (FPDiff!=0).
1532 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1533 SDValue Chain, SDValue RetAddrFrIdx,
1534 bool Is64Bit, int FPDiff, DebugLoc dl) {
1535 // Store the return address to the appropriate stack slot.
1536 if (!FPDiff) return Chain;
1537 // Calculate the new stack slot for the return address.
1538 int SlotSize = Is64Bit ? 8 : 4;
1539 int NewReturnAddrFI =
1540 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1541 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1542 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1543 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1544 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1548 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1549 MachineFunction &MF = DAG.getMachineFunction();
1550 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1551 SDValue Chain = TheCall->getChain();
1552 unsigned CC = TheCall->getCallingConv();
1553 bool isVarArg = TheCall->isVarArg();
1554 bool IsTailCall = TheCall->isTailCall() &&
1555 CC == CallingConv::Fast && PerformTailCallOpt;
1556 SDValue Callee = TheCall->getCallee();
1557 bool Is64Bit = Subtarget->is64Bit();
1558 bool IsStructRet = CallIsStructReturn(TheCall);
1559 DebugLoc dl = TheCall->getDebugLoc();
1561 assert(!(isVarArg && CC == CallingConv::Fast) &&
1562 "Var args not supported with calling convention fastcc");
1564 // Analyze operands of the call, assigning locations to each operand.
1565 SmallVector<CCValAssign, 16> ArgLocs;
1566 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1567 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1569 // Get a count of how many bytes are to be pushed on the stack.
1570 unsigned NumBytes = CCInfo.getNextStackOffset();
1571 if (PerformTailCallOpt && CC == CallingConv::Fast)
1572 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1576 // Lower arguments at fp - stackoffset + fpdiff.
1577 unsigned NumBytesCallerPushed =
1578 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1579 FPDiff = NumBytesCallerPushed - NumBytes;
1581 // Set the delta of movement of the returnaddr stackslot.
1582 // But only set if delta is greater than previous delta.
1583 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1584 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1587 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1589 SDValue RetAddrFrIdx;
1590 // Load return adress for tail calls.
1591 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1594 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1595 SmallVector<SDValue, 8> MemOpChains;
1598 // Walk the register/memloc assignments, inserting copies/loads. In the case
1599 // of tail call optimization arguments are handle later.
1600 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1601 CCValAssign &VA = ArgLocs[i];
1602 SDValue Arg = TheCall->getArg(i);
1603 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1604 bool isByVal = Flags.isByVal();
1606 // Promote the value if needed.
1607 switch (VA.getLocInfo()) {
1608 default: assert(0 && "Unknown loc info!");
1609 case CCValAssign::Full: break;
1610 case CCValAssign::SExt:
1611 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1613 case CCValAssign::ZExt:
1614 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1616 case CCValAssign::AExt:
1617 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1621 if (VA.isRegLoc()) {
1623 MVT RegVT = VA.getLocVT();
1624 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1625 switch (VA.getLocReg()) {
1628 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1630 // Special case: passing MMX values in GPR registers.
1631 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1634 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1635 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1636 // Special case: passing MMX values in XMM registers.
1637 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1638 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1639 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1644 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1646 if (!IsTailCall || (IsTailCall && isByVal)) {
1647 assert(VA.isMemLoc());
1648 if (StackPtr.getNode() == 0)
1649 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1651 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1652 Chain, Arg, Flags));
1657 if (!MemOpChains.empty())
1658 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1659 &MemOpChains[0], MemOpChains.size());
1661 // Build a sequence of copy-to-reg nodes chained together with token chain
1662 // and flag operands which copy the outgoing args into registers.
1664 // Tail call byval lowering might overwrite argument registers so in case of
1665 // tail call optimization the copies to registers are lowered later.
1667 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1668 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1669 RegsToPass[i].second, InFlag);
1670 InFlag = Chain.getValue(1);
1673 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1675 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1676 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1677 DAG.getNode(X86ISD::GlobalBaseReg,
1678 DebugLoc::getUnknownLoc(),
1681 InFlag = Chain.getValue(1);
1683 // If we are tail calling and generating PIC/GOT style code load the address
1684 // of the callee into ecx. The value in ecx is used as target of the tail
1685 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1686 // calls on PIC/GOT architectures. Normally we would just put the address of
1687 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1688 // restored (since ebx is callee saved) before jumping to the target@PLT.
1689 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1690 // Note: The actual moving to ecx is done further down.
1691 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1692 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1693 !G->getGlobal()->hasProtectedVisibility())
1694 Callee = LowerGlobalAddress(Callee, DAG);
1695 else if (isa<ExternalSymbolSDNode>(Callee))
1696 Callee = LowerExternalSymbol(Callee,DAG);
1699 if (Is64Bit && isVarArg) {
1700 // From AMD64 ABI document:
1701 // For calls that may call functions that use varargs or stdargs
1702 // (prototype-less calls or calls to functions containing ellipsis (...) in
1703 // the declaration) %al is used as hidden argument to specify the number
1704 // of SSE registers used. The contents of %al do not need to match exactly
1705 // the number of registers, but must be an ubound on the number of SSE
1706 // registers used and is in the range 0 - 8 inclusive.
1708 // FIXME: Verify this on Win64
1709 // Count the number of XMM registers allocated.
1710 static const unsigned XMMArgRegs[] = {
1711 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1712 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1714 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1715 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1716 && "SSE registers cannot be used when SSE is disabled");
1718 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1719 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1720 InFlag = Chain.getValue(1);
1724 // For tail calls lower the arguments to the 'real' stack slot.
1726 SmallVector<SDValue, 8> MemOpChains2;
1729 // Do not flag preceeding copytoreg stuff together with the following stuff.
1731 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1732 CCValAssign &VA = ArgLocs[i];
1733 if (!VA.isRegLoc()) {
1734 assert(VA.isMemLoc());
1735 SDValue Arg = TheCall->getArg(i);
1736 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1737 // Create frame index.
1738 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1739 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1740 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1741 FIN = DAG.getFrameIndex(FI, getPointerTy());
1743 if (Flags.isByVal()) {
1744 // Copy relative to framepointer.
1745 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1746 if (StackPtr.getNode() == 0)
1747 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1749 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1751 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1754 // Store relative to framepointer.
1755 MemOpChains2.push_back(
1756 DAG.getStore(Chain, dl, Arg, FIN,
1757 PseudoSourceValue::getFixedStack(FI), 0));
1762 if (!MemOpChains2.empty())
1763 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1764 &MemOpChains2[0], MemOpChains2.size());
1766 // Copy arguments to their registers.
1767 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1768 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1769 RegsToPass[i].second, InFlag);
1770 InFlag = Chain.getValue(1);
1774 // Store the return address to the appropriate stack slot.
1775 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1779 // If the callee is a GlobalAddress node (quite common, every direct call is)
1780 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1781 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1782 // We should use extra load for direct calls to dllimported functions in
1784 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1785 getTargetMachine(), true))
1786 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1788 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1789 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1790 } else if (IsTailCall) {
1791 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1793 Chain = DAG.getCopyToReg(Chain, dl,
1794 DAG.getRegister(Opc, getPointerTy()),
1796 Callee = DAG.getRegister(Opc, getPointerTy());
1797 // Add register as live out.
1798 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1801 // Returns a chain & a flag for retval copy to use.
1802 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1803 SmallVector<SDValue, 8> Ops;
1806 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1807 DAG.getIntPtrConstant(0, true), InFlag);
1808 InFlag = Chain.getValue(1);
1810 // Returns a chain & a flag for retval copy to use.
1811 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1815 Ops.push_back(Chain);
1816 Ops.push_back(Callee);
1819 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1821 // Add argument registers to the end of the list so that they are known live
1823 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1824 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1825 RegsToPass[i].second.getValueType()));
1827 // Add an implicit use GOT pointer in EBX.
1828 if (!IsTailCall && !Is64Bit &&
1829 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1830 Subtarget->isPICStyleGOT())
1831 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1833 // Add an implicit use of AL for x86 vararg functions.
1834 if (Is64Bit && isVarArg)
1835 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1837 if (InFlag.getNode())
1838 Ops.push_back(InFlag);
1841 assert(InFlag.getNode() &&
1842 "Flag must be set. Depend on flag being set in LowerRET");
1843 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1844 TheCall->getVTList(), &Ops[0], Ops.size());
1846 return SDValue(Chain.getNode(), Op.getResNo());
1849 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1850 InFlag = Chain.getValue(1);
1852 // Create the CALLSEQ_END node.
1853 unsigned NumBytesForCalleeToPush;
1854 if (IsCalleePop(isVarArg, CC))
1855 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1856 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1857 // If this is is a call to a struct-return function, the callee
1858 // pops the hidden struct pointer, so we have to push it back.
1859 // This is common for Darwin/X86, Linux & Mingw32 targets.
1860 NumBytesForCalleeToPush = 4;
1862 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1864 // Returns a flag for retval copy to use.
1865 Chain = DAG.getCALLSEQ_END(Chain,
1866 DAG.getIntPtrConstant(NumBytes, true),
1867 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1870 InFlag = Chain.getValue(1);
1872 // Handle result values, copying them out of physregs into vregs that we
1874 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1879 //===----------------------------------------------------------------------===//
1880 // Fast Calling Convention (tail call) implementation
1881 //===----------------------------------------------------------------------===//
1883 // Like std call, callee cleans arguments, convention except that ECX is
1884 // reserved for storing the tail called function address. Only 2 registers are
1885 // free for argument passing (inreg). Tail call optimization is performed
1887 // * tailcallopt is enabled
1888 // * caller/callee are fastcc
1889 // On X86_64 architecture with GOT-style position independent code only local
1890 // (within module) calls are supported at the moment.
1891 // To keep the stack aligned according to platform abi the function
1892 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1893 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1894 // If a tail called function callee has more arguments than the caller the
1895 // caller needs to make sure that there is room to move the RETADDR to. This is
1896 // achieved by reserving an area the size of the argument delta right after the
1897 // original REtADDR, but before the saved framepointer or the spilled registers
1898 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1910 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1911 /// for a 16 byte align requirement.
1912 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1913 SelectionDAG& DAG) {
1914 MachineFunction &MF = DAG.getMachineFunction();
1915 const TargetMachine &TM = MF.getTarget();
1916 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1917 unsigned StackAlignment = TFI.getStackAlignment();
1918 uint64_t AlignMask = StackAlignment - 1;
1919 int64_t Offset = StackSize;
1920 uint64_t SlotSize = TD->getPointerSize();
1921 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1922 // Number smaller than 12 so just add the difference.
1923 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1925 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1926 Offset = ((~AlignMask) & Offset) + StackAlignment +
1927 (StackAlignment-SlotSize);
1932 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1933 /// following the call is a return. A function is eligible if caller/callee
1934 /// calling conventions match, currently only fastcc supports tail calls, and
1935 /// the function CALL is immediatly followed by a RET.
1936 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1938 SelectionDAG& DAG) const {
1939 if (!PerformTailCallOpt)
1942 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1943 MachineFunction &MF = DAG.getMachineFunction();
1944 unsigned CallerCC = MF.getFunction()->getCallingConv();
1945 unsigned CalleeCC= TheCall->getCallingConv();
1946 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1947 SDValue Callee = TheCall->getCallee();
1948 // On x86/32Bit PIC/GOT tail calls are supported.
1949 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1950 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1953 // Can only do local tail calls (in same module, hidden or protected) on
1954 // x86_64 PIC/GOT at the moment.
1955 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1956 return G->getGlobal()->hasHiddenVisibility()
1957 || G->getGlobal()->hasProtectedVisibility();
1965 X86TargetLowering::createFastISel(MachineFunction &mf,
1966 MachineModuleInfo *mmo,
1968 DenseMap<const Value *, unsigned> &vm,
1969 DenseMap<const BasicBlock *,
1970 MachineBasicBlock *> &bm,
1971 DenseMap<const AllocaInst *, int> &am
1973 , SmallSet<Instruction*, 8> &cil
1976 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1984 //===----------------------------------------------------------------------===//
1985 // Other Lowering Hooks
1986 //===----------------------------------------------------------------------===//
1989 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1990 MachineFunction &MF = DAG.getMachineFunction();
1991 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1992 int ReturnAddrIndex = FuncInfo->getRAIndex();
1994 if (ReturnAddrIndex == 0) {
1995 // Set up a frame object for the return address.
1996 uint64_t SlotSize = TD->getPointerSize();
1997 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1998 FuncInfo->setRAIndex(ReturnAddrIndex);
2001 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2005 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2006 /// specific condition code, returning the condition code and the LHS/RHS of the
2007 /// comparison to make.
2008 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2009 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2011 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2012 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2013 // X > -1 -> X == 0, jump !sign.
2014 RHS = DAG.getConstant(0, RHS.getValueType());
2015 return X86::COND_NS;
2016 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2017 // X < 0 -> X == 0, jump on sign.
2019 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2021 RHS = DAG.getConstant(0, RHS.getValueType());
2022 return X86::COND_LE;
2026 switch (SetCCOpcode) {
2027 default: assert(0 && "Invalid integer condition!");
2028 case ISD::SETEQ: return X86::COND_E;
2029 case ISD::SETGT: return X86::COND_G;
2030 case ISD::SETGE: return X86::COND_GE;
2031 case ISD::SETLT: return X86::COND_L;
2032 case ISD::SETLE: return X86::COND_LE;
2033 case ISD::SETNE: return X86::COND_NE;
2034 case ISD::SETULT: return X86::COND_B;
2035 case ISD::SETUGT: return X86::COND_A;
2036 case ISD::SETULE: return X86::COND_BE;
2037 case ISD::SETUGE: return X86::COND_AE;
2041 // First determine if it is required or is profitable to flip the operands.
2043 // If LHS is a foldable load, but RHS is not, flip the condition.
2044 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2045 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2046 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2047 std::swap(LHS, RHS);
2050 switch (SetCCOpcode) {
2056 std::swap(LHS, RHS);
2060 // On a floating point condition, the flags are set as follows:
2062 // 0 | 0 | 0 | X > Y
2063 // 0 | 0 | 1 | X < Y
2064 // 1 | 0 | 0 | X == Y
2065 // 1 | 1 | 1 | unordered
2066 switch (SetCCOpcode) {
2067 default: assert(0 && "Condcode should be pre-legalized away");
2069 case ISD::SETEQ: return X86::COND_E;
2070 case ISD::SETOLT: // flipped
2072 case ISD::SETGT: return X86::COND_A;
2073 case ISD::SETOLE: // flipped
2075 case ISD::SETGE: return X86::COND_AE;
2076 case ISD::SETUGT: // flipped
2078 case ISD::SETLT: return X86::COND_B;
2079 case ISD::SETUGE: // flipped
2081 case ISD::SETLE: return X86::COND_BE;
2083 case ISD::SETNE: return X86::COND_NE;
2084 case ISD::SETUO: return X86::COND_P;
2085 case ISD::SETO: return X86::COND_NP;
2089 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2090 /// code. Current x86 isa includes the following FP cmov instructions:
2091 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2092 static bool hasFPCMov(unsigned X86CC) {
2108 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2109 /// the specified range (L, H].
2110 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2111 return (Val < 0) || (Val >= Low && Val < Hi);
2114 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2115 /// specified value.
2116 static bool isUndefOrEqual(int Val, int CmpVal) {
2117 if (Val < 0 || Val == CmpVal)
2122 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2123 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2124 /// the second operand.
2125 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2126 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2127 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2128 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2129 return (Mask[0] < 2 && Mask[1] < 2);
2133 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2134 SmallVector<int, 8> M;
2136 return ::isPSHUFDMask(M, N->getValueType(0));
2139 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2140 /// is suitable for input to PSHUFHW.
2141 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2142 if (VT != MVT::v8i16)
2145 // Lower quadword copied in order or undef.
2146 for (int i = 0; i != 4; ++i)
2147 if (Mask[i] >= 0 && Mask[i] != i)
2150 // Upper quadword shuffled.
2151 for (int i = 4; i != 8; ++i)
2152 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2158 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2159 SmallVector<int, 8> M;
2161 return ::isPSHUFHWMask(M, N->getValueType(0));
2164 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2165 /// is suitable for input to PSHUFLW.
2166 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2167 if (VT != MVT::v8i16)
2170 // Upper quadword copied in order.
2171 for (int i = 4; i != 8; ++i)
2172 if (Mask[i] >= 0 && Mask[i] != i)
2175 // Lower quadword shuffled.
2176 for (int i = 0; i != 4; ++i)
2183 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2184 SmallVector<int, 8> M;
2186 return ::isPSHUFLWMask(M, N->getValueType(0));
2189 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2190 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2191 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2192 int NumElems = VT.getVectorNumElements();
2193 if (NumElems != 2 && NumElems != 4)
2196 int Half = NumElems / 2;
2197 for (int i = 0; i < Half; ++i)
2198 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2200 for (int i = Half; i < NumElems; ++i)
2201 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2207 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2208 SmallVector<int, 8> M;
2210 return ::isSHUFPMask(M, N->getValueType(0));
2213 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2214 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2215 /// half elements to come from vector 1 (which would equal the dest.) and
2216 /// the upper half to come from vector 2.
2217 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2218 int NumElems = VT.getVectorNumElements();
2220 if (NumElems != 2 && NumElems != 4)
2223 int Half = NumElems / 2;
2224 for (int i = 0; i < Half; ++i)
2225 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2227 for (int i = Half; i < NumElems; ++i)
2228 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2233 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2234 SmallVector<int, 8> M;
2236 return isCommutedSHUFPMask(M, N->getValueType(0));
2239 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2240 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2241 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2242 if (N->getValueType(0).getVectorNumElements() != 4)
2245 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2246 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2247 isUndefOrEqual(N->getMaskElt(1), 7) &&
2248 isUndefOrEqual(N->getMaskElt(2), 2) &&
2249 isUndefOrEqual(N->getMaskElt(3), 3);
2252 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2253 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2254 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2255 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2257 if (NumElems != 2 && NumElems != 4)
2260 for (unsigned i = 0; i < NumElems/2; ++i)
2261 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2264 for (unsigned i = NumElems/2; i < NumElems; ++i)
2265 if (!isUndefOrEqual(N->getMaskElt(i), i))
2271 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2272 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2274 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2275 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2277 if (NumElems != 2 && NumElems != 4)
2280 for (unsigned i = 0; i < NumElems/2; ++i)
2281 if (!isUndefOrEqual(N->getMaskElt(i), i))
2284 for (unsigned i = 0; i < NumElems/2; ++i)
2285 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2291 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2292 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2294 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2295 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2300 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2301 isUndefOrEqual(N->getMaskElt(1), 3) &&
2302 isUndefOrEqual(N->getMaskElt(2), 2) &&
2303 isUndefOrEqual(N->getMaskElt(3), 3);
2306 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2307 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2308 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2309 bool V2IsSplat = false) {
2310 int NumElts = VT.getVectorNumElements();
2311 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2314 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2316 int BitI1 = Mask[i+1];
2317 if (!isUndefOrEqual(BitI, j))
2320 if (!isUndefOrEqual(BitI1, NumElts))
2323 if (!isUndefOrEqual(BitI1, j + NumElts))
2330 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2331 SmallVector<int, 8> M;
2333 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2336 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2337 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2338 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2339 bool V2IsSplat = false) {
2340 int NumElts = VT.getVectorNumElements();
2341 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2344 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2346 int BitI1 = Mask[i+1];
2347 if (!isUndefOrEqual(BitI, j + NumElts/2))
2350 if (isUndefOrEqual(BitI1, NumElts))
2353 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2360 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2361 SmallVector<int, 8> M;
2363 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2366 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2367 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2369 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2370 int NumElems = VT.getVectorNumElements();
2371 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2374 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2376 int BitI1 = Mask[i+1];
2377 if (!isUndefOrEqual(BitI, j))
2379 if (!isUndefOrEqual(BitI1, j))
2385 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2386 SmallVector<int, 8> M;
2388 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2391 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2392 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2394 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2395 int NumElems = VT.getVectorNumElements();
2396 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2399 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2401 int BitI1 = Mask[i+1];
2402 if (!isUndefOrEqual(BitI, j))
2404 if (!isUndefOrEqual(BitI1, j))
2410 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2411 SmallVector<int, 8> M;
2413 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2416 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2417 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2418 /// MOVSD, and MOVD, i.e. setting the lowest element.
2419 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2420 int NumElts = VT.getVectorNumElements();
2421 if (NumElts != 2 && NumElts != 4)
2424 if (!isUndefOrEqual(Mask[0], NumElts))
2427 for (int i = 1; i < NumElts; ++i)
2428 if (!isUndefOrEqual(Mask[i], i))
2434 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2435 SmallVector<int, 8> M;
2437 return ::isMOVLMask(M, N->getValueType(0));
2440 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2441 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2442 /// element of vector 2 and the other elements to come from vector 1 in order.
2443 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2444 bool V2IsSplat = false, bool V2IsUndef = false) {
2445 int NumOps = VT.getVectorNumElements();
2446 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2449 if (!isUndefOrEqual(Mask[0], 0))
2452 for (int i = 1; i < NumOps; ++i)
2453 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2454 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2455 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2461 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2462 bool V2IsUndef = false) {
2463 SmallVector<int, 8> M;
2465 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2468 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2469 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2470 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2471 if (N->getValueType(0).getVectorNumElements() != 4)
2474 // Expect 1, 1, 3, 3
2475 for (unsigned i = 0; i < 2; ++i) {
2476 int Elt = N->getMaskElt(i);
2477 if (Elt >= 0 && Elt != 1)
2482 for (unsigned i = 2; i < 4; ++i) {
2483 int Elt = N->getMaskElt(i);
2484 if (Elt >= 0 && Elt != 3)
2489 // Don't use movshdup if it can be done with a shufps.
2490 // FIXME: verify that matching u, u, 3, 3 is what we want.
2494 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2495 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2496 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2497 if (N->getValueType(0).getVectorNumElements() != 4)
2500 // Expect 0, 0, 2, 2
2501 for (unsigned i = 0; i < 2; ++i)
2502 if (N->getMaskElt(i) > 0)
2506 for (unsigned i = 2; i < 4; ++i) {
2507 int Elt = N->getMaskElt(i);
2508 if (Elt >= 0 && Elt != 2)
2513 // Don't use movsldup if it can be done with a shufps.
2517 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2518 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2519 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2520 int e = N->getValueType(0).getVectorNumElements() / 2;
2522 for (int i = 0; i < e; ++i)
2523 if (!isUndefOrEqual(N->getMaskElt(i), i))
2525 for (int i = 0; i < e; ++i)
2526 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2531 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2532 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2534 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2535 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2536 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2538 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2540 for (int i = 0; i < NumOperands; ++i) {
2541 int Val = SVOp->getMaskElt(NumOperands-i-1);
2542 if (Val < 0) Val = 0;
2543 if (Val >= NumOperands) Val -= NumOperands;
2545 if (i != NumOperands - 1)
2551 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2552 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2554 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2555 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2557 // 8 nodes, but we only care about the last 4.
2558 for (unsigned i = 7; i >= 4; --i) {
2559 int Val = SVOp->getMaskElt(i);
2568 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2569 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2571 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2572 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2574 // 8 nodes, but we only care about the first 4.
2575 for (int i = 3; i >= 0; --i) {
2576 int Val = SVOp->getMaskElt(i);
2585 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2586 /// their permute mask.
2587 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2588 SelectionDAG &DAG) {
2589 MVT VT = SVOp->getValueType(0);
2590 unsigned NumElems = VT.getVectorNumElements();
2591 SmallVector<int, 8> MaskVec;
2593 for (unsigned i = 0; i != NumElems; ++i) {
2594 int idx = SVOp->getMaskElt(i);
2596 MaskVec.push_back(idx);
2597 else if (idx < (int)NumElems)
2598 MaskVec.push_back(idx + NumElems);
2600 MaskVec.push_back(idx - NumElems);
2602 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2603 SVOp->getOperand(0), &MaskVec[0]);
2606 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2607 /// the two vector operands have swapped position.
2608 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2609 unsigned NumElems = VT.getVectorNumElements();
2610 for (unsigned i = 0; i != NumElems; ++i) {
2614 else if (idx < (int)NumElems)
2615 Mask[i] = idx + NumElems;
2617 Mask[i] = idx - NumElems;
2621 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2622 /// match movhlps. The lower half elements should come from upper half of
2623 /// V1 (and in order), and the upper half elements should come from the upper
2624 /// half of V2 (and in order).
2625 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2626 if (Op->getValueType(0).getVectorNumElements() != 4)
2628 for (unsigned i = 0, e = 2; i != e; ++i)
2629 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2631 for (unsigned i = 2; i != 4; ++i)
2632 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2637 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2638 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2640 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2641 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2643 N = N->getOperand(0).getNode();
2644 if (!ISD::isNON_EXTLoad(N))
2647 *LD = cast<LoadSDNode>(N);
2651 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2652 /// match movlp{s|d}. The lower half elements should come from lower half of
2653 /// V1 (and in order), and the upper half elements should come from the upper
2654 /// half of V2 (and in order). And since V1 will become the source of the
2655 /// MOVLP, it must be either a vector load or a scalar load to vector.
2656 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2657 ShuffleVectorSDNode *Op) {
2658 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2660 // Is V2 is a vector load, don't do this transformation. We will try to use
2661 // load folding shufps op.
2662 if (ISD::isNON_EXTLoad(V2))
2665 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2667 if (NumElems != 2 && NumElems != 4)
2669 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2670 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2672 for (unsigned i = NumElems/2; i != NumElems; ++i)
2673 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2678 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2680 static bool isSplatVector(SDNode *N) {
2681 if (N->getOpcode() != ISD::BUILD_VECTOR)
2684 SDValue SplatValue = N->getOperand(0);
2685 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2686 if (N->getOperand(i) != SplatValue)
2691 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2693 static inline bool isZeroNode(SDValue Elt) {
2694 return ((isa<ConstantSDNode>(Elt) &&
2695 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2696 (isa<ConstantFPSDNode>(Elt) &&
2697 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2700 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2701 /// to an zero vector.
2702 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2703 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2704 SDValue V1 = N->getOperand(0);
2705 SDValue V2 = N->getOperand(1);
2706 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2707 for (unsigned i = 0; i != NumElems; ++i) {
2708 int Idx = N->getMaskElt(i);
2709 if (Idx >= (int)NumElems) {
2710 unsigned Opc = V2.getOpcode();
2711 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2713 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2715 } else if (Idx >= 0) {
2716 unsigned Opc = V1.getOpcode();
2717 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2719 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2726 /// getZeroVector - Returns a vector of specified type with all zero elements.
2728 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2730 assert(VT.isVector() && "Expected a vector type");
2732 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2733 // type. This ensures they get CSE'd.
2735 if (VT.getSizeInBits() == 64) { // MMX
2736 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2737 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2738 } else if (HasSSE2) { // SSE2
2739 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2740 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2742 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2743 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2745 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2748 /// getOnesVector - Returns a vector of specified type with all bits set.
2750 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2751 assert(VT.isVector() && "Expected a vector type");
2753 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2754 // type. This ensures they get CSE'd.
2755 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2757 if (VT.getSizeInBits() == 64) // MMX
2758 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2760 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2761 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2765 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2766 /// that point to V2 points to its first element.
2767 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2768 MVT VT = SVOp->getValueType(0);
2769 unsigned NumElems = VT.getVectorNumElements();
2771 bool Changed = false;
2772 SmallVector<int, 8> MaskVec;
2773 SVOp->getMask(MaskVec);
2775 for (unsigned i = 0; i != NumElems; ++i) {
2776 if (MaskVec[i] > (int)NumElems) {
2777 MaskVec[i] = NumElems;
2782 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2783 SVOp->getOperand(1), &MaskVec[0]);
2784 return SDValue(SVOp, 0);
2787 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2788 /// operation of specified width.
2789 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2791 unsigned NumElems = VT.getVectorNumElements();
2792 SmallVector<int, 8> Mask;
2793 Mask.push_back(NumElems);
2794 for (unsigned i = 1; i != NumElems; ++i)
2796 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2799 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2800 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2802 unsigned NumElems = VT.getVectorNumElements();
2803 SmallVector<int, 8> Mask;
2804 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2806 Mask.push_back(i + NumElems);
2808 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2811 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2812 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2814 unsigned NumElems = VT.getVectorNumElements();
2815 unsigned Half = NumElems/2;
2816 SmallVector<int, 8> Mask;
2817 for (unsigned i = 0; i != Half; ++i) {
2818 Mask.push_back(i + Half);
2819 Mask.push_back(i + NumElems + Half);
2821 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2824 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2825 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2827 if (SV->getValueType(0).getVectorNumElements() <= 4)
2828 return SDValue(SV, 0);
2830 MVT PVT = MVT::v4f32;
2831 MVT VT = SV->getValueType(0);
2832 DebugLoc dl = SV->getDebugLoc();
2833 SDValue V1 = SV->getOperand(0);
2834 int NumElems = VT.getVectorNumElements();
2835 int EltNo = SV->getSplatIndex();
2837 // unpack elements to the correct location
2838 while (NumElems > 4) {
2839 if (EltNo < NumElems/2) {
2840 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2842 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2843 EltNo -= NumElems/2;
2848 // Perform the splat.
2849 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2850 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2851 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2852 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2855 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2856 /// vector of zero or undef vector. This produces a shuffle where the low
2857 /// element of V2 is swizzled into the zero/undef vector, landing at element
2858 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2859 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2860 bool isZero, bool HasSSE2,
2861 SelectionDAG &DAG) {
2862 MVT VT = V2.getValueType();
2864 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2865 unsigned NumElems = VT.getVectorNumElements();
2866 SmallVector<int, 16> MaskVec;
2867 for (unsigned i = 0; i != NumElems; ++i)
2868 // If this is the insertion idx, put the low elt of V2 here.
2869 MaskVec.push_back(i == Idx ? NumElems : i);
2870 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2873 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2874 /// a shuffle that is zero.
2876 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2877 bool Low, SelectionDAG &DAG) {
2878 unsigned NumZeros = 0;
2879 for (int i = 0; i < NumElems; ++i) {
2880 unsigned Index = Low ? i : NumElems-i-1;
2881 int Idx = SVOp->getMaskElt(Index);
2886 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2887 if (Elt.getNode() && isZeroNode(Elt))
2895 /// isVectorShift - Returns true if the shuffle can be implemented as a
2896 /// logical left or right shift of a vector.
2897 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2898 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2899 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2900 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2903 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2906 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2910 bool SeenV1 = false;
2911 bool SeenV2 = false;
2912 for (int i = NumZeros; i < NumElems; ++i) {
2913 int Val = isLeft ? (i - NumZeros) : i;
2914 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2926 if (SeenV1 && SeenV2)
2929 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2935 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2937 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2938 unsigned NumNonZero, unsigned NumZero,
2939 SelectionDAG &DAG, TargetLowering &TLI) {
2943 DebugLoc dl = Op.getDebugLoc();
2946 for (unsigned i = 0; i < 16; ++i) {
2947 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2948 if (ThisIsNonZero && First) {
2950 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2952 V = DAG.getUNDEF(MVT::v8i16);
2957 SDValue ThisElt(0, 0), LastElt(0, 0);
2958 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2959 if (LastIsNonZero) {
2960 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2961 MVT::i16, Op.getOperand(i-1));
2963 if (ThisIsNonZero) {
2964 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2965 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2966 ThisElt, DAG.getConstant(8, MVT::i8));
2968 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2972 if (ThisElt.getNode())
2973 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2974 DAG.getIntPtrConstant(i/2));
2978 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2981 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2983 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2984 unsigned NumNonZero, unsigned NumZero,
2985 SelectionDAG &DAG, TargetLowering &TLI) {
2989 DebugLoc dl = Op.getDebugLoc();
2992 for (unsigned i = 0; i < 8; ++i) {
2993 bool isNonZero = (NonZeros & (1 << i)) != 0;
2997 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2999 V = DAG.getUNDEF(MVT::v8i16);
3002 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3003 MVT::v8i16, V, Op.getOperand(i),
3004 DAG.getIntPtrConstant(i));
3011 /// getVShift - Return a vector logical shift node.
3013 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3014 unsigned NumBits, SelectionDAG &DAG,
3015 const TargetLowering &TLI, DebugLoc dl) {
3016 bool isMMX = VT.getSizeInBits() == 64;
3017 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3018 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3019 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3020 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3021 DAG.getNode(Opc, dl, ShVT, SrcOp,
3022 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3026 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3027 DebugLoc dl = Op.getDebugLoc();
3028 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3029 if (ISD::isBuildVectorAllZeros(Op.getNode())
3030 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3031 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3032 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3033 // eliminated on x86-32 hosts.
3034 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3037 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3038 return getOnesVector(Op.getValueType(), DAG, dl);
3039 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3042 MVT VT = Op.getValueType();
3043 MVT EVT = VT.getVectorElementType();
3044 unsigned EVTBits = EVT.getSizeInBits();
3046 unsigned NumElems = Op.getNumOperands();
3047 unsigned NumZero = 0;
3048 unsigned NumNonZero = 0;
3049 unsigned NonZeros = 0;
3050 bool IsAllConstants = true;
3051 SmallSet<SDValue, 8> Values;
3052 for (unsigned i = 0; i < NumElems; ++i) {
3053 SDValue Elt = Op.getOperand(i);
3054 if (Elt.getOpcode() == ISD::UNDEF)
3057 if (Elt.getOpcode() != ISD::Constant &&
3058 Elt.getOpcode() != ISD::ConstantFP)
3059 IsAllConstants = false;
3060 if (isZeroNode(Elt))
3063 NonZeros |= (1 << i);
3068 if (NumNonZero == 0) {
3069 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3070 return DAG.getUNDEF(VT);
3073 // Special case for single non-zero, non-undef, element.
3074 if (NumNonZero == 1 && NumElems <= 4) {
3075 unsigned Idx = CountTrailingZeros_32(NonZeros);
3076 SDValue Item = Op.getOperand(Idx);
3078 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3079 // the value are obviously zero, truncate the value to i32 and do the
3080 // insertion that way. Only do this if the value is non-constant or if the
3081 // value is a constant being inserted into element 0. It is cheaper to do
3082 // a constant pool load than it is to do a movd + shuffle.
3083 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3084 (!IsAllConstants || Idx == 0)) {
3085 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3086 // Handle MMX and SSE both.
3087 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3088 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3090 // Truncate the value (which may itself be a constant) to i32, and
3091 // convert it to a vector with movd (S2V+shuffle to zero extend).
3092 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3093 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3094 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3095 Subtarget->hasSSE2(), DAG);
3097 // Now we have our 32-bit value zero extended in the low element of
3098 // a vector. If Idx != 0, swizzle it into place.
3100 SmallVector<int, 4> Mask;
3101 Mask.push_back(Idx);
3102 for (unsigned i = 1; i != VecElts; ++i)
3104 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3105 DAG.getUNDEF(Item.getValueType()),
3108 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3112 // If we have a constant or non-constant insertion into the low element of
3113 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3114 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3115 // depending on what the source datatype is. Because we can only get here
3116 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3118 // Don't do this for i64 values on x86-32.
3119 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3120 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3121 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3122 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3123 Subtarget->hasSSE2(), DAG);
3126 // Is it a vector logical left shift?
3127 if (NumElems == 2 && Idx == 1 &&
3128 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3129 unsigned NumBits = VT.getSizeInBits();
3130 return getVShift(true, VT,
3131 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3132 VT, Op.getOperand(1)),
3133 NumBits/2, DAG, *this, dl);
3136 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3139 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3140 // is a non-constant being inserted into an element other than the low one,
3141 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3142 // movd/movss) to move this into the low element, then shuffle it into
3144 if (EVTBits == 32) {
3145 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3147 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3148 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3149 Subtarget->hasSSE2(), DAG);
3150 SmallVector<int, 8> MaskVec;
3151 for (unsigned i = 0; i < NumElems; i++)
3152 MaskVec.push_back(i == Idx ? 0 : 1);
3153 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3157 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3158 if (Values.size() == 1)
3161 // A vector full of immediates; various special cases are already
3162 // handled, so this is best done with a single constant-pool load.
3166 // Let legalizer expand 2-wide build_vectors.
3167 if (EVTBits == 64) {
3168 if (NumNonZero == 1) {
3169 // One half is zero or undef.
3170 unsigned Idx = CountTrailingZeros_32(NonZeros);
3171 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3172 Op.getOperand(Idx));
3173 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3174 Subtarget->hasSSE2(), DAG);
3179 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3180 if (EVTBits == 8 && NumElems == 16) {
3181 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3183 if (V.getNode()) return V;
3186 if (EVTBits == 16 && NumElems == 8) {
3187 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3189 if (V.getNode()) return V;
3192 // If element VT is == 32 bits, turn it into a number of shuffles.
3193 SmallVector<SDValue, 8> V;
3195 if (NumElems == 4 && NumZero > 0) {
3196 for (unsigned i = 0; i < 4; ++i) {
3197 bool isZero = !(NonZeros & (1 << i));
3199 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3201 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3204 for (unsigned i = 0; i < 2; ++i) {
3205 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3208 V[i] = V[i*2]; // Must be a zero vector.
3211 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3214 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3217 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3222 SmallVector<int, 8> MaskVec;
3223 bool Reverse = (NonZeros & 0x3) == 2;
3224 for (unsigned i = 0; i < 2; ++i)
3225 MaskVec.push_back(Reverse ? 1-i : i);
3226 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3227 for (unsigned i = 0; i < 2; ++i)
3228 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3229 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3232 if (Values.size() > 2) {
3233 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3234 // values to be inserted is equal to the number of elements, in which case
3235 // use the unpack code below in the hopes of matching the consecutive elts
3236 // load merge pattern for shuffles.
3237 // FIXME: We could probably just check that here directly.
3238 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3239 getSubtarget()->hasSSE41()) {
3240 V[0] = DAG.getUNDEF(VT);
3241 for (unsigned i = 0; i < NumElems; ++i)
3242 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3243 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3244 Op.getOperand(i), DAG.getIntPtrConstant(i));
3247 // Expand into a number of unpckl*.
3249 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3250 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3251 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3252 for (unsigned i = 0; i < NumElems; ++i)
3253 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3255 while (NumElems != 0) {
3256 for (unsigned i = 0; i < NumElems; ++i)
3257 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3266 // v8i16 shuffles - Prefer shuffles in the following order:
3267 // 1. [all] pshuflw, pshufhw, optional move
3268 // 2. [ssse3] 1 x pshufb
3269 // 3. [ssse3] 2 x pshufb + 1 x por
3270 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3272 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3273 SelectionDAG &DAG, X86TargetLowering &TLI) {
3274 SDValue V1 = SVOp->getOperand(0);
3275 SDValue V2 = SVOp->getOperand(1);
3276 DebugLoc dl = SVOp->getDebugLoc();
3277 SmallVector<int, 8> MaskVals;
3279 // Determine if more than 1 of the words in each of the low and high quadwords
3280 // of the result come from the same quadword of one of the two inputs. Undef
3281 // mask values count as coming from any quadword, for better codegen.
3282 SmallVector<unsigned, 4> LoQuad(4);
3283 SmallVector<unsigned, 4> HiQuad(4);
3284 BitVector InputQuads(4);
3285 for (unsigned i = 0; i < 8; ++i) {
3286 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3287 int EltIdx = SVOp->getMaskElt(i);
3288 MaskVals.push_back(EltIdx);
3297 InputQuads.set(EltIdx / 4);
3300 int BestLoQuad = -1;
3301 unsigned MaxQuad = 1;
3302 for (unsigned i = 0; i < 4; ++i) {
3303 if (LoQuad[i] > MaxQuad) {
3305 MaxQuad = LoQuad[i];
3309 int BestHiQuad = -1;
3311 for (unsigned i = 0; i < 4; ++i) {
3312 if (HiQuad[i] > MaxQuad) {
3314 MaxQuad = HiQuad[i];
3318 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3319 // of the two input vectors, shuffle them into one input vector so only a
3320 // single pshufb instruction is necessary. If There are more than 2 input
3321 // quads, disable the next transformation since it does not help SSSE3.
3322 bool V1Used = InputQuads[0] || InputQuads[1];
3323 bool V2Used = InputQuads[2] || InputQuads[3];
3324 if (TLI.getSubtarget()->hasSSSE3()) {
3325 if (InputQuads.count() == 2 && V1Used && V2Used) {
3326 BestLoQuad = InputQuads.find_first();
3327 BestHiQuad = InputQuads.find_next(BestLoQuad);
3329 if (InputQuads.count() > 2) {
3335 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3336 // the shuffle mask. If a quad is scored as -1, that means that it contains
3337 // words from all 4 input quadwords.
3339 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3340 SmallVector<int, 8> MaskV;
3341 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3342 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3343 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3344 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3345 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3346 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3348 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3349 // source words for the shuffle, to aid later transformations.
3350 bool AllWordsInNewV = true;
3351 bool InOrder[2] = { true, true };
3352 for (unsigned i = 0; i != 8; ++i) {
3353 int idx = MaskVals[i];
3355 InOrder[i/4] = false;
3356 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3358 AllWordsInNewV = false;
3362 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3363 if (AllWordsInNewV) {
3364 for (int i = 0; i != 8; ++i) {
3365 int idx = MaskVals[i];
3368 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3369 if ((idx != i) && idx < 4)
3371 if ((idx != i) && idx > 3)
3380 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3381 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3382 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3383 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3384 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3388 // If we have SSSE3, and all words of the result are from 1 input vector,
3389 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3390 // is present, fall back to case 4.
3391 if (TLI.getSubtarget()->hasSSSE3()) {
3392 SmallVector<SDValue,16> pshufbMask;
3394 // If we have elements from both input vectors, set the high bit of the
3395 // shuffle mask element to zero out elements that come from V2 in the V1
3396 // mask, and elements that come from V1 in the V2 mask, so that the two
3397 // results can be OR'd together.
3398 bool TwoInputs = V1Used && V2Used;
3399 for (unsigned i = 0; i != 8; ++i) {
3400 int EltIdx = MaskVals[i] * 2;
3401 if (TwoInputs && (EltIdx >= 16)) {
3402 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3403 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3406 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3407 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3409 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3410 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3411 DAG.getNode(ISD::BUILD_VECTOR, dl,
3412 MVT::v16i8, &pshufbMask[0], 16));
3414 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3416 // Calculate the shuffle mask for the second input, shuffle it, and
3417 // OR it with the first shuffled input.
3419 for (unsigned i = 0; i != 8; ++i) {
3420 int EltIdx = MaskVals[i] * 2;
3422 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3423 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3426 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3427 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3429 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3430 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3431 DAG.getNode(ISD::BUILD_VECTOR, dl,
3432 MVT::v16i8, &pshufbMask[0], 16));
3433 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3434 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3437 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3438 // and update MaskVals with new element order.
3439 BitVector InOrder(8);
3440 if (BestLoQuad >= 0) {
3441 SmallVector<int, 8> MaskV;
3442 for (int i = 0; i != 4; ++i) {
3443 int idx = MaskVals[i];
3445 MaskV.push_back(-1);
3447 } else if ((idx / 4) == BestLoQuad) {
3448 MaskV.push_back(idx & 3);
3451 MaskV.push_back(-1);
3454 for (unsigned i = 4; i != 8; ++i)
3456 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3460 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3461 // and update MaskVals with the new element order.
3462 if (BestHiQuad >= 0) {
3463 SmallVector<int, 8> MaskV;
3464 for (unsigned i = 0; i != 4; ++i)
3466 for (unsigned i = 4; i != 8; ++i) {
3467 int idx = MaskVals[i];
3469 MaskV.push_back(-1);
3471 } else if ((idx / 4) == BestHiQuad) {
3472 MaskV.push_back((idx & 3) + 4);
3475 MaskV.push_back(-1);
3478 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3482 // In case BestHi & BestLo were both -1, which means each quadword has a word
3483 // from each of the four input quadwords, calculate the InOrder bitvector now
3484 // before falling through to the insert/extract cleanup.
3485 if (BestLoQuad == -1 && BestHiQuad == -1) {
3487 for (int i = 0; i != 8; ++i)
3488 if (MaskVals[i] < 0 || MaskVals[i] == i)
3492 // The other elements are put in the right place using pextrw and pinsrw.
3493 for (unsigned i = 0; i != 8; ++i) {
3496 int EltIdx = MaskVals[i];
3499 SDValue ExtOp = (EltIdx < 8)
3500 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3501 DAG.getIntPtrConstant(EltIdx))
3502 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3503 DAG.getIntPtrConstant(EltIdx - 8));
3504 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3505 DAG.getIntPtrConstant(i));
3510 // v16i8 shuffles - Prefer shuffles in the following order:
3511 // 1. [ssse3] 1 x pshufb
3512 // 2. [ssse3] 2 x pshufb + 1 x por
3513 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3515 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3516 SelectionDAG &DAG, X86TargetLowering &TLI) {
3517 SDValue V1 = SVOp->getOperand(0);
3518 SDValue V2 = SVOp->getOperand(1);
3519 DebugLoc dl = SVOp->getDebugLoc();
3520 SmallVector<int, 16> MaskVals;
3521 SVOp->getMask(MaskVals);
3523 // If we have SSSE3, case 1 is generated when all result bytes come from
3524 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3525 // present, fall back to case 3.
3526 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3529 for (unsigned i = 0; i < 16; ++i) {
3530 int EltIdx = MaskVals[i];
3539 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3540 if (TLI.getSubtarget()->hasSSSE3()) {
3541 SmallVector<SDValue,16> pshufbMask;
3543 // If all result elements are from one input vector, then only translate
3544 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3546 // Otherwise, we have elements from both input vectors, and must zero out
3547 // elements that come from V2 in the first mask, and V1 in the second mask
3548 // so that we can OR them together.
3549 bool TwoInputs = !(V1Only || V2Only);
3550 for (unsigned i = 0; i != 16; ++i) {
3551 int EltIdx = MaskVals[i];
3552 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3553 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3556 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3558 // If all the elements are from V2, assign it to V1 and return after
3559 // building the first pshufb.
3562 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3563 DAG.getNode(ISD::BUILD_VECTOR, dl,
3564 MVT::v16i8, &pshufbMask[0], 16));
3568 // Calculate the shuffle mask for the second input, shuffle it, and
3569 // OR it with the first shuffled input.
3571 for (unsigned i = 0; i != 16; ++i) {
3572 int EltIdx = MaskVals[i];
3574 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3577 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3579 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3580 DAG.getNode(ISD::BUILD_VECTOR, dl,
3581 MVT::v16i8, &pshufbMask[0], 16));
3582 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3585 // No SSSE3 - Calculate in place words and then fix all out of place words
3586 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3587 // the 16 different words that comprise the two doublequadword input vectors.
3588 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3589 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3590 SDValue NewV = V2Only ? V2 : V1;
3591 for (int i = 0; i != 8; ++i) {
3592 int Elt0 = MaskVals[i*2];
3593 int Elt1 = MaskVals[i*2+1];
3595 // This word of the result is all undef, skip it.
3596 if (Elt0 < 0 && Elt1 < 0)
3599 // This word of the result is already in the correct place, skip it.
3600 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3602 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3605 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3606 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3609 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3610 // using a single extract together, load it and store it.
3611 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3612 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3613 DAG.getIntPtrConstant(Elt1 / 2));
3614 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3615 DAG.getIntPtrConstant(i));
3619 // If Elt1 is defined, extract it from the appropriate source. If the
3620 // source byte is not also odd, shift the extracted word left 8 bits
3621 // otherwise clear the bottom 8 bits if we need to do an or.
3623 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3624 DAG.getIntPtrConstant(Elt1 / 2));
3625 if ((Elt1 & 1) == 0)
3626 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3627 DAG.getConstant(8, TLI.getShiftAmountTy()));
3629 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3630 DAG.getConstant(0xFF00, MVT::i16));
3632 // If Elt0 is defined, extract it from the appropriate source. If the
3633 // source byte is not also even, shift the extracted word right 8 bits. If
3634 // Elt1 was also defined, OR the extracted values together before
3635 // inserting them in the result.
3637 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3638 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3639 if ((Elt0 & 1) != 0)
3640 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3641 DAG.getConstant(8, TLI.getShiftAmountTy()));
3643 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3644 DAG.getConstant(0x00FF, MVT::i16));
3645 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3648 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3649 DAG.getIntPtrConstant(i));
3651 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3654 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3655 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3656 /// done when every pair / quad of shuffle mask elements point to elements in
3657 /// the right sequence. e.g.
3658 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3660 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3662 TargetLowering &TLI, DebugLoc dl) {
3663 MVT VT = SVOp->getValueType(0);
3664 SDValue V1 = SVOp->getOperand(0);
3665 SDValue V2 = SVOp->getOperand(1);
3666 unsigned NumElems = VT.getVectorNumElements();
3667 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3668 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3669 MVT MaskEltVT = MaskVT.getVectorElementType();
3671 switch (VT.getSimpleVT()) {
3672 default: assert(false && "Unexpected!");
3673 case MVT::v4f32: NewVT = MVT::v2f64; break;
3674 case MVT::v4i32: NewVT = MVT::v2i64; break;
3675 case MVT::v8i16: NewVT = MVT::v4i32; break;
3676 case MVT::v16i8: NewVT = MVT::v4i32; break;
3679 if (NewWidth == 2) {
3685 int Scale = NumElems / NewWidth;
3686 SmallVector<int, 8> MaskVec;
3687 for (unsigned i = 0; i < NumElems; i += Scale) {
3689 for (int j = 0; j < Scale; ++j) {
3690 int EltIdx = SVOp->getMaskElt(i+j);
3694 StartIdx = EltIdx - (EltIdx % Scale);
3695 if (EltIdx != StartIdx + j)
3699 MaskVec.push_back(-1);
3701 MaskVec.push_back(StartIdx / Scale);
3704 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3705 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3706 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3709 /// getVZextMovL - Return a zero-extending vector move low node.
3711 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3712 SDValue SrcOp, SelectionDAG &DAG,
3713 const X86Subtarget *Subtarget, DebugLoc dl) {
3714 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3715 LoadSDNode *LD = NULL;
3716 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3717 LD = dyn_cast<LoadSDNode>(SrcOp);
3719 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3721 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3722 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3723 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3724 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3725 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3727 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3728 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3729 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3730 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3738 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3739 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3740 DAG.getNode(ISD::BIT_CONVERT, dl,
3744 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3747 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3748 SDValue V1 = SVOp->getOperand(0);
3749 SDValue V2 = SVOp->getOperand(1);
3750 DebugLoc dl = SVOp->getDebugLoc();
3751 MVT VT = SVOp->getValueType(0);
3753 SmallVector<std::pair<int, int>, 8> Locs;
3755 SmallVector<int, 8> Mask1(4U, -1);
3756 SmallVector<int, 8> PermMask;
3757 SVOp->getMask(PermMask);
3761 for (unsigned i = 0; i != 4; ++i) {
3762 int Idx = PermMask[i];
3764 Locs[i] = std::make_pair(-1, -1);
3766 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3768 Locs[i] = std::make_pair(0, NumLo);
3772 Locs[i] = std::make_pair(1, NumHi);
3774 Mask1[2+NumHi] = Idx;
3780 if (NumLo <= 2 && NumHi <= 2) {
3781 // If no more than two elements come from either vector. This can be
3782 // implemented with two shuffles. First shuffle gather the elements.
3783 // The second shuffle, which takes the first shuffle as both of its
3784 // vector operands, put the elements into the right order.
3785 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3787 SmallVector<int, 8> Mask2(4U, -1);
3789 for (unsigned i = 0; i != 4; ++i) {
3790 if (Locs[i].first == -1)
3793 unsigned Idx = (i < 2) ? 0 : 4;
3794 Idx += Locs[i].first * 2 + Locs[i].second;
3799 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3800 } else if (NumLo == 3 || NumHi == 3) {
3801 // Otherwise, we must have three elements from one vector, call it X, and
3802 // one element from the other, call it Y. First, use a shufps to build an
3803 // intermediate vector with the one element from Y and the element from X
3804 // that will be in the same half in the final destination (the indexes don't
3805 // matter). Then, use a shufps to build the final vector, taking the half
3806 // containing the element from Y from the intermediate, and the other half
3809 // Normalize it so the 3 elements come from V1.
3810 CommuteVectorShuffleMask(PermMask, VT);
3814 // Find the element from V2.
3816 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3817 int Val = PermMask[HiIndex];
3824 Mask1[0] = PermMask[HiIndex];
3826 Mask1[2] = PermMask[HiIndex^1];
3828 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3831 Mask1[0] = PermMask[0];
3832 Mask1[1] = PermMask[1];
3833 Mask1[2] = HiIndex & 1 ? 6 : 4;
3834 Mask1[3] = HiIndex & 1 ? 4 : 6;
3835 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3837 Mask1[0] = HiIndex & 1 ? 2 : 0;
3838 Mask1[1] = HiIndex & 1 ? 0 : 2;
3839 Mask1[2] = PermMask[2];
3840 Mask1[3] = PermMask[3];
3845 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3849 // Break it into (shuffle shuffle_hi, shuffle_lo).
3851 SmallVector<int,8> LoMask(4U, -1);
3852 SmallVector<int,8> HiMask(4U, -1);
3854 SmallVector<int,8> *MaskPtr = &LoMask;
3855 unsigned MaskIdx = 0;
3858 for (unsigned i = 0; i != 4; ++i) {
3865 int Idx = PermMask[i];
3867 Locs[i] = std::make_pair(-1, -1);
3868 } else if (Idx < 4) {
3869 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3870 (*MaskPtr)[LoIdx] = Idx;
3873 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3874 (*MaskPtr)[HiIdx] = Idx;
3879 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3880 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3881 SmallVector<int, 8> MaskOps;
3882 for (unsigned i = 0; i != 4; ++i) {
3883 if (Locs[i].first == -1) {
3884 MaskOps.push_back(-1);
3886 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3887 MaskOps.push_back(Idx);
3890 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3894 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3895 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3896 SDValue V1 = Op.getOperand(0);
3897 SDValue V2 = Op.getOperand(1);
3898 MVT VT = Op.getValueType();
3899 DebugLoc dl = Op.getDebugLoc();
3900 unsigned NumElems = VT.getVectorNumElements();
3901 bool isMMX = VT.getSizeInBits() == 64;
3902 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3903 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3904 bool V1IsSplat = false;
3905 bool V2IsSplat = false;
3907 if (isZeroShuffle(SVOp))
3908 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3910 // Promote splats to v4f32.
3911 if (SVOp->isSplat()) {
3912 if (isMMX || NumElems < 4)
3914 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3917 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3919 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3920 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3921 if (NewOp.getNode())
3922 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3923 LowerVECTOR_SHUFFLE(NewOp, DAG));
3924 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3925 // FIXME: Figure out a cleaner way to do this.
3926 // Try to make use of movq to zero out the top part.
3927 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3928 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3929 if (NewOp.getNode()) {
3930 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3931 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3932 DAG, Subtarget, dl);
3934 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3935 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3936 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3937 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3938 DAG, Subtarget, dl);
3942 if (X86::isPSHUFDMask(SVOp))
3945 // Check if this can be converted into a logical shift.
3946 bool isLeft = false;
3949 bool isShift = getSubtarget()->hasSSE2() &&
3950 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3951 if (isShift && ShVal.hasOneUse()) {
3952 // If the shifted value has multiple uses, it may be cheaper to use
3953 // v_set0 + movlhps or movhlps, etc.
3954 MVT EVT = VT.getVectorElementType();
3955 ShAmt *= EVT.getSizeInBits();
3956 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3959 if (X86::isMOVLMask(SVOp)) {
3962 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3963 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3968 // FIXME: fold these into legal mask.
3969 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3970 X86::isMOVSLDUPMask(SVOp) ||
3971 X86::isMOVHLPSMask(SVOp) ||
3972 X86::isMOVHPMask(SVOp) ||
3973 X86::isMOVLPMask(SVOp)))
3976 if (ShouldXformToMOVHLPS(SVOp) ||
3977 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3978 return CommuteVectorShuffle(SVOp, DAG);
3981 // No better options. Use a vshl / vsrl.
3982 MVT EVT = VT.getVectorElementType();
3983 ShAmt *= EVT.getSizeInBits();
3984 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3987 bool Commuted = false;
3988 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3989 // 1,1,1,1 -> v8i16 though.
3990 V1IsSplat = isSplatVector(V1.getNode());
3991 V2IsSplat = isSplatVector(V2.getNode());
3993 // Canonicalize the splat or undef, if present, to be on the RHS.
3994 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3995 Op = CommuteVectorShuffle(SVOp, DAG);
3996 SVOp = cast<ShuffleVectorSDNode>(Op);
3997 V1 = SVOp->getOperand(0);
3998 V2 = SVOp->getOperand(1);
3999 std::swap(V1IsSplat, V2IsSplat);
4000 std::swap(V1IsUndef, V2IsUndef);
4004 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4005 // Shuffling low element of v1 into undef, just return v1.
4008 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4009 // the instruction selector will not match, so get a canonical MOVL with
4010 // swapped operands to undo the commute.
4011 return getMOVL(DAG, dl, VT, V2, V1);
4014 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4015 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4016 X86::isUNPCKLMask(SVOp) ||
4017 X86::isUNPCKHMask(SVOp))
4021 // Normalize mask so all entries that point to V2 points to its first
4022 // element then try to match unpck{h|l} again. If match, return a
4023 // new vector_shuffle with the corrected mask.
4024 SDValue NewMask = NormalizeMask(SVOp, DAG);
4025 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4026 if (NSVOp != SVOp) {
4027 if (X86::isUNPCKLMask(NSVOp, true)) {
4029 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4036 // Commute is back and try unpck* again.
4037 // FIXME: this seems wrong.
4038 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4039 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4040 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4041 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4042 X86::isUNPCKLMask(NewSVOp) ||
4043 X86::isUNPCKHMask(NewSVOp))
4047 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4049 // Normalize the node to match x86 shuffle ops if needed
4050 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4051 return CommuteVectorShuffle(SVOp, DAG);
4053 // Check for legal shuffle and return?
4054 SmallVector<int, 16> PermMask;
4055 SVOp->getMask(PermMask);
4056 if (isShuffleMaskLegal(PermMask, VT))
4059 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4060 if (VT == MVT::v8i16) {
4061 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4062 if (NewOp.getNode())
4066 if (VT == MVT::v16i8) {
4067 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4068 if (NewOp.getNode())
4072 // Handle all 4 wide cases with a number of shuffles except for MMX.
4073 if (NumElems == 4 && !isMMX)
4074 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4080 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4081 SelectionDAG &DAG) {
4082 MVT VT = Op.getValueType();
4083 DebugLoc dl = Op.getDebugLoc();
4084 if (VT.getSizeInBits() == 8) {
4085 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4086 Op.getOperand(0), Op.getOperand(1));
4087 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4088 DAG.getValueType(VT));
4089 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4090 } else if (VT.getSizeInBits() == 16) {
4091 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4092 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4094 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4095 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4096 DAG.getNode(ISD::BIT_CONVERT, dl,
4100 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4101 Op.getOperand(0), Op.getOperand(1));
4102 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4103 DAG.getValueType(VT));
4104 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4105 } else if (VT == MVT::f32) {
4106 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4107 // the result back to FR32 register. It's only worth matching if the
4108 // result has a single use which is a store or a bitcast to i32. And in
4109 // the case of a store, it's not worth it if the index is a constant 0,
4110 // because a MOVSSmr can be used instead, which is smaller and faster.
4111 if (!Op.hasOneUse())
4113 SDNode *User = *Op.getNode()->use_begin();
4114 if ((User->getOpcode() != ISD::STORE ||
4115 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4116 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4117 (User->getOpcode() != ISD::BIT_CONVERT ||
4118 User->getValueType(0) != MVT::i32))
4120 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4121 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4124 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4125 } else if (VT == MVT::i32) {
4126 // ExtractPS works with constant index.
4127 if (isa<ConstantSDNode>(Op.getOperand(1)))
4135 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4136 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4139 if (Subtarget->hasSSE41()) {
4140 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4145 MVT VT = Op.getValueType();
4146 DebugLoc dl = Op.getDebugLoc();
4147 // TODO: handle v16i8.
4148 if (VT.getSizeInBits() == 16) {
4149 SDValue Vec = Op.getOperand(0);
4150 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4152 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4153 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4154 DAG.getNode(ISD::BIT_CONVERT, dl,
4157 // Transform it so it match pextrw which produces a 32-bit result.
4158 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4159 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4160 Op.getOperand(0), Op.getOperand(1));
4161 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4162 DAG.getValueType(VT));
4163 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4164 } else if (VT.getSizeInBits() == 32) {
4165 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4169 // SHUFPS the element to the lowest double word, then movss.
4170 int Mask[4] = { Idx, -1, -1, -1 };
4171 MVT VVT = Op.getOperand(0).getValueType();
4172 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4173 DAG.getUNDEF(VVT), Mask);
4174 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4175 DAG.getIntPtrConstant(0));
4176 } else if (VT.getSizeInBits() == 64) {
4177 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4178 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4179 // to match extract_elt for f64.
4180 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4184 // UNPCKHPD the element to the lowest double word, then movsd.
4185 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4186 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4187 int Mask[2] = { 1, -1 };
4188 MVT VVT = Op.getOperand(0).getValueType();
4189 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4190 DAG.getUNDEF(VVT), Mask);
4191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4192 DAG.getIntPtrConstant(0));
4199 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4200 MVT VT = Op.getValueType();
4201 MVT EVT = VT.getVectorElementType();
4202 DebugLoc dl = Op.getDebugLoc();
4204 SDValue N0 = Op.getOperand(0);
4205 SDValue N1 = Op.getOperand(1);
4206 SDValue N2 = Op.getOperand(2);
4208 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4209 isa<ConstantSDNode>(N2)) {
4210 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4212 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4214 if (N1.getValueType() != MVT::i32)
4215 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4216 if (N2.getValueType() != MVT::i32)
4217 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4218 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4219 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4220 // Bits [7:6] of the constant are the source select. This will always be
4221 // zero here. The DAG Combiner may combine an extract_elt index into these
4222 // bits. For example (insert (extract, 3), 2) could be matched by putting
4223 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4224 // Bits [5:4] of the constant are the destination select. This is the
4225 // value of the incoming immediate.
4226 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4227 // combine either bitwise AND or insert of float 0.0 to set these bits.
4228 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4229 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4230 } else if (EVT == MVT::i32) {
4231 // InsertPS works with constant index.
4232 if (isa<ConstantSDNode>(N2))
4239 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4240 MVT VT = Op.getValueType();
4241 MVT EVT = VT.getVectorElementType();
4243 if (Subtarget->hasSSE41())
4244 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4249 DebugLoc dl = Op.getDebugLoc();
4250 SDValue N0 = Op.getOperand(0);
4251 SDValue N1 = Op.getOperand(1);
4252 SDValue N2 = Op.getOperand(2);
4254 if (EVT.getSizeInBits() == 16) {
4255 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4256 // as its second argument.
4257 if (N1.getValueType() != MVT::i32)
4258 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4259 if (N2.getValueType() != MVT::i32)
4260 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4261 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4267 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4268 DebugLoc dl = Op.getDebugLoc();
4269 if (Op.getValueType() == MVT::v2f32)
4270 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4271 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4272 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4273 Op.getOperand(0))));
4275 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4276 MVT VT = MVT::v2i32;
4277 switch (Op.getValueType().getSimpleVT()) {
4284 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4285 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4288 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4289 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4290 // one of the above mentioned nodes. It has to be wrapped because otherwise
4291 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4292 // be used to form addressing mode. These wrapped nodes will be selected
4295 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4296 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4297 // FIXME there isn't really any debug info here, should come from the parent
4298 DebugLoc dl = CP->getDebugLoc();
4299 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4300 CP->getAlignment());
4301 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4302 // With PIC, the address is actually $g + Offset.
4303 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4304 !Subtarget->isPICStyleRIPRel()) {
4305 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4306 DAG.getNode(X86ISD::GlobalBaseReg,
4307 DebugLoc::getUnknownLoc(),
4316 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4318 SelectionDAG &DAG) const {
4319 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4320 bool ExtraLoadRequired =
4321 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4323 // Create the TargetGlobalAddress node, folding in the constant
4324 // offset if it is legal.
4326 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4327 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4330 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4331 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4333 // With PIC, the address is actually $g + Offset.
4334 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4335 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4336 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4340 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4341 // load the value at address GV, not the value of GV itself. This means that
4342 // the GlobalAddress must be in the base or index register of the address, not
4343 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4344 // The same applies for external symbols during PIC codegen
4345 if (ExtraLoadRequired)
4346 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4347 PseudoSourceValue::getGOT(), 0);
4349 // If there was a non-zero offset that we didn't fold, create an explicit
4352 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4353 DAG.getConstant(Offset, getPointerTy()));
4359 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4360 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4361 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4362 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4366 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4367 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4368 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4369 DebugLoc dl = GA->getDebugLoc();
4370 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4371 GA->getValueType(0),
4374 SDValue Ops[] = { Chain, TGA, *InFlag };
4375 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4377 SDValue Ops[] = { Chain, TGA };
4378 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4380 SDValue Flag = Chain.getValue(1);
4381 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4384 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4386 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4389 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4390 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4391 DAG.getNode(X86ISD::GlobalBaseReg,
4392 DebugLoc::getUnknownLoc(),
4394 InFlag = Chain.getValue(1);
4396 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4399 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4401 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4403 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4406 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4407 // "local exec" model.
4408 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4409 const MVT PtrVT, TLSModel::Model model,
4411 DebugLoc dl = GA->getDebugLoc();
4412 // Get the Thread Pointer
4413 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4414 DebugLoc::getUnknownLoc(), PtrVT,
4415 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4418 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4421 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4423 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4424 GA->getValueType(0),
4426 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4428 if (model == TLSModel::InitialExec)
4429 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4430 PseudoSourceValue::getGOT(), 0);
4432 // The address of the thread local variable is the add of the thread
4433 // pointer with the offset of the variable.
4434 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4438 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4439 // TODO: implement the "local dynamic" model
4440 // TODO: implement the "initial exec"model for pic executables
4441 assert(Subtarget->isTargetELF() &&
4442 "TLS not implemented for non-ELF targets");
4443 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4444 GlobalValue *GV = GA->getGlobal();
4445 TLSModel::Model model =
4446 getTLSModel (GV, getTargetMachine().getRelocationModel());
4447 if (Subtarget->is64Bit()) {
4449 case TLSModel::GeneralDynamic:
4450 case TLSModel::LocalDynamic: // not implemented
4451 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4453 case TLSModel::InitialExec:
4454 case TLSModel::LocalExec:
4455 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4459 case TLSModel::GeneralDynamic:
4460 case TLSModel::LocalDynamic: // not implemented
4461 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4463 case TLSModel::InitialExec:
4464 case TLSModel::LocalExec:
4465 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4468 assert(0 && "Unreachable");
4473 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4474 // FIXME there isn't really any debug info here
4475 DebugLoc dl = Op.getDebugLoc();
4476 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4477 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4478 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4479 // With PIC, the address is actually $g + Offset.
4480 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4481 !Subtarget->isPICStyleRIPRel()) {
4482 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4483 DAG.getNode(X86ISD::GlobalBaseReg,
4484 DebugLoc::getUnknownLoc(),
4492 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4493 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4494 // FIXME there isn't really any debug into here
4495 DebugLoc dl = JT->getDebugLoc();
4496 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4497 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4498 // With PIC, the address is actually $g + Offset.
4499 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4500 !Subtarget->isPICStyleRIPRel()) {
4501 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4502 DAG.getNode(X86ISD::GlobalBaseReg,
4503 DebugLoc::getUnknownLoc(),
4511 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4512 /// take a 2 x i32 value to shift plus a shift amount.
4513 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4514 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4515 MVT VT = Op.getValueType();
4516 unsigned VTBits = VT.getSizeInBits();
4517 DebugLoc dl = Op.getDebugLoc();
4518 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4519 SDValue ShOpLo = Op.getOperand(0);
4520 SDValue ShOpHi = Op.getOperand(1);
4521 SDValue ShAmt = Op.getOperand(2);
4522 SDValue Tmp1 = isSRA ?
4523 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4524 DAG.getConstant(VTBits - 1, MVT::i8)) :
4525 DAG.getConstant(0, VT);
4528 if (Op.getOpcode() == ISD::SHL_PARTS) {
4529 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4530 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4532 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4533 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4536 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4537 DAG.getConstant(VTBits, MVT::i8));
4538 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4539 AndNode, DAG.getConstant(0, MVT::i8));
4542 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4543 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4544 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4546 if (Op.getOpcode() == ISD::SHL_PARTS) {
4547 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4548 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4550 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4551 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4554 SDValue Ops[2] = { Lo, Hi };
4555 return DAG.getMergeValues(Ops, 2, dl);
4558 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4559 MVT SrcVT = Op.getOperand(0).getValueType();
4560 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4561 "Unknown SINT_TO_FP to lower!");
4563 // These are really Legal; return the operand so the caller accepts it as
4565 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4567 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4568 Subtarget->is64Bit()) {
4572 DebugLoc dl = Op.getDebugLoc();
4573 unsigned Size = SrcVT.getSizeInBits()/8;
4574 MachineFunction &MF = DAG.getMachineFunction();
4575 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4576 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4577 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4579 PseudoSourceValue::getFixedStack(SSFI), 0);
4580 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4583 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4585 SelectionDAG &DAG) {
4587 DebugLoc dl = Op.getDebugLoc();
4589 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4591 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4593 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4594 SmallVector<SDValue, 8> Ops;
4595 Ops.push_back(Chain);
4596 Ops.push_back(StackSlot);
4597 Ops.push_back(DAG.getValueType(SrcVT));
4598 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4599 Tys, &Ops[0], Ops.size());
4602 Chain = Result.getValue(1);
4603 SDValue InFlag = Result.getValue(2);
4605 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4606 // shouldn't be necessary except that RFP cannot be live across
4607 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4608 MachineFunction &MF = DAG.getMachineFunction();
4609 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4610 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4611 Tys = DAG.getVTList(MVT::Other);
4612 SmallVector<SDValue, 8> Ops;
4613 Ops.push_back(Chain);
4614 Ops.push_back(Result);
4615 Ops.push_back(StackSlot);
4616 Ops.push_back(DAG.getValueType(Op.getValueType()));
4617 Ops.push_back(InFlag);
4618 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4619 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4620 PseudoSourceValue::getFixedStack(SSFI), 0);
4626 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4627 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4628 // This algorithm is not obvious. Here it is in C code, more or less:
4630 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4631 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4632 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4634 // Copy ints to xmm registers.
4635 __m128i xh = _mm_cvtsi32_si128( hi );
4636 __m128i xl = _mm_cvtsi32_si128( lo );
4638 // Combine into low half of a single xmm register.
4639 __m128i x = _mm_unpacklo_epi32( xh, xl );
4643 // Merge in appropriate exponents to give the integer bits the right
4645 x = _mm_unpacklo_epi32( x, exp );
4647 // Subtract away the biases to deal with the IEEE-754 double precision
4649 d = _mm_sub_pd( (__m128d) x, bias );
4651 // All conversions up to here are exact. The correctly rounded result is
4652 // calculated using the current rounding mode using the following
4654 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4655 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4656 // store doesn't really need to be here (except
4657 // maybe to zero the other double)
4662 DebugLoc dl = Op.getDebugLoc();
4664 // Build some magic constants.
4665 std::vector<Constant*> CV0;
4666 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4667 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4668 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4669 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4670 Constant *C0 = ConstantVector::get(CV0);
4671 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4673 std::vector<Constant*> CV1;
4674 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4675 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4676 Constant *C1 = ConstantVector::get(CV1);
4677 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4679 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4680 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4682 DAG.getIntPtrConstant(1)));
4683 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4684 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4686 DAG.getIntPtrConstant(0)));
4687 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4688 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4689 PseudoSourceValue::getConstantPool(), 0,
4691 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4692 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4693 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4694 PseudoSourceValue::getConstantPool(), 0,
4696 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4698 // Add the halves; easiest way is to swap them into another reg first.
4699 int ShufMask[2] = { 1, -1 };
4700 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4701 DAG.getUNDEF(MVT::v2f64), ShufMask);
4702 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4703 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4704 DAG.getIntPtrConstant(0));
4707 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4708 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4709 DebugLoc dl = Op.getDebugLoc();
4710 // FP constant to bias correct the final result.
4711 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4714 // Load the 32-bit value into an XMM register.
4715 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4716 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4718 DAG.getIntPtrConstant(0)));
4720 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4721 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4722 DAG.getIntPtrConstant(0));
4724 // Or the load with the bias.
4725 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4726 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4727 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4729 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4730 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4731 MVT::v2f64, Bias)));
4732 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4733 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4734 DAG.getIntPtrConstant(0));
4736 // Subtract the bias.
4737 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4739 // Handle final rounding.
4740 MVT DestVT = Op.getValueType();
4742 if (DestVT.bitsLT(MVT::f64)) {
4743 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4744 DAG.getIntPtrConstant(0));
4745 } else if (DestVT.bitsGT(MVT::f64)) {
4746 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4749 // Handle final rounding.
4753 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4754 SDValue N0 = Op.getOperand(0);
4755 DebugLoc dl = Op.getDebugLoc();
4757 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4758 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4759 // the optimization here.
4760 if (DAG.SignBitIsZero(N0))
4761 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4763 MVT SrcVT = N0.getValueType();
4764 if (SrcVT == MVT::i64) {
4765 // We only handle SSE2 f64 target here; caller can expand the rest.
4766 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4769 return LowerUINT_TO_FP_i64(Op, DAG);
4770 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4771 return LowerUINT_TO_FP_i32(Op, DAG);
4774 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4776 // Make a 64-bit buffer, and use it to build an FILD.
4777 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4778 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4779 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4780 getPointerTy(), StackSlot, WordOff);
4781 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4782 StackSlot, NULL, 0);
4783 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4784 OffsetSlot, NULL, 0);
4785 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4788 std::pair<SDValue,SDValue> X86TargetLowering::
4789 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4790 DebugLoc dl = Op.getDebugLoc();
4792 MVT DstTy = Op.getValueType();
4795 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4799 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4800 DstTy.getSimpleVT() >= MVT::i16 &&
4801 "Unknown FP_TO_SINT to lower!");
4803 // These are really Legal.
4804 if (DstTy == MVT::i32 &&
4805 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4806 return std::make_pair(SDValue(), SDValue());
4807 if (Subtarget->is64Bit() &&
4808 DstTy == MVT::i64 &&
4809 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4810 return std::make_pair(SDValue(), SDValue());
4812 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4814 MachineFunction &MF = DAG.getMachineFunction();
4815 unsigned MemSize = DstTy.getSizeInBits()/8;
4816 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4817 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4820 switch (DstTy.getSimpleVT()) {
4821 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4822 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4823 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4824 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4827 SDValue Chain = DAG.getEntryNode();
4828 SDValue Value = Op.getOperand(0);
4829 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4830 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4831 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4832 PseudoSourceValue::getFixedStack(SSFI), 0);
4833 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4835 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4837 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4838 Chain = Value.getValue(1);
4839 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4840 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4843 // Build the FP_TO_INT*_IN_MEM
4844 SDValue Ops[] = { Chain, Value, StackSlot };
4845 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4847 return std::make_pair(FIST, StackSlot);
4850 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4851 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4852 SDValue FIST = Vals.first, StackSlot = Vals.second;
4853 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4854 if (FIST.getNode() == 0) return Op;
4857 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4858 FIST, StackSlot, NULL, 0);
4861 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4862 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4863 SDValue FIST = Vals.first, StackSlot = Vals.second;
4864 assert(FIST.getNode() && "Unexpected failure");
4867 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4868 FIST, StackSlot, NULL, 0);
4871 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4872 DebugLoc dl = Op.getDebugLoc();
4873 MVT VT = Op.getValueType();
4876 EltVT = VT.getVectorElementType();
4877 std::vector<Constant*> CV;
4878 if (EltVT == MVT::f64) {
4879 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4883 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4889 Constant *C = ConstantVector::get(CV);
4890 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4891 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4892 PseudoSourceValue::getConstantPool(), 0,
4894 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4897 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4898 DebugLoc dl = Op.getDebugLoc();
4899 MVT VT = Op.getValueType();
4901 unsigned EltNum = 1;
4902 if (VT.isVector()) {
4903 EltVT = VT.getVectorElementType();
4904 EltNum = VT.getVectorNumElements();
4906 std::vector<Constant*> CV;
4907 if (EltVT == MVT::f64) {
4908 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4912 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4918 Constant *C = ConstantVector::get(CV);
4919 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4920 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4921 PseudoSourceValue::getConstantPool(), 0,
4923 if (VT.isVector()) {
4924 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4925 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4926 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4928 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4930 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4934 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4935 SDValue Op0 = Op.getOperand(0);
4936 SDValue Op1 = Op.getOperand(1);
4937 DebugLoc dl = Op.getDebugLoc();
4938 MVT VT = Op.getValueType();
4939 MVT SrcVT = Op1.getValueType();
4941 // If second operand is smaller, extend it first.
4942 if (SrcVT.bitsLT(VT)) {
4943 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4946 // And if it is bigger, shrink it first.
4947 if (SrcVT.bitsGT(VT)) {
4948 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4952 // At this point the operands and the result should have the same
4953 // type, and that won't be f80 since that is not custom lowered.
4955 // First get the sign bit of second operand.
4956 std::vector<Constant*> CV;
4957 if (SrcVT == MVT::f64) {
4958 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4959 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4961 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4962 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4963 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4964 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4966 Constant *C = ConstantVector::get(CV);
4967 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4968 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4969 PseudoSourceValue::getConstantPool(), 0,
4971 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
4973 // Shift sign bit right or left if the two operands have different types.
4974 if (SrcVT.bitsGT(VT)) {
4975 // Op0 is MVT::f32, Op1 is MVT::f64.
4976 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
4977 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
4978 DAG.getConstant(32, MVT::i32));
4979 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
4980 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
4981 DAG.getIntPtrConstant(0));
4984 // Clear first operand sign bit.
4986 if (VT == MVT::f64) {
4987 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4988 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4990 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4991 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4992 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4993 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4995 C = ConstantVector::get(CV);
4996 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4997 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4998 PseudoSourceValue::getConstantPool(), 0,
5000 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5002 // Or the value with the sign bit.
5003 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5006 /// Emit nodes that will be selected as "test Op0,Op0", or something
5008 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5009 SelectionDAG &DAG) {
5010 DebugLoc dl = Op.getDebugLoc();
5012 // CF and OF aren't always set the way we want. Determine which
5013 // of these we need.
5014 bool NeedCF = false;
5015 bool NeedOF = false;
5017 case X86::COND_A: case X86::COND_AE:
5018 case X86::COND_B: case X86::COND_BE:
5021 case X86::COND_G: case X86::COND_GE:
5022 case X86::COND_L: case X86::COND_LE:
5023 case X86::COND_O: case X86::COND_NO:
5029 // See if we can use the EFLAGS value from the operand instead of
5030 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5031 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5032 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5033 unsigned Opcode = 0;
5034 unsigned NumOperands = 0;
5035 switch (Op.getNode()->getOpcode()) {
5037 // Due to an isel shortcoming, be conservative if this add is likely to
5038 // be selected as part of a load-modify-store instruction. When the root
5039 // node in a match is a store, isel doesn't know how to remap non-chain
5040 // non-flag uses of other nodes in the match, such as the ADD in this
5041 // case. This leads to the ADD being left around and reselected, with
5042 // the result being two adds in the output.
5043 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5044 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5045 if (UI->getOpcode() == ISD::STORE)
5047 if (ConstantSDNode *C =
5048 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5049 // An add of one will be selected as an INC.
5050 if (C->getAPIntValue() == 1) {
5051 Opcode = X86ISD::INC;
5055 // An add of negative one (subtract of one) will be selected as a DEC.
5056 if (C->getAPIntValue().isAllOnesValue()) {
5057 Opcode = X86ISD::DEC;
5062 // Otherwise use a regular EFLAGS-setting add.
5063 Opcode = X86ISD::ADD;
5067 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5068 // likely to be selected as part of a load-modify-store instruction.
5069 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5070 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5071 if (UI->getOpcode() == ISD::STORE)
5073 // Otherwise use a regular EFLAGS-setting sub.
5074 Opcode = X86ISD::SUB;
5081 return SDValue(Op.getNode(), 1);
5087 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5088 SmallVector<SDValue, 4> Ops;
5089 for (unsigned i = 0; i != NumOperands; ++i)
5090 Ops.push_back(Op.getOperand(i));
5091 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5092 DAG.ReplaceAllUsesWith(Op, New);
5093 return SDValue(New.getNode(), 1);
5097 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5098 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5099 DAG.getConstant(0, Op.getValueType()));
5102 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5104 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5105 SelectionDAG &DAG) {
5106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5107 if (C->getAPIntValue() == 0)
5108 return EmitTest(Op0, X86CC, DAG);
5110 DebugLoc dl = Op0.getDebugLoc();
5111 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5114 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5115 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5116 SDValue Op0 = Op.getOperand(0);
5117 SDValue Op1 = Op.getOperand(1);
5118 DebugLoc dl = Op.getDebugLoc();
5119 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5121 // Lower (X & (1 << N)) == 0 to BT(X, N).
5122 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5123 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5124 if (Op0.getOpcode() == ISD::AND &&
5126 Op1.getOpcode() == ISD::Constant &&
5127 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5128 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5130 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5131 if (ConstantSDNode *Op010C =
5132 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5133 if (Op010C->getZExtValue() == 1) {
5134 LHS = Op0.getOperand(0);
5135 RHS = Op0.getOperand(1).getOperand(1);
5137 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5138 if (ConstantSDNode *Op000C =
5139 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5140 if (Op000C->getZExtValue() == 1) {
5141 LHS = Op0.getOperand(1);
5142 RHS = Op0.getOperand(0).getOperand(1);
5144 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5145 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5146 SDValue AndLHS = Op0.getOperand(0);
5147 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5148 LHS = AndLHS.getOperand(0);
5149 RHS = AndLHS.getOperand(1);
5153 if (LHS.getNode()) {
5154 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5155 // instruction. Since the shift amount is in-range-or-undefined, we know
5156 // that doing a bittest on the i16 value is ok. We extend to i32 because
5157 // the encoding for the i16 version is larger than the i32 version.
5158 if (LHS.getValueType() == MVT::i8)
5159 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5161 // If the operand types disagree, extend the shift amount to match. Since
5162 // BT ignores high bits (like shifts) we can use anyextend.
5163 if (LHS.getValueType() != RHS.getValueType())
5164 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5166 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5167 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5168 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5169 DAG.getConstant(Cond, MVT::i8), BT);
5173 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5174 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5176 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5177 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5178 DAG.getConstant(X86CC, MVT::i8), Cond);
5181 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5183 SDValue Op0 = Op.getOperand(0);
5184 SDValue Op1 = Op.getOperand(1);
5185 SDValue CC = Op.getOperand(2);
5186 MVT VT = Op.getValueType();
5187 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5188 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5189 DebugLoc dl = Op.getDebugLoc();
5193 MVT VT0 = Op0.getValueType();
5194 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5195 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5198 switch (SetCCOpcode) {
5201 case ISD::SETEQ: SSECC = 0; break;
5203 case ISD::SETGT: Swap = true; // Fallthrough
5205 case ISD::SETOLT: SSECC = 1; break;
5207 case ISD::SETGE: Swap = true; // Fallthrough
5209 case ISD::SETOLE: SSECC = 2; break;
5210 case ISD::SETUO: SSECC = 3; break;
5212 case ISD::SETNE: SSECC = 4; break;
5213 case ISD::SETULE: Swap = true;
5214 case ISD::SETUGE: SSECC = 5; break;
5215 case ISD::SETULT: Swap = true;
5216 case ISD::SETUGT: SSECC = 6; break;
5217 case ISD::SETO: SSECC = 7; break;
5220 std::swap(Op0, Op1);
5222 // In the two special cases we can't handle, emit two comparisons.
5224 if (SetCCOpcode == ISD::SETUEQ) {
5226 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5227 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5228 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5230 else if (SetCCOpcode == ISD::SETONE) {
5232 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5233 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5234 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5236 assert(0 && "Illegal FP comparison");
5238 // Handle all other FP comparisons here.
5239 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5242 // We are handling one of the integer comparisons here. Since SSE only has
5243 // GT and EQ comparisons for integer, swapping operands and multiple
5244 // operations may be required for some comparisons.
5245 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5246 bool Swap = false, Invert = false, FlipSigns = false;
5248 switch (VT.getSimpleVT()) {
5250 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5251 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5252 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5253 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5256 switch (SetCCOpcode) {
5258 case ISD::SETNE: Invert = true;
5259 case ISD::SETEQ: Opc = EQOpc; break;
5260 case ISD::SETLT: Swap = true;
5261 case ISD::SETGT: Opc = GTOpc; break;
5262 case ISD::SETGE: Swap = true;
5263 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5264 case ISD::SETULT: Swap = true;
5265 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5266 case ISD::SETUGE: Swap = true;
5267 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5270 std::swap(Op0, Op1);
5272 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5273 // bits of the inputs before performing those operations.
5275 MVT EltVT = VT.getVectorElementType();
5276 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5278 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5279 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5281 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5282 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5285 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5287 // If the logical-not of the result is required, perform that now.
5289 Result = DAG.getNOT(dl, Result, VT);
5294 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5295 static bool isX86LogicalCmp(SDValue Op) {
5296 unsigned Opc = Op.getNode()->getOpcode();
5297 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5299 if (Op.getResNo() == 1 &&
5300 (Opc == X86ISD::ADD ||
5301 Opc == X86ISD::SUB ||
5302 Opc == X86ISD::SMUL ||
5303 Opc == X86ISD::UMUL ||
5304 Opc == X86ISD::INC ||
5305 Opc == X86ISD::DEC))
5311 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5312 bool addTest = true;
5313 SDValue Cond = Op.getOperand(0);
5314 DebugLoc dl = Op.getDebugLoc();
5317 if (Cond.getOpcode() == ISD::SETCC)
5318 Cond = LowerSETCC(Cond, DAG);
5320 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5321 // setting operand in place of the X86ISD::SETCC.
5322 if (Cond.getOpcode() == X86ISD::SETCC) {
5323 CC = Cond.getOperand(0);
5325 SDValue Cmp = Cond.getOperand(1);
5326 unsigned Opc = Cmp.getOpcode();
5327 MVT VT = Op.getValueType();
5329 bool IllegalFPCMov = false;
5330 if (VT.isFloatingPoint() && !VT.isVector() &&
5331 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5332 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5334 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5335 Opc == X86ISD::BT) { // FIXME
5342 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5343 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5347 SmallVector<SDValue, 4> Ops;
5348 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5349 // condition is true.
5350 Ops.push_back(Op.getOperand(2));
5351 Ops.push_back(Op.getOperand(1));
5353 Ops.push_back(Cond);
5354 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5357 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5358 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5359 // from the AND / OR.
5360 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5361 Opc = Op.getOpcode();
5362 if (Opc != ISD::OR && Opc != ISD::AND)
5364 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5365 Op.getOperand(0).hasOneUse() &&
5366 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5367 Op.getOperand(1).hasOneUse());
5370 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5371 // 1 and that the SETCC node has a single use.
5372 static bool isXor1OfSetCC(SDValue Op) {
5373 if (Op.getOpcode() != ISD::XOR)
5375 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5376 if (N1C && N1C->getAPIntValue() == 1) {
5377 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5378 Op.getOperand(0).hasOneUse();
5383 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5384 bool addTest = true;
5385 SDValue Chain = Op.getOperand(0);
5386 SDValue Cond = Op.getOperand(1);
5387 SDValue Dest = Op.getOperand(2);
5388 DebugLoc dl = Op.getDebugLoc();
5391 if (Cond.getOpcode() == ISD::SETCC)
5392 Cond = LowerSETCC(Cond, DAG);
5394 // FIXME: LowerXALUO doesn't handle these!!
5395 else if (Cond.getOpcode() == X86ISD::ADD ||
5396 Cond.getOpcode() == X86ISD::SUB ||
5397 Cond.getOpcode() == X86ISD::SMUL ||
5398 Cond.getOpcode() == X86ISD::UMUL)
5399 Cond = LowerXALUO(Cond, DAG);
5402 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5403 // setting operand in place of the X86ISD::SETCC.
5404 if (Cond.getOpcode() == X86ISD::SETCC) {
5405 CC = Cond.getOperand(0);
5407 SDValue Cmp = Cond.getOperand(1);
5408 unsigned Opc = Cmp.getOpcode();
5409 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5410 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5414 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5418 // These can only come from an arithmetic instruction with overflow,
5419 // e.g. SADDO, UADDO.
5420 Cond = Cond.getNode()->getOperand(1);
5427 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5428 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5429 if (CondOpc == ISD::OR) {
5430 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5431 // two branches instead of an explicit OR instruction with a
5433 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5434 isX86LogicalCmp(Cmp)) {
5435 CC = Cond.getOperand(0).getOperand(0);
5436 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5437 Chain, Dest, CC, Cmp);
5438 CC = Cond.getOperand(1).getOperand(0);
5442 } else { // ISD::AND
5443 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5444 // two branches instead of an explicit AND instruction with a
5445 // separate test. However, we only do this if this block doesn't
5446 // have a fall-through edge, because this requires an explicit
5447 // jmp when the condition is false.
5448 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5449 isX86LogicalCmp(Cmp) &&
5450 Op.getNode()->hasOneUse()) {
5451 X86::CondCode CCode =
5452 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5453 CCode = X86::GetOppositeBranchCondition(CCode);
5454 CC = DAG.getConstant(CCode, MVT::i8);
5455 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5456 // Look for an unconditional branch following this conditional branch.
5457 // We need this because we need to reverse the successors in order
5458 // to implement FCMP_OEQ.
5459 if (User.getOpcode() == ISD::BR) {
5460 SDValue FalseBB = User.getOperand(1);
5462 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5463 assert(NewBR == User);
5466 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5467 Chain, Dest, CC, Cmp);
5468 X86::CondCode CCode =
5469 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5470 CCode = X86::GetOppositeBranchCondition(CCode);
5471 CC = DAG.getConstant(CCode, MVT::i8);
5477 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5478 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5479 // It should be transformed during dag combiner except when the condition
5480 // is set by a arithmetics with overflow node.
5481 X86::CondCode CCode =
5482 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5483 CCode = X86::GetOppositeBranchCondition(CCode);
5484 CC = DAG.getConstant(CCode, MVT::i8);
5485 Cond = Cond.getOperand(0).getOperand(1);
5491 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5492 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5494 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5495 Chain, Dest, CC, Cond);
5499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5502 // that the guard pages used by the OS virtual memory manager are allocated in
5503 // correct sequence.
5505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5506 SelectionDAG &DAG) {
5507 assert(Subtarget->isTargetCygMing() &&
5508 "This should be used only on Cygwin/Mingw targets");
5509 DebugLoc dl = Op.getDebugLoc();
5512 SDValue Chain = Op.getOperand(0);
5513 SDValue Size = Op.getOperand(1);
5514 // FIXME: Ensure alignment here
5518 MVT IntPtr = getPointerTy();
5519 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5521 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5523 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5524 Flag = Chain.getValue(1);
5526 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5527 SDValue Ops[] = { Chain,
5528 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5529 DAG.getRegister(X86::EAX, IntPtr),
5530 DAG.getRegister(X86StackPtr, SPTy),
5532 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5533 Flag = Chain.getValue(1);
5535 Chain = DAG.getCALLSEQ_END(Chain,
5536 DAG.getIntPtrConstant(0, true),
5537 DAG.getIntPtrConstant(0, true),
5540 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5542 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5543 return DAG.getMergeValues(Ops1, 2, dl);
5547 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5549 SDValue Dst, SDValue Src,
5550 SDValue Size, unsigned Align,
5552 uint64_t DstSVOff) {
5553 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5555 // If not DWORD aligned or size is more than the threshold, call the library.
5556 // The libc version is likely to be faster for these cases. It can use the
5557 // address value and run time information about the CPU.
5558 if ((Align & 3) != 0 ||
5560 ConstantSize->getZExtValue() >
5561 getSubtarget()->getMaxInlineSizeThreshold()) {
5562 SDValue InFlag(0, 0);
5564 // Check to see if there is a specialized entry-point for memory zeroing.
5565 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5567 if (const char *bzeroEntry = V &&
5568 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5569 MVT IntPtr = getPointerTy();
5570 const Type *IntPtrTy = TD->getIntPtrType();
5571 TargetLowering::ArgListTy Args;
5572 TargetLowering::ArgListEntry Entry;
5574 Entry.Ty = IntPtrTy;
5575 Args.push_back(Entry);
5577 Args.push_back(Entry);
5578 std::pair<SDValue,SDValue> CallResult =
5579 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5580 CallingConv::C, false,
5581 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5582 return CallResult.second;
5585 // Otherwise have the target-independent code call memset.
5589 uint64_t SizeVal = ConstantSize->getZExtValue();
5590 SDValue InFlag(0, 0);
5593 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5594 unsigned BytesLeft = 0;
5595 bool TwoRepStos = false;
5598 uint64_t Val = ValC->getZExtValue() & 255;
5600 // If the value is a constant, then we can potentially use larger sets.
5601 switch (Align & 3) {
5602 case 2: // WORD aligned
5605 Val = (Val << 8) | Val;
5607 case 0: // DWORD aligned
5610 Val = (Val << 8) | Val;
5611 Val = (Val << 16) | Val;
5612 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5615 Val = (Val << 32) | Val;
5618 default: // Byte aligned
5621 Count = DAG.getIntPtrConstant(SizeVal);
5625 if (AVT.bitsGT(MVT::i8)) {
5626 unsigned UBytes = AVT.getSizeInBits() / 8;
5627 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5628 BytesLeft = SizeVal % UBytes;
5631 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5633 InFlag = Chain.getValue(1);
5636 Count = DAG.getIntPtrConstant(SizeVal);
5637 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5638 InFlag = Chain.getValue(1);
5641 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5644 InFlag = Chain.getValue(1);
5645 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5648 InFlag = Chain.getValue(1);
5650 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5651 SmallVector<SDValue, 8> Ops;
5652 Ops.push_back(Chain);
5653 Ops.push_back(DAG.getValueType(AVT));
5654 Ops.push_back(InFlag);
5655 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5658 InFlag = Chain.getValue(1);
5660 MVT CVT = Count.getValueType();
5661 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5662 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5663 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5666 InFlag = Chain.getValue(1);
5667 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5669 Ops.push_back(Chain);
5670 Ops.push_back(DAG.getValueType(MVT::i8));
5671 Ops.push_back(InFlag);
5672 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5673 } else if (BytesLeft) {
5674 // Handle the last 1 - 7 bytes.
5675 unsigned Offset = SizeVal - BytesLeft;
5676 MVT AddrVT = Dst.getValueType();
5677 MVT SizeVT = Size.getValueType();
5679 Chain = DAG.getMemset(Chain, dl,
5680 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5681 DAG.getConstant(Offset, AddrVT)),
5683 DAG.getConstant(BytesLeft, SizeVT),
5684 Align, DstSV, DstSVOff + Offset);
5687 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5692 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5693 SDValue Chain, SDValue Dst, SDValue Src,
5694 SDValue Size, unsigned Align,
5696 const Value *DstSV, uint64_t DstSVOff,
5697 const Value *SrcSV, uint64_t SrcSVOff) {
5698 // This requires the copy size to be a constant, preferrably
5699 // within a subtarget-specific limit.
5700 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5703 uint64_t SizeVal = ConstantSize->getZExtValue();
5704 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5707 /// If not DWORD aligned, call the library.
5708 if ((Align & 3) != 0)
5713 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5716 unsigned UBytes = AVT.getSizeInBits() / 8;
5717 unsigned CountVal = SizeVal / UBytes;
5718 SDValue Count = DAG.getIntPtrConstant(CountVal);
5719 unsigned BytesLeft = SizeVal % UBytes;
5721 SDValue InFlag(0, 0);
5722 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5725 InFlag = Chain.getValue(1);
5726 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5729 InFlag = Chain.getValue(1);
5730 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5733 InFlag = Chain.getValue(1);
5735 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5736 SmallVector<SDValue, 8> Ops;
5737 Ops.push_back(Chain);
5738 Ops.push_back(DAG.getValueType(AVT));
5739 Ops.push_back(InFlag);
5740 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5742 SmallVector<SDValue, 4> Results;
5743 Results.push_back(RepMovs);
5745 // Handle the last 1 - 7 bytes.
5746 unsigned Offset = SizeVal - BytesLeft;
5747 MVT DstVT = Dst.getValueType();
5748 MVT SrcVT = Src.getValueType();
5749 MVT SizeVT = Size.getValueType();
5750 Results.push_back(DAG.getMemcpy(Chain, dl,
5751 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5752 DAG.getConstant(Offset, DstVT)),
5753 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5754 DAG.getConstant(Offset, SrcVT)),
5755 DAG.getConstant(BytesLeft, SizeVT),
5756 Align, AlwaysInline,
5757 DstSV, DstSVOff + Offset,
5758 SrcSV, SrcSVOff + Offset));
5761 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5762 &Results[0], Results.size());
5765 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5766 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5767 DebugLoc dl = Op.getDebugLoc();
5769 if (!Subtarget->is64Bit()) {
5770 // vastart just stores the address of the VarArgsFrameIndex slot into the
5771 // memory location argument.
5772 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5773 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5777 // gp_offset (0 - 6 * 8)
5778 // fp_offset (48 - 48 + 8 * 16)
5779 // overflow_arg_area (point to parameters coming in memory).
5781 SmallVector<SDValue, 8> MemOps;
5782 SDValue FIN = Op.getOperand(1);
5784 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5785 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5787 MemOps.push_back(Store);
5790 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5791 FIN, DAG.getIntPtrConstant(4));
5792 Store = DAG.getStore(Op.getOperand(0), dl,
5793 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5795 MemOps.push_back(Store);
5797 // Store ptr to overflow_arg_area
5798 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5799 FIN, DAG.getIntPtrConstant(4));
5800 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5801 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5802 MemOps.push_back(Store);
5804 // Store ptr to reg_save_area.
5805 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5806 FIN, DAG.getIntPtrConstant(8));
5807 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5808 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5809 MemOps.push_back(Store);
5810 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5811 &MemOps[0], MemOps.size());
5814 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5815 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5816 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5817 SDValue Chain = Op.getOperand(0);
5818 SDValue SrcPtr = Op.getOperand(1);
5819 SDValue SrcSV = Op.getOperand(2);
5821 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5826 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5827 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5828 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5829 SDValue Chain = Op.getOperand(0);
5830 SDValue DstPtr = Op.getOperand(1);
5831 SDValue SrcPtr = Op.getOperand(2);
5832 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5833 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5834 DebugLoc dl = Op.getDebugLoc();
5836 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5837 DAG.getIntPtrConstant(24), 8, false,
5838 DstSV, 0, SrcSV, 0);
5842 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5843 DebugLoc dl = Op.getDebugLoc();
5844 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5846 default: return SDValue(); // Don't custom lower most intrinsics.
5847 // Comparison intrinsics.
5848 case Intrinsic::x86_sse_comieq_ss:
5849 case Intrinsic::x86_sse_comilt_ss:
5850 case Intrinsic::x86_sse_comile_ss:
5851 case Intrinsic::x86_sse_comigt_ss:
5852 case Intrinsic::x86_sse_comige_ss:
5853 case Intrinsic::x86_sse_comineq_ss:
5854 case Intrinsic::x86_sse_ucomieq_ss:
5855 case Intrinsic::x86_sse_ucomilt_ss:
5856 case Intrinsic::x86_sse_ucomile_ss:
5857 case Intrinsic::x86_sse_ucomigt_ss:
5858 case Intrinsic::x86_sse_ucomige_ss:
5859 case Intrinsic::x86_sse_ucomineq_ss:
5860 case Intrinsic::x86_sse2_comieq_sd:
5861 case Intrinsic::x86_sse2_comilt_sd:
5862 case Intrinsic::x86_sse2_comile_sd:
5863 case Intrinsic::x86_sse2_comigt_sd:
5864 case Intrinsic::x86_sse2_comige_sd:
5865 case Intrinsic::x86_sse2_comineq_sd:
5866 case Intrinsic::x86_sse2_ucomieq_sd:
5867 case Intrinsic::x86_sse2_ucomilt_sd:
5868 case Intrinsic::x86_sse2_ucomile_sd:
5869 case Intrinsic::x86_sse2_ucomigt_sd:
5870 case Intrinsic::x86_sse2_ucomige_sd:
5871 case Intrinsic::x86_sse2_ucomineq_sd: {
5873 ISD::CondCode CC = ISD::SETCC_INVALID;
5876 case Intrinsic::x86_sse_comieq_ss:
5877 case Intrinsic::x86_sse2_comieq_sd:
5881 case Intrinsic::x86_sse_comilt_ss:
5882 case Intrinsic::x86_sse2_comilt_sd:
5886 case Intrinsic::x86_sse_comile_ss:
5887 case Intrinsic::x86_sse2_comile_sd:
5891 case Intrinsic::x86_sse_comigt_ss:
5892 case Intrinsic::x86_sse2_comigt_sd:
5896 case Intrinsic::x86_sse_comige_ss:
5897 case Intrinsic::x86_sse2_comige_sd:
5901 case Intrinsic::x86_sse_comineq_ss:
5902 case Intrinsic::x86_sse2_comineq_sd:
5906 case Intrinsic::x86_sse_ucomieq_ss:
5907 case Intrinsic::x86_sse2_ucomieq_sd:
5908 Opc = X86ISD::UCOMI;
5911 case Intrinsic::x86_sse_ucomilt_ss:
5912 case Intrinsic::x86_sse2_ucomilt_sd:
5913 Opc = X86ISD::UCOMI;
5916 case Intrinsic::x86_sse_ucomile_ss:
5917 case Intrinsic::x86_sse2_ucomile_sd:
5918 Opc = X86ISD::UCOMI;
5921 case Intrinsic::x86_sse_ucomigt_ss:
5922 case Intrinsic::x86_sse2_ucomigt_sd:
5923 Opc = X86ISD::UCOMI;
5926 case Intrinsic::x86_sse_ucomige_ss:
5927 case Intrinsic::x86_sse2_ucomige_sd:
5928 Opc = X86ISD::UCOMI;
5931 case Intrinsic::x86_sse_ucomineq_ss:
5932 case Intrinsic::x86_sse2_ucomineq_sd:
5933 Opc = X86ISD::UCOMI;
5938 SDValue LHS = Op.getOperand(1);
5939 SDValue RHS = Op.getOperand(2);
5940 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5941 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5942 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5943 DAG.getConstant(X86CC, MVT::i8), Cond);
5944 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5947 // Fix vector shift instructions where the last operand is a non-immediate
5949 case Intrinsic::x86_sse2_pslli_w:
5950 case Intrinsic::x86_sse2_pslli_d:
5951 case Intrinsic::x86_sse2_pslli_q:
5952 case Intrinsic::x86_sse2_psrli_w:
5953 case Intrinsic::x86_sse2_psrli_d:
5954 case Intrinsic::x86_sse2_psrli_q:
5955 case Intrinsic::x86_sse2_psrai_w:
5956 case Intrinsic::x86_sse2_psrai_d:
5957 case Intrinsic::x86_mmx_pslli_w:
5958 case Intrinsic::x86_mmx_pslli_d:
5959 case Intrinsic::x86_mmx_pslli_q:
5960 case Intrinsic::x86_mmx_psrli_w:
5961 case Intrinsic::x86_mmx_psrli_d:
5962 case Intrinsic::x86_mmx_psrli_q:
5963 case Intrinsic::x86_mmx_psrai_w:
5964 case Intrinsic::x86_mmx_psrai_d: {
5965 SDValue ShAmt = Op.getOperand(2);
5966 if (isa<ConstantSDNode>(ShAmt))
5969 unsigned NewIntNo = 0;
5970 MVT ShAmtVT = MVT::v4i32;
5972 case Intrinsic::x86_sse2_pslli_w:
5973 NewIntNo = Intrinsic::x86_sse2_psll_w;
5975 case Intrinsic::x86_sse2_pslli_d:
5976 NewIntNo = Intrinsic::x86_sse2_psll_d;
5978 case Intrinsic::x86_sse2_pslli_q:
5979 NewIntNo = Intrinsic::x86_sse2_psll_q;
5981 case Intrinsic::x86_sse2_psrli_w:
5982 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5984 case Intrinsic::x86_sse2_psrli_d:
5985 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5987 case Intrinsic::x86_sse2_psrli_q:
5988 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5990 case Intrinsic::x86_sse2_psrai_w:
5991 NewIntNo = Intrinsic::x86_sse2_psra_w;
5993 case Intrinsic::x86_sse2_psrai_d:
5994 NewIntNo = Intrinsic::x86_sse2_psra_d;
5997 ShAmtVT = MVT::v2i32;
5999 case Intrinsic::x86_mmx_pslli_w:
6000 NewIntNo = Intrinsic::x86_mmx_psll_w;
6002 case Intrinsic::x86_mmx_pslli_d:
6003 NewIntNo = Intrinsic::x86_mmx_psll_d;
6005 case Intrinsic::x86_mmx_pslli_q:
6006 NewIntNo = Intrinsic::x86_mmx_psll_q;
6008 case Intrinsic::x86_mmx_psrli_w:
6009 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6011 case Intrinsic::x86_mmx_psrli_d:
6012 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6014 case Intrinsic::x86_mmx_psrli_q:
6015 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6017 case Intrinsic::x86_mmx_psrai_w:
6018 NewIntNo = Intrinsic::x86_mmx_psra_w;
6020 case Intrinsic::x86_mmx_psrai_d:
6021 NewIntNo = Intrinsic::x86_mmx_psra_d;
6023 default: abort(); // Can't reach here.
6028 MVT VT = Op.getValueType();
6029 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6030 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6031 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6032 DAG.getConstant(NewIntNo, MVT::i32),
6033 Op.getOperand(1), ShAmt);
6038 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6039 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6040 DebugLoc dl = Op.getDebugLoc();
6043 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6045 DAG.getConstant(TD->getPointerSize(),
6046 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6047 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6048 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6053 // Just load the return address.
6054 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6055 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6056 RetAddrFI, NULL, 0);
6059 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6060 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6061 MFI->setFrameAddressIsTaken(true);
6062 MVT VT = Op.getValueType();
6063 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6064 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6065 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6066 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6068 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6072 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6073 SelectionDAG &DAG) {
6074 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6077 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6079 MachineFunction &MF = DAG.getMachineFunction();
6080 SDValue Chain = Op.getOperand(0);
6081 SDValue Offset = Op.getOperand(1);
6082 SDValue Handler = Op.getOperand(2);
6083 DebugLoc dl = Op.getDebugLoc();
6085 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6087 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6089 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6090 DAG.getIntPtrConstant(-TD->getPointerSize()));
6091 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6092 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6093 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6094 MF.getRegInfo().addLiveOut(StoreAddrReg);
6096 return DAG.getNode(X86ISD::EH_RETURN, dl,
6098 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6101 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6102 SelectionDAG &DAG) {
6103 SDValue Root = Op.getOperand(0);
6104 SDValue Trmp = Op.getOperand(1); // trampoline
6105 SDValue FPtr = Op.getOperand(2); // nested function
6106 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6107 DebugLoc dl = Op.getDebugLoc();
6109 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6111 const X86InstrInfo *TII =
6112 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6114 if (Subtarget->is64Bit()) {
6115 SDValue OutChains[6];
6117 // Large code-model.
6119 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6120 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6122 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6123 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6125 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6127 // Load the pointer to the nested function into R11.
6128 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6129 SDValue Addr = Trmp;
6130 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6133 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6134 DAG.getConstant(2, MVT::i64));
6135 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6137 // Load the 'nest' parameter value into R10.
6138 // R10 is specified in X86CallingConv.td
6139 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6140 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6141 DAG.getConstant(10, MVT::i64));
6142 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6143 Addr, TrmpAddr, 10);
6145 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6146 DAG.getConstant(12, MVT::i64));
6147 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6149 // Jump to the nested function.
6150 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6151 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6152 DAG.getConstant(20, MVT::i64));
6153 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6154 Addr, TrmpAddr, 20);
6156 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6157 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6158 DAG.getConstant(22, MVT::i64));
6159 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6163 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6164 return DAG.getMergeValues(Ops, 2, dl);
6166 const Function *Func =
6167 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6168 unsigned CC = Func->getCallingConv();
6173 assert(0 && "Unsupported calling convention");
6174 case CallingConv::C:
6175 case CallingConv::X86_StdCall: {
6176 // Pass 'nest' parameter in ECX.
6177 // Must be kept in sync with X86CallingConv.td
6180 // Check that ECX wasn't needed by an 'inreg' parameter.
6181 const FunctionType *FTy = Func->getFunctionType();
6182 const AttrListPtr &Attrs = Func->getAttributes();
6184 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6185 unsigned InRegCount = 0;
6188 for (FunctionType::param_iterator I = FTy->param_begin(),
6189 E = FTy->param_end(); I != E; ++I, ++Idx)
6190 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6191 // FIXME: should only count parameters that are lowered to integers.
6192 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6194 if (InRegCount > 2) {
6195 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6201 case CallingConv::X86_FastCall:
6202 case CallingConv::Fast:
6203 // Pass 'nest' parameter in EAX.
6204 // Must be kept in sync with X86CallingConv.td
6209 SDValue OutChains[4];
6212 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6213 DAG.getConstant(10, MVT::i32));
6214 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6216 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6217 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6218 OutChains[0] = DAG.getStore(Root, dl,
6219 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6222 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6223 DAG.getConstant(1, MVT::i32));
6224 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6226 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6227 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6228 DAG.getConstant(5, MVT::i32));
6229 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6230 TrmpAddr, 5, false, 1);
6232 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6233 DAG.getConstant(6, MVT::i32));
6234 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6237 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6238 return DAG.getMergeValues(Ops, 2, dl);
6242 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6244 The rounding mode is in bits 11:10 of FPSR, and has the following
6251 FLT_ROUNDS, on the other hand, expects the following:
6258 To perform the conversion, we do:
6259 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6262 MachineFunction &MF = DAG.getMachineFunction();
6263 const TargetMachine &TM = MF.getTarget();
6264 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6265 unsigned StackAlignment = TFI.getStackAlignment();
6266 MVT VT = Op.getValueType();
6267 DebugLoc dl = Op.getDebugLoc();
6269 // Save FP Control Word to stack slot
6270 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6271 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6273 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6274 DAG.getEntryNode(), StackSlot);
6276 // Load FP Control Word from stack slot
6277 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6279 // Transform as necessary
6281 DAG.getNode(ISD::SRL, dl, MVT::i16,
6282 DAG.getNode(ISD::AND, dl, MVT::i16,
6283 CWD, DAG.getConstant(0x800, MVT::i16)),
6284 DAG.getConstant(11, MVT::i8));
6286 DAG.getNode(ISD::SRL, dl, MVT::i16,
6287 DAG.getNode(ISD::AND, dl, MVT::i16,
6288 CWD, DAG.getConstant(0x400, MVT::i16)),
6289 DAG.getConstant(9, MVT::i8));
6292 DAG.getNode(ISD::AND, dl, MVT::i16,
6293 DAG.getNode(ISD::ADD, dl, MVT::i16,
6294 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6295 DAG.getConstant(1, MVT::i16)),
6296 DAG.getConstant(3, MVT::i16));
6299 return DAG.getNode((VT.getSizeInBits() < 16 ?
6300 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6303 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6304 MVT VT = Op.getValueType();
6306 unsigned NumBits = VT.getSizeInBits();
6307 DebugLoc dl = Op.getDebugLoc();
6309 Op = Op.getOperand(0);
6310 if (VT == MVT::i8) {
6311 // Zero extend to i32 since there is not an i8 bsr.
6313 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6316 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6317 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6318 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6320 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6321 SmallVector<SDValue, 4> Ops;
6323 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6324 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6325 Ops.push_back(Op.getValue(1));
6326 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6328 // Finally xor with NumBits-1.
6329 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6332 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6336 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6337 MVT VT = Op.getValueType();
6339 unsigned NumBits = VT.getSizeInBits();
6340 DebugLoc dl = Op.getDebugLoc();
6342 Op = Op.getOperand(0);
6343 if (VT == MVT::i8) {
6345 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6348 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6349 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6350 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6352 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6353 SmallVector<SDValue, 4> Ops;
6355 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6356 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6357 Ops.push_back(Op.getValue(1));
6358 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6361 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6365 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6366 MVT VT = Op.getValueType();
6367 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6368 DebugLoc dl = Op.getDebugLoc();
6370 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6371 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6372 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6373 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6374 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6376 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6377 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6378 // return AloBlo + AloBhi + AhiBlo;
6380 SDValue A = Op.getOperand(0);
6381 SDValue B = Op.getOperand(1);
6383 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6384 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6385 A, DAG.getConstant(32, MVT::i32));
6386 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6387 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6388 B, DAG.getConstant(32, MVT::i32));
6389 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6390 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6392 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6393 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6395 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6396 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6398 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6399 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6400 AloBhi, DAG.getConstant(32, MVT::i32));
6401 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6402 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6403 AhiBlo, DAG.getConstant(32, MVT::i32));
6404 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6405 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6410 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6411 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6412 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6413 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6414 // has only one use.
6415 SDNode *N = Op.getNode();
6416 SDValue LHS = N->getOperand(0);
6417 SDValue RHS = N->getOperand(1);
6418 unsigned BaseOp = 0;
6420 DebugLoc dl = Op.getDebugLoc();
6422 switch (Op.getOpcode()) {
6423 default: assert(0 && "Unknown ovf instruction!");
6425 // A subtract of one will be selected as a INC. Note that INC doesn't
6426 // set CF, so we can't do this for UADDO.
6427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6428 if (C->getAPIntValue() == 1) {
6429 BaseOp = X86ISD::INC;
6433 BaseOp = X86ISD::ADD;
6437 BaseOp = X86ISD::ADD;
6441 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6442 // set CF, so we can't do this for USUBO.
6443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6444 if (C->getAPIntValue() == 1) {
6445 BaseOp = X86ISD::DEC;
6449 BaseOp = X86ISD::SUB;
6453 BaseOp = X86ISD::SUB;
6457 BaseOp = X86ISD::SMUL;
6461 BaseOp = X86ISD::UMUL;
6466 // Also sets EFLAGS.
6467 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6468 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6471 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6472 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6474 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6478 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6479 MVT T = Op.getValueType();
6480 DebugLoc dl = Op.getDebugLoc();
6483 switch(T.getSimpleVT()) {
6485 assert(false && "Invalid value type!");
6486 case MVT::i8: Reg = X86::AL; size = 1; break;
6487 case MVT::i16: Reg = X86::AX; size = 2; break;
6488 case MVT::i32: Reg = X86::EAX; size = 4; break;
6490 assert(Subtarget->is64Bit() && "Node not type legal!");
6491 Reg = X86::RAX; size = 8;
6494 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6495 Op.getOperand(2), SDValue());
6496 SDValue Ops[] = { cpIn.getValue(0),
6499 DAG.getTargetConstant(size, MVT::i8),
6501 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6502 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6504 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6508 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6509 SelectionDAG &DAG) {
6510 assert(Subtarget->is64Bit() && "Result not type legalized?");
6511 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6512 SDValue TheChain = Op.getOperand(0);
6513 DebugLoc dl = Op.getDebugLoc();
6514 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6515 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6516 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6518 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6519 DAG.getConstant(32, MVT::i8));
6521 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6524 return DAG.getMergeValues(Ops, 2, dl);
6527 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6528 SDNode *Node = Op.getNode();
6529 DebugLoc dl = Node->getDebugLoc();
6530 MVT T = Node->getValueType(0);
6531 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6532 DAG.getConstant(0, T), Node->getOperand(2));
6533 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6534 cast<AtomicSDNode>(Node)->getMemoryVT(),
6535 Node->getOperand(0),
6536 Node->getOperand(1), negOp,
6537 cast<AtomicSDNode>(Node)->getSrcValue(),
6538 cast<AtomicSDNode>(Node)->getAlignment());
6541 /// LowerOperation - Provide custom lowering hooks for some operations.
6543 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6544 switch (Op.getOpcode()) {
6545 default: assert(0 && "Should not custom lower this!");
6546 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6547 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6548 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6549 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6550 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6551 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6552 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6553 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6554 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6555 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6556 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6557 case ISD::SHL_PARTS:
6558 case ISD::SRA_PARTS:
6559 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6560 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6561 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6562 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6563 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6564 case ISD::FABS: return LowerFABS(Op, DAG);
6565 case ISD::FNEG: return LowerFNEG(Op, DAG);
6566 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6567 case ISD::SETCC: return LowerSETCC(Op, DAG);
6568 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6569 case ISD::SELECT: return LowerSELECT(Op, DAG);
6570 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6571 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6572 case ISD::CALL: return LowerCALL(Op, DAG);
6573 case ISD::RET: return LowerRET(Op, DAG);
6574 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6575 case ISD::VASTART: return LowerVASTART(Op, DAG);
6576 case ISD::VAARG: return LowerVAARG(Op, DAG);
6577 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6578 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6579 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6580 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6581 case ISD::FRAME_TO_ARGS_OFFSET:
6582 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6583 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6584 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6585 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6586 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6587 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6588 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6589 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6595 case ISD::UMULO: return LowerXALUO(Op, DAG);
6596 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6600 void X86TargetLowering::
6601 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6602 SelectionDAG &DAG, unsigned NewOp) {
6603 MVT T = Node->getValueType(0);
6604 DebugLoc dl = Node->getDebugLoc();
6605 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6607 SDValue Chain = Node->getOperand(0);
6608 SDValue In1 = Node->getOperand(1);
6609 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6610 Node->getOperand(2), DAG.getIntPtrConstant(0));
6611 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6612 Node->getOperand(2), DAG.getIntPtrConstant(1));
6613 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6614 // have a MemOperand. Pass the info through as a normal operand.
6615 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6616 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6617 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6618 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6619 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6620 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6621 Results.push_back(Result.getValue(2));
6624 /// ReplaceNodeResults - Replace a node with an illegal result type
6625 /// with a new node built out of custom code.
6626 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6627 SmallVectorImpl<SDValue>&Results,
6628 SelectionDAG &DAG) {
6629 DebugLoc dl = N->getDebugLoc();
6630 switch (N->getOpcode()) {
6632 assert(false && "Do not know how to custom type legalize this operation!");
6634 case ISD::FP_TO_SINT: {
6635 std::pair<SDValue,SDValue> Vals =
6636 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6637 SDValue FIST = Vals.first, StackSlot = Vals.second;
6638 if (FIST.getNode() != 0) {
6639 MVT VT = N->getValueType(0);
6640 // Return a load from the stack slot.
6641 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6645 case ISD::READCYCLECOUNTER: {
6646 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6647 SDValue TheChain = N->getOperand(0);
6648 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6649 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6651 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6653 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6654 SDValue Ops[] = { eax, edx };
6655 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6656 Results.push_back(edx.getValue(1));
6659 case ISD::ATOMIC_CMP_SWAP: {
6660 MVT T = N->getValueType(0);
6661 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6662 SDValue cpInL, cpInH;
6663 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6664 DAG.getConstant(0, MVT::i32));
6665 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6666 DAG.getConstant(1, MVT::i32));
6667 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6668 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6670 SDValue swapInL, swapInH;
6671 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6672 DAG.getConstant(0, MVT::i32));
6673 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6674 DAG.getConstant(1, MVT::i32));
6675 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6677 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6678 swapInL.getValue(1));
6679 SDValue Ops[] = { swapInH.getValue(0),
6681 swapInH.getValue(1) };
6682 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6683 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6684 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6685 MVT::i32, Result.getValue(1));
6686 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6687 MVT::i32, cpOutL.getValue(2));
6688 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6689 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6690 Results.push_back(cpOutH.getValue(1));
6693 case ISD::ATOMIC_LOAD_ADD:
6694 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6696 case ISD::ATOMIC_LOAD_AND:
6697 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6699 case ISD::ATOMIC_LOAD_NAND:
6700 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6702 case ISD::ATOMIC_LOAD_OR:
6703 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6705 case ISD::ATOMIC_LOAD_SUB:
6706 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6708 case ISD::ATOMIC_LOAD_XOR:
6709 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6711 case ISD::ATOMIC_SWAP:
6712 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6717 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6719 default: return NULL;
6720 case X86ISD::BSF: return "X86ISD::BSF";
6721 case X86ISD::BSR: return "X86ISD::BSR";
6722 case X86ISD::SHLD: return "X86ISD::SHLD";
6723 case X86ISD::SHRD: return "X86ISD::SHRD";
6724 case X86ISD::FAND: return "X86ISD::FAND";
6725 case X86ISD::FOR: return "X86ISD::FOR";
6726 case X86ISD::FXOR: return "X86ISD::FXOR";
6727 case X86ISD::FSRL: return "X86ISD::FSRL";
6728 case X86ISD::FILD: return "X86ISD::FILD";
6729 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6730 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6731 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6732 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6733 case X86ISD::FLD: return "X86ISD::FLD";
6734 case X86ISD::FST: return "X86ISD::FST";
6735 case X86ISD::CALL: return "X86ISD::CALL";
6736 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6737 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6738 case X86ISD::BT: return "X86ISD::BT";
6739 case X86ISD::CMP: return "X86ISD::CMP";
6740 case X86ISD::COMI: return "X86ISD::COMI";
6741 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6742 case X86ISD::SETCC: return "X86ISD::SETCC";
6743 case X86ISD::CMOV: return "X86ISD::CMOV";
6744 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6745 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6746 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6747 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6748 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6749 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6750 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6751 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6752 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6753 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6754 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6755 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6756 case X86ISD::FMAX: return "X86ISD::FMAX";
6757 case X86ISD::FMIN: return "X86ISD::FMIN";
6758 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6759 case X86ISD::FRCP: return "X86ISD::FRCP";
6760 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6761 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6762 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6763 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6764 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6765 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6766 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6767 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6768 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6769 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6770 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6771 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6772 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6773 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6774 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6775 case X86ISD::VSHL: return "X86ISD::VSHL";
6776 case X86ISD::VSRL: return "X86ISD::VSRL";
6777 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6778 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6779 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6780 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6781 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6782 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6783 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6784 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6785 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6786 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6787 case X86ISD::ADD: return "X86ISD::ADD";
6788 case X86ISD::SUB: return "X86ISD::SUB";
6789 case X86ISD::SMUL: return "X86ISD::SMUL";
6790 case X86ISD::UMUL: return "X86ISD::UMUL";
6791 case X86ISD::INC: return "X86ISD::INC";
6792 case X86ISD::DEC: return "X86ISD::DEC";
6793 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6797 // isLegalAddressingMode - Return true if the addressing mode represented
6798 // by AM is legal for this target, for a load/store of the specified type.
6799 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6800 const Type *Ty) const {
6801 // X86 supports extremely general addressing modes.
6803 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6804 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6808 // We can only fold this if we don't need an extra load.
6809 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6811 // If BaseGV requires a register, we cannot also have a BaseReg.
6812 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6816 // X86-64 only supports addr of globals in small code model.
6817 if (Subtarget->is64Bit()) {
6818 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6820 // If lower 4G is not available, then we must use rip-relative addressing.
6821 if (AM.BaseOffs || AM.Scale > 1)
6832 // These scales always work.
6837 // These scales are formed with basereg+scalereg. Only accept if there is
6842 default: // Other stuff never works.
6850 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6851 if (!Ty1->isInteger() || !Ty2->isInteger())
6853 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6854 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6855 if (NumBits1 <= NumBits2)
6857 return Subtarget->is64Bit() || NumBits1 < 64;
6860 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6861 if (!VT1.isInteger() || !VT2.isInteger())
6863 unsigned NumBits1 = VT1.getSizeInBits();
6864 unsigned NumBits2 = VT2.getSizeInBits();
6865 if (NumBits1 <= NumBits2)
6867 return Subtarget->is64Bit() || NumBits1 < 64;
6870 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6871 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6872 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6875 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6876 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6877 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6880 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6881 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6882 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6883 /// are assumed to be legal.
6885 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6887 // Only do shuffles on 128-bit vector types for now.
6888 if (VT.getSizeInBits() == 64)
6891 // FIXME: pshufb, blends, palignr, shifts.
6892 return (VT.getVectorNumElements() == 2 ||
6893 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6894 isMOVLMask(M, VT) ||
6895 isSHUFPMask(M, VT) ||
6896 isPSHUFDMask(M, VT) ||
6897 isPSHUFHWMask(M, VT) ||
6898 isPSHUFLWMask(M, VT) ||
6899 isUNPCKLMask(M, VT) ||
6900 isUNPCKHMask(M, VT) ||
6901 isUNPCKL_v_undef_Mask(M, VT) ||
6902 isUNPCKH_v_undef_Mask(M, VT));
6906 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6908 unsigned NumElts = VT.getVectorNumElements();
6909 // FIXME: This collection of masks seems suspect.
6912 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6913 return (isMOVLMask(Mask, VT) ||
6914 isCommutedMOVLMask(Mask, VT, true) ||
6915 isSHUFPMask(Mask, VT) ||
6916 isCommutedSHUFPMask(Mask, VT));
6921 //===----------------------------------------------------------------------===//
6922 // X86 Scheduler Hooks
6923 //===----------------------------------------------------------------------===//
6925 // private utility function
6927 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6928 MachineBasicBlock *MBB,
6936 TargetRegisterClass *RC,
6937 bool invSrc) const {
6938 // For the atomic bitwise operator, we generate
6941 // ld t1 = [bitinstr.addr]
6942 // op t2 = t1, [bitinstr.val]
6944 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6946 // fallthrough -->nextMBB
6947 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6948 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6949 MachineFunction::iterator MBBIter = MBB;
6952 /// First build the CFG
6953 MachineFunction *F = MBB->getParent();
6954 MachineBasicBlock *thisMBB = MBB;
6955 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6956 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6957 F->insert(MBBIter, newMBB);
6958 F->insert(MBBIter, nextMBB);
6960 // Move all successors to thisMBB to nextMBB
6961 nextMBB->transferSuccessors(thisMBB);
6963 // Update thisMBB to fall through to newMBB
6964 thisMBB->addSuccessor(newMBB);
6966 // newMBB jumps to itself and fall through to nextMBB
6967 newMBB->addSuccessor(nextMBB);
6968 newMBB->addSuccessor(newMBB);
6970 // Insert instructions into newMBB based on incoming instruction
6971 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
6972 "unexpected number of operands");
6973 DebugLoc dl = bInstr->getDebugLoc();
6974 MachineOperand& destOper = bInstr->getOperand(0);
6975 MachineOperand* argOpers[2 + X86AddrNumOperands];
6976 int numArgs = bInstr->getNumOperands() - 1;
6977 for (int i=0; i < numArgs; ++i)
6978 argOpers[i] = &bInstr->getOperand(i+1);
6980 // x86 address has 4 operands: base, index, scale, and displacement
6981 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
6982 int valArgIndx = lastAddrIndx + 1;
6984 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6985 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
6986 for (int i=0; i <= lastAddrIndx; ++i)
6987 (*MIB).addOperand(*argOpers[i]);
6989 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6991 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
6996 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6997 assert((argOpers[valArgIndx]->isReg() ||
6998 argOpers[valArgIndx]->isImm()) &&
7000 if (argOpers[valArgIndx]->isReg())
7001 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7003 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7005 (*MIB).addOperand(*argOpers[valArgIndx]);
7007 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7010 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7011 for (int i=0; i <= lastAddrIndx; ++i)
7012 (*MIB).addOperand(*argOpers[i]);
7014 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7015 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7017 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7021 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7023 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7027 // private utility function: 64 bit atomics on 32 bit host.
7029 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7030 MachineBasicBlock *MBB,
7035 bool invSrc) const {
7036 // For the atomic bitwise operator, we generate
7037 // thisMBB (instructions are in pairs, except cmpxchg8b)
7038 // ld t1,t2 = [bitinstr.addr]
7040 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7041 // op t5, t6 <- out1, out2, [bitinstr.val]
7042 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7043 // mov ECX, EBX <- t5, t6
7044 // mov EAX, EDX <- t1, t2
7045 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7046 // mov t3, t4 <- EAX, EDX
7048 // result in out1, out2
7049 // fallthrough -->nextMBB
7051 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7052 const unsigned LoadOpc = X86::MOV32rm;
7053 const unsigned copyOpc = X86::MOV32rr;
7054 const unsigned NotOpc = X86::NOT32r;
7055 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7056 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7057 MachineFunction::iterator MBBIter = MBB;
7060 /// First build the CFG
7061 MachineFunction *F = MBB->getParent();
7062 MachineBasicBlock *thisMBB = MBB;
7063 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7064 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7065 F->insert(MBBIter, newMBB);
7066 F->insert(MBBIter, nextMBB);
7068 // Move all successors to thisMBB to nextMBB
7069 nextMBB->transferSuccessors(thisMBB);
7071 // Update thisMBB to fall through to newMBB
7072 thisMBB->addSuccessor(newMBB);
7074 // newMBB jumps to itself and fall through to nextMBB
7075 newMBB->addSuccessor(nextMBB);
7076 newMBB->addSuccessor(newMBB);
7078 DebugLoc dl = bInstr->getDebugLoc();
7079 // Insert instructions into newMBB based on incoming instruction
7080 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7081 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7082 "unexpected number of operands");
7083 MachineOperand& dest1Oper = bInstr->getOperand(0);
7084 MachineOperand& dest2Oper = bInstr->getOperand(1);
7085 MachineOperand* argOpers[2 + X86AddrNumOperands];
7086 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7087 argOpers[i] = &bInstr->getOperand(i+2);
7089 // x86 address has 4 operands: base, index, scale, and displacement
7090 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7092 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7093 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7094 for (int i=0; i <= lastAddrIndx; ++i)
7095 (*MIB).addOperand(*argOpers[i]);
7096 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7097 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7098 // add 4 to displacement.
7099 for (int i=0; i <= lastAddrIndx-2; ++i)
7100 (*MIB).addOperand(*argOpers[i]);
7101 MachineOperand newOp3 = *(argOpers[3]);
7103 newOp3.setImm(newOp3.getImm()+4);
7105 newOp3.setOffset(newOp3.getOffset()+4);
7106 (*MIB).addOperand(newOp3);
7107 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7109 // t3/4 are defined later, at the bottom of the loop
7110 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7111 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7112 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7113 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7114 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7115 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7117 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7118 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7120 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7121 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7127 int valArgIndx = lastAddrIndx + 1;
7128 assert((argOpers[valArgIndx]->isReg() ||
7129 argOpers[valArgIndx]->isImm()) &&
7131 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7132 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7133 if (argOpers[valArgIndx]->isReg())
7134 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7136 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7137 if (regOpcL != X86::MOV32rr)
7139 (*MIB).addOperand(*argOpers[valArgIndx]);
7140 assert(argOpers[valArgIndx + 1]->isReg() ==
7141 argOpers[valArgIndx]->isReg());
7142 assert(argOpers[valArgIndx + 1]->isImm() ==
7143 argOpers[valArgIndx]->isImm());
7144 if (argOpers[valArgIndx + 1]->isReg())
7145 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7147 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7148 if (regOpcH != X86::MOV32rr)
7150 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7152 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7154 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7157 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7159 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7162 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7163 for (int i=0; i <= lastAddrIndx; ++i)
7164 (*MIB).addOperand(*argOpers[i]);
7166 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7167 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7169 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7170 MIB.addReg(X86::EAX);
7171 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7172 MIB.addReg(X86::EDX);
7175 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7177 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7181 // private utility function
7183 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7184 MachineBasicBlock *MBB,
7185 unsigned cmovOpc) const {
7186 // For the atomic min/max operator, we generate
7189 // ld t1 = [min/max.addr]
7190 // mov t2 = [min/max.val]
7192 // cmov[cond] t2 = t1
7194 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7196 // fallthrough -->nextMBB
7198 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7199 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7200 MachineFunction::iterator MBBIter = MBB;
7203 /// First build the CFG
7204 MachineFunction *F = MBB->getParent();
7205 MachineBasicBlock *thisMBB = MBB;
7206 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7207 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7208 F->insert(MBBIter, newMBB);
7209 F->insert(MBBIter, nextMBB);
7211 // Move all successors to thisMBB to nextMBB
7212 nextMBB->transferSuccessors(thisMBB);
7214 // Update thisMBB to fall through to newMBB
7215 thisMBB->addSuccessor(newMBB);
7217 // newMBB jumps to newMBB and fall through to nextMBB
7218 newMBB->addSuccessor(nextMBB);
7219 newMBB->addSuccessor(newMBB);
7221 DebugLoc dl = mInstr->getDebugLoc();
7222 // Insert instructions into newMBB based on incoming instruction
7223 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7224 "unexpected number of operands");
7225 MachineOperand& destOper = mInstr->getOperand(0);
7226 MachineOperand* argOpers[2 + X86AddrNumOperands];
7227 int numArgs = mInstr->getNumOperands() - 1;
7228 for (int i=0; i < numArgs; ++i)
7229 argOpers[i] = &mInstr->getOperand(i+1);
7231 // x86 address has 4 operands: base, index, scale, and displacement
7232 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7233 int valArgIndx = lastAddrIndx + 1;
7235 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7236 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7237 for (int i=0; i <= lastAddrIndx; ++i)
7238 (*MIB).addOperand(*argOpers[i]);
7240 // We only support register and immediate values
7241 assert((argOpers[valArgIndx]->isReg() ||
7242 argOpers[valArgIndx]->isImm()) &&
7245 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7246 if (argOpers[valArgIndx]->isReg())
7247 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7249 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7250 (*MIB).addOperand(*argOpers[valArgIndx]);
7252 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7255 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7260 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7261 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7265 // Cmp and exchange if none has modified the memory location
7266 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7267 for (int i=0; i <= lastAddrIndx; ++i)
7268 (*MIB).addOperand(*argOpers[i]);
7270 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7271 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7273 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7274 MIB.addReg(X86::EAX);
7277 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7279 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7285 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7286 MachineBasicBlock *BB) const {
7287 DebugLoc dl = MI->getDebugLoc();
7288 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7289 switch (MI->getOpcode()) {
7290 default: assert(false && "Unexpected instr type to insert");
7291 case X86::CMOV_V1I64:
7292 case X86::CMOV_FR32:
7293 case X86::CMOV_FR64:
7294 case X86::CMOV_V4F32:
7295 case X86::CMOV_V2F64:
7296 case X86::CMOV_V2I64: {
7297 // To "insert" a SELECT_CC instruction, we actually have to insert the
7298 // diamond control-flow pattern. The incoming instruction knows the
7299 // destination vreg to set, the condition code register to branch on, the
7300 // true/false values to select between, and a branch opcode to use.
7301 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7302 MachineFunction::iterator It = BB;
7308 // cmpTY ccX, r1, r2
7310 // fallthrough --> copy0MBB
7311 MachineBasicBlock *thisMBB = BB;
7312 MachineFunction *F = BB->getParent();
7313 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7314 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7316 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7317 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7318 F->insert(It, copy0MBB);
7319 F->insert(It, sinkMBB);
7320 // Update machine-CFG edges by transferring all successors of the current
7321 // block to the new block which will contain the Phi node for the select.
7322 sinkMBB->transferSuccessors(BB);
7324 // Add the true and fallthrough blocks as its successors.
7325 BB->addSuccessor(copy0MBB);
7326 BB->addSuccessor(sinkMBB);
7329 // %FalseValue = ...
7330 // # fallthrough to sinkMBB
7333 // Update machine-CFG edges
7334 BB->addSuccessor(sinkMBB);
7337 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7340 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7341 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7342 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7344 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7348 case X86::FP32_TO_INT16_IN_MEM:
7349 case X86::FP32_TO_INT32_IN_MEM:
7350 case X86::FP32_TO_INT64_IN_MEM:
7351 case X86::FP64_TO_INT16_IN_MEM:
7352 case X86::FP64_TO_INT32_IN_MEM:
7353 case X86::FP64_TO_INT64_IN_MEM:
7354 case X86::FP80_TO_INT16_IN_MEM:
7355 case X86::FP80_TO_INT32_IN_MEM:
7356 case X86::FP80_TO_INT64_IN_MEM: {
7357 // Change the floating point control register to use "round towards zero"
7358 // mode when truncating to an integer value.
7359 MachineFunction *F = BB->getParent();
7360 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7361 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7363 // Load the old value of the high byte of the control word...
7365 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7366 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7369 // Set the high part to be round to zero...
7370 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7373 // Reload the modified control word now...
7374 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7376 // Restore the memory image of control word to original value
7377 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7380 // Get the X86 opcode to use.
7382 switch (MI->getOpcode()) {
7383 default: assert(0 && "illegal opcode!");
7384 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7385 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7386 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7387 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7388 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7389 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7390 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7391 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7392 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7396 MachineOperand &Op = MI->getOperand(0);
7398 AM.BaseType = X86AddressMode::RegBase;
7399 AM.Base.Reg = Op.getReg();
7401 AM.BaseType = X86AddressMode::FrameIndexBase;
7402 AM.Base.FrameIndex = Op.getIndex();
7404 Op = MI->getOperand(1);
7406 AM.Scale = Op.getImm();
7407 Op = MI->getOperand(2);
7409 AM.IndexReg = Op.getImm();
7410 Op = MI->getOperand(3);
7411 if (Op.isGlobal()) {
7412 AM.GV = Op.getGlobal();
7414 AM.Disp = Op.getImm();
7416 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7417 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7419 // Reload the original control word now.
7420 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7422 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7425 case X86::ATOMAND32:
7426 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7427 X86::AND32ri, X86::MOV32rm,
7428 X86::LCMPXCHG32, X86::MOV32rr,
7429 X86::NOT32r, X86::EAX,
7430 X86::GR32RegisterClass);
7432 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7433 X86::OR32ri, X86::MOV32rm,
7434 X86::LCMPXCHG32, X86::MOV32rr,
7435 X86::NOT32r, X86::EAX,
7436 X86::GR32RegisterClass);
7437 case X86::ATOMXOR32:
7438 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7439 X86::XOR32ri, X86::MOV32rm,
7440 X86::LCMPXCHG32, X86::MOV32rr,
7441 X86::NOT32r, X86::EAX,
7442 X86::GR32RegisterClass);
7443 case X86::ATOMNAND32:
7444 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7445 X86::AND32ri, X86::MOV32rm,
7446 X86::LCMPXCHG32, X86::MOV32rr,
7447 X86::NOT32r, X86::EAX,
7448 X86::GR32RegisterClass, true);
7449 case X86::ATOMMIN32:
7450 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7451 case X86::ATOMMAX32:
7452 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7453 case X86::ATOMUMIN32:
7454 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7455 case X86::ATOMUMAX32:
7456 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7458 case X86::ATOMAND16:
7459 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7460 X86::AND16ri, X86::MOV16rm,
7461 X86::LCMPXCHG16, X86::MOV16rr,
7462 X86::NOT16r, X86::AX,
7463 X86::GR16RegisterClass);
7465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7466 X86::OR16ri, X86::MOV16rm,
7467 X86::LCMPXCHG16, X86::MOV16rr,
7468 X86::NOT16r, X86::AX,
7469 X86::GR16RegisterClass);
7470 case X86::ATOMXOR16:
7471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7472 X86::XOR16ri, X86::MOV16rm,
7473 X86::LCMPXCHG16, X86::MOV16rr,
7474 X86::NOT16r, X86::AX,
7475 X86::GR16RegisterClass);
7476 case X86::ATOMNAND16:
7477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7478 X86::AND16ri, X86::MOV16rm,
7479 X86::LCMPXCHG16, X86::MOV16rr,
7480 X86::NOT16r, X86::AX,
7481 X86::GR16RegisterClass, true);
7482 case X86::ATOMMIN16:
7483 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7484 case X86::ATOMMAX16:
7485 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7486 case X86::ATOMUMIN16:
7487 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7488 case X86::ATOMUMAX16:
7489 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7492 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7493 X86::AND8ri, X86::MOV8rm,
7494 X86::LCMPXCHG8, X86::MOV8rr,
7495 X86::NOT8r, X86::AL,
7496 X86::GR8RegisterClass);
7498 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7499 X86::OR8ri, X86::MOV8rm,
7500 X86::LCMPXCHG8, X86::MOV8rr,
7501 X86::NOT8r, X86::AL,
7502 X86::GR8RegisterClass);
7504 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7505 X86::XOR8ri, X86::MOV8rm,
7506 X86::LCMPXCHG8, X86::MOV8rr,
7507 X86::NOT8r, X86::AL,
7508 X86::GR8RegisterClass);
7509 case X86::ATOMNAND8:
7510 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7511 X86::AND8ri, X86::MOV8rm,
7512 X86::LCMPXCHG8, X86::MOV8rr,
7513 X86::NOT8r, X86::AL,
7514 X86::GR8RegisterClass, true);
7515 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7516 // This group is for 64-bit host.
7517 case X86::ATOMAND64:
7518 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7519 X86::AND64ri32, X86::MOV64rm,
7520 X86::LCMPXCHG64, X86::MOV64rr,
7521 X86::NOT64r, X86::RAX,
7522 X86::GR64RegisterClass);
7524 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7525 X86::OR64ri32, X86::MOV64rm,
7526 X86::LCMPXCHG64, X86::MOV64rr,
7527 X86::NOT64r, X86::RAX,
7528 X86::GR64RegisterClass);
7529 case X86::ATOMXOR64:
7530 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7531 X86::XOR64ri32, X86::MOV64rm,
7532 X86::LCMPXCHG64, X86::MOV64rr,
7533 X86::NOT64r, X86::RAX,
7534 X86::GR64RegisterClass);
7535 case X86::ATOMNAND64:
7536 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7537 X86::AND64ri32, X86::MOV64rm,
7538 X86::LCMPXCHG64, X86::MOV64rr,
7539 X86::NOT64r, X86::RAX,
7540 X86::GR64RegisterClass, true);
7541 case X86::ATOMMIN64:
7542 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7543 case X86::ATOMMAX64:
7544 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7545 case X86::ATOMUMIN64:
7546 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7547 case X86::ATOMUMAX64:
7548 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7550 // This group does 64-bit operations on a 32-bit host.
7551 case X86::ATOMAND6432:
7552 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7553 X86::AND32rr, X86::AND32rr,
7554 X86::AND32ri, X86::AND32ri,
7556 case X86::ATOMOR6432:
7557 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7558 X86::OR32rr, X86::OR32rr,
7559 X86::OR32ri, X86::OR32ri,
7561 case X86::ATOMXOR6432:
7562 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7563 X86::XOR32rr, X86::XOR32rr,
7564 X86::XOR32ri, X86::XOR32ri,
7566 case X86::ATOMNAND6432:
7567 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7568 X86::AND32rr, X86::AND32rr,
7569 X86::AND32ri, X86::AND32ri,
7571 case X86::ATOMADD6432:
7572 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7573 X86::ADD32rr, X86::ADC32rr,
7574 X86::ADD32ri, X86::ADC32ri,
7576 case X86::ATOMSUB6432:
7577 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7578 X86::SUB32rr, X86::SBB32rr,
7579 X86::SUB32ri, X86::SBB32ri,
7581 case X86::ATOMSWAP6432:
7582 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7583 X86::MOV32rr, X86::MOV32rr,
7584 X86::MOV32ri, X86::MOV32ri,
7589 //===----------------------------------------------------------------------===//
7590 // X86 Optimization Hooks
7591 //===----------------------------------------------------------------------===//
7593 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7597 const SelectionDAG &DAG,
7598 unsigned Depth) const {
7599 unsigned Opc = Op.getOpcode();
7600 assert((Opc >= ISD::BUILTIN_OP_END ||
7601 Opc == ISD::INTRINSIC_WO_CHAIN ||
7602 Opc == ISD::INTRINSIC_W_CHAIN ||
7603 Opc == ISD::INTRINSIC_VOID) &&
7604 "Should use MaskedValueIsZero if you don't know whether Op"
7605 " is a target node!");
7607 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7616 // These nodes' second result is a boolean.
7617 if (Op.getResNo() == 0)
7621 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7622 Mask.getBitWidth() - 1);
7627 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7628 /// node is a GlobalAddress + offset.
7629 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7630 GlobalValue* &GA, int64_t &Offset) const{
7631 if (N->getOpcode() == X86ISD::Wrapper) {
7632 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7633 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7634 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7638 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7641 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7642 const TargetLowering &TLI) {
7645 if (TLI.isGAPlusOffset(Base, GV, Offset))
7646 return (GV->getAlignment() >= N && (Offset % N) == 0);
7647 // DAG combine handles the stack object case.
7651 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7652 MVT EVT, SDNode *&Base,
7653 SelectionDAG &DAG, MachineFrameInfo *MFI,
7654 const TargetLowering &TLI) {
7656 for (unsigned i = 0; i < NumElems; ++i) {
7657 if (N->getMaskElt(i) < 0) {
7663 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7664 if (!Elt.getNode() ||
7665 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7668 Base = Elt.getNode();
7669 if (Base->getOpcode() == ISD::UNDEF)
7673 if (Elt.getOpcode() == ISD::UNDEF)
7676 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7677 EVT.getSizeInBits()/8, i, MFI))
7683 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7684 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7685 /// if the load addresses are consecutive, non-overlapping, and in the right
7686 /// order. In the case of v2i64, it will see if it can rewrite the
7687 /// shuffle to be an appropriate build vector so it can take advantage of
7688 // performBuildVectorCombine.
7689 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7690 const TargetLowering &TLI) {
7691 DebugLoc dl = N->getDebugLoc();
7692 MVT VT = N->getValueType(0);
7693 MVT EVT = VT.getVectorElementType();
7694 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7695 unsigned NumElems = VT.getVectorNumElements();
7697 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7698 // where the upper half is 0, it is advantageous to rewrite it as a build
7699 // vector of (0, val) so it can use movq.
7700 if (VT == MVT::v2i64) {
7702 In[0] = N->getOperand(0);
7703 In[1] = N->getOperand(1);
7704 int Idx0 = SVN->getMaskElt(0);
7705 int Idx1 = SVN->getMaskElt(1);
7706 // FIXME: can we take advantage of undef index?
7707 if (Idx0 >= 0 && Idx1 >= 0 &&
7708 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7709 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7710 ConstantSDNode* InsertVecIdx =
7711 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7713 InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7714 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7715 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7716 In[Idx0/2].getOperand(1),
7717 In[Idx1/2].getOperand(Idx1 % 2));
7722 // Try to combine a vector_shuffle into a 128-bit load.
7723 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7724 SDNode *Base = NULL;
7725 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7728 LoadSDNode *LD = cast<LoadSDNode>(Base);
7729 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7730 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7731 LD->getSrcValue(), LD->getSrcValueOffset(),
7733 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7734 LD->getSrcValue(), LD->getSrcValueOffset(),
7735 LD->isVolatile(), LD->getAlignment());
7738 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7739 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7740 TargetLowering::DAGCombinerInfo &DCI,
7741 const X86Subtarget *Subtarget,
7742 const TargetLowering &TLI) {
7743 unsigned NumOps = N->getNumOperands();
7744 DebugLoc dl = N->getDebugLoc();
7746 // Ignore single operand BUILD_VECTOR.
7750 MVT VT = N->getValueType(0);
7751 MVT EVT = VT.getVectorElementType();
7752 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7753 // We are looking for load i64 and zero extend. We want to transform
7754 // it before legalizer has a chance to expand it. Also look for i64
7755 // BUILD_PAIR bit casted to f64.
7757 // This must be an insertion into a zero vector.
7758 SDValue HighElt = N->getOperand(1);
7759 if (!isZeroNode(HighElt))
7762 // Value must be a load.
7763 SDNode *Base = N->getOperand(0).getNode();
7764 if (!isa<LoadSDNode>(Base)) {
7765 if (Base->getOpcode() != ISD::BIT_CONVERT)
7767 Base = Base->getOperand(0).getNode();
7768 if (!isa<LoadSDNode>(Base))
7772 // Transform it into VZEXT_LOAD addr.
7773 LoadSDNode *LD = cast<LoadSDNode>(Base);
7775 // Load must not be an extload.
7776 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7779 // Load type should legal type so we don't have to legalize it.
7780 if (!TLI.isTypeLegal(VT))
7783 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7784 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7785 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7786 TargetLowering::TargetLoweringOpt TLO(DAG);
7787 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7788 DCI.CommitTargetLoweringOpt(TLO);
7792 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7793 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7794 const X86Subtarget *Subtarget) {
7795 DebugLoc DL = N->getDebugLoc();
7796 SDValue Cond = N->getOperand(0);
7797 // Get the LHS/RHS of the select.
7798 SDValue LHS = N->getOperand(1);
7799 SDValue RHS = N->getOperand(2);
7801 // If we have SSE[12] support, try to form min/max nodes.
7802 if (Subtarget->hasSSE2() &&
7803 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7804 Cond.getOpcode() == ISD::SETCC) {
7805 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7807 unsigned Opcode = 0;
7808 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7811 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7814 if (!UnsafeFPMath) break;
7816 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7818 Opcode = X86ISD::FMIN;
7821 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7824 if (!UnsafeFPMath) break;
7826 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7828 Opcode = X86ISD::FMAX;
7831 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7834 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7837 if (!UnsafeFPMath) break;
7839 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7841 Opcode = X86ISD::FMIN;
7844 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7847 if (!UnsafeFPMath) break;
7849 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7851 Opcode = X86ISD::FMAX;
7857 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7860 // If this is a select between two integer constants, try to do some
7862 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7863 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7864 // Don't do this for crazy integer types.
7865 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7866 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7867 // so that TrueC (the true value) is larger than FalseC.
7868 bool NeedsCondInvert = false;
7870 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7871 // Efficiently invertible.
7872 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7873 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7874 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7875 NeedsCondInvert = true;
7876 std::swap(TrueC, FalseC);
7879 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7880 if (FalseC->getAPIntValue() == 0 &&
7881 TrueC->getAPIntValue().isPowerOf2()) {
7882 if (NeedsCondInvert) // Invert the condition if needed.
7883 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7884 DAG.getConstant(1, Cond.getValueType()));
7886 // Zero extend the condition if needed.
7887 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7889 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7890 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7891 DAG.getConstant(ShAmt, MVT::i8));
7894 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7895 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7896 if (NeedsCondInvert) // Invert the condition if needed.
7897 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7898 DAG.getConstant(1, Cond.getValueType()));
7900 // Zero extend the condition if needed.
7901 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7902 FalseC->getValueType(0), Cond);
7903 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7904 SDValue(FalseC, 0));
7907 // Optimize cases that will turn into an LEA instruction. This requires
7908 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7909 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7910 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7911 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7913 bool isFastMultiplier = false;
7915 switch ((unsigned char)Diff) {
7917 case 1: // result = add base, cond
7918 case 2: // result = lea base( , cond*2)
7919 case 3: // result = lea base(cond, cond*2)
7920 case 4: // result = lea base( , cond*4)
7921 case 5: // result = lea base(cond, cond*4)
7922 case 8: // result = lea base( , cond*8)
7923 case 9: // result = lea base(cond, cond*8)
7924 isFastMultiplier = true;
7929 if (isFastMultiplier) {
7930 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7931 if (NeedsCondInvert) // Invert the condition if needed.
7932 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7933 DAG.getConstant(1, Cond.getValueType()));
7935 // Zero extend the condition if needed.
7936 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7938 // Scale the condition by the difference.
7940 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7941 DAG.getConstant(Diff, Cond.getValueType()));
7943 // Add the base if non-zero.
7944 if (FalseC->getAPIntValue() != 0)
7945 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7946 SDValue(FalseC, 0));
7956 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7957 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7958 TargetLowering::DAGCombinerInfo &DCI) {
7959 DebugLoc DL = N->getDebugLoc();
7961 // If the flag operand isn't dead, don't touch this CMOV.
7962 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7965 // If this is a select between two integer constants, try to do some
7966 // optimizations. Note that the operands are ordered the opposite of SELECT
7968 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7969 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7970 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7971 // larger than FalseC (the false value).
7972 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7974 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7975 CC = X86::GetOppositeBranchCondition(CC);
7976 std::swap(TrueC, FalseC);
7979 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
7980 // This is efficient for any integer data type (including i8/i16) and
7982 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7983 SDValue Cond = N->getOperand(3);
7984 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7985 DAG.getConstant(CC, MVT::i8), Cond);
7987 // Zero extend the condition if needed.
7988 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7990 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7991 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7992 DAG.getConstant(ShAmt, MVT::i8));
7993 if (N->getNumValues() == 2) // Dead flag value?
7994 return DCI.CombineTo(N, Cond, SDValue());
7998 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
7999 // for any integer data type, including i8/i16.
8000 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8001 SDValue Cond = N->getOperand(3);
8002 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8003 DAG.getConstant(CC, MVT::i8), Cond);
8005 // Zero extend the condition if needed.
8006 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8007 FalseC->getValueType(0), Cond);
8008 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8009 SDValue(FalseC, 0));
8011 if (N->getNumValues() == 2) // Dead flag value?
8012 return DCI.CombineTo(N, Cond, SDValue());
8016 // Optimize cases that will turn into an LEA instruction. This requires
8017 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8018 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8019 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8020 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8022 bool isFastMultiplier = false;
8024 switch ((unsigned char)Diff) {
8026 case 1: // result = add base, cond
8027 case 2: // result = lea base( , cond*2)
8028 case 3: // result = lea base(cond, cond*2)
8029 case 4: // result = lea base( , cond*4)
8030 case 5: // result = lea base(cond, cond*4)
8031 case 8: // result = lea base( , cond*8)
8032 case 9: // result = lea base(cond, cond*8)
8033 isFastMultiplier = true;
8038 if (isFastMultiplier) {
8039 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8040 SDValue Cond = N->getOperand(3);
8041 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8042 DAG.getConstant(CC, MVT::i8), Cond);
8043 // Zero extend the condition if needed.
8044 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8046 // Scale the condition by the difference.
8048 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8049 DAG.getConstant(Diff, Cond.getValueType()));
8051 // Add the base if non-zero.
8052 if (FalseC->getAPIntValue() != 0)
8053 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8054 SDValue(FalseC, 0));
8055 if (N->getNumValues() == 2) // Dead flag value?
8056 return DCI.CombineTo(N, Cond, SDValue());
8066 /// PerformMulCombine - Optimize a single multiply with constant into two
8067 /// in order to implement it with two cheaper instructions, e.g.
8068 /// LEA + SHL, LEA + LEA.
8069 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8070 TargetLowering::DAGCombinerInfo &DCI) {
8071 if (DAG.getMachineFunction().
8072 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8075 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8078 MVT VT = N->getValueType(0);
8082 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8085 uint64_t MulAmt = C->getZExtValue();
8086 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8089 uint64_t MulAmt1 = 0;
8090 uint64_t MulAmt2 = 0;
8091 if ((MulAmt % 9) == 0) {
8093 MulAmt2 = MulAmt / 9;
8094 } else if ((MulAmt % 5) == 0) {
8096 MulAmt2 = MulAmt / 5;
8097 } else if ((MulAmt % 3) == 0) {
8099 MulAmt2 = MulAmt / 3;
8102 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8103 DebugLoc DL = N->getDebugLoc();
8105 if (isPowerOf2_64(MulAmt2) &&
8106 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8107 // If second multiplifer is pow2, issue it first. We want the multiply by
8108 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8110 std::swap(MulAmt1, MulAmt2);
8113 if (isPowerOf2_64(MulAmt1))
8114 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8115 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8117 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8118 DAG.getConstant(MulAmt1, VT));
8120 if (isPowerOf2_64(MulAmt2))
8121 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8122 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8124 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8125 DAG.getConstant(MulAmt2, VT));
8127 // Do not add new nodes to DAG combiner worklist.
8128 DCI.CombineTo(N, NewMul, false);
8134 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8136 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8137 const X86Subtarget *Subtarget) {
8138 // On X86 with SSE2 support, we can transform this to a vector shift if
8139 // all elements are shifted by the same amount. We can't do this in legalize
8140 // because the a constant vector is typically transformed to a constant pool
8141 // so we have no knowledge of the shift amount.
8142 if (!Subtarget->hasSSE2())
8145 MVT VT = N->getValueType(0);
8146 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8149 SDValue ShAmtOp = N->getOperand(1);
8150 MVT EltVT = VT.getVectorElementType();
8151 DebugLoc DL = N->getDebugLoc();
8153 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8154 unsigned NumElts = VT.getVectorNumElements();
8156 for (; i != NumElts; ++i) {
8157 SDValue Arg = ShAmtOp.getOperand(i);
8158 if (Arg.getOpcode() == ISD::UNDEF) continue;
8162 for (; i != NumElts; ++i) {
8163 SDValue Arg = ShAmtOp.getOperand(i);
8164 if (Arg.getOpcode() == ISD::UNDEF) continue;
8165 if (Arg != BaseShAmt) {
8169 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8170 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8171 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8172 DAG.getIntPtrConstant(0));
8176 if (EltVT.bitsGT(MVT::i32))
8177 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8178 else if (EltVT.bitsLT(MVT::i32))
8179 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8181 // The shift amount is identical so we can do a vector shift.
8182 SDValue ValOp = N->getOperand(0);
8183 switch (N->getOpcode()) {
8185 assert(0 && "Unknown shift opcode!");
8188 if (VT == MVT::v2i64)
8189 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8190 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8192 if (VT == MVT::v4i32)
8193 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8194 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8196 if (VT == MVT::v8i16)
8197 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8198 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8202 if (VT == MVT::v4i32)
8203 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8204 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8206 if (VT == MVT::v8i16)
8207 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8208 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8212 if (VT == MVT::v2i64)
8213 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8214 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8216 if (VT == MVT::v4i32)
8217 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8218 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8220 if (VT == MVT::v8i16)
8221 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8222 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8229 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8230 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8231 const X86Subtarget *Subtarget) {
8232 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8233 // the FP state in cases where an emms may be missing.
8234 // A preferable solution to the general problem is to figure out the right
8235 // places to insert EMMS. This qualifies as a quick hack.
8237 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8238 StoreSDNode *St = cast<StoreSDNode>(N);
8239 MVT VT = St->getValue().getValueType();
8240 if (VT.getSizeInBits() != 64)
8243 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8244 if ((VT.isVector() ||
8245 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8246 isa<LoadSDNode>(St->getValue()) &&
8247 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8248 St->getChain().hasOneUse() && !St->isVolatile()) {
8249 SDNode* LdVal = St->getValue().getNode();
8251 int TokenFactorIndex = -1;
8252 SmallVector<SDValue, 8> Ops;
8253 SDNode* ChainVal = St->getChain().getNode();
8254 // Must be a store of a load. We currently handle two cases: the load
8255 // is a direct child, and it's under an intervening TokenFactor. It is
8256 // possible to dig deeper under nested TokenFactors.
8257 if (ChainVal == LdVal)
8258 Ld = cast<LoadSDNode>(St->getChain());
8259 else if (St->getValue().hasOneUse() &&
8260 ChainVal->getOpcode() == ISD::TokenFactor) {
8261 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8262 if (ChainVal->getOperand(i).getNode() == LdVal) {
8263 TokenFactorIndex = i;
8264 Ld = cast<LoadSDNode>(St->getValue());
8266 Ops.push_back(ChainVal->getOperand(i));
8270 if (!Ld || !ISD::isNormalLoad(Ld))
8273 // If this is not the MMX case, i.e. we are just turning i64 load/store
8274 // into f64 load/store, avoid the transformation if there are multiple
8275 // uses of the loaded value.
8276 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8279 DebugLoc LdDL = Ld->getDebugLoc();
8280 DebugLoc StDL = N->getDebugLoc();
8281 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8282 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8284 if (Subtarget->is64Bit() || F64IsLegal) {
8285 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8286 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8287 Ld->getBasePtr(), Ld->getSrcValue(),
8288 Ld->getSrcValueOffset(), Ld->isVolatile(),
8289 Ld->getAlignment());
8290 SDValue NewChain = NewLd.getValue(1);
8291 if (TokenFactorIndex != -1) {
8292 Ops.push_back(NewChain);
8293 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8296 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8297 St->getSrcValue(), St->getSrcValueOffset(),
8298 St->isVolatile(), St->getAlignment());
8301 // Otherwise, lower to two pairs of 32-bit loads / stores.
8302 SDValue LoAddr = Ld->getBasePtr();
8303 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8304 DAG.getConstant(4, MVT::i32));
8306 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8307 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8308 Ld->isVolatile(), Ld->getAlignment());
8309 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8310 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8312 MinAlign(Ld->getAlignment(), 4));
8314 SDValue NewChain = LoLd.getValue(1);
8315 if (TokenFactorIndex != -1) {
8316 Ops.push_back(LoLd);
8317 Ops.push_back(HiLd);
8318 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8322 LoAddr = St->getBasePtr();
8323 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8324 DAG.getConstant(4, MVT::i32));
8326 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8327 St->getSrcValue(), St->getSrcValueOffset(),
8328 St->isVolatile(), St->getAlignment());
8329 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8331 St->getSrcValueOffset() + 4,
8333 MinAlign(St->getAlignment(), 4));
8334 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8339 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8340 /// X86ISD::FXOR nodes.
8341 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8342 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8343 // F[X]OR(0.0, x) -> x
8344 // F[X]OR(x, 0.0) -> x
8345 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8346 if (C->getValueAPF().isPosZero())
8347 return N->getOperand(1);
8348 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8349 if (C->getValueAPF().isPosZero())
8350 return N->getOperand(0);
8354 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8355 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8356 // FAND(0.0, x) -> 0.0
8357 // FAND(x, 0.0) -> 0.0
8358 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8359 if (C->getValueAPF().isPosZero())
8360 return N->getOperand(0);
8361 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8362 if (C->getValueAPF().isPosZero())
8363 return N->getOperand(1);
8367 static SDValue PerformBTCombine(SDNode *N,
8369 TargetLowering::DAGCombinerInfo &DCI) {
8370 // BT ignores high bits in the bit index operand.
8371 SDValue Op1 = N->getOperand(1);
8372 if (Op1.hasOneUse()) {
8373 unsigned BitWidth = Op1.getValueSizeInBits();
8374 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8375 APInt KnownZero, KnownOne;
8376 TargetLowering::TargetLoweringOpt TLO(DAG);
8377 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8378 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8379 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8380 DCI.CommitTargetLoweringOpt(TLO);
8385 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8386 DAGCombinerInfo &DCI) const {
8387 SelectionDAG &DAG = DCI.DAG;
8388 switch (N->getOpcode()) {
8390 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8391 case ISD::BUILD_VECTOR:
8392 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8393 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8394 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8395 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8398 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8399 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8401 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8402 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8403 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8409 //===----------------------------------------------------------------------===//
8410 // X86 Inline Assembly Support
8411 //===----------------------------------------------------------------------===//
8413 /// getConstraintType - Given a constraint letter, return the type of
8414 /// constraint it is for this target.
8415 X86TargetLowering::ConstraintType
8416 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8417 if (Constraint.size() == 1) {
8418 switch (Constraint[0]) {
8430 return C_RegisterClass;
8438 return TargetLowering::getConstraintType(Constraint);
8441 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8442 /// with another that has more specific requirements based on the type of the
8443 /// corresponding operand.
8444 const char *X86TargetLowering::
8445 LowerXConstraint(MVT ConstraintVT) const {
8446 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8447 // 'f' like normal targets.
8448 if (ConstraintVT.isFloatingPoint()) {
8449 if (Subtarget->hasSSE2())
8451 if (Subtarget->hasSSE1())
8455 return TargetLowering::LowerXConstraint(ConstraintVT);
8458 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8459 /// vector. If it is invalid, don't add anything to Ops.
8460 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8463 std::vector<SDValue>&Ops,
8464 SelectionDAG &DAG) const {
8465 SDValue Result(0, 0);
8467 switch (Constraint) {
8470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8471 if (C->getZExtValue() <= 31) {
8472 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8479 if (C->getZExtValue() <= 63) {
8480 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8487 if (C->getZExtValue() <= 255) {
8488 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8494 // 32-bit signed value
8495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8496 const ConstantInt *CI = C->getConstantIntValue();
8497 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8498 // Widen to 64 bits here to get it sign extended.
8499 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8502 // FIXME gcc accepts some relocatable values here too, but only in certain
8503 // memory models; it's complicated.
8508 // 32-bit unsigned value
8509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8510 const ConstantInt *CI = C->getConstantIntValue();
8511 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8512 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8516 // FIXME gcc accepts some relocatable values here too, but only in certain
8517 // memory models; it's complicated.
8521 // Literal immediates are always ok.
8522 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8523 // Widen to 64 bits here to get it sign extended.
8524 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8528 // If we are in non-pic codegen mode, we allow the address of a global (with
8529 // an optional displacement) to be used with 'i'.
8530 GlobalAddressSDNode *GA = 0;
8533 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8535 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8536 Offset += GA->getOffset();
8538 } else if (Op.getOpcode() == ISD::ADD) {
8539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8540 Offset += C->getZExtValue();
8541 Op = Op.getOperand(0);
8544 } else if (Op.getOpcode() == ISD::SUB) {
8545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8546 Offset += -C->getZExtValue();
8547 Op = Op.getOperand(0);
8552 // Otherwise, this isn't something we can handle, reject it.
8557 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8559 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8566 if (Result.getNode()) {
8567 Ops.push_back(Result);
8570 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8574 std::vector<unsigned> X86TargetLowering::
8575 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8577 if (Constraint.size() == 1) {
8578 // FIXME: not handling fp-stack yet!
8579 switch (Constraint[0]) { // GCC X86 Constraint Letters
8580 default: break; // Unknown constraint letter
8581 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8584 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8585 else if (VT == MVT::i16)
8586 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8587 else if (VT == MVT::i8)
8588 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8589 else if (VT == MVT::i64)
8590 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8595 return std::vector<unsigned>();
8598 std::pair<unsigned, const TargetRegisterClass*>
8599 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8601 // First, see if this is a constraint that directly corresponds to an LLVM
8603 if (Constraint.size() == 1) {
8604 // GCC Constraint Letters
8605 switch (Constraint[0]) {
8607 case 'r': // GENERAL_REGS
8608 case 'R': // LEGACY_REGS
8609 case 'l': // INDEX_REGS
8611 return std::make_pair(0U, X86::GR8RegisterClass);
8613 return std::make_pair(0U, X86::GR16RegisterClass);
8614 if (VT == MVT::i32 || !Subtarget->is64Bit())
8615 return std::make_pair(0U, X86::GR32RegisterClass);
8616 return std::make_pair(0U, X86::GR64RegisterClass);
8617 case 'f': // FP Stack registers.
8618 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8619 // value to the correct fpstack register class.
8620 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8621 return std::make_pair(0U, X86::RFP32RegisterClass);
8622 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8623 return std::make_pair(0U, X86::RFP64RegisterClass);
8624 return std::make_pair(0U, X86::RFP80RegisterClass);
8625 case 'y': // MMX_REGS if MMX allowed.
8626 if (!Subtarget->hasMMX()) break;
8627 return std::make_pair(0U, X86::VR64RegisterClass);
8628 case 'Y': // SSE_REGS if SSE2 allowed
8629 if (!Subtarget->hasSSE2()) break;
8631 case 'x': // SSE_REGS if SSE1 allowed
8632 if (!Subtarget->hasSSE1()) break;
8634 switch (VT.getSimpleVT()) {
8636 // Scalar SSE types.
8639 return std::make_pair(0U, X86::FR32RegisterClass);
8642 return std::make_pair(0U, X86::FR64RegisterClass);
8650 return std::make_pair(0U, X86::VR128RegisterClass);
8656 // Use the default implementation in TargetLowering to convert the register
8657 // constraint into a member of a register class.
8658 std::pair<unsigned, const TargetRegisterClass*> Res;
8659 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8661 // Not found as a standard register?
8662 if (Res.second == 0) {
8663 // GCC calls "st(0)" just plain "st".
8664 if (StringsEqualNoCase("{st}", Constraint)) {
8665 Res.first = X86::ST0;
8666 Res.second = X86::RFP80RegisterClass;
8668 // 'A' means EAX + EDX.
8669 if (Constraint == "A") {
8670 Res.first = X86::EAX;
8671 Res.second = X86::GRADRegisterClass;
8676 // Otherwise, check to see if this is a register class of the wrong value
8677 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8678 // turn into {ax},{dx}.
8679 if (Res.second->hasType(VT))
8680 return Res; // Correct type already, nothing to do.
8682 // All of the single-register GCC register classes map their values onto
8683 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8684 // really want an 8-bit or 32-bit register, map to the appropriate register
8685 // class and return the appropriate register.
8686 if (Res.second == X86::GR16RegisterClass) {
8687 if (VT == MVT::i8) {
8688 unsigned DestReg = 0;
8689 switch (Res.first) {
8691 case X86::AX: DestReg = X86::AL; break;
8692 case X86::DX: DestReg = X86::DL; break;
8693 case X86::CX: DestReg = X86::CL; break;
8694 case X86::BX: DestReg = X86::BL; break;
8697 Res.first = DestReg;
8698 Res.second = X86::GR8RegisterClass;
8700 } else if (VT == MVT::i32) {
8701 unsigned DestReg = 0;
8702 switch (Res.first) {
8704 case X86::AX: DestReg = X86::EAX; break;
8705 case X86::DX: DestReg = X86::EDX; break;
8706 case X86::CX: DestReg = X86::ECX; break;
8707 case X86::BX: DestReg = X86::EBX; break;
8708 case X86::SI: DestReg = X86::ESI; break;
8709 case X86::DI: DestReg = X86::EDI; break;
8710 case X86::BP: DestReg = X86::EBP; break;
8711 case X86::SP: DestReg = X86::ESP; break;
8714 Res.first = DestReg;
8715 Res.second = X86::GR32RegisterClass;
8717 } else if (VT == MVT::i64) {
8718 unsigned DestReg = 0;
8719 switch (Res.first) {
8721 case X86::AX: DestReg = X86::RAX; break;
8722 case X86::DX: DestReg = X86::RDX; break;
8723 case X86::CX: DestReg = X86::RCX; break;
8724 case X86::BX: DestReg = X86::RBX; break;
8725 case X86::SI: DestReg = X86::RSI; break;
8726 case X86::DI: DestReg = X86::RDI; break;
8727 case X86::BP: DestReg = X86::RBP; break;
8728 case X86::SP: DestReg = X86::RSP; break;
8731 Res.first = DestReg;
8732 Res.second = X86::GR64RegisterClass;
8735 } else if (Res.second == X86::FR32RegisterClass ||
8736 Res.second == X86::FR64RegisterClass ||
8737 Res.second == X86::VR128RegisterClass) {
8738 // Handle references to XMM physical registers that got mapped into the
8739 // wrong class. This can happen with constraints like {xmm0} where the
8740 // target independent register mapper will just pick the first match it can
8741 // find, ignoring the required type.
8743 Res.second = X86::FR32RegisterClass;
8744 else if (VT == MVT::f64)
8745 Res.second = X86::FR64RegisterClass;
8746 else if (X86::VR128RegisterClass->hasType(VT))
8747 Res.second = X86::VR128RegisterClass;
8753 //===----------------------------------------------------------------------===//
8754 // X86 Widen vector type
8755 //===----------------------------------------------------------------------===//
8757 /// getWidenVectorType: given a vector type, returns the type to widen
8758 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8759 /// If there is no vector type that we want to widen to, returns MVT::Other
8760 /// When and where to widen is target dependent based on the cost of
8761 /// scalarizing vs using the wider vector type.
8763 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8764 assert(VT.isVector());
8765 if (isTypeLegal(VT))
8768 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8769 // type based on element type. This would speed up our search (though
8770 // it may not be worth it since the size of the list is relatively
8772 MVT EltVT = VT.getVectorElementType();
8773 unsigned NElts = VT.getVectorNumElements();
8775 // On X86, it make sense to widen any vector wider than 1
8779 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8780 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8781 MVT SVT = (MVT::SimpleValueType)nVT;
8783 if (isTypeLegal(SVT) &&
8784 SVT.getVectorElementType() == EltVT &&
8785 SVT.getVectorNumElements() > NElts)