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"
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47 : TargetLowering(TM) {
48 Subtarget = &TM.getSubtarget<X86Subtarget>();
49 X86ScalarSSEf64 = Subtarget->hasSSE2();
50 X86ScalarSSEf32 = Subtarget->hasSSE1();
51 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setSetCCResultContents(ZeroOrOneSetCCResult);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // SETOEQ and SETUNE require checking two conditions.
98 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
99 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
100 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
101 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
105 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
107 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
111 if (Subtarget->is64Bit()) {
112 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
115 if (X86ScalarSSEf64) {
116 // We have an impenetrably clever algorithm for ui64->double only.
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
118 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
119 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
121 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
124 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
127 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
128 // SSE has no i16 to fp conversion, only i32
129 if (X86ScalarSSEf32) {
130 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
131 // f32 and f64 cases are Legal, f80 case is not
132 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
134 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
135 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
138 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
139 // are Legal, f80 is custom lowered.
140 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
143 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
145 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
146 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
148 if (X86ScalarSSEf32) {
149 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
150 // f32 and f64 cases are Legal, f80 case is not
151 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
153 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
154 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
157 // Handle FP_TO_UINT by promoting the destination to a larger signed
159 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
160 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
161 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
163 if (Subtarget->is64Bit()) {
164 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
167 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
168 // Expand FP_TO_UINT into a select.
169 // FIXME: We would like to use a Custom expander here eventually to do
170 // the optimal thing for SSE vs. the default expansion in the legalizer.
171 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
173 // With SSE3 we can use fisttpll to convert to a signed i64.
174 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
177 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
178 if (!X86ScalarSSEf64) {
179 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
180 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
183 // Scalar integer divide and remainder are lowered to use operations that
184 // produce two results, to match the available instructions. This exposes
185 // the two-result form to trivial CSE, which is able to combine x/y and x%y
186 // into a single instruction.
188 // Scalar integer multiply-high is also lowered to use two-result
189 // operations, to match the available instructions. However, plain multiply
190 // (low) operations are left as Legal, as there are single-result
191 // instructions for this in x86. Using the two-result multiply instructions
192 // when both high and low results are needed must be arranged by dagcombine.
193 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
194 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
195 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
196 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
197 setOperationAction(ISD::SREM , MVT::i8 , Expand);
198 setOperationAction(ISD::UREM , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
200 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
201 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
202 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
203 setOperationAction(ISD::SREM , MVT::i16 , Expand);
204 setOperationAction(ISD::UREM , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
206 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
207 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
208 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
209 setOperationAction(ISD::SREM , MVT::i32 , Expand);
210 setOperationAction(ISD::UREM , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
212 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
213 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
214 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
215 setOperationAction(ISD::SREM , MVT::i64 , Expand);
216 setOperationAction(ISD::UREM , MVT::i64 , Expand);
218 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
219 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
220 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
221 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
222 if (Subtarget->is64Bit())
223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
225 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
227 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
228 setOperationAction(ISD::FREM , MVT::f32 , Expand);
229 setOperationAction(ISD::FREM , MVT::f64 , Expand);
230 setOperationAction(ISD::FREM , MVT::f80 , Expand);
231 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
233 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
236 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
237 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
238 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
239 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
240 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
241 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
248 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
249 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
251 // These should be promoted to a larger select which is supported.
252 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
253 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
254 // X86 wants to expand cmov itself.
255 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
256 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
257 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
258 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
259 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
260 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
261 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
262 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
263 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
264 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
265 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
266 if (Subtarget->is64Bit()) {
267 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
268 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
270 // X86 ret instruction may pop stack.
271 setOperationAction(ISD::RET , MVT::Other, Custom);
272 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
275 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
276 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
277 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
279 if (Subtarget->is64Bit())
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
284 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
285 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
286 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
288 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
289 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
290 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
291 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
292 if (Subtarget->is64Bit()) {
293 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
294 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
295 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
298 if (Subtarget->hasSSE1())
299 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
301 if (!Subtarget->hasSSE2())
302 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
304 // Expand certain atomics
305 setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
306 setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
307 setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
308 setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
310 setOperationAction(ISD::ATOMIC_LOAD_SUB_8 , MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
315 if (!Subtarget->is64Bit()) {
316 setOperationAction(ISD::ATOMIC_LOAD_ADD_64, MVT::i64, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_AND_64, MVT::i64, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_OR_64, MVT::i64, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_XOR_64, MVT::i64, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_NAND_64, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_SWAP_64, MVT::i64, Custom);
325 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
326 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
327 // FIXME - use subtarget debug flags
328 if (!Subtarget->isTargetDarwin() &&
329 !Subtarget->isTargetELF() &&
330 !Subtarget->isTargetCygMing()) {
331 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
332 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
335 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
336 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
337 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
338 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
339 if (Subtarget->is64Bit()) {
340 setExceptionPointerRegister(X86::RAX);
341 setExceptionSelectorRegister(X86::RDX);
343 setExceptionPointerRegister(X86::EAX);
344 setExceptionSelectorRegister(X86::EDX);
346 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
347 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
349 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
351 setOperationAction(ISD::TRAP, MVT::Other, Legal);
353 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
354 setOperationAction(ISD::VASTART , MVT::Other, Custom);
355 setOperationAction(ISD::VAEND , MVT::Other, Expand);
356 if (Subtarget->is64Bit()) {
357 setOperationAction(ISD::VAARG , MVT::Other, Custom);
358 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
360 setOperationAction(ISD::VAARG , MVT::Other, Expand);
361 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
364 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
365 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
366 if (Subtarget->is64Bit())
367 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
368 if (Subtarget->isTargetCygMing())
369 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
371 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
373 if (X86ScalarSSEf64) {
374 // f32 and f64 use SSE.
375 // Set up the FP register classes.
376 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
377 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
379 // Use ANDPD to simulate FABS.
380 setOperationAction(ISD::FABS , MVT::f64, Custom);
381 setOperationAction(ISD::FABS , MVT::f32, Custom);
383 // Use XORP to simulate FNEG.
384 setOperationAction(ISD::FNEG , MVT::f64, Custom);
385 setOperationAction(ISD::FNEG , MVT::f32, Custom);
387 // Use ANDPD and ORPD to simulate FCOPYSIGN.
388 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
389 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
391 // We don't support sin/cos/fmod
392 setOperationAction(ISD::FSIN , MVT::f64, Expand);
393 setOperationAction(ISD::FCOS , MVT::f64, Expand);
394 setOperationAction(ISD::FSIN , MVT::f32, Expand);
395 setOperationAction(ISD::FCOS , MVT::f32, Expand);
397 // Expand FP immediates into loads from the stack, except for the special
399 addLegalFPImmediate(APFloat(+0.0)); // xorpd
400 addLegalFPImmediate(APFloat(+0.0f)); // xorps
402 // Floating truncations from f80 and extensions to f80 go through memory.
403 // If optimizing, we lie about this though and handle it in
404 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
406 setConvertAction(MVT::f32, MVT::f80, Expand);
407 setConvertAction(MVT::f64, MVT::f80, Expand);
408 setConvertAction(MVT::f80, MVT::f32, Expand);
409 setConvertAction(MVT::f80, MVT::f64, Expand);
411 } else if (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
440 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
441 // this though and handle it in InstructionSelectPreprocess so that
442 // dagcombine2 can hack on these.
444 setConvertAction(MVT::f32, MVT::f64, Expand);
445 setConvertAction(MVT::f32, MVT::f80, Expand);
446 setConvertAction(MVT::f80, MVT::f32, Expand);
447 setConvertAction(MVT::f64, MVT::f32, Expand);
448 // And x87->x87 truncations also.
449 setConvertAction(MVT::f80, MVT::f64, Expand);
453 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
454 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
457 // f32 and f64 in x87.
458 // Set up the FP register classes.
459 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
460 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
462 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
463 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
467 // Floating truncations go through memory. If optimizing, we lie about
468 // this though and handle it in InstructionSelectPreprocess so that
469 // dagcombine2 can hack on these.
471 setConvertAction(MVT::f80, MVT::f32, Expand);
472 setConvertAction(MVT::f64, MVT::f32, Expand);
473 setConvertAction(MVT::f80, MVT::f64, Expand);
477 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
478 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
480 addLegalFPImmediate(APFloat(+0.0)); // FLD0
481 addLegalFPImmediate(APFloat(+1.0)); // FLD1
482 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
483 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
484 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
490 // Long double always uses X87.
491 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
492 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
496 APFloat TmpFlt(+0.0);
497 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
499 addLegalFPImmediate(TmpFlt); // FLD0
501 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
502 APFloat TmpFlt2(+1.0);
503 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505 addLegalFPImmediate(TmpFlt2); // FLD1
506 TmpFlt2.changeSign();
507 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
511 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
512 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
515 // Always use a library call for pow.
516 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
517 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
518 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
520 setOperationAction(ISD::FLOG, MVT::f80, Expand);
521 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
522 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
523 setOperationAction(ISD::FEXP, MVT::f80, Expand);
524 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
526 // First set operation action for all vector types to expand. Then we
527 // will selectively turn on ones that can be effectively codegen'd.
528 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
529 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
530 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
545 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
575 if (Subtarget->hasMMX()) {
576 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
577 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
578 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
579 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
580 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
582 // FIXME: add MMX packed arithmetics
584 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
585 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
586 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
587 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
589 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
590 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
591 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
592 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
594 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
595 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
597 setOperationAction(ISD::AND, MVT::v8i8, Promote);
598 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
599 setOperationAction(ISD::AND, MVT::v4i16, Promote);
600 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
601 setOperationAction(ISD::AND, MVT::v2i32, Promote);
602 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
603 setOperationAction(ISD::AND, MVT::v1i64, Legal);
605 setOperationAction(ISD::OR, MVT::v8i8, Promote);
606 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
607 setOperationAction(ISD::OR, MVT::v4i16, Promote);
608 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
609 setOperationAction(ISD::OR, MVT::v2i32, Promote);
610 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
611 setOperationAction(ISD::OR, MVT::v1i64, Legal);
613 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
614 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
615 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
616 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
617 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
618 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
619 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
621 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
622 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
623 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
624 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
625 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
626 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
627 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
631 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
632 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
633 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
634 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
635 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
637 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
638 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
639 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
640 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
642 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
643 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
644 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
645 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
647 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
650 if (Subtarget->hasSSE1()) {
651 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
653 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
654 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
655 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
656 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
657 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
658 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
659 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
661 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
663 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
664 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
667 if (Subtarget->hasSSE2()) {
668 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
669 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
670 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
671 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
672 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
674 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
675 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
676 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
677 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
678 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
679 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
680 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
681 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
682 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
683 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
684 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
685 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
686 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
687 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
688 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
690 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
691 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
692 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
693 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
695 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
696 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
698 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
699 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
701 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
702 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
703 MVT VT = (MVT::SimpleValueType)i;
704 // Do not attempt to custom lower non-power-of-2 vectors
705 if (!isPowerOf2_32(VT.getVectorNumElements()))
707 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
708 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
709 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
711 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
713 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
714 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
717 if (Subtarget->is64Bit()) {
718 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
719 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
722 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
723 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
724 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
725 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
726 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
727 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
728 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
729 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
730 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
731 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
732 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
733 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
736 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
738 // Custom lower v2i64 and v2f64 selects.
739 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
740 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
741 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
742 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
746 if (Subtarget->hasSSE41()) {
747 // FIXME: Do we need to handle scalar-to-vector here?
748 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
749 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
751 // i8 and i16 vectors are custom , because the source register and source
752 // source memory operand types are not the same width. f32 vectors are
753 // custom since the immediate controlling the insert encodes additional
755 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
756 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
757 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
760 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
761 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
765 if (Subtarget->is64Bit()) {
766 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
771 if (Subtarget->hasSSE42()) {
772 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
775 // We want to custom lower some of our intrinsics.
776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
778 // We have target-specific dag combine patterns for the following nodes:
779 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
780 setTargetDAGCombine(ISD::BUILD_VECTOR);
781 setTargetDAGCombine(ISD::SELECT);
782 setTargetDAGCombine(ISD::STORE);
784 computeRegisterProperties();
786 // FIXME: These should be based on subtarget info. Plus, the values should
787 // be smaller when we are in optimizing for size mode.
788 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
789 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
790 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
791 allowUnalignedMemoryAccesses = true; // x86 supports it!
792 setPrefLoopAlignment(16);
796 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
801 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
802 /// the desired ByVal argument alignment.
803 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
806 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
807 if (VTy->getBitWidth() == 128)
809 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
810 unsigned EltAlign = 0;
811 getMaxByValAlign(ATy->getElementType(), EltAlign);
812 if (EltAlign > MaxAlign)
814 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
815 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
816 unsigned EltAlign = 0;
817 getMaxByValAlign(STy->getElementType(i), EltAlign);
818 if (EltAlign > MaxAlign)
827 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
828 /// function arguments in the caller parameter area. For X86, aggregates
829 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
830 /// are at 4-byte boundaries.
831 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
832 if (Subtarget->is64Bit()) {
833 // Max of 8 and alignment of type.
834 unsigned TyAlign = TD->getABITypeAlignment(Ty);
841 if (Subtarget->hasSSE1())
842 getMaxByValAlign(Ty, Align);
846 /// getOptimalMemOpType - Returns the target specific optimal type for load
847 /// and store operations as a result of memset, memcpy, and memmove
848 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
851 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
852 bool isSrcConst, bool isSrcStr) const {
853 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
855 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
857 if (Subtarget->is64Bit() && Size >= 8)
863 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
865 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
866 SelectionDAG &DAG) const {
867 if (usesGlobalOffsetTable())
868 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
869 if (!Subtarget->isPICStyleRIPRel())
870 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
874 //===----------------------------------------------------------------------===//
875 // Return Value Calling Convention Implementation
876 //===----------------------------------------------------------------------===//
878 #include "X86GenCallingConv.inc"
880 /// LowerRET - Lower an ISD::RET node.
881 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
882 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
884 SmallVector<CCValAssign, 16> RVLocs;
885 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
886 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
887 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
888 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
890 // If this is the first return lowered for this function, add the regs to the
891 // liveout set for the function.
892 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
893 for (unsigned i = 0; i != RVLocs.size(); ++i)
894 if (RVLocs[i].isRegLoc())
895 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
897 SDValue Chain = Op.getOperand(0);
899 // Handle tail call return.
900 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
901 if (Chain.getOpcode() == X86ISD::TAILCALL) {
902 SDValue TailCall = Chain;
903 SDValue TargetAddress = TailCall.getOperand(1);
904 SDValue StackAdjustment = TailCall.getOperand(2);
905 assert(((TargetAddress.getOpcode() == ISD::Register &&
906 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
907 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
908 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
909 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
910 "Expecting an global address, external symbol, or register");
911 assert(StackAdjustment.getOpcode() == ISD::Constant &&
912 "Expecting a const value");
914 SmallVector<SDValue,8> Operands;
915 Operands.push_back(Chain.getOperand(0));
916 Operands.push_back(TargetAddress);
917 Operands.push_back(StackAdjustment);
918 // Copy registers used by the call. Last operand is a flag so it is not
920 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
921 Operands.push_back(Chain.getOperand(i));
923 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
930 SmallVector<SDValue, 6> RetOps;
931 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
932 // Operand #1 = Bytes To Pop
933 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
935 // Copy the result values into the output registers.
936 for (unsigned i = 0; i != RVLocs.size(); ++i) {
937 CCValAssign &VA = RVLocs[i];
938 assert(VA.isRegLoc() && "Can only return in registers!");
939 SDValue ValToCopy = Op.getOperand(i*2+1);
941 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
942 // the RET instruction and handled by the FP Stackifier.
943 if (RVLocs[i].getLocReg() == X86::ST0 ||
944 RVLocs[i].getLocReg() == X86::ST1) {
945 // If this is a copy from an xmm register to ST(0), use an FPExtend to
946 // change the value to the FP stack register class.
947 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
948 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
949 RetOps.push_back(ValToCopy);
950 // Don't emit a copytoreg.
954 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
955 Flag = Chain.getValue(1);
958 // The x86-64 ABI for returning structs by value requires that we copy
959 // the sret argument into %rax for the return. We saved the argument into
960 // a virtual register in the entry block, so now we copy the value out
962 if (Subtarget->is64Bit() &&
963 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
964 MachineFunction &MF = DAG.getMachineFunction();
965 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
966 unsigned Reg = FuncInfo->getSRetReturnReg();
968 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
969 FuncInfo->setSRetReturnReg(Reg);
971 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
973 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
974 Flag = Chain.getValue(1);
977 RetOps[0] = Chain; // Update chain.
979 // Add the flag if we have it.
981 RetOps.push_back(Flag);
983 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
987 /// LowerCallResult - Lower the result values of an ISD::CALL into the
988 /// appropriate copies out of appropriate physical registers. This assumes that
989 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
990 /// being lowered. The returns a SDNode with the same number of values as the
992 SDNode *X86TargetLowering::
993 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
994 unsigned CallingConv, SelectionDAG &DAG) {
996 // Assign locations to each value returned by this call.
997 SmallVector<CCValAssign, 16> RVLocs;
998 bool isVarArg = TheCall->isVarArg();
999 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1000 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1002 SmallVector<SDValue, 8> ResultVals;
1004 // Copy all of the result registers out of their specified physreg.
1005 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1006 MVT CopyVT = RVLocs[i].getValVT();
1008 // If this is a call to a function that returns an fp value on the floating
1009 // point stack, but where we prefer to use the value in xmm registers, copy
1010 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1011 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1012 RVLocs[i].getLocReg() == X86::ST1) &&
1013 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1017 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1018 CopyVT, InFlag).getValue(1);
1019 SDValue Val = Chain.getValue(0);
1020 InFlag = Chain.getValue(2);
1022 if (CopyVT != RVLocs[i].getValVT()) {
1023 // Round the F80 the right size, which also moves to the appropriate xmm
1025 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1026 // This truncation won't change the value.
1027 DAG.getIntPtrConstant(1));
1030 ResultVals.push_back(Val);
1033 // Merge everything together with a MERGE_VALUES node.
1034 ResultVals.push_back(Chain);
1035 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1036 ResultVals.size()).getNode();
1040 //===----------------------------------------------------------------------===//
1041 // C & StdCall & Fast Calling Convention implementation
1042 //===----------------------------------------------------------------------===//
1043 // StdCall calling convention seems to be standard for many Windows' API
1044 // routines and around. It differs from C calling convention just a little:
1045 // callee should clean up the stack, not caller. Symbols should be also
1046 // decorated in some fancy way :) It doesn't support any vector arguments.
1047 // For info on fast calling convention see Fast Calling Convention (tail call)
1048 // implementation LowerX86_32FastCCCallTo.
1050 /// AddLiveIn - This helper function adds the specified physical register to the
1051 /// MachineFunction as a live in value. It also creates a corresponding virtual
1052 /// register for it.
1053 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1054 const TargetRegisterClass *RC) {
1055 assert(RC->contains(PReg) && "Not the correct regclass!");
1056 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1057 MF.getRegInfo().addLiveIn(PReg, VReg);
1061 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1063 static bool CallIsStructReturn(CallSDNode *TheCall) {
1064 unsigned NumOps = TheCall->getNumArgs();
1068 return TheCall->getArgFlags(0).isSRet();
1071 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1072 /// return semantics.
1073 static bool ArgsAreStructReturn(SDValue Op) {
1074 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1078 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1081 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1082 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1084 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1088 switch (CallingConv) {
1091 case CallingConv::X86_StdCall:
1092 return !Subtarget->is64Bit();
1093 case CallingConv::X86_FastCall:
1094 return !Subtarget->is64Bit();
1095 case CallingConv::Fast:
1096 return PerformTailCallOpt;
1100 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1101 /// given CallingConvention value.
1102 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1103 if (Subtarget->is64Bit()) {
1104 if (Subtarget->isTargetWin64())
1105 return CC_X86_Win64_C;
1106 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1107 return CC_X86_64_TailCall;
1112 if (CC == CallingConv::X86_FastCall)
1113 return CC_X86_32_FastCall;
1114 else if (CC == CallingConv::Fast)
1115 return CC_X86_32_FastCC;
1120 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1121 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1123 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1124 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1125 if (CC == CallingConv::X86_FastCall)
1127 else if (CC == CallingConv::X86_StdCall)
1133 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1134 /// in a register before calling.
1135 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1136 return !IsTailCall && !Is64Bit &&
1137 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138 Subtarget->isPICStyleGOT();
1141 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1142 /// address to be loaded in a register.
1144 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1145 return !Is64Bit && IsTailCall &&
1146 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1147 Subtarget->isPICStyleGOT();
1150 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1151 /// by "Src" to address "Dst" with size and alignment information specified by
1152 /// the specific parameter attribute. The copy will be passed as a byval
1153 /// function parameter.
1155 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1156 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1157 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1158 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1159 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1162 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1163 const CCValAssign &VA,
1164 MachineFrameInfo *MFI,
1166 SDValue Root, unsigned i) {
1167 // Create the nodes corresponding to a load from this parameter slot.
1168 ISD::ArgFlagsTy Flags =
1169 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1170 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1171 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1173 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1174 // changed with more analysis.
1175 // In case of tail call optimization mark all arguments mutable. Since they
1176 // could be overwritten by lowering of arguments in case of a tail call.
1177 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1178 VA.getLocMemOffset(), isImmutable);
1179 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1180 if (Flags.isByVal())
1182 return DAG.getLoad(VA.getValVT(), Root, FIN,
1183 PseudoSourceValue::getFixedStack(FI), 0);
1187 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1188 MachineFunction &MF = DAG.getMachineFunction();
1189 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1191 const Function* Fn = MF.getFunction();
1192 if (Fn->hasExternalLinkage() &&
1193 Subtarget->isTargetCygMing() &&
1194 Fn->getName() == "main")
1195 FuncInfo->setForceFramePointer(true);
1197 // Decorate the function name.
1198 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1200 MachineFrameInfo *MFI = MF.getFrameInfo();
1201 SDValue Root = Op.getOperand(0);
1202 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1203 unsigned CC = MF.getFunction()->getCallingConv();
1204 bool Is64Bit = Subtarget->is64Bit();
1205 bool IsWin64 = Subtarget->isTargetWin64();
1207 assert(!(isVarArg && CC == CallingConv::Fast) &&
1208 "Var args not supported with calling convention fastcc");
1210 // Assign locations to all of the incoming arguments.
1211 SmallVector<CCValAssign, 16> ArgLocs;
1212 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1213 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1215 SmallVector<SDValue, 8> ArgValues;
1216 unsigned LastVal = ~0U;
1217 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1218 CCValAssign &VA = ArgLocs[i];
1219 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1221 assert(VA.getValNo() != LastVal &&
1222 "Don't support value assigned to multiple locs yet");
1223 LastVal = VA.getValNo();
1225 if (VA.isRegLoc()) {
1226 MVT RegVT = VA.getLocVT();
1227 TargetRegisterClass *RC;
1228 if (RegVT == MVT::i32)
1229 RC = X86::GR32RegisterClass;
1230 else if (Is64Bit && RegVT == MVT::i64)
1231 RC = X86::GR64RegisterClass;
1232 else if (RegVT == MVT::f32)
1233 RC = X86::FR32RegisterClass;
1234 else if (RegVT == MVT::f64)
1235 RC = X86::FR64RegisterClass;
1236 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1237 RC = X86::VR128RegisterClass;
1238 else if (RegVT.isVector()) {
1239 assert(RegVT.getSizeInBits() == 64);
1241 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1243 // Darwin calling convention passes MMX values in either GPRs or
1244 // XMMs in x86-64. Other targets pass them in memory.
1245 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1246 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1249 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1254 assert(0 && "Unknown argument type!");
1257 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1258 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1260 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1261 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1263 if (VA.getLocInfo() == CCValAssign::SExt)
1264 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1265 DAG.getValueType(VA.getValVT()));
1266 else if (VA.getLocInfo() == CCValAssign::ZExt)
1267 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1268 DAG.getValueType(VA.getValVT()));
1270 if (VA.getLocInfo() != CCValAssign::Full)
1271 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1273 // Handle MMX values passed in GPRs.
1274 if (Is64Bit && RegVT != VA.getLocVT()) {
1275 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1276 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1277 else if (RC == X86::VR128RegisterClass) {
1278 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1279 DAG.getConstant(0, MVT::i64));
1280 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1284 ArgValues.push_back(ArgValue);
1286 assert(VA.isMemLoc());
1287 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1291 // The x86-64 ABI for returning structs by value requires that we copy
1292 // the sret argument into %rax for the return. Save the argument into
1293 // a virtual register so that we can access it from the return points.
1294 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1297 unsigned Reg = FuncInfo->getSRetReturnReg();
1299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1300 FuncInfo->setSRetReturnReg(Reg);
1302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1303 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1306 unsigned StackSize = CCInfo.getNextStackOffset();
1307 // align stack specially for tail calls
1308 if (PerformTailCallOpt && CC == CallingConv::Fast)
1309 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1311 // If the function takes variable number of arguments, make a frame index for
1312 // the start of the first vararg value... for expansion of llvm.va_start.
1314 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1315 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1318 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1320 // FIXME: We should really autogenerate these arrays
1321 static const unsigned GPR64ArgRegsWin64[] = {
1322 X86::RCX, X86::RDX, X86::R8, X86::R9
1324 static const unsigned XMMArgRegsWin64[] = {
1325 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1327 static const unsigned GPR64ArgRegs64Bit[] = {
1328 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1330 static const unsigned XMMArgRegs64Bit[] = {
1331 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1332 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1334 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1337 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1338 GPR64ArgRegs = GPR64ArgRegsWin64;
1339 XMMArgRegs = XMMArgRegsWin64;
1341 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1342 GPR64ArgRegs = GPR64ArgRegs64Bit;
1343 XMMArgRegs = XMMArgRegs64Bit;
1345 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1347 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1350 // For X86-64, if there are vararg parameters that are passed via
1351 // registers, then we must store them to their spots on the stack so they
1352 // may be loaded by deferencing the result of va_next.
1353 VarArgsGPOffset = NumIntRegs * 8;
1354 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1355 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1356 TotalNumXMMRegs * 16, 16);
1358 // Store the integer parameter registers.
1359 SmallVector<SDValue, 8> MemOps;
1360 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1361 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1362 DAG.getIntPtrConstant(VarArgsGPOffset));
1363 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1364 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1365 X86::GR64RegisterClass);
1366 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1368 DAG.getStore(Val.getValue(1), Val, FIN,
1369 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1370 MemOps.push_back(Store);
1371 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1372 DAG.getIntPtrConstant(8));
1375 // Now store the XMM (fp + vector) parameter registers.
1376 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1377 DAG.getIntPtrConstant(VarArgsFPOffset));
1378 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1379 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1380 X86::VR128RegisterClass);
1381 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1383 DAG.getStore(Val.getValue(1), Val, FIN,
1384 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1385 MemOps.push_back(Store);
1386 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1387 DAG.getIntPtrConstant(16));
1389 if (!MemOps.empty())
1390 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1391 &MemOps[0], MemOps.size());
1395 ArgValues.push_back(Root);
1397 // Some CCs need callee pop.
1398 if (IsCalleePop(isVarArg, CC)) {
1399 BytesToPopOnReturn = StackSize; // Callee pops everything.
1400 BytesCallerReserves = 0;
1402 BytesToPopOnReturn = 0; // Callee pops nothing.
1403 // If this is an sret function, the return should pop the hidden pointer.
1404 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1405 BytesToPopOnReturn = 4;
1406 BytesCallerReserves = StackSize;
1410 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1411 if (CC == CallingConv::X86_FastCall)
1412 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1415 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1417 // Return the new list of results.
1418 return DAG.getMergeValues(Op.getNode()->getVTList(), &ArgValues[0],
1419 ArgValues.size()).getValue(Op.getResNo());
1423 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1424 const SDValue &StackPtr,
1425 const CCValAssign &VA,
1427 SDValue Arg, ISD::ArgFlagsTy Flags) {
1428 unsigned LocMemOffset = VA.getLocMemOffset();
1429 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1430 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1431 if (Flags.isByVal()) {
1432 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1434 return DAG.getStore(Chain, Arg, PtrOff,
1435 PseudoSourceValue::getStack(), LocMemOffset);
1438 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1439 /// optimization is performed and it is required.
1441 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1442 SDValue &OutRetAddr,
1447 if (!IsTailCall || FPDiff==0) return Chain;
1449 // Adjust the Return address stack slot.
1450 MVT VT = getPointerTy();
1451 OutRetAddr = getReturnAddressFrameIndex(DAG);
1452 // Load the "old" Return address.
1453 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1454 return SDValue(OutRetAddr.getNode(), 1);
1457 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1458 /// optimization is performed and it is required (FPDiff!=0).
1460 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1461 SDValue Chain, SDValue RetAddrFrIdx,
1462 bool Is64Bit, int FPDiff) {
1463 // Store the return address to the appropriate stack slot.
1464 if (!FPDiff) return Chain;
1465 // Calculate the new stack slot for the return address.
1466 int SlotSize = Is64Bit ? 8 : 4;
1467 int NewReturnAddrFI =
1468 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1469 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1470 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1471 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1472 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1476 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1477 MachineFunction &MF = DAG.getMachineFunction();
1478 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1479 SDValue Chain = TheCall->getChain();
1480 unsigned CC = TheCall->getCallingConv();
1481 bool isVarArg = TheCall->isVarArg();
1482 bool IsTailCall = TheCall->isTailCall() &&
1483 CC == CallingConv::Fast && PerformTailCallOpt;
1484 SDValue Callee = TheCall->getCallee();
1485 bool Is64Bit = Subtarget->is64Bit();
1486 bool IsStructRet = CallIsStructReturn(TheCall);
1488 assert(!(isVarArg && CC == CallingConv::Fast) &&
1489 "Var args not supported with calling convention fastcc");
1491 // Analyze operands of the call, assigning locations to each operand.
1492 SmallVector<CCValAssign, 16> ArgLocs;
1493 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1494 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1496 // Get a count of how many bytes are to be pushed on the stack.
1497 unsigned NumBytes = CCInfo.getNextStackOffset();
1498 if (PerformTailCallOpt && CC == CallingConv::Fast)
1499 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1503 // Lower arguments at fp - stackoffset + fpdiff.
1504 unsigned NumBytesCallerPushed =
1505 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1506 FPDiff = NumBytesCallerPushed - NumBytes;
1508 // Set the delta of movement of the returnaddr stackslot.
1509 // But only set if delta is greater than previous delta.
1510 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1511 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1514 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1516 SDValue RetAddrFrIdx;
1517 // Load return adress for tail calls.
1518 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1521 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1522 SmallVector<SDValue, 8> MemOpChains;
1525 // Walk the register/memloc assignments, inserting copies/loads. In the case
1526 // of tail call optimization arguments are handle later.
1527 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1528 CCValAssign &VA = ArgLocs[i];
1529 SDValue Arg = TheCall->getArg(i);
1530 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1531 bool isByVal = Flags.isByVal();
1533 // Promote the value if needed.
1534 switch (VA.getLocInfo()) {
1535 default: assert(0 && "Unknown loc info!");
1536 case CCValAssign::Full: break;
1537 case CCValAssign::SExt:
1538 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1540 case CCValAssign::ZExt:
1541 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1543 case CCValAssign::AExt:
1544 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1548 if (VA.isRegLoc()) {
1550 MVT RegVT = VA.getLocVT();
1551 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1552 switch (VA.getLocReg()) {
1555 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1557 // Special case: passing MMX values in GPR registers.
1558 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1561 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1562 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1563 // Special case: passing MMX values in XMM registers.
1564 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1565 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1566 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1567 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1568 getMOVLMask(2, DAG));
1573 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1575 if (!IsTailCall || (IsTailCall && isByVal)) {
1576 assert(VA.isMemLoc());
1577 if (StackPtr.getNode() == 0)
1578 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1580 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1581 Chain, Arg, Flags));
1586 if (!MemOpChains.empty())
1587 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1588 &MemOpChains[0], MemOpChains.size());
1590 // Build a sequence of copy-to-reg nodes chained together with token chain
1591 // and flag operands which copy the outgoing args into registers.
1593 // Tail call byval lowering might overwrite argument registers so in case of
1594 // tail call optimization the copies to registers are lowered later.
1596 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1597 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1599 InFlag = Chain.getValue(1);
1602 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1604 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1605 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1606 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1608 InFlag = Chain.getValue(1);
1610 // If we are tail calling and generating PIC/GOT style code load the address
1611 // of the callee into ecx. The value in ecx is used as target of the tail
1612 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1613 // calls on PIC/GOT architectures. Normally we would just put the address of
1614 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1615 // restored (since ebx is callee saved) before jumping to the target@PLT.
1616 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1617 // Note: The actual moving to ecx is done further down.
1618 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1619 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1620 !G->getGlobal()->hasProtectedVisibility())
1621 Callee = LowerGlobalAddress(Callee, DAG);
1622 else if (isa<ExternalSymbolSDNode>(Callee))
1623 Callee = LowerExternalSymbol(Callee,DAG);
1626 if (Is64Bit && isVarArg) {
1627 // From AMD64 ABI document:
1628 // For calls that may call functions that use varargs or stdargs
1629 // (prototype-less calls or calls to functions containing ellipsis (...) in
1630 // the declaration) %al is used as hidden argument to specify the number
1631 // of SSE registers used. The contents of %al do not need to match exactly
1632 // the number of registers, but must be an ubound on the number of SSE
1633 // registers used and is in the range 0 - 8 inclusive.
1635 // FIXME: Verify this on Win64
1636 // Count the number of XMM registers allocated.
1637 static const unsigned XMMArgRegs[] = {
1638 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1639 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1641 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1643 Chain = DAG.getCopyToReg(Chain, X86::AL,
1644 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1645 InFlag = Chain.getValue(1);
1649 // For tail calls lower the arguments to the 'real' stack slot.
1651 SmallVector<SDValue, 8> MemOpChains2;
1654 // Do not flag preceeding copytoreg stuff together with the following stuff.
1656 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1657 CCValAssign &VA = ArgLocs[i];
1658 if (!VA.isRegLoc()) {
1659 assert(VA.isMemLoc());
1660 SDValue Arg = TheCall->getArg(i);
1661 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1662 // Create frame index.
1663 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1664 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1665 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1666 FIN = DAG.getFrameIndex(FI, getPointerTy());
1668 if (Flags.isByVal()) {
1669 // Copy relative to framepointer.
1670 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1671 if (StackPtr.getNode() == 0)
1672 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1673 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1675 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1678 // Store relative to framepointer.
1679 MemOpChains2.push_back(
1680 DAG.getStore(Chain, Arg, FIN,
1681 PseudoSourceValue::getFixedStack(FI), 0));
1686 if (!MemOpChains2.empty())
1687 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1688 &MemOpChains2[0], MemOpChains2.size());
1690 // Copy arguments to their registers.
1691 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1692 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1694 InFlag = Chain.getValue(1);
1698 // Store the return address to the appropriate stack slot.
1699 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1703 // If the callee is a GlobalAddress node (quite common, every direct call is)
1704 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1705 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1706 // We should use extra load for direct calls to dllimported functions in
1708 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1709 getTargetMachine(), true))
1710 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1712 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1713 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1714 } else if (IsTailCall) {
1715 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1717 Chain = DAG.getCopyToReg(Chain,
1718 DAG.getRegister(Opc, getPointerTy()),
1720 Callee = DAG.getRegister(Opc, getPointerTy());
1721 // Add register as live out.
1722 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1725 // Returns a chain & a flag for retval copy to use.
1726 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1727 SmallVector<SDValue, 8> Ops;
1730 Ops.push_back(Chain);
1731 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1732 Ops.push_back(DAG.getIntPtrConstant(0, true));
1733 if (InFlag.getNode())
1734 Ops.push_back(InFlag);
1735 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1736 InFlag = Chain.getValue(1);
1738 // Returns a chain & a flag for retval copy to use.
1739 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1743 Ops.push_back(Chain);
1744 Ops.push_back(Callee);
1747 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1749 // Add argument registers to the end of the list so that they are known live
1751 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1752 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1753 RegsToPass[i].second.getValueType()));
1755 // Add an implicit use GOT pointer in EBX.
1756 if (!IsTailCall && !Is64Bit &&
1757 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1758 Subtarget->isPICStyleGOT())
1759 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1761 // Add an implicit use of AL for x86 vararg functions.
1762 if (Is64Bit && isVarArg)
1763 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1765 if (InFlag.getNode())
1766 Ops.push_back(InFlag);
1769 assert(InFlag.getNode() &&
1770 "Flag must be set. Depend on flag being set in LowerRET");
1771 Chain = DAG.getNode(X86ISD::TAILCALL,
1772 TheCall->getVTList(), &Ops[0], Ops.size());
1774 return SDValue(Chain.getNode(), Op.getResNo());
1777 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1778 InFlag = Chain.getValue(1);
1780 // Create the CALLSEQ_END node.
1781 unsigned NumBytesForCalleeToPush;
1782 if (IsCalleePop(isVarArg, CC))
1783 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1784 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1785 // If this is is a call to a struct-return function, the callee
1786 // pops the hidden struct pointer, so we have to push it back.
1787 // This is common for Darwin/X86, Linux & Mingw32 targets.
1788 NumBytesForCalleeToPush = 4;
1790 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1792 // Returns a flag for retval copy to use.
1793 Chain = DAG.getCALLSEQ_END(Chain,
1794 DAG.getIntPtrConstant(NumBytes, true),
1795 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1798 InFlag = Chain.getValue(1);
1800 // Handle result values, copying them out of physregs into vregs that we
1802 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1807 //===----------------------------------------------------------------------===//
1808 // Fast Calling Convention (tail call) implementation
1809 //===----------------------------------------------------------------------===//
1811 // Like std call, callee cleans arguments, convention except that ECX is
1812 // reserved for storing the tail called function address. Only 2 registers are
1813 // free for argument passing (inreg). Tail call optimization is performed
1815 // * tailcallopt is enabled
1816 // * caller/callee are fastcc
1817 // On X86_64 architecture with GOT-style position independent code only local
1818 // (within module) calls are supported at the moment.
1819 // To keep the stack aligned according to platform abi the function
1820 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1821 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1822 // If a tail called function callee has more arguments than the caller the
1823 // caller needs to make sure that there is room to move the RETADDR to. This is
1824 // achieved by reserving an area the size of the argument delta right after the
1825 // original REtADDR, but before the saved framepointer or the spilled registers
1826 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1838 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1839 /// for a 16 byte align requirement.
1840 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1841 SelectionDAG& DAG) {
1842 MachineFunction &MF = DAG.getMachineFunction();
1843 const TargetMachine &TM = MF.getTarget();
1844 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1845 unsigned StackAlignment = TFI.getStackAlignment();
1846 uint64_t AlignMask = StackAlignment - 1;
1847 int64_t Offset = StackSize;
1848 uint64_t SlotSize = TD->getPointerSize();
1849 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1850 // Number smaller than 12 so just add the difference.
1851 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1853 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1854 Offset = ((~AlignMask) & Offset) + StackAlignment +
1855 (StackAlignment-SlotSize);
1860 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1861 /// following the call is a return. A function is eligible if caller/callee
1862 /// calling conventions match, currently only fastcc supports tail calls, and
1863 /// the function CALL is immediatly followed by a RET.
1864 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1866 SelectionDAG& DAG) const {
1867 if (!PerformTailCallOpt)
1870 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1871 MachineFunction &MF = DAG.getMachineFunction();
1872 unsigned CallerCC = MF.getFunction()->getCallingConv();
1873 unsigned CalleeCC= TheCall->getCallingConv();
1874 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1875 SDValue Callee = TheCall->getCallee();
1876 // On x86/32Bit PIC/GOT tail calls are supported.
1877 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1878 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1881 // Can only do local tail calls (in same module, hidden or protected) on
1882 // x86_64 PIC/GOT at the moment.
1883 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1884 return G->getGlobal()->hasHiddenVisibility()
1885 || G->getGlobal()->hasProtectedVisibility();
1893 X86TargetLowering::createFastISel(MachineFunction &mf,
1894 MachineModuleInfo *mmo,
1895 DenseMap<const Value *, unsigned> &vm,
1896 DenseMap<const BasicBlock *,
1897 MachineBasicBlock *> &bm,
1898 DenseMap<const AllocaInst *, int> &am
1900 , SmallSet<Instruction*, 8> &cil
1903 return X86::createFastISel(mf, mmo, vm, bm, am
1911 //===----------------------------------------------------------------------===//
1912 // Other Lowering Hooks
1913 //===----------------------------------------------------------------------===//
1916 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1917 MachineFunction &MF = DAG.getMachineFunction();
1918 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919 int ReturnAddrIndex = FuncInfo->getRAIndex();
1920 uint64_t SlotSize = TD->getPointerSize();
1922 if (ReturnAddrIndex == 0) {
1923 // Set up a frame object for the return address.
1924 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1925 FuncInfo->setRAIndex(ReturnAddrIndex);
1928 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1932 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1933 /// specific condition code. It returns a false if it cannot do a direct
1934 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1936 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1937 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1938 SelectionDAG &DAG) {
1939 X86CC = X86::COND_INVALID;
1941 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1942 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1943 // X > -1 -> X == 0, jump !sign.
1944 RHS = DAG.getConstant(0, RHS.getValueType());
1945 X86CC = X86::COND_NS;
1947 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1948 // X < 0 -> X == 0, jump on sign.
1949 X86CC = X86::COND_S;
1951 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1953 RHS = DAG.getConstant(0, RHS.getValueType());
1954 X86CC = X86::COND_LE;
1959 switch (SetCCOpcode) {
1961 case ISD::SETEQ: X86CC = X86::COND_E; break;
1962 case ISD::SETGT: X86CC = X86::COND_G; break;
1963 case ISD::SETGE: X86CC = X86::COND_GE; break;
1964 case ISD::SETLT: X86CC = X86::COND_L; break;
1965 case ISD::SETLE: X86CC = X86::COND_LE; break;
1966 case ISD::SETNE: X86CC = X86::COND_NE; break;
1967 case ISD::SETULT: X86CC = X86::COND_B; break;
1968 case ISD::SETUGT: X86CC = X86::COND_A; break;
1969 case ISD::SETULE: X86CC = X86::COND_BE; break;
1970 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1973 // First determine if it is required or is profitable to flip the operands.
1975 // If LHS is a foldable load, but RHS is not, flip the condition.
1976 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1977 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1978 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1979 std::swap(LHS, RHS);
1982 switch (SetCCOpcode) {
1988 std::swap(LHS, RHS);
1992 // On a floating point condition, the flags are set as follows:
1994 // 0 | 0 | 0 | X > Y
1995 // 0 | 0 | 1 | X < Y
1996 // 1 | 0 | 0 | X == Y
1997 // 1 | 1 | 1 | unordered
1998 switch (SetCCOpcode) {
2002 X86CC = X86::COND_E;
2004 case ISD::SETOLT: // flipped
2007 X86CC = X86::COND_A;
2009 case ISD::SETOLE: // flipped
2012 X86CC = X86::COND_AE;
2014 case ISD::SETUGT: // flipped
2017 X86CC = X86::COND_B;
2019 case ISD::SETUGE: // flipped
2022 X86CC = X86::COND_BE;
2026 X86CC = X86::COND_NE;
2029 X86CC = X86::COND_P;
2032 X86CC = X86::COND_NP;
2037 return X86CC != X86::COND_INVALID;
2040 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2041 /// code. Current x86 isa includes the following FP cmov instructions:
2042 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2043 static bool hasFPCMov(unsigned X86CC) {
2059 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2060 /// true if Op is undef or if its value falls within the specified range (L, H].
2061 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2062 if (Op.getOpcode() == ISD::UNDEF)
2065 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2066 return (Val >= Low && Val < Hi);
2069 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2070 /// true if Op is undef or if its value equal to the specified value.
2071 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2072 if (Op.getOpcode() == ISD::UNDEF)
2074 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2077 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2078 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2079 bool X86::isPSHUFDMask(SDNode *N) {
2080 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2082 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2085 // Check if the value doesn't reference the second vector.
2086 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2087 SDValue Arg = N->getOperand(i);
2088 if (Arg.getOpcode() == ISD::UNDEF) continue;
2089 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2090 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2097 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2098 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2099 bool X86::isPSHUFHWMask(SDNode *N) {
2100 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2102 if (N->getNumOperands() != 8)
2105 // Lower quadword copied in order.
2106 for (unsigned i = 0; i != 4; ++i) {
2107 SDValue Arg = N->getOperand(i);
2108 if (Arg.getOpcode() == ISD::UNDEF) continue;
2109 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2110 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2114 // Upper quadword shuffled.
2115 for (unsigned i = 4; i != 8; ++i) {
2116 SDValue Arg = N->getOperand(i);
2117 if (Arg.getOpcode() == ISD::UNDEF) continue;
2118 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2119 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2120 if (Val < 4 || Val > 7)
2127 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2128 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2129 bool X86::isPSHUFLWMask(SDNode *N) {
2130 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2132 if (N->getNumOperands() != 8)
2135 // Upper quadword copied in order.
2136 for (unsigned i = 4; i != 8; ++i)
2137 if (!isUndefOrEqual(N->getOperand(i), i))
2140 // Lower quadword shuffled.
2141 for (unsigned i = 0; i != 4; ++i)
2142 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2148 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2149 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2150 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2151 if (NumElems != 2 && NumElems != 4) return false;
2153 unsigned Half = NumElems / 2;
2154 for (unsigned i = 0; i < Half; ++i)
2155 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2157 for (unsigned i = Half; i < NumElems; ++i)
2158 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2164 bool X86::isSHUFPMask(SDNode *N) {
2165 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2166 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2169 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2170 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2171 /// half elements to come from vector 1 (which would equal the dest.) and
2172 /// the upper half to come from vector 2.
2173 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2174 if (NumOps != 2 && NumOps != 4) return false;
2176 unsigned Half = NumOps / 2;
2177 for (unsigned i = 0; i < Half; ++i)
2178 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2180 for (unsigned i = Half; i < NumOps; ++i)
2181 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2186 static bool isCommutedSHUFP(SDNode *N) {
2187 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2188 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2191 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2192 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2193 bool X86::isMOVHLPSMask(SDNode *N) {
2194 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2196 if (N->getNumOperands() != 4)
2199 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2200 return isUndefOrEqual(N->getOperand(0), 6) &&
2201 isUndefOrEqual(N->getOperand(1), 7) &&
2202 isUndefOrEqual(N->getOperand(2), 2) &&
2203 isUndefOrEqual(N->getOperand(3), 3);
2206 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2207 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2209 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2210 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2212 if (N->getNumOperands() != 4)
2215 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2216 return isUndefOrEqual(N->getOperand(0), 2) &&
2217 isUndefOrEqual(N->getOperand(1), 3) &&
2218 isUndefOrEqual(N->getOperand(2), 2) &&
2219 isUndefOrEqual(N->getOperand(3), 3);
2222 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2223 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2224 bool X86::isMOVLPMask(SDNode *N) {
2225 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2227 unsigned NumElems = N->getNumOperands();
2228 if (NumElems != 2 && NumElems != 4)
2231 for (unsigned i = 0; i < NumElems/2; ++i)
2232 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2235 for (unsigned i = NumElems/2; i < NumElems; ++i)
2236 if (!isUndefOrEqual(N->getOperand(i), i))
2242 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2243 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2245 bool X86::isMOVHPMask(SDNode *N) {
2246 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2248 unsigned NumElems = N->getNumOperands();
2249 if (NumElems != 2 && NumElems != 4)
2252 for (unsigned i = 0; i < NumElems/2; ++i)
2253 if (!isUndefOrEqual(N->getOperand(i), i))
2256 for (unsigned i = 0; i < NumElems/2; ++i) {
2257 SDValue Arg = N->getOperand(i + NumElems/2);
2258 if (!isUndefOrEqual(Arg, i + NumElems))
2265 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2266 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2267 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2268 bool V2IsSplat = false) {
2269 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2272 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2273 SDValue BitI = Elts[i];
2274 SDValue BitI1 = Elts[i+1];
2275 if (!isUndefOrEqual(BitI, j))
2278 if (isUndefOrEqual(BitI1, NumElts))
2281 if (!isUndefOrEqual(BitI1, j + NumElts))
2289 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2290 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2291 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2294 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2295 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2296 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2297 bool V2IsSplat = false) {
2298 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2301 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2302 SDValue BitI = Elts[i];
2303 SDValue BitI1 = Elts[i+1];
2304 if (!isUndefOrEqual(BitI, j + NumElts/2))
2307 if (isUndefOrEqual(BitI1, NumElts))
2310 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2318 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2319 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2320 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2323 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2324 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2326 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2327 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2329 unsigned NumElems = N->getNumOperands();
2330 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2333 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2334 SDValue BitI = N->getOperand(i);
2335 SDValue BitI1 = N->getOperand(i+1);
2337 if (!isUndefOrEqual(BitI, j))
2339 if (!isUndefOrEqual(BitI1, j))
2346 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2347 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2349 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2350 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2352 unsigned NumElems = N->getNumOperands();
2353 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2356 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2357 SDValue BitI = N->getOperand(i);
2358 SDValue BitI1 = N->getOperand(i + 1);
2360 if (!isUndefOrEqual(BitI, j))
2362 if (!isUndefOrEqual(BitI1, j))
2369 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2370 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2371 /// MOVSD, and MOVD, i.e. setting the lowest element.
2372 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2373 if (NumElts != 2 && NumElts != 4)
2376 if (!isUndefOrEqual(Elts[0], NumElts))
2379 for (unsigned i = 1; i < NumElts; ++i) {
2380 if (!isUndefOrEqual(Elts[i], i))
2387 bool X86::isMOVLMask(SDNode *N) {
2388 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2389 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2392 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2393 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2394 /// element of vector 2 and the other elements to come from vector 1 in order.
2395 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2396 bool V2IsSplat = false,
2397 bool V2IsUndef = false) {
2398 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2401 if (!isUndefOrEqual(Ops[0], 0))
2404 for (unsigned i = 1; i < NumOps; ++i) {
2405 SDValue Arg = Ops[i];
2406 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2407 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2408 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2415 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2416 bool V2IsUndef = false) {
2417 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2418 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2419 V2IsSplat, V2IsUndef);
2422 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2423 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2424 bool X86::isMOVSHDUPMask(SDNode *N) {
2425 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2427 if (N->getNumOperands() != 4)
2430 // Expect 1, 1, 3, 3
2431 for (unsigned i = 0; i < 2; ++i) {
2432 SDValue Arg = N->getOperand(i);
2433 if (Arg.getOpcode() == ISD::UNDEF) continue;
2434 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2435 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2436 if (Val != 1) return false;
2440 for (unsigned i = 2; i < 4; ++i) {
2441 SDValue Arg = N->getOperand(i);
2442 if (Arg.getOpcode() == ISD::UNDEF) continue;
2443 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2444 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2445 if (Val != 3) return false;
2449 // Don't use movshdup if it can be done with a shufps.
2453 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2454 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2455 bool X86::isMOVSLDUPMask(SDNode *N) {
2456 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2458 if (N->getNumOperands() != 4)
2461 // Expect 0, 0, 2, 2
2462 for (unsigned i = 0; i < 2; ++i) {
2463 SDValue Arg = N->getOperand(i);
2464 if (Arg.getOpcode() == ISD::UNDEF) continue;
2465 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2466 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2467 if (Val != 0) return false;
2471 for (unsigned i = 2; i < 4; ++i) {
2472 SDValue Arg = N->getOperand(i);
2473 if (Arg.getOpcode() == ISD::UNDEF) continue;
2474 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2475 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2476 if (Val != 2) return false;
2480 // Don't use movshdup if it can be done with a shufps.
2484 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2485 /// specifies a identity operation on the LHS or RHS.
2486 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2487 unsigned NumElems = N->getNumOperands();
2488 for (unsigned i = 0; i < NumElems; ++i)
2489 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2494 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2495 /// a splat of a single element.
2496 static bool isSplatMask(SDNode *N) {
2497 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2499 // This is a splat operation if each element of the permute is the same, and
2500 // if the value doesn't reference the second vector.
2501 unsigned NumElems = N->getNumOperands();
2502 SDValue ElementBase;
2504 for (; i != NumElems; ++i) {
2505 SDValue Elt = N->getOperand(i);
2506 if (isa<ConstantSDNode>(Elt)) {
2512 if (!ElementBase.getNode())
2515 for (; i != NumElems; ++i) {
2516 SDValue Arg = N->getOperand(i);
2517 if (Arg.getOpcode() == ISD::UNDEF) continue;
2518 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2519 if (Arg != ElementBase) return false;
2522 // Make sure it is a splat of the first vector operand.
2523 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2526 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2527 /// a splat of a single element and it's a 2 or 4 element mask.
2528 bool X86::isSplatMask(SDNode *N) {
2529 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2531 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2532 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2534 return ::isSplatMask(N);
2537 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2538 /// specifies a splat of zero element.
2539 bool X86::isSplatLoMask(SDNode *N) {
2540 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2542 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2543 if (!isUndefOrEqual(N->getOperand(i), 0))
2548 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2549 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2550 bool X86::isMOVDDUPMask(SDNode *N) {
2551 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2553 unsigned e = N->getNumOperands() / 2;
2554 for (unsigned i = 0; i < e; ++i)
2555 if (!isUndefOrEqual(N->getOperand(i), i))
2557 for (unsigned i = 0; i < e; ++i)
2558 if (!isUndefOrEqual(N->getOperand(e+i), i))
2563 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2564 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2566 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2567 unsigned NumOperands = N->getNumOperands();
2568 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2570 for (unsigned i = 0; i < NumOperands; ++i) {
2572 SDValue Arg = N->getOperand(NumOperands-i-1);
2573 if (Arg.getOpcode() != ISD::UNDEF)
2574 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2575 if (Val >= NumOperands) Val -= NumOperands;
2577 if (i != NumOperands - 1)
2584 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2585 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2587 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2589 // 8 nodes, but we only care about the last 4.
2590 for (unsigned i = 7; i >= 4; --i) {
2592 SDValue Arg = N->getOperand(i);
2593 if (Arg.getOpcode() != ISD::UNDEF)
2594 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2603 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2604 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2606 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2608 // 8 nodes, but we only care about the first 4.
2609 for (int i = 3; i >= 0; --i) {
2611 SDValue Arg = N->getOperand(i);
2612 if (Arg.getOpcode() != ISD::UNDEF)
2613 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2622 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2623 /// specifies a 8 element shuffle that can be broken into a pair of
2624 /// PSHUFHW and PSHUFLW.
2625 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2626 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2628 if (N->getNumOperands() != 8)
2631 // Lower quadword shuffled.
2632 for (unsigned i = 0; i != 4; ++i) {
2633 SDValue Arg = N->getOperand(i);
2634 if (Arg.getOpcode() == ISD::UNDEF) continue;
2635 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2636 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2641 // Upper quadword shuffled.
2642 for (unsigned i = 4; i != 8; ++i) {
2643 SDValue Arg = N->getOperand(i);
2644 if (Arg.getOpcode() == ISD::UNDEF) continue;
2645 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2646 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2647 if (Val < 4 || Val > 7)
2654 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2655 /// values in ther permute mask.
2656 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2657 SDValue &V2, SDValue &Mask,
2658 SelectionDAG &DAG) {
2659 MVT VT = Op.getValueType();
2660 MVT MaskVT = Mask.getValueType();
2661 MVT EltVT = MaskVT.getVectorElementType();
2662 unsigned NumElems = Mask.getNumOperands();
2663 SmallVector<SDValue, 8> MaskVec;
2665 for (unsigned i = 0; i != NumElems; ++i) {
2666 SDValue Arg = Mask.getOperand(i);
2667 if (Arg.getOpcode() == ISD::UNDEF) {
2668 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2671 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2672 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2674 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2676 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2680 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2681 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2684 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2685 /// the two vector operands have swapped position.
2687 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2688 MVT MaskVT = Mask.getValueType();
2689 MVT EltVT = MaskVT.getVectorElementType();
2690 unsigned NumElems = Mask.getNumOperands();
2691 SmallVector<SDValue, 8> MaskVec;
2692 for (unsigned i = 0; i != NumElems; ++i) {
2693 SDValue Arg = Mask.getOperand(i);
2694 if (Arg.getOpcode() == ISD::UNDEF) {
2695 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2698 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2699 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2701 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2703 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2705 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2709 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2710 /// match movhlps. The lower half elements should come from upper half of
2711 /// V1 (and in order), and the upper half elements should come from the upper
2712 /// half of V2 (and in order).
2713 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2714 unsigned NumElems = Mask->getNumOperands();
2717 for (unsigned i = 0, e = 2; i != e; ++i)
2718 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2720 for (unsigned i = 2; i != 4; ++i)
2721 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2726 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2727 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2729 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2730 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2732 N = N->getOperand(0).getNode();
2733 if (!ISD::isNON_EXTLoad(N))
2736 *LD = cast<LoadSDNode>(N);
2740 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2741 /// match movlp{s|d}. The lower half elements should come from lower half of
2742 /// V1 (and in order), and the upper half elements should come from the upper
2743 /// half of V2 (and in order). And since V1 will become the source of the
2744 /// MOVLP, it must be either a vector load or a scalar load to vector.
2745 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2746 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2748 // Is V2 is a vector load, don't do this transformation. We will try to use
2749 // load folding shufps op.
2750 if (ISD::isNON_EXTLoad(V2))
2753 unsigned NumElems = Mask->getNumOperands();
2754 if (NumElems != 2 && NumElems != 4)
2756 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2757 if (!isUndefOrEqual(Mask->getOperand(i), i))
2759 for (unsigned i = NumElems/2; i != NumElems; ++i)
2760 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2765 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2767 static bool isSplatVector(SDNode *N) {
2768 if (N->getOpcode() != ISD::BUILD_VECTOR)
2771 SDValue SplatValue = N->getOperand(0);
2772 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2773 if (N->getOperand(i) != SplatValue)
2778 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2780 static bool isUndefShuffle(SDNode *N) {
2781 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2784 SDValue V1 = N->getOperand(0);
2785 SDValue V2 = N->getOperand(1);
2786 SDValue Mask = N->getOperand(2);
2787 unsigned NumElems = Mask.getNumOperands();
2788 for (unsigned i = 0; i != NumElems; ++i) {
2789 SDValue Arg = Mask.getOperand(i);
2790 if (Arg.getOpcode() != ISD::UNDEF) {
2791 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2792 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2794 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2801 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2803 static inline bool isZeroNode(SDValue Elt) {
2804 return ((isa<ConstantSDNode>(Elt) &&
2805 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2806 (isa<ConstantFPSDNode>(Elt) &&
2807 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2810 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2811 /// to an zero vector.
2812 static bool isZeroShuffle(SDNode *N) {
2813 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2816 SDValue V1 = N->getOperand(0);
2817 SDValue V2 = N->getOperand(1);
2818 SDValue Mask = N->getOperand(2);
2819 unsigned NumElems = Mask.getNumOperands();
2820 for (unsigned i = 0; i != NumElems; ++i) {
2821 SDValue Arg = Mask.getOperand(i);
2822 if (Arg.getOpcode() == ISD::UNDEF)
2825 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2826 if (Idx < NumElems) {
2827 unsigned Opc = V1.getNode()->getOpcode();
2828 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2830 if (Opc != ISD::BUILD_VECTOR ||
2831 !isZeroNode(V1.getNode()->getOperand(Idx)))
2833 } else if (Idx >= NumElems) {
2834 unsigned Opc = V2.getNode()->getOpcode();
2835 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2837 if (Opc != ISD::BUILD_VECTOR ||
2838 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2845 /// getZeroVector - Returns a vector of specified type with all zero elements.
2847 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2848 assert(VT.isVector() && "Expected a vector type");
2850 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2851 // type. This ensures they get CSE'd.
2853 if (VT.getSizeInBits() == 64) { // MMX
2854 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2855 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2856 } else if (HasSSE2) { // SSE2
2857 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2858 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2860 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2861 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2863 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2866 /// getOnesVector - Returns a vector of specified type with all bits set.
2868 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2869 assert(VT.isVector() && "Expected a vector type");
2871 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2872 // type. This ensures they get CSE'd.
2873 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2875 if (VT.getSizeInBits() == 64) // MMX
2876 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2878 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2879 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2883 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2884 /// that point to V2 points to its first element.
2885 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2886 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2888 bool Changed = false;
2889 SmallVector<SDValue, 8> MaskVec;
2890 unsigned NumElems = Mask.getNumOperands();
2891 for (unsigned i = 0; i != NumElems; ++i) {
2892 SDValue Arg = Mask.getOperand(i);
2893 if (Arg.getOpcode() != ISD::UNDEF) {
2894 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2895 if (Val > NumElems) {
2896 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2900 MaskVec.push_back(Arg);
2904 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2905 &MaskVec[0], MaskVec.size());
2909 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2910 /// operation of specified width.
2911 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2912 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2913 MVT BaseVT = MaskVT.getVectorElementType();
2915 SmallVector<SDValue, 8> MaskVec;
2916 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2917 for (unsigned i = 1; i != NumElems; ++i)
2918 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2919 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2922 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2923 /// of specified width.
2924 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2925 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2926 MVT BaseVT = MaskVT.getVectorElementType();
2927 SmallVector<SDValue, 8> MaskVec;
2928 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2929 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2930 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2932 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2935 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2936 /// of specified width.
2937 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2938 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2939 MVT BaseVT = MaskVT.getVectorElementType();
2940 unsigned Half = NumElems/2;
2941 SmallVector<SDValue, 8> MaskVec;
2942 for (unsigned i = 0; i != Half; ++i) {
2943 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2944 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2946 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2949 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2950 /// element #0 of a vector with the specified index, leaving the rest of the
2951 /// elements in place.
2952 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2953 SelectionDAG &DAG) {
2954 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2955 MVT BaseVT = MaskVT.getVectorElementType();
2956 SmallVector<SDValue, 8> MaskVec;
2957 // Element #0 of the result gets the elt we are replacing.
2958 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2959 for (unsigned i = 1; i != NumElems; ++i)
2960 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2961 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2964 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2965 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2966 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2967 MVT VT = Op.getValueType();
2970 SDValue V1 = Op.getOperand(0);
2971 SDValue Mask = Op.getOperand(2);
2972 unsigned NumElems = Mask.getNumOperands();
2973 // Special handling of v4f32 -> v4i32.
2974 if (VT != MVT::v4f32) {
2975 Mask = getUnpacklMask(NumElems, DAG);
2976 while (NumElems > 4) {
2977 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2980 Mask = getZeroVector(MVT::v4i32, true, DAG);
2983 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2984 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2985 DAG.getNode(ISD::UNDEF, PVT), Mask);
2986 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2989 /// isVectorLoad - Returns true if the node is a vector load, a scalar
2990 /// load that's promoted to vector, or a load bitcasted.
2991 static bool isVectorLoad(SDValue Op) {
2992 assert(Op.getValueType().isVector() && "Expected a vector type");
2993 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
2994 Op.getOpcode() == ISD::BIT_CONVERT) {
2995 return isa<LoadSDNode>(Op.getOperand(0));
2997 return isa<LoadSDNode>(Op);
3001 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3003 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3004 SelectionDAG &DAG, bool HasSSE3) {
3005 // If we have sse3 and shuffle has more than one use or input is a load, then
3006 // use movddup. Otherwise, use movlhps.
3007 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3008 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3009 MVT VT = Op.getValueType();
3012 unsigned NumElems = PVT.getVectorNumElements();
3013 if (NumElems == 2) {
3014 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3015 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3017 assert(NumElems == 4);
3018 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3019 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3020 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3023 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3024 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3025 DAG.getNode(ISD::UNDEF, PVT), Mask);
3026 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3029 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3030 /// vector of zero or undef vector. This produces a shuffle where the low
3031 /// element of V2 is swizzled into the zero/undef vector, landing at element
3032 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3033 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3034 bool isZero, bool HasSSE2,
3035 SelectionDAG &DAG) {
3036 MVT VT = V2.getValueType();
3038 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3039 unsigned NumElems = V2.getValueType().getVectorNumElements();
3040 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3041 MVT EVT = MaskVT.getVectorElementType();
3042 SmallVector<SDValue, 16> MaskVec;
3043 for (unsigned i = 0; i != NumElems; ++i)
3044 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3045 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3047 MaskVec.push_back(DAG.getConstant(i, EVT));
3048 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3049 &MaskVec[0], MaskVec.size());
3050 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3053 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3054 /// a shuffle that is zero.
3056 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3057 unsigned NumElems, bool Low,
3058 SelectionDAG &DAG) {
3059 unsigned NumZeros = 0;
3060 for (unsigned i = 0; i < NumElems; ++i) {
3061 unsigned Index = Low ? i : NumElems-i-1;
3062 SDValue Idx = Mask.getOperand(Index);
3063 if (Idx.getOpcode() == ISD::UNDEF) {
3067 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3068 if (Elt.getNode() && isZeroNode(Elt))
3076 /// isVectorShift - Returns true if the shuffle can be implemented as a
3077 /// logical left or right shift of a vector.
3078 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3079 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3080 unsigned NumElems = Mask.getNumOperands();
3083 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3086 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3091 bool SeenV1 = false;
3092 bool SeenV2 = false;
3093 for (unsigned i = NumZeros; i < NumElems; ++i) {
3094 unsigned Val = isLeft ? (i - NumZeros) : i;
3095 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3096 if (Idx.getOpcode() == ISD::UNDEF)
3098 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3099 if (Index < NumElems)
3108 if (SeenV1 && SeenV2)
3111 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3117 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3119 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3120 unsigned NumNonZero, unsigned NumZero,
3121 SelectionDAG &DAG, TargetLowering &TLI) {
3127 for (unsigned i = 0; i < 16; ++i) {
3128 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3129 if (ThisIsNonZero && First) {
3131 V = getZeroVector(MVT::v8i16, true, DAG);
3133 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3138 SDValue ThisElt(0, 0), LastElt(0, 0);
3139 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3140 if (LastIsNonZero) {
3141 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3143 if (ThisIsNonZero) {
3144 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3145 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3146 ThisElt, DAG.getConstant(8, MVT::i8));
3148 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3152 if (ThisElt.getNode())
3153 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3154 DAG.getIntPtrConstant(i/2));
3158 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3161 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3163 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3164 unsigned NumNonZero, unsigned NumZero,
3165 SelectionDAG &DAG, TargetLowering &TLI) {
3171 for (unsigned i = 0; i < 8; ++i) {
3172 bool isNonZero = (NonZeros & (1 << i)) != 0;
3176 V = getZeroVector(MVT::v8i16, true, DAG);
3178 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3181 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3182 DAG.getIntPtrConstant(i));
3189 /// getVShift - Return a vector logical shift node.
3191 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3192 unsigned NumBits, SelectionDAG &DAG,
3193 const TargetLowering &TLI) {
3194 bool isMMX = VT.getSizeInBits() == 64;
3195 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3196 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3197 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3198 return DAG.getNode(ISD::BIT_CONVERT, VT,
3199 DAG.getNode(Opc, ShVT, SrcOp,
3200 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3204 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3205 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3206 if (ISD::isBuildVectorAllZeros(Op.getNode())
3207 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3208 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3209 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3210 // eliminated on x86-32 hosts.
3211 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3214 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3215 return getOnesVector(Op.getValueType(), DAG);
3216 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3219 MVT VT = Op.getValueType();
3220 MVT EVT = VT.getVectorElementType();
3221 unsigned EVTBits = EVT.getSizeInBits();
3223 unsigned NumElems = Op.getNumOperands();
3224 unsigned NumZero = 0;
3225 unsigned NumNonZero = 0;
3226 unsigned NonZeros = 0;
3227 bool IsAllConstants = true;
3228 SmallSet<SDValue, 8> Values;
3229 for (unsigned i = 0; i < NumElems; ++i) {
3230 SDValue Elt = Op.getOperand(i);
3231 if (Elt.getOpcode() == ISD::UNDEF)
3234 if (Elt.getOpcode() != ISD::Constant &&
3235 Elt.getOpcode() != ISD::ConstantFP)
3236 IsAllConstants = false;
3237 if (isZeroNode(Elt))
3240 NonZeros |= (1 << i);
3245 if (NumNonZero == 0) {
3246 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3247 return DAG.getNode(ISD::UNDEF, VT);
3250 // Special case for single non-zero, non-undef, element.
3251 if (NumNonZero == 1 && NumElems <= 4) {
3252 unsigned Idx = CountTrailingZeros_32(NonZeros);
3253 SDValue Item = Op.getOperand(Idx);
3255 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3256 // the value are obviously zero, truncate the value to i32 and do the
3257 // insertion that way. Only do this if the value is non-constant or if the
3258 // value is a constant being inserted into element 0. It is cheaper to do
3259 // a constant pool load than it is to do a movd + shuffle.
3260 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3261 (!IsAllConstants || Idx == 0)) {
3262 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3263 // Handle MMX and SSE both.
3264 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3265 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3267 // Truncate the value (which may itself be a constant) to i32, and
3268 // convert it to a vector with movd (S2V+shuffle to zero extend).
3269 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3270 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3271 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3272 Subtarget->hasSSE2(), DAG);
3274 // Now we have our 32-bit value zero extended in the low element of
3275 // a vector. If Idx != 0, swizzle it into place.
3278 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3279 getSwapEltZeroMask(VecElts, Idx, DAG)
3281 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3283 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3287 // If we have a constant or non-constant insertion into the low element of
3288 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3289 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3290 // depending on what the source datatype is. Because we can only get here
3291 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3293 // Don't do this for i64 values on x86-32.
3294 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3295 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3296 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3297 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3298 Subtarget->hasSSE2(), DAG);
3301 // Is it a vector logical left shift?
3302 if (NumElems == 2 && Idx == 1 &&
3303 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3304 unsigned NumBits = VT.getSizeInBits();
3305 return getVShift(true, VT,
3306 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3307 NumBits/2, DAG, *this);
3310 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3313 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3314 // is a non-constant being inserted into an element other than the low one,
3315 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3316 // movd/movss) to move this into the low element, then shuffle it into
3318 if (EVTBits == 32) {
3319 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3321 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3322 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3323 Subtarget->hasSSE2(), DAG);
3324 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3325 MVT MaskEVT = MaskVT.getVectorElementType();
3326 SmallVector<SDValue, 8> MaskVec;
3327 for (unsigned i = 0; i < NumElems; i++)
3328 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3329 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3330 &MaskVec[0], MaskVec.size());
3331 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3332 DAG.getNode(ISD::UNDEF, VT), Mask);
3336 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3337 if (Values.size() == 1)
3340 // A vector full of immediates; various special cases are already
3341 // handled, so this is best done with a single constant-pool load.
3345 // Let legalizer expand 2-wide build_vectors.
3346 if (EVTBits == 64) {
3347 if (NumNonZero == 1) {
3348 // One half is zero or undef.
3349 unsigned Idx = CountTrailingZeros_32(NonZeros);
3350 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3351 Op.getOperand(Idx));
3352 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3353 Subtarget->hasSSE2(), DAG);
3358 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3359 if (EVTBits == 8 && NumElems == 16) {
3360 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3362 if (V.getNode()) return V;
3365 if (EVTBits == 16 && NumElems == 8) {
3366 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3368 if (V.getNode()) return V;
3371 // If element VT is == 32 bits, turn it into a number of shuffles.
3372 SmallVector<SDValue, 8> V;
3374 if (NumElems == 4 && NumZero > 0) {
3375 for (unsigned i = 0; i < 4; ++i) {
3376 bool isZero = !(NonZeros & (1 << i));
3378 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3380 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3383 for (unsigned i = 0; i < 2; ++i) {
3384 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3387 V[i] = V[i*2]; // Must be a zero vector.
3390 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3391 getMOVLMask(NumElems, DAG));
3394 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3395 getMOVLMask(NumElems, DAG));
3398 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3399 getUnpacklMask(NumElems, DAG));
3404 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3405 MVT EVT = MaskVT.getVectorElementType();
3406 SmallVector<SDValue, 8> MaskVec;
3407 bool Reverse = (NonZeros & 0x3) == 2;
3408 for (unsigned i = 0; i < 2; ++i)
3410 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3412 MaskVec.push_back(DAG.getConstant(i, EVT));
3413 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3414 for (unsigned i = 0; i < 2; ++i)
3416 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3418 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3419 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3420 &MaskVec[0], MaskVec.size());
3421 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3424 if (Values.size() > 2) {
3425 // Expand into a number of unpckl*.
3427 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3428 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3429 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3430 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3431 for (unsigned i = 0; i < NumElems; ++i)
3432 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3434 while (NumElems != 0) {
3435 for (unsigned i = 0; i < NumElems; ++i)
3436 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3447 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3448 SDValue PermMask, SelectionDAG &DAG,
3449 TargetLowering &TLI) {
3451 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3452 MVT MaskEVT = MaskVT.getVectorElementType();
3453 MVT PtrVT = TLI.getPointerTy();
3454 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3455 PermMask.getNode()->op_end());
3457 // First record which half of which vector the low elements come from.
3458 SmallVector<unsigned, 4> LowQuad(4);
3459 for (unsigned i = 0; i < 4; ++i) {
3460 SDValue Elt = MaskElts[i];
3461 if (Elt.getOpcode() == ISD::UNDEF)
3463 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3464 int QuadIdx = EltIdx / 4;
3468 int BestLowQuad = -1;
3469 unsigned MaxQuad = 1;
3470 for (unsigned i = 0; i < 4; ++i) {
3471 if (LowQuad[i] > MaxQuad) {
3473 MaxQuad = LowQuad[i];
3477 // Record which half of which vector the high elements come from.
3478 SmallVector<unsigned, 4> HighQuad(4);
3479 for (unsigned i = 4; i < 8; ++i) {
3480 SDValue Elt = MaskElts[i];
3481 if (Elt.getOpcode() == ISD::UNDEF)
3483 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3484 int QuadIdx = EltIdx / 4;
3485 ++HighQuad[QuadIdx];
3488 int BestHighQuad = -1;
3490 for (unsigned i = 0; i < 4; ++i) {
3491 if (HighQuad[i] > MaxQuad) {
3493 MaxQuad = HighQuad[i];
3497 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3498 if (BestLowQuad != -1 || BestHighQuad != -1) {
3499 // First sort the 4 chunks in order using shufpd.
3500 SmallVector<SDValue, 8> MaskVec;
3502 if (BestLowQuad != -1)
3503 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3505 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3507 if (BestHighQuad != -1)
3508 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3510 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3512 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3513 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3514 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3515 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3516 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3518 // Now sort high and low parts separately.
3519 BitVector InOrder(8);
3520 if (BestLowQuad != -1) {
3521 // Sort lower half in order using PSHUFLW.
3523 bool AnyOutOrder = false;
3525 for (unsigned i = 0; i != 4; ++i) {
3526 SDValue Elt = MaskElts[i];
3527 if (Elt.getOpcode() == ISD::UNDEF) {
3528 MaskVec.push_back(Elt);
3531 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3535 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3537 // If this element is in the right place after this shuffle, then
3539 if ((int)(EltIdx / 4) == BestLowQuad)
3544 for (unsigned i = 4; i != 8; ++i)
3545 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3546 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3547 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3551 if (BestHighQuad != -1) {
3552 // Sort high half in order using PSHUFHW if possible.
3555 for (unsigned i = 0; i != 4; ++i)
3556 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3558 bool AnyOutOrder = false;
3559 for (unsigned i = 4; i != 8; ++i) {
3560 SDValue Elt = MaskElts[i];
3561 if (Elt.getOpcode() == ISD::UNDEF) {
3562 MaskVec.push_back(Elt);
3565 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3569 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3571 // If this element is in the right place after this shuffle, then
3573 if ((int)(EltIdx / 4) == BestHighQuad)
3579 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3580 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3584 // The other elements are put in the right place using pextrw and pinsrw.
3585 for (unsigned i = 0; i != 8; ++i) {
3588 SDValue Elt = MaskElts[i];
3589 if (Elt.getOpcode() == ISD::UNDEF)
3591 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3592 SDValue ExtOp = (EltIdx < 8)
3593 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3594 DAG.getConstant(EltIdx, PtrVT))
3595 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3596 DAG.getConstant(EltIdx - 8, PtrVT));
3597 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3598 DAG.getConstant(i, PtrVT));
3604 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3605 // few as possible. First, let's find out how many elements are already in the
3607 unsigned V1InOrder = 0;
3608 unsigned V1FromV1 = 0;
3609 unsigned V2InOrder = 0;
3610 unsigned V2FromV2 = 0;
3611 SmallVector<SDValue, 8> V1Elts;
3612 SmallVector<SDValue, 8> V2Elts;
3613 for (unsigned i = 0; i < 8; ++i) {
3614 SDValue Elt = MaskElts[i];
3615 if (Elt.getOpcode() == ISD::UNDEF) {
3616 V1Elts.push_back(Elt);
3617 V2Elts.push_back(Elt);
3622 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3624 V1Elts.push_back(Elt);
3625 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3627 } else if (EltIdx == i+8) {
3628 V1Elts.push_back(Elt);
3629 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3631 } else if (EltIdx < 8) {
3632 V1Elts.push_back(Elt);
3635 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3640 if (V2InOrder > V1InOrder) {
3641 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3643 std::swap(V1Elts, V2Elts);
3644 std::swap(V1FromV1, V2FromV2);
3647 if ((V1FromV1 + V1InOrder) != 8) {
3648 // Some elements are from V2.
3650 // If there are elements that are from V1 but out of place,
3651 // then first sort them in place
3652 SmallVector<SDValue, 8> MaskVec;
3653 for (unsigned i = 0; i < 8; ++i) {
3654 SDValue Elt = V1Elts[i];
3655 if (Elt.getOpcode() == ISD::UNDEF) {
3656 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3659 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3661 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3663 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3665 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3666 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3670 for (unsigned i = 0; i < 8; ++i) {
3671 SDValue Elt = V1Elts[i];
3672 if (Elt.getOpcode() == ISD::UNDEF)
3674 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3677 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3678 DAG.getConstant(EltIdx - 8, PtrVT));
3679 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3680 DAG.getConstant(i, PtrVT));
3684 // All elements are from V1.
3686 for (unsigned i = 0; i < 8; ++i) {
3687 SDValue Elt = V1Elts[i];
3688 if (Elt.getOpcode() == ISD::UNDEF)
3690 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3691 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3692 DAG.getConstant(EltIdx, PtrVT));
3693 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3694 DAG.getConstant(i, PtrVT));
3700 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3701 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3702 /// done when every pair / quad of shuffle mask elements point to elements in
3703 /// the right sequence. e.g.
3704 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3706 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3708 SDValue PermMask, SelectionDAG &DAG,
3709 TargetLowering &TLI) {
3710 unsigned NumElems = PermMask.getNumOperands();
3711 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3712 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3713 MVT MaskEltVT = MaskVT.getVectorElementType();
3715 switch (VT.getSimpleVT()) {
3716 default: assert(false && "Unexpected!");
3717 case MVT::v4f32: NewVT = MVT::v2f64; break;
3718 case MVT::v4i32: NewVT = MVT::v2i64; break;
3719 case MVT::v8i16: NewVT = MVT::v4i32; break;
3720 case MVT::v16i8: NewVT = MVT::v4i32; break;
3723 if (NewWidth == 2) {
3729 unsigned Scale = NumElems / NewWidth;
3730 SmallVector<SDValue, 8> MaskVec;
3731 for (unsigned i = 0; i < NumElems; i += Scale) {
3732 unsigned StartIdx = ~0U;
3733 for (unsigned j = 0; j < Scale; ++j) {
3734 SDValue Elt = PermMask.getOperand(i+j);
3735 if (Elt.getOpcode() == ISD::UNDEF)
3737 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3738 if (StartIdx == ~0U)
3739 StartIdx = EltIdx - (EltIdx % Scale);
3740 if (EltIdx != StartIdx + j)
3743 if (StartIdx == ~0U)
3744 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3746 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3749 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3750 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3751 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3752 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3753 &MaskVec[0], MaskVec.size()));
3756 /// getVZextMovL - Return a zero-extending vector move low node.
3758 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3759 SDValue SrcOp, SelectionDAG &DAG,
3760 const X86Subtarget *Subtarget) {
3761 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3762 LoadSDNode *LD = NULL;
3763 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3764 LD = dyn_cast<LoadSDNode>(SrcOp);
3766 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3768 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3769 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3770 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3771 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3772 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3774 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3775 return DAG.getNode(ISD::BIT_CONVERT, VT,
3776 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3777 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3784 return DAG.getNode(ISD::BIT_CONVERT, VT,
3785 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3786 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3789 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3792 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3793 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3794 MVT MaskVT = PermMask.getValueType();
3795 MVT MaskEVT = MaskVT.getVectorElementType();
3796 SmallVector<std::pair<int, int>, 8> Locs;
3798 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3801 for (unsigned i = 0; i != 4; ++i) {
3802 SDValue Elt = PermMask.getOperand(i);
3803 if (Elt.getOpcode() == ISD::UNDEF) {
3804 Locs[i] = std::make_pair(-1, -1);
3806 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3807 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3809 Locs[i] = std::make_pair(0, NumLo);
3813 Locs[i] = std::make_pair(1, NumHi);
3815 Mask1[2+NumHi] = Elt;
3821 if (NumLo <= 2 && NumHi <= 2) {
3822 // If no more than two elements come from either vector. This can be
3823 // implemented with two shuffles. First shuffle gather the elements.
3824 // The second shuffle, which takes the first shuffle as both of its
3825 // vector operands, put the elements into the right order.
3826 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3827 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3828 &Mask1[0], Mask1.size()));
3830 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3831 for (unsigned i = 0; i != 4; ++i) {
3832 if (Locs[i].first == -1)
3835 unsigned Idx = (i < 2) ? 0 : 4;
3836 Idx += Locs[i].first * 2 + Locs[i].second;
3837 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3841 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3842 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3843 &Mask2[0], Mask2.size()));
3844 } else if (NumLo == 3 || NumHi == 3) {
3845 // Otherwise, we must have three elements from one vector, call it X, and
3846 // one element from the other, call it Y. First, use a shufps to build an
3847 // intermediate vector with the one element from Y and the element from X
3848 // that will be in the same half in the final destination (the indexes don't
3849 // matter). Then, use a shufps to build the final vector, taking the half
3850 // containing the element from Y from the intermediate, and the other half
3853 // Normalize it so the 3 elements come from V1.
3854 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3858 // Find the element from V2.
3860 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3861 SDValue Elt = PermMask.getOperand(HiIndex);
3862 if (Elt.getOpcode() == ISD::UNDEF)
3864 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3869 Mask1[0] = PermMask.getOperand(HiIndex);
3870 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3871 Mask1[2] = PermMask.getOperand(HiIndex^1);
3872 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3873 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3874 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3877 Mask1[0] = PermMask.getOperand(0);
3878 Mask1[1] = PermMask.getOperand(1);
3879 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3880 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3881 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3882 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3884 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3885 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3886 Mask1[2] = PermMask.getOperand(2);
3887 Mask1[3] = PermMask.getOperand(3);
3888 if (Mask1[2].getOpcode() != ISD::UNDEF)
3890 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3892 if (Mask1[3].getOpcode() != ISD::UNDEF)
3894 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3896 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3897 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3901 // Break it into (shuffle shuffle_hi, shuffle_lo).
3903 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3904 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3905 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3906 unsigned MaskIdx = 0;
3909 for (unsigned i = 0; i != 4; ++i) {
3916 SDValue Elt = PermMask.getOperand(i);
3917 if (Elt.getOpcode() == ISD::UNDEF) {
3918 Locs[i] = std::make_pair(-1, -1);
3919 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3920 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3921 (*MaskPtr)[LoIdx] = Elt;
3924 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3925 (*MaskPtr)[HiIdx] = Elt;
3930 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3931 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3932 &LoMask[0], LoMask.size()));
3933 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3934 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3935 &HiMask[0], HiMask.size()));
3936 SmallVector<SDValue, 8> MaskOps;
3937 for (unsigned i = 0; i != 4; ++i) {
3938 if (Locs[i].first == -1) {
3939 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3941 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3942 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3945 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3946 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3947 &MaskOps[0], MaskOps.size()));
3951 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3952 SDValue V1 = Op.getOperand(0);
3953 SDValue V2 = Op.getOperand(1);
3954 SDValue PermMask = Op.getOperand(2);
3955 MVT VT = Op.getValueType();
3956 unsigned NumElems = PermMask.getNumOperands();
3957 bool isMMX = VT.getSizeInBits() == 64;
3958 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3959 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3960 bool V1IsSplat = false;
3961 bool V2IsSplat = false;
3963 if (isUndefShuffle(Op.getNode()))
3964 return DAG.getNode(ISD::UNDEF, VT);
3966 if (isZeroShuffle(Op.getNode()))
3967 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3969 if (isIdentityMask(PermMask.getNode()))
3971 else if (isIdentityMask(PermMask.getNode(), true))
3974 // Canonicalize movddup shuffles.
3975 if (V2IsUndef && Subtarget->hasSSE2() &&
3976 VT.getSizeInBits() == 128 &&
3977 X86::isMOVDDUPMask(PermMask.getNode()))
3978 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
3980 if (isSplatMask(PermMask.getNode())) {
3981 if (isMMX || NumElems < 4) return Op;
3982 // Promote it to a v4{if}32 splat.
3983 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3986 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3988 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3989 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3990 if (NewOp.getNode())
3991 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3992 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3993 // FIXME: Figure out a cleaner way to do this.
3994 // Try to make use of movq to zero out the top part.
3995 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3996 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3998 if (NewOp.getNode()) {
3999 SDValue NewV1 = NewOp.getOperand(0);
4000 SDValue NewV2 = NewOp.getOperand(1);
4001 SDValue NewMask = NewOp.getOperand(2);
4002 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4003 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4004 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4007 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4008 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4010 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4011 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4016 // Check if this can be converted into a logical shift.
4017 bool isLeft = false;
4020 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4021 if (isShift && ShVal.hasOneUse()) {
4022 // If the shifted value has multiple uses, it may be cheaper to use
4023 // v_set0 + movlhps or movhlps, etc.
4024 MVT EVT = VT.getVectorElementType();
4025 ShAmt *= EVT.getSizeInBits();
4026 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4029 if (X86::isMOVLMask(PermMask.getNode())) {
4032 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4033 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4038 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4039 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4040 X86::isMOVHLPSMask(PermMask.getNode()) ||
4041 X86::isMOVHPMask(PermMask.getNode()) ||
4042 X86::isMOVLPMask(PermMask.getNode())))
4045 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4046 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4047 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4050 // No better options. Use a vshl / vsrl.
4051 MVT EVT = VT.getVectorElementType();
4052 ShAmt *= EVT.getSizeInBits();
4053 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4056 bool Commuted = false;
4057 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4058 // 1,1,1,1 -> v8i16 though.
4059 V1IsSplat = isSplatVector(V1.getNode());
4060 V2IsSplat = isSplatVector(V2.getNode());
4062 // Canonicalize the splat or undef, if present, to be on the RHS.
4063 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4064 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4065 std::swap(V1IsSplat, V2IsSplat);
4066 std::swap(V1IsUndef, V2IsUndef);
4070 // FIXME: Figure out a cleaner way to do this.
4071 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4072 if (V2IsUndef) return V1;
4073 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4075 // V2 is a splat, so the mask may be malformed. That is, it may point
4076 // to any V2 element. The instruction selectior won't like this. Get
4077 // a corrected mask and commute to form a proper MOVS{S|D}.
4078 SDValue NewMask = getMOVLMask(NumElems, DAG);
4079 if (NewMask.getNode() != PermMask.getNode())
4080 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4085 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4086 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4087 X86::isUNPCKLMask(PermMask.getNode()) ||
4088 X86::isUNPCKHMask(PermMask.getNode()))
4092 // Normalize mask so all entries that point to V2 points to its first
4093 // element then try to match unpck{h|l} again. If match, return a
4094 // new vector_shuffle with the corrected mask.
4095 SDValue NewMask = NormalizeMask(PermMask, DAG);
4096 if (NewMask.getNode() != PermMask.getNode()) {
4097 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4098 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4099 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4100 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4101 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4102 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4107 // Normalize the node to match x86 shuffle ops if needed
4108 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4109 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4112 // Commute is back and try unpck* again.
4113 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4114 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4115 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4116 X86::isUNPCKLMask(PermMask.getNode()) ||
4117 X86::isUNPCKHMask(PermMask.getNode()))
4121 // Try PSHUF* first, then SHUFP*.
4122 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4123 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4124 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4125 if (V2.getOpcode() != ISD::UNDEF)
4126 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4127 DAG.getNode(ISD::UNDEF, VT), PermMask);
4132 if (Subtarget->hasSSE2() &&
4133 (X86::isPSHUFDMask(PermMask.getNode()) ||
4134 X86::isPSHUFHWMask(PermMask.getNode()) ||
4135 X86::isPSHUFLWMask(PermMask.getNode()))) {
4137 if (VT == MVT::v4f32) {
4139 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4140 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4141 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4142 } else if (V2.getOpcode() != ISD::UNDEF)
4143 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4144 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4146 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4150 // Binary or unary shufps.
4151 if (X86::isSHUFPMask(PermMask.getNode()) ||
4152 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4156 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4157 if (VT == MVT::v8i16) {
4158 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4159 if (NewOp.getNode())
4163 // Handle all 4 wide cases with a number of shuffles except for MMX.
4164 if (NumElems == 4 && !isMMX)
4165 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4171 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4172 SelectionDAG &DAG) {
4173 MVT VT = Op.getValueType();
4174 if (VT.getSizeInBits() == 8) {
4175 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4176 Op.getOperand(0), Op.getOperand(1));
4177 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4178 DAG.getValueType(VT));
4179 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4180 } else if (VT.getSizeInBits() == 16) {
4181 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4182 Op.getOperand(0), Op.getOperand(1));
4183 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4184 DAG.getValueType(VT));
4185 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4186 } else if (VT == MVT::f32) {
4187 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4188 // the result back to FR32 register. It's only worth matching if the
4189 // result has a single use which is a store or a bitcast to i32.
4190 if (!Op.hasOneUse())
4192 SDNode *User = *Op.getNode()->use_begin();
4193 if (User->getOpcode() != ISD::STORE &&
4194 (User->getOpcode() != ISD::BIT_CONVERT ||
4195 User->getValueType(0) != MVT::i32))
4197 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4198 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4200 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4207 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4208 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4211 if (Subtarget->hasSSE41()) {
4212 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4217 MVT VT = Op.getValueType();
4218 // TODO: handle v16i8.
4219 if (VT.getSizeInBits() == 16) {
4220 SDValue Vec = Op.getOperand(0);
4221 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4223 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4224 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4225 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4227 // Transform it so it match pextrw which produces a 32-bit result.
4228 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4229 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4230 Op.getOperand(0), Op.getOperand(1));
4231 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4232 DAG.getValueType(VT));
4233 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4234 } else if (VT.getSizeInBits() == 32) {
4235 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4238 // SHUFPS the element to the lowest double word, then movss.
4239 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4240 SmallVector<SDValue, 8> IdxVec;
4242 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4244 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4246 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4248 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4249 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4250 &IdxVec[0], IdxVec.size());
4251 SDValue Vec = Op.getOperand(0);
4252 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4253 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4254 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4255 DAG.getIntPtrConstant(0));
4256 } else if (VT.getSizeInBits() == 64) {
4257 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4258 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4259 // to match extract_elt for f64.
4260 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4264 // UNPCKHPD the element to the lowest double word, then movsd.
4265 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4266 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4267 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4268 SmallVector<SDValue, 8> IdxVec;
4269 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4271 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4272 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4273 &IdxVec[0], IdxVec.size());
4274 SDValue Vec = Op.getOperand(0);
4275 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4276 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4277 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4278 DAG.getIntPtrConstant(0));
4285 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4286 MVT VT = Op.getValueType();
4287 MVT EVT = VT.getVectorElementType();
4289 SDValue N0 = Op.getOperand(0);
4290 SDValue N1 = Op.getOperand(1);
4291 SDValue N2 = Op.getOperand(2);
4293 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4294 isa<ConstantSDNode>(N2)) {
4295 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4297 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4299 if (N1.getValueType() != MVT::i32)
4300 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4301 if (N2.getValueType() != MVT::i32)
4302 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4303 return DAG.getNode(Opc, VT, N0, N1, N2);
4304 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4305 // Bits [7:6] of the constant are the source select. This will always be
4306 // zero here. The DAG Combiner may combine an extract_elt index into these
4307 // bits. For example (insert (extract, 3), 2) could be matched by putting
4308 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4309 // Bits [5:4] of the constant are the destination select. This is the
4310 // value of the incoming immediate.
4311 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4312 // combine either bitwise AND or insert of float 0.0 to set these bits.
4313 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4314 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4320 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4321 MVT VT = Op.getValueType();
4322 MVT EVT = VT.getVectorElementType();
4324 if (Subtarget->hasSSE41())
4325 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4330 SDValue N0 = Op.getOperand(0);
4331 SDValue N1 = Op.getOperand(1);
4332 SDValue N2 = Op.getOperand(2);
4334 if (EVT.getSizeInBits() == 16) {
4335 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4336 // as its second argument.
4337 if (N1.getValueType() != MVT::i32)
4338 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4339 if (N2.getValueType() != MVT::i32)
4340 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4341 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4347 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4348 if (Op.getValueType() == MVT::v2f32)
4349 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4350 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4351 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4352 Op.getOperand(0))));
4354 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4355 MVT VT = MVT::v2i32;
4356 switch (Op.getValueType().getSimpleVT()) {
4363 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4364 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4367 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4368 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4369 // one of the above mentioned nodes. It has to be wrapped because otherwise
4370 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4371 // be used to form addressing mode. These wrapped nodes will be selected
4374 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4375 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4376 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4378 CP->getAlignment());
4379 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4380 // With PIC, the address is actually $g + Offset.
4381 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4382 !Subtarget->isPICStyleRIPRel()) {
4383 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4384 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4392 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4394 SelectionDAG &DAG) const {
4395 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4396 bool ExtraLoadRequired =
4397 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4399 // Create the TargetGlobalAddress node, folding in the constant
4400 // offset if it is legal.
4402 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4403 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4406 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4407 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4409 // With PIC, the address is actually $g + Offset.
4410 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4411 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4412 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4416 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4417 // load the value at address GV, not the value of GV itself. This means that
4418 // the GlobalAddress must be in the base or index register of the address, not
4419 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4420 // The same applies for external symbols during PIC codegen
4421 if (ExtraLoadRequired)
4422 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4423 PseudoSourceValue::getGOT(), 0);
4425 // If there was a non-zero offset that we didn't fold, create an explicit
4428 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4429 DAG.getConstant(Offset, getPointerTy()));
4435 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4436 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4437 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4438 return LowerGlobalAddress(GV, Offset, DAG);
4441 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4443 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4446 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4447 DAG.getNode(X86ISD::GlobalBaseReg,
4449 InFlag = Chain.getValue(1);
4451 // emit leal symbol@TLSGD(,%ebx,1), %eax
4452 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4453 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4454 GA->getValueType(0),
4456 SDValue Ops[] = { Chain, TGA, InFlag };
4457 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4458 InFlag = Result.getValue(2);
4459 Chain = Result.getValue(1);
4461 // call ___tls_get_addr. This function receives its argument in
4462 // the register EAX.
4463 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4464 InFlag = Chain.getValue(1);
4466 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4467 SDValue Ops1[] = { Chain,
4468 DAG.getTargetExternalSymbol("___tls_get_addr",
4470 DAG.getRegister(X86::EAX, PtrVT),
4471 DAG.getRegister(X86::EBX, PtrVT),
4473 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4474 InFlag = Chain.getValue(1);
4476 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4479 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4481 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4483 SDValue InFlag, Chain;
4485 // emit leaq symbol@TLSGD(%rip), %rdi
4486 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4487 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4488 GA->getValueType(0),
4490 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4491 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4492 Chain = Result.getValue(1);
4493 InFlag = Result.getValue(2);
4495 // call __tls_get_addr. This function receives its argument in
4496 // the register RDI.
4497 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4498 InFlag = Chain.getValue(1);
4500 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4501 SDValue Ops1[] = { Chain,
4502 DAG.getTargetExternalSymbol("__tls_get_addr",
4504 DAG.getRegister(X86::RDI, PtrVT),
4506 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4507 InFlag = Chain.getValue(1);
4509 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4512 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4513 // "local exec" model.
4514 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4516 // Get the Thread Pointer
4517 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4518 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4520 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4521 GA->getValueType(0),
4523 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4525 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4526 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4527 PseudoSourceValue::getGOT(), 0);
4529 // The address of the thread local variable is the add of the thread
4530 // pointer with the offset of the variable.
4531 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4535 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4536 // TODO: implement the "local dynamic" model
4537 // TODO: implement the "initial exec"model for pic executables
4538 assert(Subtarget->isTargetELF() &&
4539 "TLS not implemented for non-ELF targets");
4540 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4541 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4542 // otherwise use the "Local Exec"TLS Model
4543 if (Subtarget->is64Bit()) {
4544 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4546 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4547 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4549 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4554 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4555 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4556 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4557 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4558 // With PIC, the address is actually $g + Offset.
4559 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4560 !Subtarget->isPICStyleRIPRel()) {
4561 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4562 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4569 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4570 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4571 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4572 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4573 // With PIC, the address is actually $g + Offset.
4574 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4575 !Subtarget->isPICStyleRIPRel()) {
4576 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4577 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4584 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4585 /// take a 2 x i32 value to shift plus a shift amount.
4586 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4587 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4588 MVT VT = Op.getValueType();
4589 unsigned VTBits = VT.getSizeInBits();
4590 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4591 SDValue ShOpLo = Op.getOperand(0);
4592 SDValue ShOpHi = Op.getOperand(1);
4593 SDValue ShAmt = Op.getOperand(2);
4594 SDValue Tmp1 = isSRA ?
4595 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4596 DAG.getConstant(0, VT);
4599 if (Op.getOpcode() == ISD::SHL_PARTS) {
4600 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4601 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4603 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4604 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4607 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4608 DAG.getConstant(VTBits, MVT::i8));
4609 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4610 AndNode, DAG.getConstant(0, MVT::i8));
4613 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4614 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4615 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4617 if (Op.getOpcode() == ISD::SHL_PARTS) {
4618 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4619 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4621 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4622 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4625 SDValue Ops[2] = { Lo, Hi };
4626 return DAG.getMergeValues(Ops, 2);
4629 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4630 MVT SrcVT = Op.getOperand(0).getValueType();
4631 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4632 "Unknown SINT_TO_FP to lower!");
4634 // These are really Legal; caller falls through into that case.
4635 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4637 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4638 Subtarget->is64Bit())
4641 unsigned Size = SrcVT.getSizeInBits()/8;
4642 MachineFunction &MF = DAG.getMachineFunction();
4643 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4644 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4645 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4647 PseudoSourceValue::getFixedStack(SSFI), 0);
4651 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4653 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4655 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4656 SmallVector<SDValue, 8> Ops;
4657 Ops.push_back(Chain);
4658 Ops.push_back(StackSlot);
4659 Ops.push_back(DAG.getValueType(SrcVT));
4660 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4661 Tys, &Ops[0], Ops.size());
4664 Chain = Result.getValue(1);
4665 SDValue InFlag = Result.getValue(2);
4667 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4668 // shouldn't be necessary except that RFP cannot be live across
4669 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4670 MachineFunction &MF = DAG.getMachineFunction();
4671 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4672 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4673 Tys = DAG.getVTList(MVT::Other);
4674 SmallVector<SDValue, 8> Ops;
4675 Ops.push_back(Chain);
4676 Ops.push_back(Result);
4677 Ops.push_back(StackSlot);
4678 Ops.push_back(DAG.getValueType(Op.getValueType()));
4679 Ops.push_back(InFlag);
4680 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4681 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4682 PseudoSourceValue::getFixedStack(SSFI), 0);
4688 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4689 MVT SrcVT = Op.getOperand(0).getValueType();
4690 assert(SrcVT.getSimpleVT() == MVT::i64 && "Unknown UINT_TO_FP to lower!");
4692 // We only handle SSE2 f64 target here; caller can handle the rest.
4693 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4696 // This algorithm is not obvious. Here it is in C code, more or less:
4698 double uint64_to_double( uint32_t hi, uint32_t lo )
4700 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4701 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4703 // copy ints to xmm registers
4704 __m128i xh = _mm_cvtsi32_si128( hi );
4705 __m128i xl = _mm_cvtsi32_si128( lo );
4707 // combine into low half of a single xmm register
4708 __m128i x = _mm_unpacklo_epi32( xh, xl );
4712 // merge in appropriate exponents to give the integer bits the
4714 x = _mm_unpacklo_epi32( x, exp );
4716 // subtract away the biases to deal with the IEEE-754 double precision
4718 d = _mm_sub_pd( (__m128d) x, bias );
4720 // All conversions up to here are exact. The correctly rounded result is
4721 // calculated using the
4722 // current rounding mode using the following horizontal add.
4723 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4724 _mm_store_sd( &sd, d ); //since we are returning doubles in XMM, this
4725 // store doesn't really need to be here (except maybe to zero the other
4731 // Build some magic constants.
4732 std::vector<Constant*>CV0;
4733 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4734 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4735 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4736 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4737 Constant *C0 = ConstantVector::get(CV0);
4738 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4740 std::vector<Constant*>CV1;
4741 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4742 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4743 Constant *C1 = ConstantVector::get(CV1);
4744 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4746 SmallVector<SDValue, 4> MaskVec;
4747 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4748 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4749 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4750 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4751 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4753 SmallVector<SDValue, 4> MaskVec2;
4754 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4755 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4756 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4759 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4760 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4762 DAG.getIntPtrConstant(1)));
4763 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4764 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4766 DAG.getIntPtrConstant(0)));
4767 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4768 XR1, XR2, UnpcklMask);
4769 SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4770 PseudoSourceValue::getConstantPool(), 0, false, 16);
4771 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4772 Unpck1, CLod0, UnpcklMask);
4773 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4774 SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4775 PseudoSourceValue::getConstantPool(), 0, false, 16);
4776 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4777 // Add the halves; easiest way is to swap them into another reg first.
4778 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4779 Sub, Sub, ShufMask);
4780 SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4781 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4782 DAG.getIntPtrConstant(0));
4785 std::pair<SDValue,SDValue> X86TargetLowering::
4786 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4787 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4788 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4789 "Unknown FP_TO_SINT to lower!");
4791 // These are really Legal.
4792 if (Op.getValueType() == MVT::i32 &&
4793 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4794 return std::make_pair(SDValue(), SDValue());
4795 if (Subtarget->is64Bit() &&
4796 Op.getValueType() == MVT::i64 &&
4797 Op.getOperand(0).getValueType() != MVT::f80)
4798 return std::make_pair(SDValue(), SDValue());
4800 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4802 MachineFunction &MF = DAG.getMachineFunction();
4803 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4804 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4805 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4807 switch (Op.getValueType().getSimpleVT()) {
4808 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4809 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4810 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4811 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4814 SDValue Chain = DAG.getEntryNode();
4815 SDValue Value = Op.getOperand(0);
4816 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4817 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4818 Chain = DAG.getStore(Chain, Value, StackSlot,
4819 PseudoSourceValue::getFixedStack(SSFI), 0);
4820 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4822 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4824 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4825 Chain = Value.getValue(1);
4826 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4827 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4830 // Build the FP_TO_INT*_IN_MEM
4831 SDValue Ops[] = { Chain, Value, StackSlot };
4832 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4834 return std::make_pair(FIST, StackSlot);
4837 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4838 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4839 SDValue FIST = Vals.first, StackSlot = Vals.second;
4840 if (FIST.getNode() == 0) return SDValue();
4843 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4846 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4847 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4848 SDValue FIST = Vals.first, StackSlot = Vals.second;
4849 if (FIST.getNode() == 0) return 0;
4851 MVT VT = N->getValueType(0);
4853 // Return a load from the stack slot.
4854 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4856 // Use MERGE_VALUES to drop the chain result value and get a node with one
4857 // result. This requires turning off getMergeValues simplification, since
4858 // otherwise it will give us Res back.
4859 return DAG.getMergeValues(&Res, 1, false).getNode();
4862 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4863 MVT VT = Op.getValueType();
4866 EltVT = VT.getVectorElementType();
4867 std::vector<Constant*> CV;
4868 if (EltVT == MVT::f64) {
4869 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4873 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4879 Constant *C = ConstantVector::get(CV);
4880 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4881 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4882 PseudoSourceValue::getConstantPool(), 0,
4884 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4887 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4888 MVT VT = Op.getValueType();
4890 unsigned EltNum = 1;
4891 if (VT.isVector()) {
4892 EltVT = VT.getVectorElementType();
4893 EltNum = VT.getVectorNumElements();
4895 std::vector<Constant*> CV;
4896 if (EltVT == MVT::f64) {
4897 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4901 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4907 Constant *C = ConstantVector::get(CV);
4908 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4909 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4910 PseudoSourceValue::getConstantPool(), 0,
4912 if (VT.isVector()) {
4913 return DAG.getNode(ISD::BIT_CONVERT, VT,
4914 DAG.getNode(ISD::XOR, MVT::v2i64,
4915 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4916 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4918 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4922 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4923 SDValue Op0 = Op.getOperand(0);
4924 SDValue Op1 = Op.getOperand(1);
4925 MVT VT = Op.getValueType();
4926 MVT SrcVT = Op1.getValueType();
4928 // If second operand is smaller, extend it first.
4929 if (SrcVT.bitsLT(VT)) {
4930 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4933 // And if it is bigger, shrink it first.
4934 if (SrcVT.bitsGT(VT)) {
4935 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4939 // At this point the operands and the result should have the same
4940 // type, and that won't be f80 since that is not custom lowered.
4942 // First get the sign bit of second operand.
4943 std::vector<Constant*> CV;
4944 if (SrcVT == MVT::f64) {
4945 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4946 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4948 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4949 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4950 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4951 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4953 Constant *C = ConstantVector::get(CV);
4954 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4955 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4956 PseudoSourceValue::getConstantPool(), 0,
4958 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4960 // Shift sign bit right or left if the two operands have different types.
4961 if (SrcVT.bitsGT(VT)) {
4962 // Op0 is MVT::f32, Op1 is MVT::f64.
4963 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4964 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4965 DAG.getConstant(32, MVT::i32));
4966 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4967 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4968 DAG.getIntPtrConstant(0));
4971 // Clear first operand sign bit.
4973 if (VT == MVT::f64) {
4974 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4975 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4977 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4978 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4979 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4980 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4982 C = ConstantVector::get(CV);
4983 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4984 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4985 PseudoSourceValue::getConstantPool(), 0,
4987 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4989 // Or the value with the sign bit.
4990 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4993 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4994 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4996 SDValue Op0 = Op.getOperand(0);
4997 SDValue Op1 = Op.getOperand(1);
4998 SDValue CC = Op.getOperand(2);
4999 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5002 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
5004 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5005 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5006 DAG.getConstant(X86CC, MVT::i8), Cond);
5009 assert(0 && "Illegal SetCC!");
5013 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5015 SDValue Op0 = Op.getOperand(0);
5016 SDValue Op1 = Op.getOperand(1);
5017 SDValue CC = Op.getOperand(2);
5018 MVT VT = Op.getValueType();
5019 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5020 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5024 MVT VT0 = Op0.getValueType();
5025 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5026 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5029 switch (SetCCOpcode) {
5032 case ISD::SETEQ: SSECC = 0; break;
5034 case ISD::SETGT: Swap = true; // Fallthrough
5036 case ISD::SETOLT: SSECC = 1; break;
5038 case ISD::SETGE: Swap = true; // Fallthrough
5040 case ISD::SETOLE: SSECC = 2; break;
5041 case ISD::SETUO: SSECC = 3; break;
5043 case ISD::SETNE: SSECC = 4; break;
5044 case ISD::SETULE: Swap = true;
5045 case ISD::SETUGE: SSECC = 5; break;
5046 case ISD::SETULT: Swap = true;
5047 case ISD::SETUGT: SSECC = 6; break;
5048 case ISD::SETO: SSECC = 7; break;
5051 std::swap(Op0, Op1);
5053 // In the two special cases we can't handle, emit two comparisons.
5055 if (SetCCOpcode == ISD::SETUEQ) {
5057 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5058 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5059 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5061 else if (SetCCOpcode == ISD::SETONE) {
5063 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5064 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5065 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5067 assert(0 && "Illegal FP comparison");
5069 // Handle all other FP comparisons here.
5070 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5073 // We are handling one of the integer comparisons here. Since SSE only has
5074 // GT and EQ comparisons for integer, swapping operands and multiple
5075 // operations may be required for some comparisons.
5076 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5077 bool Swap = false, Invert = false, FlipSigns = false;
5079 switch (VT.getSimpleVT()) {
5081 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5082 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5083 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5084 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5087 switch (SetCCOpcode) {
5089 case ISD::SETNE: Invert = true;
5090 case ISD::SETEQ: Opc = EQOpc; break;
5091 case ISD::SETLT: Swap = true;
5092 case ISD::SETGT: Opc = GTOpc; break;
5093 case ISD::SETGE: Swap = true;
5094 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5095 case ISD::SETULT: Swap = true;
5096 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5097 case ISD::SETUGE: Swap = true;
5098 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5101 std::swap(Op0, Op1);
5103 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5104 // bits of the inputs before performing those operations.
5106 MVT EltVT = VT.getVectorElementType();
5107 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
5108 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5109 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5111 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5112 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5115 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5117 // If the logical-not of the result is required, perform that now.
5119 MVT EltVT = VT.getVectorElementType();
5120 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5121 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5122 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5124 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5129 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5130 bool addTest = true;
5131 SDValue Cond = Op.getOperand(0);
5134 if (Cond.getOpcode() == ISD::SETCC)
5135 Cond = LowerSETCC(Cond, DAG);
5137 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5138 // setting operand in place of the X86ISD::SETCC.
5139 if (Cond.getOpcode() == X86ISD::SETCC) {
5140 CC = Cond.getOperand(0);
5142 SDValue Cmp = Cond.getOperand(1);
5143 unsigned Opc = Cmp.getOpcode();
5144 MVT VT = Op.getValueType();
5146 bool IllegalFPCMov = false;
5147 if (VT.isFloatingPoint() && !VT.isVector() &&
5148 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5149 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5151 if ((Opc == X86ISD::CMP ||
5152 Opc == X86ISD::COMI ||
5153 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
5160 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5161 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5164 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5166 SmallVector<SDValue, 4> Ops;
5167 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5168 // condition is true.
5169 Ops.push_back(Op.getOperand(2));
5170 Ops.push_back(Op.getOperand(1));
5172 Ops.push_back(Cond);
5173 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5176 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5177 bool addTest = true;
5178 SDValue Chain = Op.getOperand(0);
5179 SDValue Cond = Op.getOperand(1);
5180 SDValue Dest = Op.getOperand(2);
5183 if (Cond.getOpcode() == ISD::SETCC)
5184 Cond = LowerSETCC(Cond, DAG);
5186 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5187 // setting operand in place of the X86ISD::SETCC.
5188 if (Cond.getOpcode() == X86ISD::SETCC) {
5189 CC = Cond.getOperand(0);
5191 SDValue Cmp = Cond.getOperand(1);
5192 unsigned Opc = Cmp.getOpcode();
5193 if (Opc == X86ISD::CMP ||
5194 Opc == X86ISD::COMI ||
5195 Opc == X86ISD::UCOMI) {
5199 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5200 // two branches instead of an explicit OR instruction with a
5202 } else if (Cond.getOpcode() == ISD::OR &&
5204 Cond.getOperand(0).getOpcode() == X86ISD::SETCC &&
5205 Cond.getOperand(0).hasOneUse() &&
5206 Cond.getOperand(1).getOpcode() == X86ISD::SETCC &&
5207 Cond.getOperand(1).hasOneUse()) {
5208 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5209 unsigned Opc = Cmp.getOpcode();
5210 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5211 (Opc == X86ISD::CMP ||
5212 Opc == X86ISD::COMI ||
5213 Opc == X86ISD::UCOMI)) {
5214 CC = Cond.getOperand(0).getOperand(0);
5215 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5216 Chain, Dest, CC, Cmp);
5217 CC = Cond.getOperand(1).getOperand(0);
5221 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5222 // two branches instead of an explicit AND instruction with a
5223 // separate test. However, we only do this if this block doesn't
5224 // have a fall-through edge, because this requires an explicit
5225 // jmp when the condition is false.
5226 } else if (Cond.getOpcode() == ISD::AND &&
5228 Cond.getOperand(0).getOpcode() == X86ISD::SETCC &&
5229 Cond.getOperand(0).hasOneUse() &&
5230 Cond.getOperand(1).getOpcode() == X86ISD::SETCC &&
5231 Cond.getOperand(1).hasOneUse()) {
5232 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5233 unsigned Opc = Cmp.getOpcode();
5234 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5235 (Opc == X86ISD::CMP ||
5236 Opc == X86ISD::COMI ||
5237 Opc == X86ISD::UCOMI) &&
5238 Op.getNode()->hasOneUse()) {
5239 X86::CondCode CCode =
5240 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5241 CCode = X86::GetOppositeBranchCondition(CCode);
5242 CC = DAG.getConstant(CCode, MVT::i8);
5243 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5244 // Look for an unconditional branch following this conditional branch.
5245 // We need this because we need to reverse the successors in order
5246 // to implement FCMP_OEQ.
5247 if (User.getOpcode() == ISD::BR) {
5248 SDValue FalseBB = User.getOperand(1);
5250 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5251 assert(NewBR == User);
5254 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5255 Chain, Dest, CC, Cmp);
5256 X86::CondCode CCode =
5257 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5258 CCode = X86::GetOppositeBranchCondition(CCode);
5259 CC = DAG.getConstant(CCode, MVT::i8);
5267 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5268 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5270 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5271 Chain, Dest, CC, Cond);
5275 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5276 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5277 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5278 // that the guard pages used by the OS virtual memory manager are allocated in
5279 // correct sequence.
5281 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5282 SelectionDAG &DAG) {
5283 assert(Subtarget->isTargetCygMing() &&
5284 "This should be used only on Cygwin/Mingw targets");
5287 SDValue Chain = Op.getOperand(0);
5288 SDValue Size = Op.getOperand(1);
5289 // FIXME: Ensure alignment here
5293 MVT IntPtr = getPointerTy();
5294 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5296 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5298 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5299 Flag = Chain.getValue(1);
5301 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5302 SDValue Ops[] = { Chain,
5303 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5304 DAG.getRegister(X86::EAX, IntPtr),
5305 DAG.getRegister(X86StackPtr, SPTy),
5307 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5308 Flag = Chain.getValue(1);
5310 Chain = DAG.getCALLSEQ_END(Chain,
5311 DAG.getIntPtrConstant(0, true),
5312 DAG.getIntPtrConstant(0, true),
5315 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5317 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5318 return DAG.getMergeValues(Ops1, 2);
5322 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5324 SDValue Dst, SDValue Src,
5325 SDValue Size, unsigned Align,
5327 uint64_t DstSVOff) {
5328 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5330 // If not DWORD aligned or size is more than the threshold, call the library.
5331 // The libc version is likely to be faster for these cases. It can use the
5332 // address value and run time information about the CPU.
5333 if ((Align & 3) != 0 ||
5335 ConstantSize->getZExtValue() >
5336 getSubtarget()->getMaxInlineSizeThreshold()) {
5337 SDValue InFlag(0, 0);
5339 // Check to see if there is a specialized entry-point for memory zeroing.
5340 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5342 if (const char *bzeroEntry = V &&
5343 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5344 MVT IntPtr = getPointerTy();
5345 const Type *IntPtrTy = TD->getIntPtrType();
5346 TargetLowering::ArgListTy Args;
5347 TargetLowering::ArgListEntry Entry;
5349 Entry.Ty = IntPtrTy;
5350 Args.push_back(Entry);
5352 Args.push_back(Entry);
5353 std::pair<SDValue,SDValue> CallResult =
5354 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5355 CallingConv::C, false,
5356 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5357 return CallResult.second;
5360 // Otherwise have the target-independent code call memset.
5364 uint64_t SizeVal = ConstantSize->getZExtValue();
5365 SDValue InFlag(0, 0);
5368 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5369 unsigned BytesLeft = 0;
5370 bool TwoRepStos = false;
5373 uint64_t Val = ValC->getZExtValue() & 255;
5375 // If the value is a constant, then we can potentially use larger sets.
5376 switch (Align & 3) {
5377 case 2: // WORD aligned
5380 Val = (Val << 8) | Val;
5382 case 0: // DWORD aligned
5385 Val = (Val << 8) | Val;
5386 Val = (Val << 16) | Val;
5387 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5390 Val = (Val << 32) | Val;
5393 default: // Byte aligned
5396 Count = DAG.getIntPtrConstant(SizeVal);
5400 if (AVT.bitsGT(MVT::i8)) {
5401 unsigned UBytes = AVT.getSizeInBits() / 8;
5402 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5403 BytesLeft = SizeVal % UBytes;
5406 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5408 InFlag = Chain.getValue(1);
5411 Count = DAG.getIntPtrConstant(SizeVal);
5412 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5413 InFlag = Chain.getValue(1);
5416 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5418 InFlag = Chain.getValue(1);
5419 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5421 InFlag = Chain.getValue(1);
5423 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5424 SmallVector<SDValue, 8> Ops;
5425 Ops.push_back(Chain);
5426 Ops.push_back(DAG.getValueType(AVT));
5427 Ops.push_back(InFlag);
5428 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5431 InFlag = Chain.getValue(1);
5433 MVT CVT = Count.getValueType();
5434 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5435 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5436 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5438 InFlag = Chain.getValue(1);
5439 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5441 Ops.push_back(Chain);
5442 Ops.push_back(DAG.getValueType(MVT::i8));
5443 Ops.push_back(InFlag);
5444 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5445 } else if (BytesLeft) {
5446 // Handle the last 1 - 7 bytes.
5447 unsigned Offset = SizeVal - BytesLeft;
5448 MVT AddrVT = Dst.getValueType();
5449 MVT SizeVT = Size.getValueType();
5451 Chain = DAG.getMemset(Chain,
5452 DAG.getNode(ISD::ADD, AddrVT, Dst,
5453 DAG.getConstant(Offset, AddrVT)),
5455 DAG.getConstant(BytesLeft, SizeVT),
5456 Align, DstSV, DstSVOff + Offset);
5459 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5464 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5465 SDValue Chain, SDValue Dst, SDValue Src,
5466 SDValue Size, unsigned Align,
5468 const Value *DstSV, uint64_t DstSVOff,
5469 const Value *SrcSV, uint64_t SrcSVOff) {
5470 // This requires the copy size to be a constant, preferrably
5471 // within a subtarget-specific limit.
5472 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5475 uint64_t SizeVal = ConstantSize->getZExtValue();
5476 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5479 /// If not DWORD aligned, call the library.
5480 if ((Align & 3) != 0)
5485 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5488 unsigned UBytes = AVT.getSizeInBits() / 8;
5489 unsigned CountVal = SizeVal / UBytes;
5490 SDValue Count = DAG.getIntPtrConstant(CountVal);
5491 unsigned BytesLeft = SizeVal % UBytes;
5493 SDValue InFlag(0, 0);
5494 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5496 InFlag = Chain.getValue(1);
5497 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5499 InFlag = Chain.getValue(1);
5500 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5502 InFlag = Chain.getValue(1);
5504 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5505 SmallVector<SDValue, 8> Ops;
5506 Ops.push_back(Chain);
5507 Ops.push_back(DAG.getValueType(AVT));
5508 Ops.push_back(InFlag);
5509 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5511 SmallVector<SDValue, 4> Results;
5512 Results.push_back(RepMovs);
5514 // Handle the last 1 - 7 bytes.
5515 unsigned Offset = SizeVal - BytesLeft;
5516 MVT DstVT = Dst.getValueType();
5517 MVT SrcVT = Src.getValueType();
5518 MVT SizeVT = Size.getValueType();
5519 Results.push_back(DAG.getMemcpy(Chain,
5520 DAG.getNode(ISD::ADD, DstVT, Dst,
5521 DAG.getConstant(Offset, DstVT)),
5522 DAG.getNode(ISD::ADD, SrcVT, Src,
5523 DAG.getConstant(Offset, SrcVT)),
5524 DAG.getConstant(BytesLeft, SizeVT),
5525 Align, AlwaysInline,
5526 DstSV, DstSVOff + Offset,
5527 SrcSV, SrcSVOff + Offset));
5530 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5533 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5534 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5535 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5536 SDValue TheChain = N->getOperand(0);
5537 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5538 if (Subtarget->is64Bit()) {
5539 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5540 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5541 MVT::i64, rax.getValue(2));
5542 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5543 DAG.getConstant(32, MVT::i8));
5545 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5548 return DAG.getMergeValues(Ops, 2).getNode();
5551 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5552 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5553 MVT::i32, eax.getValue(2));
5554 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5555 SDValue Ops[] = { eax, edx };
5556 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5558 // Use a MERGE_VALUES to return the value and chain.
5559 Ops[1] = edx.getValue(1);
5560 return DAG.getMergeValues(Ops, 2).getNode();
5563 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5564 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5566 if (!Subtarget->is64Bit()) {
5567 // vastart just stores the address of the VarArgsFrameIndex slot into the
5568 // memory location argument.
5569 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5570 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5574 // gp_offset (0 - 6 * 8)
5575 // fp_offset (48 - 48 + 8 * 16)
5576 // overflow_arg_area (point to parameters coming in memory).
5578 SmallVector<SDValue, 8> MemOps;
5579 SDValue FIN = Op.getOperand(1);
5581 SDValue Store = DAG.getStore(Op.getOperand(0),
5582 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5584 MemOps.push_back(Store);
5587 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5588 Store = DAG.getStore(Op.getOperand(0),
5589 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5591 MemOps.push_back(Store);
5593 // Store ptr to overflow_arg_area
5594 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5595 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5596 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5597 MemOps.push_back(Store);
5599 // Store ptr to reg_save_area.
5600 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5601 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5602 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5603 MemOps.push_back(Store);
5604 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5607 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5608 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5609 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5610 SDValue Chain = Op.getOperand(0);
5611 SDValue SrcPtr = Op.getOperand(1);
5612 SDValue SrcSV = Op.getOperand(2);
5614 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5619 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5620 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5621 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5622 SDValue Chain = Op.getOperand(0);
5623 SDValue DstPtr = Op.getOperand(1);
5624 SDValue SrcPtr = Op.getOperand(2);
5625 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5626 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5628 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5629 DAG.getIntPtrConstant(24), 8, false,
5630 DstSV, 0, SrcSV, 0);
5634 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5635 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5637 default: return SDValue(); // Don't custom lower most intrinsics.
5638 // Comparison intrinsics.
5639 case Intrinsic::x86_sse_comieq_ss:
5640 case Intrinsic::x86_sse_comilt_ss:
5641 case Intrinsic::x86_sse_comile_ss:
5642 case Intrinsic::x86_sse_comigt_ss:
5643 case Intrinsic::x86_sse_comige_ss:
5644 case Intrinsic::x86_sse_comineq_ss:
5645 case Intrinsic::x86_sse_ucomieq_ss:
5646 case Intrinsic::x86_sse_ucomilt_ss:
5647 case Intrinsic::x86_sse_ucomile_ss:
5648 case Intrinsic::x86_sse_ucomigt_ss:
5649 case Intrinsic::x86_sse_ucomige_ss:
5650 case Intrinsic::x86_sse_ucomineq_ss:
5651 case Intrinsic::x86_sse2_comieq_sd:
5652 case Intrinsic::x86_sse2_comilt_sd:
5653 case Intrinsic::x86_sse2_comile_sd:
5654 case Intrinsic::x86_sse2_comigt_sd:
5655 case Intrinsic::x86_sse2_comige_sd:
5656 case Intrinsic::x86_sse2_comineq_sd:
5657 case Intrinsic::x86_sse2_ucomieq_sd:
5658 case Intrinsic::x86_sse2_ucomilt_sd:
5659 case Intrinsic::x86_sse2_ucomile_sd:
5660 case Intrinsic::x86_sse2_ucomigt_sd:
5661 case Intrinsic::x86_sse2_ucomige_sd:
5662 case Intrinsic::x86_sse2_ucomineq_sd: {
5664 ISD::CondCode CC = ISD::SETCC_INVALID;
5667 case Intrinsic::x86_sse_comieq_ss:
5668 case Intrinsic::x86_sse2_comieq_sd:
5672 case Intrinsic::x86_sse_comilt_ss:
5673 case Intrinsic::x86_sse2_comilt_sd:
5677 case Intrinsic::x86_sse_comile_ss:
5678 case Intrinsic::x86_sse2_comile_sd:
5682 case Intrinsic::x86_sse_comigt_ss:
5683 case Intrinsic::x86_sse2_comigt_sd:
5687 case Intrinsic::x86_sse_comige_ss:
5688 case Intrinsic::x86_sse2_comige_sd:
5692 case Intrinsic::x86_sse_comineq_ss:
5693 case Intrinsic::x86_sse2_comineq_sd:
5697 case Intrinsic::x86_sse_ucomieq_ss:
5698 case Intrinsic::x86_sse2_ucomieq_sd:
5699 Opc = X86ISD::UCOMI;
5702 case Intrinsic::x86_sse_ucomilt_ss:
5703 case Intrinsic::x86_sse2_ucomilt_sd:
5704 Opc = X86ISD::UCOMI;
5707 case Intrinsic::x86_sse_ucomile_ss:
5708 case Intrinsic::x86_sse2_ucomile_sd:
5709 Opc = X86ISD::UCOMI;
5712 case Intrinsic::x86_sse_ucomigt_ss:
5713 case Intrinsic::x86_sse2_ucomigt_sd:
5714 Opc = X86ISD::UCOMI;
5717 case Intrinsic::x86_sse_ucomige_ss:
5718 case Intrinsic::x86_sse2_ucomige_sd:
5719 Opc = X86ISD::UCOMI;
5722 case Intrinsic::x86_sse_ucomineq_ss:
5723 case Intrinsic::x86_sse2_ucomineq_sd:
5724 Opc = X86ISD::UCOMI;
5730 SDValue LHS = Op.getOperand(1);
5731 SDValue RHS = Op.getOperand(2);
5732 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5734 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5735 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5736 DAG.getConstant(X86CC, MVT::i8), Cond);
5737 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5740 // Fix vector shift instructions where the last operand is a non-immediate
5742 case Intrinsic::x86_sse2_pslli_w:
5743 case Intrinsic::x86_sse2_pslli_d:
5744 case Intrinsic::x86_sse2_pslli_q:
5745 case Intrinsic::x86_sse2_psrli_w:
5746 case Intrinsic::x86_sse2_psrli_d:
5747 case Intrinsic::x86_sse2_psrli_q:
5748 case Intrinsic::x86_sse2_psrai_w:
5749 case Intrinsic::x86_sse2_psrai_d:
5750 case Intrinsic::x86_mmx_pslli_w:
5751 case Intrinsic::x86_mmx_pslli_d:
5752 case Intrinsic::x86_mmx_pslli_q:
5753 case Intrinsic::x86_mmx_psrli_w:
5754 case Intrinsic::x86_mmx_psrli_d:
5755 case Intrinsic::x86_mmx_psrli_q:
5756 case Intrinsic::x86_mmx_psrai_w:
5757 case Intrinsic::x86_mmx_psrai_d: {
5758 SDValue ShAmt = Op.getOperand(2);
5759 if (isa<ConstantSDNode>(ShAmt))
5762 unsigned NewIntNo = 0;
5763 MVT ShAmtVT = MVT::v4i32;
5765 case Intrinsic::x86_sse2_pslli_w:
5766 NewIntNo = Intrinsic::x86_sse2_psll_w;
5768 case Intrinsic::x86_sse2_pslli_d:
5769 NewIntNo = Intrinsic::x86_sse2_psll_d;
5771 case Intrinsic::x86_sse2_pslli_q:
5772 NewIntNo = Intrinsic::x86_sse2_psll_q;
5774 case Intrinsic::x86_sse2_psrli_w:
5775 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5777 case Intrinsic::x86_sse2_psrli_d:
5778 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5780 case Intrinsic::x86_sse2_psrli_q:
5781 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5783 case Intrinsic::x86_sse2_psrai_w:
5784 NewIntNo = Intrinsic::x86_sse2_psra_w;
5786 case Intrinsic::x86_sse2_psrai_d:
5787 NewIntNo = Intrinsic::x86_sse2_psra_d;
5790 ShAmtVT = MVT::v2i32;
5792 case Intrinsic::x86_mmx_pslli_w:
5793 NewIntNo = Intrinsic::x86_mmx_psll_w;
5795 case Intrinsic::x86_mmx_pslli_d:
5796 NewIntNo = Intrinsic::x86_mmx_psll_d;
5798 case Intrinsic::x86_mmx_pslli_q:
5799 NewIntNo = Intrinsic::x86_mmx_psll_q;
5801 case Intrinsic::x86_mmx_psrli_w:
5802 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5804 case Intrinsic::x86_mmx_psrli_d:
5805 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5807 case Intrinsic::x86_mmx_psrli_q:
5808 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5810 case Intrinsic::x86_mmx_psrai_w:
5811 NewIntNo = Intrinsic::x86_mmx_psra_w;
5813 case Intrinsic::x86_mmx_psrai_d:
5814 NewIntNo = Intrinsic::x86_mmx_psra_d;
5816 default: abort(); // Can't reach here.
5821 MVT VT = Op.getValueType();
5822 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5823 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5824 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5825 DAG.getConstant(NewIntNo, MVT::i32),
5826 Op.getOperand(1), ShAmt);
5831 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5832 // Depths > 0 not supported yet!
5833 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5836 // Just load the return address
5837 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5838 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5841 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5842 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5843 MFI->setFrameAddressIsTaken(true);
5844 MVT VT = Op.getValueType();
5845 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5846 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5847 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5849 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5853 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5854 SelectionDAG &DAG) {
5855 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5858 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5860 MachineFunction &MF = DAG.getMachineFunction();
5861 SDValue Chain = Op.getOperand(0);
5862 SDValue Offset = Op.getOperand(1);
5863 SDValue Handler = Op.getOperand(2);
5865 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5867 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5869 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5870 DAG.getIntPtrConstant(-TD->getPointerSize()));
5871 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5872 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5873 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5874 MF.getRegInfo().addLiveOut(StoreAddrReg);
5876 return DAG.getNode(X86ISD::EH_RETURN,
5878 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5881 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5882 SelectionDAG &DAG) {
5883 SDValue Root = Op.getOperand(0);
5884 SDValue Trmp = Op.getOperand(1); // trampoline
5885 SDValue FPtr = Op.getOperand(2); // nested function
5886 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5888 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5890 const X86InstrInfo *TII =
5891 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5893 if (Subtarget->is64Bit()) {
5894 SDValue OutChains[6];
5896 // Large code-model.
5898 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5899 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5901 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5902 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5904 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5906 // Load the pointer to the nested function into R11.
5907 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5908 SDValue Addr = Trmp;
5909 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5912 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5913 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5915 // Load the 'nest' parameter value into R10.
5916 // R10 is specified in X86CallingConv.td
5917 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5918 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5919 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5922 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5923 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5925 // Jump to the nested function.
5926 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5927 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5928 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5931 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5932 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5933 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5937 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5938 return DAG.getMergeValues(Ops, 2);
5940 const Function *Func =
5941 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5942 unsigned CC = Func->getCallingConv();
5947 assert(0 && "Unsupported calling convention");
5948 case CallingConv::C:
5949 case CallingConv::X86_StdCall: {
5950 // Pass 'nest' parameter in ECX.
5951 // Must be kept in sync with X86CallingConv.td
5954 // Check that ECX wasn't needed by an 'inreg' parameter.
5955 const FunctionType *FTy = Func->getFunctionType();
5956 const AttrListPtr &Attrs = Func->getAttributes();
5958 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5959 unsigned InRegCount = 0;
5962 for (FunctionType::param_iterator I = FTy->param_begin(),
5963 E = FTy->param_end(); I != E; ++I, ++Idx)
5964 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
5965 // FIXME: should only count parameters that are lowered to integers.
5966 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5968 if (InRegCount > 2) {
5969 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5975 case CallingConv::X86_FastCall:
5976 case CallingConv::Fast:
5977 // Pass 'nest' parameter in EAX.
5978 // Must be kept in sync with X86CallingConv.td
5983 SDValue OutChains[4];
5986 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5987 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5989 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5990 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5991 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5994 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5995 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5997 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5998 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5999 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6000 TrmpAddr, 5, false, 1);
6002 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6003 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6006 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6007 return DAG.getMergeValues(Ops, 2);
6011 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6013 The rounding mode is in bits 11:10 of FPSR, and has the following
6020 FLT_ROUNDS, on the other hand, expects the following:
6027 To perform the conversion, we do:
6028 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6031 MachineFunction &MF = DAG.getMachineFunction();
6032 const TargetMachine &TM = MF.getTarget();
6033 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6034 unsigned StackAlignment = TFI.getStackAlignment();
6035 MVT VT = Op.getValueType();
6037 // Save FP Control Word to stack slot
6038 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6039 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6041 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6042 DAG.getEntryNode(), StackSlot);
6044 // Load FP Control Word from stack slot
6045 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6047 // Transform as necessary
6049 DAG.getNode(ISD::SRL, MVT::i16,
6050 DAG.getNode(ISD::AND, MVT::i16,
6051 CWD, DAG.getConstant(0x800, MVT::i16)),
6052 DAG.getConstant(11, MVT::i8));
6054 DAG.getNode(ISD::SRL, MVT::i16,
6055 DAG.getNode(ISD::AND, MVT::i16,
6056 CWD, DAG.getConstant(0x400, MVT::i16)),
6057 DAG.getConstant(9, MVT::i8));
6060 DAG.getNode(ISD::AND, MVT::i16,
6061 DAG.getNode(ISD::ADD, MVT::i16,
6062 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6063 DAG.getConstant(1, MVT::i16)),
6064 DAG.getConstant(3, MVT::i16));
6067 return DAG.getNode((VT.getSizeInBits() < 16 ?
6068 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6071 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6072 MVT VT = Op.getValueType();
6074 unsigned NumBits = VT.getSizeInBits();
6076 Op = Op.getOperand(0);
6077 if (VT == MVT::i8) {
6078 // Zero extend to i32 since there is not an i8 bsr.
6080 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6083 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6084 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6085 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6087 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6088 SmallVector<SDValue, 4> Ops;
6090 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6091 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6092 Ops.push_back(Op.getValue(1));
6093 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6095 // Finally xor with NumBits-1.
6096 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6099 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6103 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6104 MVT VT = Op.getValueType();
6106 unsigned NumBits = VT.getSizeInBits();
6108 Op = Op.getOperand(0);
6109 if (VT == MVT::i8) {
6111 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6114 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6115 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6116 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6118 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6119 SmallVector<SDValue, 4> Ops;
6121 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6122 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6123 Ops.push_back(Op.getValue(1));
6124 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6127 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6131 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6132 MVT T = Op.getValueType();
6135 switch(T.getSimpleVT()) {
6137 assert(false && "Invalid value type!");
6138 case MVT::i8: Reg = X86::AL; size = 1; break;
6139 case MVT::i16: Reg = X86::AX; size = 2; break;
6140 case MVT::i32: Reg = X86::EAX; size = 4; break;
6142 if (Subtarget->is64Bit()) {
6143 Reg = X86::RAX; size = 8;
6144 } else //Should go away when LegalizeType stuff lands
6145 return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
6148 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6149 Op.getOperand(2), SDValue());
6150 SDValue Ops[] = { cpIn.getValue(0),
6153 DAG.getTargetConstant(size, MVT::i8),
6155 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6156 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6158 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6162 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
6163 SelectionDAG &DAG) {
6164 MVT T = Op->getValueType(0);
6165 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6166 SDValue cpInL, cpInH;
6167 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
6168 DAG.getConstant(0, MVT::i32));
6169 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
6170 DAG.getConstant(1, MVT::i32));
6171 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
6173 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
6174 cpInH, cpInL.getValue(1));
6175 SDValue swapInL, swapInH;
6176 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
6177 DAG.getConstant(0, MVT::i32));
6178 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
6179 DAG.getConstant(1, MVT::i32));
6180 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
6181 swapInL, cpInH.getValue(1));
6182 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
6183 swapInH, swapInL.getValue(1));
6184 SDValue Ops[] = { swapInH.getValue(0),
6186 swapInH.getValue(1) };
6187 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6188 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6189 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6190 Result.getValue(1));
6191 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6192 cpOutL.getValue(2));
6193 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6194 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6195 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
6196 return DAG.getMergeValues(Vals, 2).getNode();
6199 SDValue X86TargetLowering::LowerATOMIC_BINARY_64(SDValue Op,
6202 SDNode *Node = Op.getNode();
6203 MVT T = Node->getValueType(0);
6204 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6206 SDValue Chain = Node->getOperand(0);
6207 SDValue In1 = Node->getOperand(1);
6208 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6209 Node->getOperand(2), DAG.getIntPtrConstant(0));
6210 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6211 Node->getOperand(2), DAG.getIntPtrConstant(1));
6212 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6213 // have a MemOperand. Pass the info through as a normal operand.
6214 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6215 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6216 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6217 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6218 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6219 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6220 SDValue Vals[2] = { ResultVal, Result.getValue(2) };
6221 return SDValue(DAG.getMergeValues(Vals, 2).getNode(), 0);
6224 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6225 SDNode *Node = Op.getNode();
6226 MVT T = Node->getValueType(0);
6227 SDValue negOp = DAG.getNode(ISD::SUB, T,
6228 DAG.getConstant(0, T), Node->getOperand(2));
6229 return DAG.getAtomic((Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_8 ?
6230 ISD::ATOMIC_LOAD_ADD_8 :
6231 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_16 ?
6232 ISD::ATOMIC_LOAD_ADD_16 :
6233 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_32 ?
6234 ISD::ATOMIC_LOAD_ADD_32 :
6235 ISD::ATOMIC_LOAD_ADD_64),
6236 Node->getOperand(0),
6237 Node->getOperand(1), negOp,
6238 cast<AtomicSDNode>(Node)->getSrcValue(),
6239 cast<AtomicSDNode>(Node)->getAlignment());
6242 /// LowerOperation - Provide custom lowering hooks for some operations.
6244 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6245 switch (Op.getOpcode()) {
6246 default: assert(0 && "Should not custom lower this!");
6247 case ISD::ATOMIC_CMP_SWAP_8:
6248 case ISD::ATOMIC_CMP_SWAP_16:
6249 case ISD::ATOMIC_CMP_SWAP_32:
6250 case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
6251 case ISD::ATOMIC_LOAD_SUB_8:
6252 case ISD::ATOMIC_LOAD_SUB_16:
6253 case ISD::ATOMIC_LOAD_SUB_32: return LowerLOAD_SUB(Op,DAG);
6254 case ISD::ATOMIC_LOAD_SUB_64: return (Subtarget->is64Bit()) ?
6255 LowerLOAD_SUB(Op,DAG) :
6256 LowerATOMIC_BINARY_64(Op,DAG,
6257 X86ISD::ATOMSUB64_DAG);
6258 case ISD::ATOMIC_LOAD_AND_64: return LowerATOMIC_BINARY_64(Op,DAG,
6259 X86ISD::ATOMAND64_DAG);
6260 case ISD::ATOMIC_LOAD_OR_64: return LowerATOMIC_BINARY_64(Op, DAG,
6261 X86ISD::ATOMOR64_DAG);
6262 case ISD::ATOMIC_LOAD_XOR_64: return LowerATOMIC_BINARY_64(Op,DAG,
6263 X86ISD::ATOMXOR64_DAG);
6264 case ISD::ATOMIC_LOAD_NAND_64:return LowerATOMIC_BINARY_64(Op,DAG,
6265 X86ISD::ATOMNAND64_DAG);
6266 case ISD::ATOMIC_LOAD_ADD_64: return LowerATOMIC_BINARY_64(Op,DAG,
6267 X86ISD::ATOMADD64_DAG);
6268 case ISD::ATOMIC_SWAP_64: return LowerATOMIC_BINARY_64(Op,DAG,
6269 X86ISD::ATOMSWAP64_DAG);
6270 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6271 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6272 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6273 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6274 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6275 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6276 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6277 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6278 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6279 case ISD::SHL_PARTS:
6280 case ISD::SRA_PARTS:
6281 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6282 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6283 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6284 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6285 case ISD::FABS: return LowerFABS(Op, DAG);
6286 case ISD::FNEG: return LowerFNEG(Op, DAG);
6287 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6288 case ISD::SETCC: return LowerSETCC(Op, DAG);
6289 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6290 case ISD::SELECT: return LowerSELECT(Op, DAG);
6291 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6292 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6293 case ISD::CALL: return LowerCALL(Op, DAG);
6294 case ISD::RET: return LowerRET(Op, DAG);
6295 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6296 case ISD::VASTART: return LowerVASTART(Op, DAG);
6297 case ISD::VAARG: return LowerVAARG(Op, DAG);
6298 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6299 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6300 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6301 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6302 case ISD::FRAME_TO_ARGS_OFFSET:
6303 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6304 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6305 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6306 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6307 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6308 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6309 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6311 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6312 case ISD::READCYCLECOUNTER:
6313 return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6317 /// ReplaceNodeResults - Replace a node with an illegal result type
6318 /// with a new node built out of custom code.
6319 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6320 switch (N->getOpcode()) {
6322 return X86TargetLowering::LowerOperation(SDValue (N, 0), DAG).getNode();
6323 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
6324 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
6325 case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6329 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6331 default: return NULL;
6332 case X86ISD::BSF: return "X86ISD::BSF";
6333 case X86ISD::BSR: return "X86ISD::BSR";
6334 case X86ISD::SHLD: return "X86ISD::SHLD";
6335 case X86ISD::SHRD: return "X86ISD::SHRD";
6336 case X86ISD::FAND: return "X86ISD::FAND";
6337 case X86ISD::FOR: return "X86ISD::FOR";
6338 case X86ISD::FXOR: return "X86ISD::FXOR";
6339 case X86ISD::FSRL: return "X86ISD::FSRL";
6340 case X86ISD::FILD: return "X86ISD::FILD";
6341 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6342 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6343 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6344 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6345 case X86ISD::FLD: return "X86ISD::FLD";
6346 case X86ISD::FST: return "X86ISD::FST";
6347 case X86ISD::CALL: return "X86ISD::CALL";
6348 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6349 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6350 case X86ISD::CMP: return "X86ISD::CMP";
6351 case X86ISD::COMI: return "X86ISD::COMI";
6352 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6353 case X86ISD::SETCC: return "X86ISD::SETCC";
6354 case X86ISD::CMOV: return "X86ISD::CMOV";
6355 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6356 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6357 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6358 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6359 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6360 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6361 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6362 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6363 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6364 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6365 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6366 case X86ISD::FMAX: return "X86ISD::FMAX";
6367 case X86ISD::FMIN: return "X86ISD::FMIN";
6368 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6369 case X86ISD::FRCP: return "X86ISD::FRCP";
6370 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6371 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6372 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6373 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6374 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6375 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6376 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6377 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6378 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6379 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6380 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6381 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6382 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6383 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6384 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6385 case X86ISD::VSHL: return "X86ISD::VSHL";
6386 case X86ISD::VSRL: return "X86ISD::VSRL";
6387 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6388 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6389 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6390 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6391 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6392 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6393 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6394 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6395 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6396 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6400 // isLegalAddressingMode - Return true if the addressing mode represented
6401 // by AM is legal for this target, for a load/store of the specified type.
6402 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6403 const Type *Ty) const {
6404 // X86 supports extremely general addressing modes.
6406 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6407 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6411 // We can only fold this if we don't need an extra load.
6412 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6415 // X86-64 only supports addr of globals in small code model.
6416 if (Subtarget->is64Bit()) {
6417 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6419 // If lower 4G is not available, then we must use rip-relative addressing.
6420 if (AM.BaseOffs || AM.Scale > 1)
6431 // These scales always work.
6436 // These scales are formed with basereg+scalereg. Only accept if there is
6441 default: // Other stuff never works.
6449 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6450 if (!Ty1->isInteger() || !Ty2->isInteger())
6452 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6453 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6454 if (NumBits1 <= NumBits2)
6456 return Subtarget->is64Bit() || NumBits1 < 64;
6459 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6460 if (!VT1.isInteger() || !VT2.isInteger())
6462 unsigned NumBits1 = VT1.getSizeInBits();
6463 unsigned NumBits2 = VT2.getSizeInBits();
6464 if (NumBits1 <= NumBits2)
6466 return Subtarget->is64Bit() || NumBits1 < 64;
6469 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6470 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6471 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6472 /// are assumed to be legal.
6474 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6475 // Only do shuffles on 128-bit vector types for now.
6476 if (VT.getSizeInBits() == 64) return false;
6477 return (Mask.getNode()->getNumOperands() <= 4 ||
6478 isIdentityMask(Mask.getNode()) ||
6479 isIdentityMask(Mask.getNode(), true) ||
6480 isSplatMask(Mask.getNode()) ||
6481 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6482 X86::isUNPCKLMask(Mask.getNode()) ||
6483 X86::isUNPCKHMask(Mask.getNode()) ||
6484 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6485 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6489 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6490 MVT EVT, SelectionDAG &DAG) const {
6491 unsigned NumElts = BVOps.size();
6492 // Only do shuffles on 128-bit vector types for now.
6493 if (EVT.getSizeInBits() * NumElts == 64) return false;
6494 if (NumElts == 2) return true;
6496 return (isMOVLMask(&BVOps[0], 4) ||
6497 isCommutedMOVL(&BVOps[0], 4, true) ||
6498 isSHUFPMask(&BVOps[0], 4) ||
6499 isCommutedSHUFP(&BVOps[0], 4));
6504 //===----------------------------------------------------------------------===//
6505 // X86 Scheduler Hooks
6506 //===----------------------------------------------------------------------===//
6508 // private utility function
6510 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6511 MachineBasicBlock *MBB,
6519 TargetRegisterClass *RC,
6521 // For the atomic bitwise operator, we generate
6524 // ld t1 = [bitinstr.addr]
6525 // op t2 = t1, [bitinstr.val]
6527 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6529 // fallthrough -->nextMBB
6530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6531 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6532 MachineFunction::iterator MBBIter = MBB;
6535 /// First build the CFG
6536 MachineFunction *F = MBB->getParent();
6537 MachineBasicBlock *thisMBB = MBB;
6538 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6539 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6540 F->insert(MBBIter, newMBB);
6541 F->insert(MBBIter, nextMBB);
6543 // Move all successors to thisMBB to nextMBB
6544 nextMBB->transferSuccessors(thisMBB);
6546 // Update thisMBB to fall through to newMBB
6547 thisMBB->addSuccessor(newMBB);
6549 // newMBB jumps to itself and fall through to nextMBB
6550 newMBB->addSuccessor(nextMBB);
6551 newMBB->addSuccessor(newMBB);
6553 // Insert instructions into newMBB based on incoming instruction
6554 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6555 MachineOperand& destOper = bInstr->getOperand(0);
6556 MachineOperand* argOpers[6];
6557 int numArgs = bInstr->getNumOperands() - 1;
6558 for (int i=0; i < numArgs; ++i)
6559 argOpers[i] = &bInstr->getOperand(i+1);
6561 // x86 address has 4 operands: base, index, scale, and displacement
6562 int lastAddrIndx = 3; // [0,3]
6565 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6566 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6567 for (int i=0; i <= lastAddrIndx; ++i)
6568 (*MIB).addOperand(*argOpers[i]);
6570 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6572 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6577 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6578 assert((argOpers[valArgIndx]->isReg() ||
6579 argOpers[valArgIndx]->isImm()) &&
6581 if (argOpers[valArgIndx]->isReg())
6582 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6584 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6586 (*MIB).addOperand(*argOpers[valArgIndx]);
6588 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6591 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6592 for (int i=0; i <= lastAddrIndx; ++i)
6593 (*MIB).addOperand(*argOpers[i]);
6595 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6596 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6598 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6602 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6604 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6608 // private utility function: 64 bit atomics on 32 bit host.
6610 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6611 MachineBasicBlock *MBB,
6617 // For the atomic bitwise operator, we generate
6618 // thisMBB (instructions are in pairs, except cmpxchg8b)
6619 // ld t1,t2 = [bitinstr.addr]
6621 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6622 // op t5, t6 <- out1, out2, [bitinstr.val]
6623 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
6624 // mov ECX, EBX <- t5, t6
6625 // mov EAX, EDX <- t1, t2
6626 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6627 // mov t3, t4 <- EAX, EDX
6629 // result in out1, out2
6630 // fallthrough -->nextMBB
6632 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6633 const unsigned LoadOpc = X86::MOV32rm;
6634 const unsigned copyOpc = X86::MOV32rr;
6635 const unsigned NotOpc = X86::NOT32r;
6636 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6637 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6638 MachineFunction::iterator MBBIter = MBB;
6641 /// First build the CFG
6642 MachineFunction *F = MBB->getParent();
6643 MachineBasicBlock *thisMBB = MBB;
6644 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6645 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6646 F->insert(MBBIter, newMBB);
6647 F->insert(MBBIter, nextMBB);
6649 // Move all successors to thisMBB to nextMBB
6650 nextMBB->transferSuccessors(thisMBB);
6652 // Update thisMBB to fall through to newMBB
6653 thisMBB->addSuccessor(newMBB);
6655 // newMBB jumps to itself and fall through to nextMBB
6656 newMBB->addSuccessor(nextMBB);
6657 newMBB->addSuccessor(newMBB);
6659 // Insert instructions into newMBB based on incoming instruction
6660 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6661 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6662 MachineOperand& dest1Oper = bInstr->getOperand(0);
6663 MachineOperand& dest2Oper = bInstr->getOperand(1);
6664 MachineOperand* argOpers[6];
6665 for (int i=0; i < 6; ++i)
6666 argOpers[i] = &bInstr->getOperand(i+2);
6668 // x86 address has 4 operands: base, index, scale, and displacement
6669 int lastAddrIndx = 3; // [0,3]
6671 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6672 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6673 for (int i=0; i <= lastAddrIndx; ++i)
6674 (*MIB).addOperand(*argOpers[i]);
6675 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6676 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6677 // add 4 to displacement.
6678 for (int i=0; i <= lastAddrIndx-1; ++i)
6679 (*MIB).addOperand(*argOpers[i]);
6680 MachineOperand newOp3 = *(argOpers[3]);
6682 newOp3.setImm(newOp3.getImm()+4);
6684 newOp3.setOffset(newOp3.getOffset()+4);
6685 (*MIB).addOperand(newOp3);
6687 // t3/4 are defined later, at the bottom of the loop
6688 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6689 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6690 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6691 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6692 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6693 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6695 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6696 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6698 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6699 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6705 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6707 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6708 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6709 if (argOpers[4]->isReg())
6710 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6712 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6713 if (regOpcL != X86::MOV32rr)
6715 (*MIB).addOperand(*argOpers[4]);
6716 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6717 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6718 if (argOpers[5]->isReg())
6719 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6721 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6722 if (regOpcH != X86::MOV32rr)
6724 (*MIB).addOperand(*argOpers[5]);
6726 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6728 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6731 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6733 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
6736 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
6737 for (int i=0; i <= lastAddrIndx; ++i)
6738 (*MIB).addOperand(*argOpers[i]);
6740 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6741 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6743 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
6744 MIB.addReg(X86::EAX);
6745 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
6746 MIB.addReg(X86::EDX);
6749 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6751 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6755 // private utility function
6757 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6758 MachineBasicBlock *MBB,
6760 // For the atomic min/max operator, we generate
6763 // ld t1 = [min/max.addr]
6764 // mov t2 = [min/max.val]
6766 // cmov[cond] t2 = t1
6768 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6770 // fallthrough -->nextMBB
6772 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6773 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6774 MachineFunction::iterator MBBIter = MBB;
6777 /// First build the CFG
6778 MachineFunction *F = MBB->getParent();
6779 MachineBasicBlock *thisMBB = MBB;
6780 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6781 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6782 F->insert(MBBIter, newMBB);
6783 F->insert(MBBIter, nextMBB);
6785 // Move all successors to thisMBB to nextMBB
6786 nextMBB->transferSuccessors(thisMBB);
6788 // Update thisMBB to fall through to newMBB
6789 thisMBB->addSuccessor(newMBB);
6791 // newMBB jumps to newMBB and fall through to nextMBB
6792 newMBB->addSuccessor(nextMBB);
6793 newMBB->addSuccessor(newMBB);
6795 // Insert instructions into newMBB based on incoming instruction
6796 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6797 MachineOperand& destOper = mInstr->getOperand(0);
6798 MachineOperand* argOpers[6];
6799 int numArgs = mInstr->getNumOperands() - 1;
6800 for (int i=0; i < numArgs; ++i)
6801 argOpers[i] = &mInstr->getOperand(i+1);
6803 // x86 address has 4 operands: base, index, scale, and displacement
6804 int lastAddrIndx = 3; // [0,3]
6807 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6808 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6809 for (int i=0; i <= lastAddrIndx; ++i)
6810 (*MIB).addOperand(*argOpers[i]);
6812 // We only support register and immediate values
6813 assert((argOpers[valArgIndx]->isReg() ||
6814 argOpers[valArgIndx]->isImm()) &&
6817 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6818 if (argOpers[valArgIndx]->isReg())
6819 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6821 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6822 (*MIB).addOperand(*argOpers[valArgIndx]);
6824 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6827 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6832 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6833 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6837 // Cmp and exchange if none has modified the memory location
6838 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6839 for (int i=0; i <= lastAddrIndx; ++i)
6840 (*MIB).addOperand(*argOpers[i]);
6842 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6843 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6845 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6846 MIB.addReg(X86::EAX);
6849 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6851 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6857 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6858 MachineBasicBlock *BB) {
6859 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6860 switch (MI->getOpcode()) {
6861 default: assert(false && "Unexpected instr type to insert");
6862 case X86::CMOV_FR32:
6863 case X86::CMOV_FR64:
6864 case X86::CMOV_V4F32:
6865 case X86::CMOV_V2F64:
6866 case X86::CMOV_V2I64: {
6867 // To "insert" a SELECT_CC instruction, we actually have to insert the
6868 // diamond control-flow pattern. The incoming instruction knows the
6869 // destination vreg to set, the condition code register to branch on, the
6870 // true/false values to select between, and a branch opcode to use.
6871 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6872 MachineFunction::iterator It = BB;
6878 // cmpTY ccX, r1, r2
6880 // fallthrough --> copy0MBB
6881 MachineBasicBlock *thisMBB = BB;
6882 MachineFunction *F = BB->getParent();
6883 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6884 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6886 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6887 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6888 F->insert(It, copy0MBB);
6889 F->insert(It, sinkMBB);
6890 // Update machine-CFG edges by transferring all successors of the current
6891 // block to the new block which will contain the Phi node for the select.
6892 sinkMBB->transferSuccessors(BB);
6894 // Add the true and fallthrough blocks as its successors.
6895 BB->addSuccessor(copy0MBB);
6896 BB->addSuccessor(sinkMBB);
6899 // %FalseValue = ...
6900 // # fallthrough to sinkMBB
6903 // Update machine-CFG edges
6904 BB->addSuccessor(sinkMBB);
6907 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6910 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6911 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6912 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6914 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6918 case X86::FP32_TO_INT16_IN_MEM:
6919 case X86::FP32_TO_INT32_IN_MEM:
6920 case X86::FP32_TO_INT64_IN_MEM:
6921 case X86::FP64_TO_INT16_IN_MEM:
6922 case X86::FP64_TO_INT32_IN_MEM:
6923 case X86::FP64_TO_INT64_IN_MEM:
6924 case X86::FP80_TO_INT16_IN_MEM:
6925 case X86::FP80_TO_INT32_IN_MEM:
6926 case X86::FP80_TO_INT64_IN_MEM: {
6927 // Change the floating point control register to use "round towards zero"
6928 // mode when truncating to an integer value.
6929 MachineFunction *F = BB->getParent();
6930 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6931 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6933 // Load the old value of the high byte of the control word...
6935 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6936 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6938 // Set the high part to be round to zero...
6939 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6942 // Reload the modified control word now...
6943 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6945 // Restore the memory image of control word to original value
6946 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6949 // Get the X86 opcode to use.
6951 switch (MI->getOpcode()) {
6952 default: assert(0 && "illegal opcode!");
6953 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6954 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6955 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6956 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6957 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6958 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6959 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6960 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6961 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6965 MachineOperand &Op = MI->getOperand(0);
6967 AM.BaseType = X86AddressMode::RegBase;
6968 AM.Base.Reg = Op.getReg();
6970 AM.BaseType = X86AddressMode::FrameIndexBase;
6971 AM.Base.FrameIndex = Op.getIndex();
6973 Op = MI->getOperand(1);
6975 AM.Scale = Op.getImm();
6976 Op = MI->getOperand(2);
6978 AM.IndexReg = Op.getImm();
6979 Op = MI->getOperand(3);
6980 if (Op.isGlobal()) {
6981 AM.GV = Op.getGlobal();
6983 AM.Disp = Op.getImm();
6985 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6986 .addReg(MI->getOperand(4).getReg());
6988 // Reload the original control word now.
6989 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6991 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6994 case X86::ATOMAND32:
6995 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6996 X86::AND32ri, X86::MOV32rm,
6997 X86::LCMPXCHG32, X86::MOV32rr,
6998 X86::NOT32r, X86::EAX,
6999 X86::GR32RegisterClass);
7001 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7002 X86::OR32ri, X86::MOV32rm,
7003 X86::LCMPXCHG32, X86::MOV32rr,
7004 X86::NOT32r, X86::EAX,
7005 X86::GR32RegisterClass);
7006 case X86::ATOMXOR32:
7007 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7008 X86::XOR32ri, X86::MOV32rm,
7009 X86::LCMPXCHG32, X86::MOV32rr,
7010 X86::NOT32r, X86::EAX,
7011 X86::GR32RegisterClass);
7012 case X86::ATOMNAND32:
7013 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7014 X86::AND32ri, X86::MOV32rm,
7015 X86::LCMPXCHG32, X86::MOV32rr,
7016 X86::NOT32r, X86::EAX,
7017 X86::GR32RegisterClass, true);
7018 case X86::ATOMMIN32:
7019 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7020 case X86::ATOMMAX32:
7021 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7022 case X86::ATOMUMIN32:
7023 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7024 case X86::ATOMUMAX32:
7025 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7027 case X86::ATOMAND16:
7028 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7029 X86::AND16ri, X86::MOV16rm,
7030 X86::LCMPXCHG16, X86::MOV16rr,
7031 X86::NOT16r, X86::AX,
7032 X86::GR16RegisterClass);
7034 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7035 X86::OR16ri, X86::MOV16rm,
7036 X86::LCMPXCHG16, X86::MOV16rr,
7037 X86::NOT16r, X86::AX,
7038 X86::GR16RegisterClass);
7039 case X86::ATOMXOR16:
7040 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7041 X86::XOR16ri, X86::MOV16rm,
7042 X86::LCMPXCHG16, X86::MOV16rr,
7043 X86::NOT16r, X86::AX,
7044 X86::GR16RegisterClass);
7045 case X86::ATOMNAND16:
7046 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7047 X86::AND16ri, X86::MOV16rm,
7048 X86::LCMPXCHG16, X86::MOV16rr,
7049 X86::NOT16r, X86::AX,
7050 X86::GR16RegisterClass, true);
7051 case X86::ATOMMIN16:
7052 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7053 case X86::ATOMMAX16:
7054 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7055 case X86::ATOMUMIN16:
7056 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7057 case X86::ATOMUMAX16:
7058 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7061 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7062 X86::AND8ri, X86::MOV8rm,
7063 X86::LCMPXCHG8, X86::MOV8rr,
7064 X86::NOT8r, X86::AL,
7065 X86::GR8RegisterClass);
7067 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7068 X86::OR8ri, X86::MOV8rm,
7069 X86::LCMPXCHG8, X86::MOV8rr,
7070 X86::NOT8r, X86::AL,
7071 X86::GR8RegisterClass);
7073 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7074 X86::XOR8ri, X86::MOV8rm,
7075 X86::LCMPXCHG8, X86::MOV8rr,
7076 X86::NOT8r, X86::AL,
7077 X86::GR8RegisterClass);
7078 case X86::ATOMNAND8:
7079 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7080 X86::AND8ri, X86::MOV8rm,
7081 X86::LCMPXCHG8, X86::MOV8rr,
7082 X86::NOT8r, X86::AL,
7083 X86::GR8RegisterClass, true);
7084 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7085 // This group is for 64-bit host.
7086 case X86::ATOMAND64:
7087 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7088 X86::AND64ri32, X86::MOV64rm,
7089 X86::LCMPXCHG64, X86::MOV64rr,
7090 X86::NOT64r, X86::RAX,
7091 X86::GR64RegisterClass);
7093 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7094 X86::OR64ri32, X86::MOV64rm,
7095 X86::LCMPXCHG64, X86::MOV64rr,
7096 X86::NOT64r, X86::RAX,
7097 X86::GR64RegisterClass);
7098 case X86::ATOMXOR64:
7099 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7100 X86::XOR64ri32, X86::MOV64rm,
7101 X86::LCMPXCHG64, X86::MOV64rr,
7102 X86::NOT64r, X86::RAX,
7103 X86::GR64RegisterClass);
7104 case X86::ATOMNAND64:
7105 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7106 X86::AND64ri32, X86::MOV64rm,
7107 X86::LCMPXCHG64, X86::MOV64rr,
7108 X86::NOT64r, X86::RAX,
7109 X86::GR64RegisterClass, true);
7110 case X86::ATOMMIN64:
7111 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7112 case X86::ATOMMAX64:
7113 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7114 case X86::ATOMUMIN64:
7115 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7116 case X86::ATOMUMAX64:
7117 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7119 // This group does 64-bit operations on a 32-bit host.
7120 case X86::ATOMAND6432:
7121 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7122 X86::AND32rr, X86::AND32rr,
7123 X86::AND32ri, X86::AND32ri,
7125 case X86::ATOMOR6432:
7126 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7127 X86::OR32rr, X86::OR32rr,
7128 X86::OR32ri, X86::OR32ri,
7130 case X86::ATOMXOR6432:
7131 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7132 X86::XOR32rr, X86::XOR32rr,
7133 X86::XOR32ri, X86::XOR32ri,
7135 case X86::ATOMNAND6432:
7136 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7137 X86::AND32rr, X86::AND32rr,
7138 X86::AND32ri, X86::AND32ri,
7140 case X86::ATOMADD6432:
7141 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7142 X86::ADD32rr, X86::ADC32rr,
7143 X86::ADD32ri, X86::ADC32ri,
7145 case X86::ATOMSUB6432:
7146 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7147 X86::SUB32rr, X86::SBB32rr,
7148 X86::SUB32ri, X86::SBB32ri,
7150 case X86::ATOMSWAP6432:
7151 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7152 X86::MOV32rr, X86::MOV32rr,
7153 X86::MOV32ri, X86::MOV32ri,
7158 //===----------------------------------------------------------------------===//
7159 // X86 Optimization Hooks
7160 //===----------------------------------------------------------------------===//
7162 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7166 const SelectionDAG &DAG,
7167 unsigned Depth) const {
7168 unsigned Opc = Op.getOpcode();
7169 assert((Opc >= ISD::BUILTIN_OP_END ||
7170 Opc == ISD::INTRINSIC_WO_CHAIN ||
7171 Opc == ISD::INTRINSIC_W_CHAIN ||
7172 Opc == ISD::INTRINSIC_VOID) &&
7173 "Should use MaskedValueIsZero if you don't know whether Op"
7174 " is a target node!");
7176 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7180 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7181 Mask.getBitWidth() - 1);
7186 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7187 /// node is a GlobalAddress + offset.
7188 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7189 GlobalValue* &GA, int64_t &Offset) const{
7190 if (N->getOpcode() == X86ISD::Wrapper) {
7191 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7192 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7193 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7197 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7200 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7201 const TargetLowering &TLI) {
7204 if (TLI.isGAPlusOffset(Base, GV, Offset))
7205 return (GV->getAlignment() >= N && (Offset % N) == 0);
7206 // DAG combine handles the stack object case.
7210 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7211 unsigned NumElems, MVT EVT,
7213 SelectionDAG &DAG, MachineFrameInfo *MFI,
7214 const TargetLowering &TLI) {
7216 for (unsigned i = 0; i < NumElems; ++i) {
7217 SDValue Idx = PermMask.getOperand(i);
7218 if (Idx.getOpcode() == ISD::UNDEF) {
7224 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7225 if (!Elt.getNode() ||
7226 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7229 Base = Elt.getNode();
7230 if (Base->getOpcode() == ISD::UNDEF)
7234 if (Elt.getOpcode() == ISD::UNDEF)
7237 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7238 EVT.getSizeInBits()/8, i, MFI))
7244 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7245 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7246 /// if the load addresses are consecutive, non-overlapping, and in the right
7248 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7249 const TargetLowering &TLI) {
7250 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7251 MVT VT = N->getValueType(0);
7252 MVT EVT = VT.getVectorElementType();
7253 SDValue PermMask = N->getOperand(2);
7254 unsigned NumElems = PermMask.getNumOperands();
7255 SDNode *Base = NULL;
7256 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7260 LoadSDNode *LD = cast<LoadSDNode>(Base);
7261 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7262 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7263 LD->getSrcValueOffset(), LD->isVolatile());
7264 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7265 LD->getSrcValueOffset(), LD->isVolatile(),
7266 LD->getAlignment());
7269 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7270 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7271 const X86Subtarget *Subtarget,
7272 const TargetLowering &TLI) {
7273 unsigned NumOps = N->getNumOperands();
7275 // Ignore single operand BUILD_VECTOR.
7279 MVT VT = N->getValueType(0);
7280 MVT EVT = VT.getVectorElementType();
7281 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7282 // We are looking for load i64 and zero extend. We want to transform
7283 // it before legalizer has a chance to expand it. Also look for i64
7284 // BUILD_PAIR bit casted to f64.
7286 // This must be an insertion into a zero vector.
7287 SDValue HighElt = N->getOperand(1);
7288 if (!isZeroNode(HighElt))
7291 // Value must be a load.
7292 SDNode *Base = N->getOperand(0).getNode();
7293 if (!isa<LoadSDNode>(Base)) {
7294 if (Base->getOpcode() != ISD::BIT_CONVERT)
7296 Base = Base->getOperand(0).getNode();
7297 if (!isa<LoadSDNode>(Base))
7301 // Transform it into VZEXT_LOAD addr.
7302 LoadSDNode *LD = cast<LoadSDNode>(Base);
7304 // Load must not be an extload.
7305 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7308 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7309 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7310 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7311 DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7315 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7316 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7317 const X86Subtarget *Subtarget) {
7318 SDValue Cond = N->getOperand(0);
7320 // If we have SSE[12] support, try to form min/max nodes.
7321 if (Subtarget->hasSSE2() &&
7322 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7323 if (Cond.getOpcode() == ISD::SETCC) {
7324 // Get the LHS/RHS of the select.
7325 SDValue LHS = N->getOperand(1);
7326 SDValue RHS = N->getOperand(2);
7327 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7329 unsigned Opcode = 0;
7330 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7333 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7336 if (!UnsafeFPMath) break;
7338 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7340 Opcode = X86ISD::FMIN;
7343 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7346 if (!UnsafeFPMath) break;
7348 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7350 Opcode = X86ISD::FMAX;
7353 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7356 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7359 if (!UnsafeFPMath) break;
7361 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7363 Opcode = X86ISD::FMIN;
7366 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7369 if (!UnsafeFPMath) break;
7371 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7373 Opcode = X86ISD::FMAX;
7379 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7387 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7388 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7389 const X86Subtarget *Subtarget) {
7390 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7391 // the FP state in cases where an emms may be missing.
7392 // A preferable solution to the general problem is to figure out the right
7393 // places to insert EMMS. This qualifies as a quick hack.
7394 StoreSDNode *St = cast<StoreSDNode>(N);
7395 if (St->getValue().getValueType().isVector() &&
7396 St->getValue().getValueType().getSizeInBits() == 64 &&
7397 isa<LoadSDNode>(St->getValue()) &&
7398 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7399 St->getChain().hasOneUse() && !St->isVolatile()) {
7400 SDNode* LdVal = St->getValue().getNode();
7402 int TokenFactorIndex = -1;
7403 SmallVector<SDValue, 8> Ops;
7404 SDNode* ChainVal = St->getChain().getNode();
7405 // Must be a store of a load. We currently handle two cases: the load
7406 // is a direct child, and it's under an intervening TokenFactor. It is
7407 // possible to dig deeper under nested TokenFactors.
7408 if (ChainVal == LdVal)
7409 Ld = cast<LoadSDNode>(St->getChain());
7410 else if (St->getValue().hasOneUse() &&
7411 ChainVal->getOpcode() == ISD::TokenFactor) {
7412 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7413 if (ChainVal->getOperand(i).getNode() == LdVal) {
7414 TokenFactorIndex = i;
7415 Ld = cast<LoadSDNode>(St->getValue());
7417 Ops.push_back(ChainVal->getOperand(i));
7421 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7422 if (Subtarget->is64Bit()) {
7423 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7424 Ld->getBasePtr(), Ld->getSrcValue(),
7425 Ld->getSrcValueOffset(), Ld->isVolatile(),
7426 Ld->getAlignment());
7427 SDValue NewChain = NewLd.getValue(1);
7428 if (TokenFactorIndex != -1) {
7429 Ops.push_back(NewChain);
7430 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7433 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7434 St->getSrcValue(), St->getSrcValueOffset(),
7435 St->isVolatile(), St->getAlignment());
7438 // Otherwise, lower to two 32-bit copies.
7439 SDValue LoAddr = Ld->getBasePtr();
7440 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7441 DAG.getConstant(4, MVT::i32));
7443 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7444 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7445 Ld->isVolatile(), Ld->getAlignment());
7446 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7447 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7449 MinAlign(Ld->getAlignment(), 4));
7451 SDValue NewChain = LoLd.getValue(1);
7452 if (TokenFactorIndex != -1) {
7453 Ops.push_back(LoLd);
7454 Ops.push_back(HiLd);
7455 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7459 LoAddr = St->getBasePtr();
7460 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7461 DAG.getConstant(4, MVT::i32));
7463 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7464 St->getSrcValue(), St->getSrcValueOffset(),
7465 St->isVolatile(), St->getAlignment());
7466 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7468 St->getSrcValueOffset() + 4,
7470 MinAlign(St->getAlignment(), 4));
7471 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7477 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7478 /// X86ISD::FXOR nodes.
7479 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7480 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7481 // F[X]OR(0.0, x) -> x
7482 // F[X]OR(x, 0.0) -> x
7483 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7484 if (C->getValueAPF().isPosZero())
7485 return N->getOperand(1);
7486 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7487 if (C->getValueAPF().isPosZero())
7488 return N->getOperand(0);
7492 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7493 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7494 // FAND(0.0, x) -> 0.0
7495 // FAND(x, 0.0) -> 0.0
7496 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7497 if (C->getValueAPF().isPosZero())
7498 return N->getOperand(0);
7499 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7500 if (C->getValueAPF().isPosZero())
7501 return N->getOperand(1);
7506 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7507 DAGCombinerInfo &DCI) const {
7508 SelectionDAG &DAG = DCI.DAG;
7509 switch (N->getOpcode()) {
7511 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7512 case ISD::BUILD_VECTOR:
7513 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7514 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7515 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7517 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7518 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7524 //===----------------------------------------------------------------------===//
7525 // X86 Inline Assembly Support
7526 //===----------------------------------------------------------------------===//
7528 /// getConstraintType - Given a constraint letter, return the type of
7529 /// constraint it is for this target.
7530 X86TargetLowering::ConstraintType
7531 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7532 if (Constraint.size() == 1) {
7533 switch (Constraint[0]) {
7544 return C_RegisterClass;
7549 return TargetLowering::getConstraintType(Constraint);
7552 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7553 /// with another that has more specific requirements based on the type of the
7554 /// corresponding operand.
7555 const char *X86TargetLowering::
7556 LowerXConstraint(MVT ConstraintVT) const {
7557 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7558 // 'f' like normal targets.
7559 if (ConstraintVT.isFloatingPoint()) {
7560 if (Subtarget->hasSSE2())
7562 if (Subtarget->hasSSE1())
7566 return TargetLowering::LowerXConstraint(ConstraintVT);
7569 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7570 /// vector. If it is invalid, don't add anything to Ops.
7571 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7574 std::vector<SDValue>&Ops,
7575 SelectionDAG &DAG) const {
7576 SDValue Result(0, 0);
7578 switch (Constraint) {
7581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7582 if (C->getZExtValue() <= 31) {
7583 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7589 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7590 if (C->getZExtValue() <= 63) {
7591 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7598 if (C->getZExtValue() <= 255) {
7599 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7605 // Literal immediates are always ok.
7606 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7607 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7611 // If we are in non-pic codegen mode, we allow the address of a global (with
7612 // an optional displacement) to be used with 'i'.
7613 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7616 // Match either (GA) or (GA+C)
7618 Offset = GA->getOffset();
7619 } else if (Op.getOpcode() == ISD::ADD) {
7620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7621 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7623 Offset = GA->getOffset()+C->getZExtValue();
7625 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7626 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7628 Offset = GA->getOffset()+C->getZExtValue();
7636 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
7638 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7644 // Otherwise, not valid for this mode.
7649 if (Result.getNode()) {
7650 Ops.push_back(Result);
7653 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7657 std::vector<unsigned> X86TargetLowering::
7658 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7660 if (Constraint.size() == 1) {
7661 // FIXME: not handling fp-stack yet!
7662 switch (Constraint[0]) { // GCC X86 Constraint Letters
7663 default: break; // Unknown constraint letter
7664 case 'A': // EAX/EDX
7665 if (VT == MVT::i32 || VT == MVT::i64)
7666 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7668 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7671 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7672 else if (VT == MVT::i16)
7673 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7674 else if (VT == MVT::i8)
7675 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7676 else if (VT == MVT::i64)
7677 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7682 return std::vector<unsigned>();
7685 std::pair<unsigned, const TargetRegisterClass*>
7686 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7688 // First, see if this is a constraint that directly corresponds to an LLVM
7690 if (Constraint.size() == 1) {
7691 // GCC Constraint Letters
7692 switch (Constraint[0]) {
7694 case 'r': // GENERAL_REGS
7695 case 'R': // LEGACY_REGS
7696 case 'l': // INDEX_REGS
7698 return std::make_pair(0U, X86::GR8RegisterClass);
7700 return std::make_pair(0U, X86::GR16RegisterClass);
7701 if (VT == MVT::i32 || !Subtarget->is64Bit())
7702 return std::make_pair(0U, X86::GR32RegisterClass);
7703 return std::make_pair(0U, X86::GR64RegisterClass);
7704 case 'f': // FP Stack registers.
7705 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7706 // value to the correct fpstack register class.
7707 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7708 return std::make_pair(0U, X86::RFP32RegisterClass);
7709 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7710 return std::make_pair(0U, X86::RFP64RegisterClass);
7711 return std::make_pair(0U, X86::RFP80RegisterClass);
7712 case 'y': // MMX_REGS if MMX allowed.
7713 if (!Subtarget->hasMMX()) break;
7714 return std::make_pair(0U, X86::VR64RegisterClass);
7715 case 'Y': // SSE_REGS if SSE2 allowed
7716 if (!Subtarget->hasSSE2()) break;
7718 case 'x': // SSE_REGS if SSE1 allowed
7719 if (!Subtarget->hasSSE1()) break;
7721 switch (VT.getSimpleVT()) {
7723 // Scalar SSE types.
7726 return std::make_pair(0U, X86::FR32RegisterClass);
7729 return std::make_pair(0U, X86::FR64RegisterClass);
7737 return std::make_pair(0U, X86::VR128RegisterClass);
7743 // Use the default implementation in TargetLowering to convert the register
7744 // constraint into a member of a register class.
7745 std::pair<unsigned, const TargetRegisterClass*> Res;
7746 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7748 // Not found as a standard register?
7749 if (Res.second == 0) {
7750 // GCC calls "st(0)" just plain "st".
7751 if (StringsEqualNoCase("{st}", Constraint)) {
7752 Res.first = X86::ST0;
7753 Res.second = X86::RFP80RegisterClass;
7759 // Otherwise, check to see if this is a register class of the wrong value
7760 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7761 // turn into {ax},{dx}.
7762 if (Res.second->hasType(VT))
7763 return Res; // Correct type already, nothing to do.
7765 // All of the single-register GCC register classes map their values onto
7766 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7767 // really want an 8-bit or 32-bit register, map to the appropriate register
7768 // class and return the appropriate register.
7769 if (Res.second == X86::GR16RegisterClass) {
7770 if (VT == MVT::i8) {
7771 unsigned DestReg = 0;
7772 switch (Res.first) {
7774 case X86::AX: DestReg = X86::AL; break;
7775 case X86::DX: DestReg = X86::DL; break;
7776 case X86::CX: DestReg = X86::CL; break;
7777 case X86::BX: DestReg = X86::BL; break;
7780 Res.first = DestReg;
7781 Res.second = Res.second = X86::GR8RegisterClass;
7783 } else if (VT == MVT::i32) {
7784 unsigned DestReg = 0;
7785 switch (Res.first) {
7787 case X86::AX: DestReg = X86::EAX; break;
7788 case X86::DX: DestReg = X86::EDX; break;
7789 case X86::CX: DestReg = X86::ECX; break;
7790 case X86::BX: DestReg = X86::EBX; break;
7791 case X86::SI: DestReg = X86::ESI; break;
7792 case X86::DI: DestReg = X86::EDI; break;
7793 case X86::BP: DestReg = X86::EBP; break;
7794 case X86::SP: DestReg = X86::ESP; break;
7797 Res.first = DestReg;
7798 Res.second = Res.second = X86::GR32RegisterClass;
7800 } else if (VT == MVT::i64) {
7801 unsigned DestReg = 0;
7802 switch (Res.first) {
7804 case X86::AX: DestReg = X86::RAX; break;
7805 case X86::DX: DestReg = X86::RDX; break;
7806 case X86::CX: DestReg = X86::RCX; break;
7807 case X86::BX: DestReg = X86::RBX; break;
7808 case X86::SI: DestReg = X86::RSI; break;
7809 case X86::DI: DestReg = X86::RDI; break;
7810 case X86::BP: DestReg = X86::RBP; break;
7811 case X86::SP: DestReg = X86::RSP; break;
7814 Res.first = DestReg;
7815 Res.second = Res.second = X86::GR64RegisterClass;
7818 } else if (Res.second == X86::FR32RegisterClass ||
7819 Res.second == X86::FR64RegisterClass ||
7820 Res.second == X86::VR128RegisterClass) {
7821 // Handle references to XMM physical registers that got mapped into the
7822 // wrong class. This can happen with constraints like {xmm0} where the
7823 // target independent register mapper will just pick the first match it can
7824 // find, ignoring the required type.
7826 Res.second = X86::FR32RegisterClass;
7827 else if (VT == MVT::f64)
7828 Res.second = X86::FR64RegisterClass;
7829 else if (X86::VR128RegisterClass->hasType(VT))
7830 Res.second = X86::VR128RegisterClass;