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 setLoadXAction(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 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
99 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
101 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
103 if (Subtarget->is64Bit()) {
104 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
105 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
108 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
109 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
111 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
114 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
116 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
117 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
118 // SSE has no i16 to fp conversion, only i32
119 if (X86ScalarSSEf32) {
120 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
121 // f32 and f64 cases are Legal, f80 case is not
122 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
125 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
128 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
129 // are Legal, f80 is custom lowered.
130 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
131 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
133 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
135 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
136 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
138 if (X86ScalarSSEf32) {
139 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
140 // f32 and f64 cases are Legal, f80 case is not
141 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
144 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
147 // Handle FP_TO_UINT by promoting the destination to a larger signed
149 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
151 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
153 if (Subtarget->is64Bit()) {
154 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
155 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
157 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
158 // Expand FP_TO_UINT into a select.
159 // FIXME: We would like to use a Custom expander here eventually to do
160 // the optimal thing for SSE vs. the default expansion in the legalizer.
161 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
163 // With SSE3 we can use fisttpll to convert to a signed i64.
164 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
167 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
168 if (!X86ScalarSSEf64) {
169 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
170 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
173 // Scalar integer divide and remainder are lowered to use operations that
174 // produce two results, to match the available instructions. This exposes
175 // the two-result form to trivial CSE, which is able to combine x/y and x%y
176 // into a single instruction.
178 // Scalar integer multiply-high is also lowered to use two-result
179 // operations, to match the available instructions. However, plain multiply
180 // (low) operations are left as Legal, as there are single-result
181 // instructions for this in x86. Using the two-result multiply instructions
182 // when both high and low results are needed must be arranged by dagcombine.
183 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
184 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
185 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
187 setOperationAction(ISD::SREM , MVT::i8 , Expand);
188 setOperationAction(ISD::UREM , MVT::i8 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
193 setOperationAction(ISD::SREM , MVT::i16 , Expand);
194 setOperationAction(ISD::UREM , MVT::i16 , Expand);
195 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
196 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
197 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
199 setOperationAction(ISD::SREM , MVT::i32 , Expand);
200 setOperationAction(ISD::UREM , MVT::i32 , Expand);
201 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
202 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
203 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
205 setOperationAction(ISD::SREM , MVT::i64 , Expand);
206 setOperationAction(ISD::UREM , MVT::i64 , Expand);
208 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
209 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
210 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
211 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
212 if (Subtarget->is64Bit())
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
217 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FREM , MVT::f80 , Expand);
221 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
229 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
230 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
231 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
238 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
239 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
241 // These should be promoted to a larger select which is supported.
242 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
243 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
244 // X86 wants to expand cmov itself.
245 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
246 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
249 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
252 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
258 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
260 // X86 ret instruction may pop stack.
261 setOperationAction(ISD::RET , MVT::Other, Custom);
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 if (Subtarget->is64Bit())
270 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
272 if (Subtarget->is64Bit()) {
273 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
274 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
275 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
276 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
278 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
281 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
284 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
285 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
288 if (Subtarget->hasSSE1())
289 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
291 if (!Subtarget->hasSSE2())
292 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
294 // Expand certain atomics
295 setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
296 setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
298 setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
300 setOperationAction(ISD::ATOMIC_LOAD_SUB_8, MVT::i8, Expand);
301 setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Expand);
302 setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Expand);
303 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Expand);
305 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
306 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
307 // FIXME - use subtarget debug flags
308 if (!Subtarget->isTargetDarwin() &&
309 !Subtarget->isTargetELF() &&
310 !Subtarget->isTargetCygMing()) {
311 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
312 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
315 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
316 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
317 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
318 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
319 if (Subtarget->is64Bit()) {
320 setExceptionPointerRegister(X86::RAX);
321 setExceptionSelectorRegister(X86::RDX);
323 setExceptionPointerRegister(X86::EAX);
324 setExceptionSelectorRegister(X86::EDX);
326 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
327 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
329 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
331 setOperationAction(ISD::TRAP, MVT::Other, Legal);
333 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
334 setOperationAction(ISD::VASTART , MVT::Other, Custom);
335 setOperationAction(ISD::VAEND , MVT::Other, Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::VAARG , MVT::Other, Custom);
338 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
340 setOperationAction(ISD::VAARG , MVT::Other, Expand);
341 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
344 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
345 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
346 if (Subtarget->is64Bit())
347 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
348 if (Subtarget->isTargetCygMing())
349 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
351 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
353 if (X86ScalarSSEf64) {
354 // f32 and f64 use SSE.
355 // Set up the FP register classes.
356 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
359 // Use ANDPD to simulate FABS.
360 setOperationAction(ISD::FABS , MVT::f64, Custom);
361 setOperationAction(ISD::FABS , MVT::f32, Custom);
363 // Use XORP to simulate FNEG.
364 setOperationAction(ISD::FNEG , MVT::f64, Custom);
365 setOperationAction(ISD::FNEG , MVT::f32, Custom);
367 // Use ANDPD and ORPD to simulate FCOPYSIGN.
368 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
369 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
371 // We don't support sin/cos/fmod
372 setOperationAction(ISD::FSIN , MVT::f64, Expand);
373 setOperationAction(ISD::FCOS , MVT::f64, Expand);
374 setOperationAction(ISD::FSIN , MVT::f32, Expand);
375 setOperationAction(ISD::FCOS , MVT::f32, Expand);
377 // Expand FP immediates into loads from the stack, except for the special
379 addLegalFPImmediate(APFloat(+0.0)); // xorpd
380 addLegalFPImmediate(APFloat(+0.0f)); // xorps
382 // Floating truncations from f80 and extensions to f80 go through memory.
383 // If optimizing, we lie about this though and handle it in
384 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
386 setConvertAction(MVT::f32, MVT::f80, Expand);
387 setConvertAction(MVT::f64, MVT::f80, Expand);
388 setConvertAction(MVT::f80, MVT::f32, Expand);
389 setConvertAction(MVT::f80, MVT::f64, Expand);
391 } else if (X86ScalarSSEf32) {
392 // Use SSE for f32, x87 for f64.
393 // Set up the FP register classes.
394 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
395 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
397 // Use ANDPS to simulate FABS.
398 setOperationAction(ISD::FABS , MVT::f32, Custom);
400 // Use XORP to simulate FNEG.
401 setOperationAction(ISD::FNEG , MVT::f32, Custom);
403 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
405 // Use ANDPS and ORPS to simulate FCOPYSIGN.
406 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
407 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
409 // We don't support sin/cos/fmod
410 setOperationAction(ISD::FSIN , MVT::f32, Expand);
411 setOperationAction(ISD::FCOS , MVT::f32, Expand);
413 // Special cases we handle for FP constants.
414 addLegalFPImmediate(APFloat(+0.0f)); // xorps
415 addLegalFPImmediate(APFloat(+0.0)); // FLD0
416 addLegalFPImmediate(APFloat(+1.0)); // FLD1
417 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
418 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
420 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
421 // this though and handle it in InstructionSelectPreprocess so that
422 // dagcombine2 can hack on these.
424 setConvertAction(MVT::f32, MVT::f64, Expand);
425 setConvertAction(MVT::f32, MVT::f80, Expand);
426 setConvertAction(MVT::f80, MVT::f32, Expand);
427 setConvertAction(MVT::f64, MVT::f32, Expand);
428 // And x87->x87 truncations also.
429 setConvertAction(MVT::f80, MVT::f64, Expand);
433 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
434 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
437 // f32 and f64 in x87.
438 // Set up the FP register classes.
439 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
440 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
442 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
443 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
444 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
445 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
447 // Floating truncations go through memory. If optimizing, we lie about
448 // this though and handle it in InstructionSelectPreprocess so that
449 // dagcombine2 can hack on these.
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 setConvertAction(MVT::f80, MVT::f64, Expand);
457 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
458 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
460 addLegalFPImmediate(APFloat(+0.0)); // FLD0
461 addLegalFPImmediate(APFloat(+1.0)); // FLD1
462 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
463 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
464 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
465 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
466 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
467 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
470 // Long double always uses X87.
471 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
472 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
473 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
475 APFloat TmpFlt(+0.0);
476 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
477 addLegalFPImmediate(TmpFlt); // FLD0
479 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
480 APFloat TmpFlt2(+1.0);
481 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
482 addLegalFPImmediate(TmpFlt2); // FLD1
483 TmpFlt2.changeSign();
484 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
488 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
489 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
492 // Always use a library call for pow.
493 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
494 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
495 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
497 setOperationAction(ISD::FLOG, MVT::f32, Expand);
498 setOperationAction(ISD::FLOG, MVT::f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::f80, Expand);
500 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
501 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
502 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
503 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
504 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
505 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
506 setOperationAction(ISD::FEXP, MVT::f32, Expand);
507 setOperationAction(ISD::FEXP, MVT::f64, Expand);
508 setOperationAction(ISD::FEXP, MVT::f80, Expand);
509 setOperationAction(ISD::FEXP2, MVT::f32, Expand);
510 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
511 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
513 // First set operation action for all vector types to expand. Then we
514 // will selectively turn on ones that can be effectively codegen'd.
515 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
516 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
517 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
532 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
562 if (Subtarget->hasMMX()) {
563 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
564 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
565 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
566 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
567 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
569 // FIXME: add MMX packed arithmetics
571 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
572 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
573 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
574 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
576 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
577 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
578 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
579 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
581 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
582 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
584 setOperationAction(ISD::AND, MVT::v8i8, Promote);
585 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
586 setOperationAction(ISD::AND, MVT::v4i16, Promote);
587 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
588 setOperationAction(ISD::AND, MVT::v2i32, Promote);
589 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
590 setOperationAction(ISD::AND, MVT::v1i64, Legal);
592 setOperationAction(ISD::OR, MVT::v8i8, Promote);
593 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
594 setOperationAction(ISD::OR, MVT::v4i16, Promote);
595 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
596 setOperationAction(ISD::OR, MVT::v2i32, Promote);
597 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
598 setOperationAction(ISD::OR, MVT::v1i64, Legal);
600 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
601 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
602 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
603 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
604 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
605 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
606 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
608 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
609 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
610 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
611 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
612 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
613 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
614 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
615 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
616 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
620 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
621 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
622 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
624 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
625 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
626 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
627 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
630 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
634 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
637 if (Subtarget->hasSSE1()) {
638 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
640 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
641 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
642 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
643 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
644 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
645 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
646 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
650 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
651 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
654 if (Subtarget->hasSSE2()) {
655 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
656 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
657 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
658 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
659 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
661 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
662 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
663 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
664 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
665 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
666 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
667 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
668 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
669 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
670 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
671 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
672 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
673 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
674 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
675 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
678 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
682 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
684 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
686 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
688 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
689 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
690 MVT VT = (MVT::SimpleValueType)i;
691 // Do not attempt to custom lower non-power-of-2 vectors
692 if (!isPowerOf2_32(VT.getVectorNumElements()))
694 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
695 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
698 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
699 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
700 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
701 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
704 if (Subtarget->is64Bit()) {
705 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
706 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
709 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
710 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
711 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
712 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
713 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
714 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
715 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
716 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
717 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
718 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
719 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
720 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
725 // Custom lower v2i64 and v2f64 selects.
726 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
727 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
728 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
729 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
733 if (Subtarget->hasSSE41()) {
734 // FIXME: Do we need to handle scalar-to-vector here?
735 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
736 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
738 // i8 and i16 vectors are custom , because the source register and source
739 // source memory operand types are not the same width. f32 vectors are
740 // custom since the immediate controlling the insert encodes additional
742 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
743 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
744 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
745 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
750 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
752 if (Subtarget->is64Bit()) {
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
758 if (Subtarget->hasSSE42()) {
759 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
762 // We want to custom lower some of our intrinsics.
763 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
765 // We have target-specific dag combine patterns for the following nodes:
766 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
767 setTargetDAGCombine(ISD::BUILD_VECTOR);
768 setTargetDAGCombine(ISD::SELECT);
769 setTargetDAGCombine(ISD::STORE);
771 computeRegisterProperties();
773 // FIXME: These should be based on subtarget info. Plus, the values should
774 // be smaller when we are in optimizing for size mode.
775 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
776 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
777 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
778 allowUnalignedMemoryAccesses = true; // x86 supports it!
779 setPrefLoopAlignment(16);
783 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
788 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
789 /// the desired ByVal argument alignment.
790 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
793 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
794 if (VTy->getBitWidth() == 128)
796 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
797 unsigned EltAlign = 0;
798 getMaxByValAlign(ATy->getElementType(), EltAlign);
799 if (EltAlign > MaxAlign)
801 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
802 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
803 unsigned EltAlign = 0;
804 getMaxByValAlign(STy->getElementType(i), EltAlign);
805 if (EltAlign > MaxAlign)
814 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
815 /// function arguments in the caller parameter area. For X86, aggregates
816 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
817 /// are at 4-byte boundaries.
818 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
819 if (Subtarget->is64Bit()) {
820 // Max of 8 and alignment of type.
821 unsigned TyAlign = TD->getABITypeAlignment(Ty);
828 if (Subtarget->hasSSE1())
829 getMaxByValAlign(Ty, Align);
833 /// getOptimalMemOpType - Returns the target specific optimal type for load
834 /// and store operations as a result of memset, memcpy, and memmove
835 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
838 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
839 bool isSrcConst, bool isSrcStr) const {
840 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
842 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
844 if (Subtarget->is64Bit() && Size >= 8)
850 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
852 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
853 SelectionDAG &DAG) const {
854 if (usesGlobalOffsetTable())
855 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
856 if (!Subtarget->isPICStyleRIPRel())
857 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
861 //===----------------------------------------------------------------------===//
862 // Return Value Calling Convention Implementation
863 //===----------------------------------------------------------------------===//
865 #include "X86GenCallingConv.inc"
867 /// LowerRET - Lower an ISD::RET node.
868 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
869 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
871 SmallVector<CCValAssign, 16> RVLocs;
872 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
873 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
874 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
875 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
877 // If this is the first return lowered for this function, add the regs to the
878 // liveout set for the function.
879 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
880 for (unsigned i = 0; i != RVLocs.size(); ++i)
881 if (RVLocs[i].isRegLoc())
882 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
884 SDValue Chain = Op.getOperand(0);
886 // Handle tail call return.
887 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
888 if (Chain.getOpcode() == X86ISD::TAILCALL) {
889 SDValue TailCall = Chain;
890 SDValue TargetAddress = TailCall.getOperand(1);
891 SDValue StackAdjustment = TailCall.getOperand(2);
892 assert(((TargetAddress.getOpcode() == ISD::Register &&
893 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
894 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
895 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
896 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
897 "Expecting an global address, external symbol, or register");
898 assert(StackAdjustment.getOpcode() == ISD::Constant &&
899 "Expecting a const value");
901 SmallVector<SDValue,8> Operands;
902 Operands.push_back(Chain.getOperand(0));
903 Operands.push_back(TargetAddress);
904 Operands.push_back(StackAdjustment);
905 // Copy registers used by the call. Last operand is a flag so it is not
907 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
908 Operands.push_back(Chain.getOperand(i));
910 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
917 SmallVector<SDValue, 6> RetOps;
918 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
919 // Operand #1 = Bytes To Pop
920 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
922 // Copy the result values into the output registers.
923 for (unsigned i = 0; i != RVLocs.size(); ++i) {
924 CCValAssign &VA = RVLocs[i];
925 assert(VA.isRegLoc() && "Can only return in registers!");
926 SDValue ValToCopy = Op.getOperand(i*2+1);
928 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
929 // the RET instruction and handled by the FP Stackifier.
930 if (RVLocs[i].getLocReg() == X86::ST0 ||
931 RVLocs[i].getLocReg() == X86::ST1) {
932 // If this is a copy from an xmm register to ST(0), use an FPExtend to
933 // change the value to the FP stack register class.
934 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
935 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
936 RetOps.push_back(ValToCopy);
937 // Don't emit a copytoreg.
941 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
942 Flag = Chain.getValue(1);
945 // The x86-64 ABI for returning structs by value requires that we copy
946 // the sret argument into %rax for the return. We saved the argument into
947 // a virtual register in the entry block, so now we copy the value out
949 if (Subtarget->is64Bit() &&
950 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
951 MachineFunction &MF = DAG.getMachineFunction();
952 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
953 unsigned Reg = FuncInfo->getSRetReturnReg();
955 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
956 FuncInfo->setSRetReturnReg(Reg);
958 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
960 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
961 Flag = Chain.getValue(1);
964 RetOps[0] = Chain; // Update chain.
966 // Add the flag if we have it.
968 RetOps.push_back(Flag);
970 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
974 /// LowerCallResult - Lower the result values of an ISD::CALL into the
975 /// appropriate copies out of appropriate physical registers. This assumes that
976 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
977 /// being lowered. The returns a SDNode with the same number of values as the
979 SDNode *X86TargetLowering::
980 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
981 unsigned CallingConv, SelectionDAG &DAG) {
983 // Assign locations to each value returned by this call.
984 SmallVector<CCValAssign, 16> RVLocs;
985 bool isVarArg = TheCall->isVarArg();
986 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
987 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
989 SmallVector<SDValue, 8> ResultVals;
991 // Copy all of the result registers out of their specified physreg.
992 for (unsigned i = 0; i != RVLocs.size(); ++i) {
993 MVT CopyVT = RVLocs[i].getValVT();
995 // If this is a call to a function that returns an fp value on the floating
996 // point stack, but where we prefer to use the value in xmm registers, copy
997 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
998 if ((RVLocs[i].getLocReg() == X86::ST0 ||
999 RVLocs[i].getLocReg() == X86::ST1) &&
1000 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1004 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1005 CopyVT, InFlag).getValue(1);
1006 SDValue Val = Chain.getValue(0);
1007 InFlag = Chain.getValue(2);
1009 if (CopyVT != RVLocs[i].getValVT()) {
1010 // Round the F80 the right size, which also moves to the appropriate xmm
1012 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1013 // This truncation won't change the value.
1014 DAG.getIntPtrConstant(1));
1017 ResultVals.push_back(Val);
1020 // Merge everything together with a MERGE_VALUES node.
1021 ResultVals.push_back(Chain);
1022 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1023 ResultVals.size()).getNode();
1027 //===----------------------------------------------------------------------===//
1028 // C & StdCall & Fast Calling Convention implementation
1029 //===----------------------------------------------------------------------===//
1030 // StdCall calling convention seems to be standard for many Windows' API
1031 // routines and around. It differs from C calling convention just a little:
1032 // callee should clean up the stack, not caller. Symbols should be also
1033 // decorated in some fancy way :) It doesn't support any vector arguments.
1034 // For info on fast calling convention see Fast Calling Convention (tail call)
1035 // implementation LowerX86_32FastCCCallTo.
1037 /// AddLiveIn - This helper function adds the specified physical register to the
1038 /// MachineFunction as a live in value. It also creates a corresponding virtual
1039 /// register for it.
1040 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1041 const TargetRegisterClass *RC) {
1042 assert(RC->contains(PReg) && "Not the correct regclass!");
1043 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1044 MF.getRegInfo().addLiveIn(PReg, VReg);
1048 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1050 static bool CallIsStructReturn(CallSDNode *TheCall) {
1051 unsigned NumOps = TheCall->getNumArgs();
1055 return TheCall->getArgFlags(0).isSRet();
1058 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1059 /// return semantics.
1060 static bool ArgsAreStructReturn(SDValue Op) {
1061 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1065 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1068 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1069 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1071 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1075 switch (CallingConv) {
1078 case CallingConv::X86_StdCall:
1079 return !Subtarget->is64Bit();
1080 case CallingConv::X86_FastCall:
1081 return !Subtarget->is64Bit();
1082 case CallingConv::Fast:
1083 return PerformTailCallOpt;
1087 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1088 /// given CallingConvention value.
1089 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1090 if (Subtarget->is64Bit()) {
1091 if (Subtarget->isTargetWin64())
1092 return CC_X86_Win64_C;
1093 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1094 return CC_X86_64_TailCall;
1099 if (CC == CallingConv::X86_FastCall)
1100 return CC_X86_32_FastCall;
1101 else if (CC == CallingConv::Fast)
1102 return CC_X86_32_FastCC;
1107 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1108 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1110 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1111 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1112 if (CC == CallingConv::X86_FastCall)
1114 else if (CC == CallingConv::X86_StdCall)
1120 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1121 /// in a register before calling.
1122 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1123 return !IsTailCall && !Is64Bit &&
1124 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1125 Subtarget->isPICStyleGOT();
1128 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1129 /// address to be loaded in a register.
1131 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1132 return !Is64Bit && IsTailCall &&
1133 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1134 Subtarget->isPICStyleGOT();
1137 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1138 /// by "Src" to address "Dst" with size and alignment information specified by
1139 /// the specific parameter attribute. The copy will be passed as a byval
1140 /// function parameter.
1142 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1143 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1144 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1145 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1146 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1149 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1150 const CCValAssign &VA,
1151 MachineFrameInfo *MFI,
1153 SDValue Root, unsigned i) {
1154 // Create the nodes corresponding to a load from this parameter slot.
1155 ISD::ArgFlagsTy Flags =
1156 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1157 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1158 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1160 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1161 // changed with more analysis.
1162 // In case of tail call optimization mark all arguments mutable. Since they
1163 // could be overwritten by lowering of arguments in case of a tail call.
1164 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1165 VA.getLocMemOffset(), isImmutable);
1166 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1167 if (Flags.isByVal())
1169 return DAG.getLoad(VA.getValVT(), Root, FIN,
1170 PseudoSourceValue::getFixedStack(FI), 0);
1174 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1175 MachineFunction &MF = DAG.getMachineFunction();
1176 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1178 const Function* Fn = MF.getFunction();
1179 if (Fn->hasExternalLinkage() &&
1180 Subtarget->isTargetCygMing() &&
1181 Fn->getName() == "main")
1182 FuncInfo->setForceFramePointer(true);
1184 // Decorate the function name.
1185 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1187 MachineFrameInfo *MFI = MF.getFrameInfo();
1188 SDValue Root = Op.getOperand(0);
1189 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1190 unsigned CC = MF.getFunction()->getCallingConv();
1191 bool Is64Bit = Subtarget->is64Bit();
1192 bool IsWin64 = Subtarget->isTargetWin64();
1194 assert(!(isVarArg && CC == CallingConv::Fast) &&
1195 "Var args not supported with calling convention fastcc");
1197 // Assign locations to all of the incoming arguments.
1198 SmallVector<CCValAssign, 16> ArgLocs;
1199 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1200 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1202 SmallVector<SDValue, 8> ArgValues;
1203 unsigned LastVal = ~0U;
1204 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1205 CCValAssign &VA = ArgLocs[i];
1206 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1208 assert(VA.getValNo() != LastVal &&
1209 "Don't support value assigned to multiple locs yet");
1210 LastVal = VA.getValNo();
1212 if (VA.isRegLoc()) {
1213 MVT RegVT = VA.getLocVT();
1214 TargetRegisterClass *RC;
1215 if (RegVT == MVT::i32)
1216 RC = X86::GR32RegisterClass;
1217 else if (Is64Bit && RegVT == MVT::i64)
1218 RC = X86::GR64RegisterClass;
1219 else if (RegVT == MVT::f32)
1220 RC = X86::FR32RegisterClass;
1221 else if (RegVT == MVT::f64)
1222 RC = X86::FR64RegisterClass;
1223 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1224 RC = X86::VR128RegisterClass;
1225 else if (RegVT.isVector()) {
1226 assert(RegVT.getSizeInBits() == 64);
1228 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1230 // Darwin calling convention passes MMX values in either GPRs or
1231 // XMMs in x86-64. Other targets pass them in memory.
1232 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1233 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1236 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1241 assert(0 && "Unknown argument type!");
1244 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1245 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1247 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1248 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1250 if (VA.getLocInfo() == CCValAssign::SExt)
1251 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1252 DAG.getValueType(VA.getValVT()));
1253 else if (VA.getLocInfo() == CCValAssign::ZExt)
1254 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1255 DAG.getValueType(VA.getValVT()));
1257 if (VA.getLocInfo() != CCValAssign::Full)
1258 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1260 // Handle MMX values passed in GPRs.
1261 if (Is64Bit && RegVT != VA.getLocVT()) {
1262 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1263 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1264 else if (RC == X86::VR128RegisterClass) {
1265 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1266 DAG.getConstant(0, MVT::i64));
1267 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1271 ArgValues.push_back(ArgValue);
1273 assert(VA.isMemLoc());
1274 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1278 // The x86-64 ABI for returning structs by value requires that we copy
1279 // the sret argument into %rax for the return. Save the argument into
1280 // a virtual register so that we can access it from the return points.
1281 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1282 MachineFunction &MF = DAG.getMachineFunction();
1283 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1284 unsigned Reg = FuncInfo->getSRetReturnReg();
1286 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1287 FuncInfo->setSRetReturnReg(Reg);
1289 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1290 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1293 unsigned StackSize = CCInfo.getNextStackOffset();
1294 // align stack specially for tail calls
1295 if (PerformTailCallOpt && CC == CallingConv::Fast)
1296 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1298 // If the function takes variable number of arguments, make a frame index for
1299 // the start of the first vararg value... for expansion of llvm.va_start.
1301 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1302 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1305 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1307 // FIXME: We should really autogenerate these arrays
1308 static const unsigned GPR64ArgRegsWin64[] = {
1309 X86::RCX, X86::RDX, X86::R8, X86::R9
1311 static const unsigned XMMArgRegsWin64[] = {
1312 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1314 static const unsigned GPR64ArgRegs64Bit[] = {
1315 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1317 static const unsigned XMMArgRegs64Bit[] = {
1318 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1319 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1321 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1324 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1325 GPR64ArgRegs = GPR64ArgRegsWin64;
1326 XMMArgRegs = XMMArgRegsWin64;
1328 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1329 GPR64ArgRegs = GPR64ArgRegs64Bit;
1330 XMMArgRegs = XMMArgRegs64Bit;
1332 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1334 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1337 // For X86-64, if there are vararg parameters that are passed via
1338 // registers, then we must store them to their spots on the stack so they
1339 // may be loaded by deferencing the result of va_next.
1340 VarArgsGPOffset = NumIntRegs * 8;
1341 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1342 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1343 TotalNumXMMRegs * 16, 16);
1345 // Store the integer parameter registers.
1346 SmallVector<SDValue, 8> MemOps;
1347 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1348 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1349 DAG.getIntPtrConstant(VarArgsGPOffset));
1350 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1351 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1352 X86::GR64RegisterClass);
1353 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1355 DAG.getStore(Val.getValue(1), Val, FIN,
1356 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1357 MemOps.push_back(Store);
1358 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1359 DAG.getIntPtrConstant(8));
1362 // Now store the XMM (fp + vector) parameter registers.
1363 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1364 DAG.getIntPtrConstant(VarArgsFPOffset));
1365 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1366 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1367 X86::VR128RegisterClass);
1368 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1370 DAG.getStore(Val.getValue(1), Val, FIN,
1371 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1372 MemOps.push_back(Store);
1373 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1374 DAG.getIntPtrConstant(16));
1376 if (!MemOps.empty())
1377 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1378 &MemOps[0], MemOps.size());
1382 ArgValues.push_back(Root);
1384 // Some CCs need callee pop.
1385 if (IsCalleePop(isVarArg, CC)) {
1386 BytesToPopOnReturn = StackSize; // Callee pops everything.
1387 BytesCallerReserves = 0;
1389 BytesToPopOnReturn = 0; // Callee pops nothing.
1390 // If this is an sret function, the return should pop the hidden pointer.
1391 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1392 BytesToPopOnReturn = 4;
1393 BytesCallerReserves = StackSize;
1397 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1398 if (CC == CallingConv::X86_FastCall)
1399 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1402 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1404 // Return the new list of results.
1405 return DAG.getMergeValues(Op.getNode()->getVTList(), &ArgValues[0],
1406 ArgValues.size()).getValue(Op.getResNo());
1410 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1411 const SDValue &StackPtr,
1412 const CCValAssign &VA,
1414 SDValue Arg, ISD::ArgFlagsTy Flags) {
1415 unsigned LocMemOffset = VA.getLocMemOffset();
1416 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1418 if (Flags.isByVal()) {
1419 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1421 return DAG.getStore(Chain, Arg, PtrOff,
1422 PseudoSourceValue::getStack(), LocMemOffset);
1425 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1426 /// optimization is performed and it is required.
1428 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1429 SDValue &OutRetAddr,
1434 if (!IsTailCall || FPDiff==0) return Chain;
1436 // Adjust the Return address stack slot.
1437 MVT VT = getPointerTy();
1438 OutRetAddr = getReturnAddressFrameIndex(DAG);
1439 // Load the "old" Return address.
1440 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1441 return SDValue(OutRetAddr.getNode(), 1);
1444 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1445 /// optimization is performed and it is required (FPDiff!=0).
1447 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1448 SDValue Chain, SDValue RetAddrFrIdx,
1449 bool Is64Bit, int FPDiff) {
1450 // Store the return address to the appropriate stack slot.
1451 if (!FPDiff) return Chain;
1452 // Calculate the new stack slot for the return address.
1453 int SlotSize = Is64Bit ? 8 : 4;
1454 int NewReturnAddrFI =
1455 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1456 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1457 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1458 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1459 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1463 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1464 MachineFunction &MF = DAG.getMachineFunction();
1465 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1466 SDValue Chain = TheCall->getChain();
1467 unsigned CC = TheCall->getCallingConv();
1468 bool isVarArg = TheCall->isVarArg();
1469 bool IsTailCall = TheCall->isTailCall() &&
1470 CC == CallingConv::Fast && PerformTailCallOpt;
1471 SDValue Callee = TheCall->getCallee();
1472 bool Is64Bit = Subtarget->is64Bit();
1473 bool IsStructRet = CallIsStructReturn(TheCall);
1475 assert(!(isVarArg && CC == CallingConv::Fast) &&
1476 "Var args not supported with calling convention fastcc");
1478 // Analyze operands of the call, assigning locations to each operand.
1479 SmallVector<CCValAssign, 16> ArgLocs;
1480 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1481 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1483 // Get a count of how many bytes are to be pushed on the stack.
1484 unsigned NumBytes = CCInfo.getNextStackOffset();
1485 if (PerformTailCallOpt && CC == CallingConv::Fast)
1486 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1490 // Lower arguments at fp - stackoffset + fpdiff.
1491 unsigned NumBytesCallerPushed =
1492 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1493 FPDiff = NumBytesCallerPushed - NumBytes;
1495 // Set the delta of movement of the returnaddr stackslot.
1496 // But only set if delta is greater than previous delta.
1497 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1498 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1501 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1503 SDValue RetAddrFrIdx;
1504 // Load return adress for tail calls.
1505 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1508 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1509 SmallVector<SDValue, 8> MemOpChains;
1512 // Walk the register/memloc assignments, inserting copies/loads. In the case
1513 // of tail call optimization arguments are handle later.
1514 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515 CCValAssign &VA = ArgLocs[i];
1516 SDValue Arg = TheCall->getArg(i);
1517 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1518 bool isByVal = Flags.isByVal();
1520 // Promote the value if needed.
1521 switch (VA.getLocInfo()) {
1522 default: assert(0 && "Unknown loc info!");
1523 case CCValAssign::Full: break;
1524 case CCValAssign::SExt:
1525 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1527 case CCValAssign::ZExt:
1528 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1530 case CCValAssign::AExt:
1531 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1535 if (VA.isRegLoc()) {
1537 MVT RegVT = VA.getLocVT();
1538 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1539 switch (VA.getLocReg()) {
1542 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1544 // Special case: passing MMX values in GPR registers.
1545 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1548 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1549 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1550 // Special case: passing MMX values in XMM registers.
1551 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1552 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1553 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1554 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1555 getMOVLMask(2, DAG));
1560 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1562 if (!IsTailCall || (IsTailCall && isByVal)) {
1563 assert(VA.isMemLoc());
1564 if (StackPtr.getNode() == 0)
1565 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1567 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1568 Chain, Arg, Flags));
1573 if (!MemOpChains.empty())
1574 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1575 &MemOpChains[0], MemOpChains.size());
1577 // Build a sequence of copy-to-reg nodes chained together with token chain
1578 // and flag operands which copy the outgoing args into registers.
1580 // Tail call byval lowering might overwrite argument registers so in case of
1581 // tail call optimization the copies to registers are lowered later.
1583 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1584 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1586 InFlag = Chain.getValue(1);
1589 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1591 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1592 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1593 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1595 InFlag = Chain.getValue(1);
1597 // If we are tail calling and generating PIC/GOT style code load the address
1598 // of the callee into ecx. The value in ecx is used as target of the tail
1599 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1600 // calls on PIC/GOT architectures. Normally we would just put the address of
1601 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1602 // restored (since ebx is callee saved) before jumping to the target@PLT.
1603 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1604 // Note: The actual moving to ecx is done further down.
1605 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1606 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1607 !G->getGlobal()->hasProtectedVisibility())
1608 Callee = LowerGlobalAddress(Callee, DAG);
1609 else if (isa<ExternalSymbolSDNode>(Callee))
1610 Callee = LowerExternalSymbol(Callee,DAG);
1613 if (Is64Bit && isVarArg) {
1614 // From AMD64 ABI document:
1615 // For calls that may call functions that use varargs or stdargs
1616 // (prototype-less calls or calls to functions containing ellipsis (...) in
1617 // the declaration) %al is used as hidden argument to specify the number
1618 // of SSE registers used. The contents of %al do not need to match exactly
1619 // the number of registers, but must be an ubound on the number of SSE
1620 // registers used and is in the range 0 - 8 inclusive.
1622 // FIXME: Verify this on Win64
1623 // Count the number of XMM registers allocated.
1624 static const unsigned XMMArgRegs[] = {
1625 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1626 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1628 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1630 Chain = DAG.getCopyToReg(Chain, X86::AL,
1631 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1632 InFlag = Chain.getValue(1);
1636 // For tail calls lower the arguments to the 'real' stack slot.
1638 SmallVector<SDValue, 8> MemOpChains2;
1641 // Do not flag preceeding copytoreg stuff together with the following stuff.
1643 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1644 CCValAssign &VA = ArgLocs[i];
1645 if (!VA.isRegLoc()) {
1646 assert(VA.isMemLoc());
1647 SDValue Arg = TheCall->getArg(i);
1648 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1649 // Create frame index.
1650 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1651 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1652 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1653 FIN = DAG.getFrameIndex(FI, getPointerTy());
1655 if (Flags.isByVal()) {
1656 // Copy relative to framepointer.
1657 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1658 if (StackPtr.getNode() == 0)
1659 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1660 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1662 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1665 // Store relative to framepointer.
1666 MemOpChains2.push_back(
1667 DAG.getStore(Chain, Arg, FIN,
1668 PseudoSourceValue::getFixedStack(FI), 0));
1673 if (!MemOpChains2.empty())
1674 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1675 &MemOpChains2[0], MemOpChains2.size());
1677 // Copy arguments to their registers.
1678 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1679 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1681 InFlag = Chain.getValue(1);
1685 // Store the return address to the appropriate stack slot.
1686 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1690 // If the callee is a GlobalAddress node (quite common, every direct call is)
1691 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1692 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1693 // We should use extra load for direct calls to dllimported functions in
1695 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1696 getTargetMachine(), true))
1697 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1698 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1699 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1700 } else if (IsTailCall) {
1701 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1703 Chain = DAG.getCopyToReg(Chain,
1704 DAG.getRegister(Opc, getPointerTy()),
1706 Callee = DAG.getRegister(Opc, getPointerTy());
1707 // Add register as live out.
1708 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1711 // Returns a chain & a flag for retval copy to use.
1712 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1713 SmallVector<SDValue, 8> Ops;
1716 Ops.push_back(Chain);
1717 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1718 Ops.push_back(DAG.getIntPtrConstant(0));
1719 if (InFlag.getNode())
1720 Ops.push_back(InFlag);
1721 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1722 InFlag = Chain.getValue(1);
1724 // Returns a chain & a flag for retval copy to use.
1725 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1729 Ops.push_back(Chain);
1730 Ops.push_back(Callee);
1733 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1735 // Add argument registers to the end of the list so that they are known live
1737 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1738 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1739 RegsToPass[i].second.getValueType()));
1741 // Add an implicit use GOT pointer in EBX.
1742 if (!IsTailCall && !Is64Bit &&
1743 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1744 Subtarget->isPICStyleGOT())
1745 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1747 // Add an implicit use of AL for x86 vararg functions.
1748 if (Is64Bit && isVarArg)
1749 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1751 if (InFlag.getNode())
1752 Ops.push_back(InFlag);
1755 assert(InFlag.getNode() &&
1756 "Flag must be set. Depend on flag being set in LowerRET");
1757 Chain = DAG.getNode(X86ISD::TAILCALL,
1758 TheCall->getVTList(), &Ops[0], Ops.size());
1760 return SDValue(Chain.getNode(), Op.getResNo());
1763 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1764 InFlag = Chain.getValue(1);
1766 // Create the CALLSEQ_END node.
1767 unsigned NumBytesForCalleeToPush;
1768 if (IsCalleePop(isVarArg, CC))
1769 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1770 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1771 // If this is is a call to a struct-return function, the callee
1772 // pops the hidden struct pointer, so we have to push it back.
1773 // This is common for Darwin/X86, Linux & Mingw32 targets.
1774 NumBytesForCalleeToPush = 4;
1776 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1778 // Returns a flag for retval copy to use.
1779 Chain = DAG.getCALLSEQ_END(Chain,
1780 DAG.getIntPtrConstant(NumBytes),
1781 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1783 InFlag = Chain.getValue(1);
1785 // Handle result values, copying them out of physregs into vregs that we
1787 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1792 //===----------------------------------------------------------------------===//
1793 // Fast Calling Convention (tail call) implementation
1794 //===----------------------------------------------------------------------===//
1796 // Like std call, callee cleans arguments, convention except that ECX is
1797 // reserved for storing the tail called function address. Only 2 registers are
1798 // free for argument passing (inreg). Tail call optimization is performed
1800 // * tailcallopt is enabled
1801 // * caller/callee are fastcc
1802 // On X86_64 architecture with GOT-style position independent code only local
1803 // (within module) calls are supported at the moment.
1804 // To keep the stack aligned according to platform abi the function
1805 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1806 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1807 // If a tail called function callee has more arguments than the caller the
1808 // caller needs to make sure that there is room to move the RETADDR to. This is
1809 // achieved by reserving an area the size of the argument delta right after the
1810 // original REtADDR, but before the saved framepointer or the spilled registers
1811 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1823 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1824 /// for a 16 byte align requirement.
1825 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1826 SelectionDAG& DAG) {
1827 MachineFunction &MF = DAG.getMachineFunction();
1828 const TargetMachine &TM = MF.getTarget();
1829 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1830 unsigned StackAlignment = TFI.getStackAlignment();
1831 uint64_t AlignMask = StackAlignment - 1;
1832 int64_t Offset = StackSize;
1833 uint64_t SlotSize = TD->getPointerSize();
1834 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1835 // Number smaller than 12 so just add the difference.
1836 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1838 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1839 Offset = ((~AlignMask) & Offset) + StackAlignment +
1840 (StackAlignment-SlotSize);
1845 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1846 /// following the call is a return. A function is eligible if caller/callee
1847 /// calling conventions match, currently only fastcc supports tail calls, and
1848 /// the function CALL is immediatly followed by a RET.
1849 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1851 SelectionDAG& DAG) const {
1852 if (!PerformTailCallOpt)
1855 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1856 MachineFunction &MF = DAG.getMachineFunction();
1857 unsigned CallerCC = MF.getFunction()->getCallingConv();
1858 unsigned CalleeCC= TheCall->getCallingConv();
1859 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1860 SDValue Callee = TheCall->getCallee();
1861 // On x86/32Bit PIC/GOT tail calls are supported.
1862 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1863 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1866 // Can only do local tail calls (in same module, hidden or protected) on
1867 // x86_64 PIC/GOT at the moment.
1868 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1869 return G->getGlobal()->hasHiddenVisibility()
1870 || G->getGlobal()->hasProtectedVisibility();
1878 X86TargetLowering::createFastISel(MachineFunction &mf,
1879 DenseMap<const Value *, unsigned> &vm,
1880 DenseMap<const BasicBlock *,
1881 MachineBasicBlock *> &bm,
1882 DenseMap<const AllocaInst *, int> &am) {
1884 return X86::createFastISel(mf, vm, bm, am);
1888 //===----------------------------------------------------------------------===//
1889 // Other Lowering Hooks
1890 //===----------------------------------------------------------------------===//
1893 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1894 MachineFunction &MF = DAG.getMachineFunction();
1895 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1896 int ReturnAddrIndex = FuncInfo->getRAIndex();
1897 uint64_t SlotSize = TD->getPointerSize();
1899 if (ReturnAddrIndex == 0) {
1900 // Set up a frame object for the return address.
1901 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1902 FuncInfo->setRAIndex(ReturnAddrIndex);
1905 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1909 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1910 /// specific condition code. It returns a false if it cannot do a direct
1911 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1913 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1914 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1915 SelectionDAG &DAG) {
1916 X86CC = X86::COND_INVALID;
1918 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1919 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1920 // X > -1 -> X == 0, jump !sign.
1921 RHS = DAG.getConstant(0, RHS.getValueType());
1922 X86CC = X86::COND_NS;
1924 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1925 // X < 0 -> X == 0, jump on sign.
1926 X86CC = X86::COND_S;
1928 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1930 RHS = DAG.getConstant(0, RHS.getValueType());
1931 X86CC = X86::COND_LE;
1936 switch (SetCCOpcode) {
1938 case ISD::SETEQ: X86CC = X86::COND_E; break;
1939 case ISD::SETGT: X86CC = X86::COND_G; break;
1940 case ISD::SETGE: X86CC = X86::COND_GE; break;
1941 case ISD::SETLT: X86CC = X86::COND_L; break;
1942 case ISD::SETLE: X86CC = X86::COND_LE; break;
1943 case ISD::SETNE: X86CC = X86::COND_NE; break;
1944 case ISD::SETULT: X86CC = X86::COND_B; break;
1945 case ISD::SETUGT: X86CC = X86::COND_A; break;
1946 case ISD::SETULE: X86CC = X86::COND_BE; break;
1947 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1950 // First determine if it requires or is profitable to flip the operands.
1952 switch (SetCCOpcode) {
1962 // If LHS is a foldable load, but RHS is not, flip the condition.
1964 (ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1965 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1966 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1970 std::swap(LHS, RHS);
1972 // On a floating point condition, the flags are set as follows:
1974 // 0 | 0 | 0 | X > Y
1975 // 0 | 0 | 1 | X < Y
1976 // 1 | 0 | 0 | X == Y
1977 // 1 | 1 | 1 | unordered
1978 switch (SetCCOpcode) {
1982 X86CC = X86::COND_E;
1984 case ISD::SETOLT: // flipped
1987 X86CC = X86::COND_A;
1989 case ISD::SETOLE: // flipped
1992 X86CC = X86::COND_AE;
1994 case ISD::SETUGT: // flipped
1997 X86CC = X86::COND_B;
1999 case ISD::SETUGE: // flipped
2002 X86CC = X86::COND_BE;
2006 X86CC = X86::COND_NE;
2009 X86CC = X86::COND_P;
2012 X86CC = X86::COND_NP;
2017 return X86CC != X86::COND_INVALID;
2020 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2021 /// code. Current x86 isa includes the following FP cmov instructions:
2022 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2023 static bool hasFPCMov(unsigned X86CC) {
2039 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2040 /// true if Op is undef or if its value falls within the specified range (L, H].
2041 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2042 if (Op.getOpcode() == ISD::UNDEF)
2045 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2046 return (Val >= Low && Val < Hi);
2049 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2050 /// true if Op is undef or if its value equal to the specified value.
2051 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2052 if (Op.getOpcode() == ISD::UNDEF)
2054 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2057 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2058 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2059 bool X86::isPSHUFDMask(SDNode *N) {
2060 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2062 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2065 // Check if the value doesn't reference the second vector.
2066 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2067 SDValue Arg = N->getOperand(i);
2068 if (Arg.getOpcode() == ISD::UNDEF) continue;
2069 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2070 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2077 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2078 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2079 bool X86::isPSHUFHWMask(SDNode *N) {
2080 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2082 if (N->getNumOperands() != 8)
2085 // Lower quadword copied in order.
2086 for (unsigned i = 0; i != 4; ++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() != i)
2094 // Upper quadword shuffled.
2095 for (unsigned i = 4; i != 8; ++i) {
2096 SDValue Arg = N->getOperand(i);
2097 if (Arg.getOpcode() == ISD::UNDEF) continue;
2098 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2099 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2100 if (Val < 4 || Val > 7)
2107 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2108 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2109 bool X86::isPSHUFLWMask(SDNode *N) {
2110 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2112 if (N->getNumOperands() != 8)
2115 // Upper quadword copied in order.
2116 for (unsigned i = 4; i != 8; ++i)
2117 if (!isUndefOrEqual(N->getOperand(i), i))
2120 // Lower quadword shuffled.
2121 for (unsigned i = 0; i != 4; ++i)
2122 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2128 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2129 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2130 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2131 if (NumElems != 2 && NumElems != 4) return false;
2133 unsigned Half = NumElems / 2;
2134 for (unsigned i = 0; i < Half; ++i)
2135 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2137 for (unsigned i = Half; i < NumElems; ++i)
2138 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2144 bool X86::isSHUFPMask(SDNode *N) {
2145 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2146 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2149 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2150 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2151 /// half elements to come from vector 1 (which would equal the dest.) and
2152 /// the upper half to come from vector 2.
2153 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2154 if (NumOps != 2 && NumOps != 4) return false;
2156 unsigned Half = NumOps / 2;
2157 for (unsigned i = 0; i < Half; ++i)
2158 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2160 for (unsigned i = Half; i < NumOps; ++i)
2161 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2166 static bool isCommutedSHUFP(SDNode *N) {
2167 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2168 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2171 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2172 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2173 bool X86::isMOVHLPSMask(SDNode *N) {
2174 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2176 if (N->getNumOperands() != 4)
2179 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2180 return isUndefOrEqual(N->getOperand(0), 6) &&
2181 isUndefOrEqual(N->getOperand(1), 7) &&
2182 isUndefOrEqual(N->getOperand(2), 2) &&
2183 isUndefOrEqual(N->getOperand(3), 3);
2186 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2187 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2189 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2190 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2192 if (N->getNumOperands() != 4)
2195 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2196 return isUndefOrEqual(N->getOperand(0), 2) &&
2197 isUndefOrEqual(N->getOperand(1), 3) &&
2198 isUndefOrEqual(N->getOperand(2), 2) &&
2199 isUndefOrEqual(N->getOperand(3), 3);
2202 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2203 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2204 bool X86::isMOVLPMask(SDNode *N) {
2205 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207 unsigned NumElems = N->getNumOperands();
2208 if (NumElems != 2 && NumElems != 4)
2211 for (unsigned i = 0; i < NumElems/2; ++i)
2212 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2215 for (unsigned i = NumElems/2; i < NumElems; ++i)
2216 if (!isUndefOrEqual(N->getOperand(i), i))
2222 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2223 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2225 bool X86::isMOVHPMask(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228 unsigned NumElems = N->getNumOperands();
2229 if (NumElems != 2 && NumElems != 4)
2232 for (unsigned i = 0; i < NumElems/2; ++i)
2233 if (!isUndefOrEqual(N->getOperand(i), i))
2236 for (unsigned i = 0; i < NumElems/2; ++i) {
2237 SDValue Arg = N->getOperand(i + NumElems/2);
2238 if (!isUndefOrEqual(Arg, i + NumElems))
2245 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2246 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2247 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2248 bool V2IsSplat = false) {
2249 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2252 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2253 SDValue BitI = Elts[i];
2254 SDValue BitI1 = Elts[i+1];
2255 if (!isUndefOrEqual(BitI, j))
2258 if (isUndefOrEqual(BitI1, NumElts))
2261 if (!isUndefOrEqual(BitI1, j + NumElts))
2269 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2270 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2271 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2274 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2275 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2276 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2277 bool V2IsSplat = false) {
2278 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2281 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2282 SDValue BitI = Elts[i];
2283 SDValue BitI1 = Elts[i+1];
2284 if (!isUndefOrEqual(BitI, j + NumElts/2))
2287 if (isUndefOrEqual(BitI1, NumElts))
2290 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2298 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2299 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2300 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2303 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2304 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2306 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2307 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2309 unsigned NumElems = N->getNumOperands();
2310 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2313 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2314 SDValue BitI = N->getOperand(i);
2315 SDValue BitI1 = N->getOperand(i+1);
2317 if (!isUndefOrEqual(BitI, j))
2319 if (!isUndefOrEqual(BitI1, j))
2326 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2327 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2329 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2330 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2332 unsigned NumElems = N->getNumOperands();
2333 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2336 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2337 SDValue BitI = N->getOperand(i);
2338 SDValue BitI1 = N->getOperand(i + 1);
2340 if (!isUndefOrEqual(BitI, j))
2342 if (!isUndefOrEqual(BitI1, j))
2349 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2350 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2351 /// MOVSD, and MOVD, i.e. setting the lowest element.
2352 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2353 if (NumElts != 2 && NumElts != 4)
2356 if (!isUndefOrEqual(Elts[0], NumElts))
2359 for (unsigned i = 1; i < NumElts; ++i) {
2360 if (!isUndefOrEqual(Elts[i], i))
2367 bool X86::isMOVLMask(SDNode *N) {
2368 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2369 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2372 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2373 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2374 /// element of vector 2 and the other elements to come from vector 1 in order.
2375 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2376 bool V2IsSplat = false,
2377 bool V2IsUndef = false) {
2378 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2381 if (!isUndefOrEqual(Ops[0], 0))
2384 for (unsigned i = 1; i < NumOps; ++i) {
2385 SDValue Arg = Ops[i];
2386 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2387 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2388 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2395 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2396 bool V2IsUndef = false) {
2397 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2398 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2399 V2IsSplat, V2IsUndef);
2402 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2403 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2404 bool X86::isMOVSHDUPMask(SDNode *N) {
2405 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2407 if (N->getNumOperands() != 4)
2410 // Expect 1, 1, 3, 3
2411 for (unsigned i = 0; i < 2; ++i) {
2412 SDValue Arg = N->getOperand(i);
2413 if (Arg.getOpcode() == ISD::UNDEF) continue;
2414 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2415 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2416 if (Val != 1) return false;
2420 for (unsigned i = 2; i < 4; ++i) {
2421 SDValue Arg = N->getOperand(i);
2422 if (Arg.getOpcode() == ISD::UNDEF) continue;
2423 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2424 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2425 if (Val != 3) return false;
2429 // Don't use movshdup if it can be done with a shufps.
2433 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2434 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2435 bool X86::isMOVSLDUPMask(SDNode *N) {
2436 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2438 if (N->getNumOperands() != 4)
2441 // Expect 0, 0, 2, 2
2442 for (unsigned i = 0; i < 2; ++i) {
2443 SDValue Arg = N->getOperand(i);
2444 if (Arg.getOpcode() == ISD::UNDEF) continue;
2445 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2446 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2447 if (Val != 0) return false;
2451 for (unsigned i = 2; i < 4; ++i) {
2452 SDValue Arg = N->getOperand(i);
2453 if (Arg.getOpcode() == ISD::UNDEF) continue;
2454 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2455 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2456 if (Val != 2) return false;
2460 // Don't use movshdup if it can be done with a shufps.
2464 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2465 /// specifies a identity operation on the LHS or RHS.
2466 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2467 unsigned NumElems = N->getNumOperands();
2468 for (unsigned i = 0; i < NumElems; ++i)
2469 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2474 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2475 /// a splat of a single element.
2476 static bool isSplatMask(SDNode *N) {
2477 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2479 // This is a splat operation if each element of the permute is the same, and
2480 // if the value doesn't reference the second vector.
2481 unsigned NumElems = N->getNumOperands();
2482 SDValue ElementBase;
2484 for (; i != NumElems; ++i) {
2485 SDValue Elt = N->getOperand(i);
2486 if (isa<ConstantSDNode>(Elt)) {
2492 if (!ElementBase.getNode())
2495 for (; i != NumElems; ++i) {
2496 SDValue Arg = N->getOperand(i);
2497 if (Arg.getOpcode() == ISD::UNDEF) continue;
2498 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2499 if (Arg != ElementBase) return false;
2502 // Make sure it is a splat of the first vector operand.
2503 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2506 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2507 /// a splat of a single element and it's a 2 or 4 element mask.
2508 bool X86::isSplatMask(SDNode *N) {
2509 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2511 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2512 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2514 return ::isSplatMask(N);
2517 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2518 /// specifies a splat of zero element.
2519 bool X86::isSplatLoMask(SDNode *N) {
2520 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2522 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2523 if (!isUndefOrEqual(N->getOperand(i), 0))
2528 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2529 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2531 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2532 unsigned NumOperands = N->getNumOperands();
2533 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2535 for (unsigned i = 0; i < NumOperands; ++i) {
2537 SDValue Arg = N->getOperand(NumOperands-i-1);
2538 if (Arg.getOpcode() != ISD::UNDEF)
2539 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2540 if (Val >= NumOperands) Val -= NumOperands;
2542 if (i != NumOperands - 1)
2549 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2550 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2552 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2554 // 8 nodes, but we only care about the last 4.
2555 for (unsigned i = 7; i >= 4; --i) {
2557 SDValue Arg = N->getOperand(i);
2558 if (Arg.getOpcode() != ISD::UNDEF)
2559 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2568 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2569 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2571 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2573 // 8 nodes, but we only care about the first 4.
2574 for (int i = 3; i >= 0; --i) {
2576 SDValue Arg = N->getOperand(i);
2577 if (Arg.getOpcode() != ISD::UNDEF)
2578 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2587 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2588 /// specifies a 8 element shuffle that can be broken into a pair of
2589 /// PSHUFHW and PSHUFLW.
2590 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2591 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2593 if (N->getNumOperands() != 8)
2596 // Lower quadword shuffled.
2597 for (unsigned i = 0; i != 4; ++i) {
2598 SDValue Arg = N->getOperand(i);
2599 if (Arg.getOpcode() == ISD::UNDEF) continue;
2600 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2601 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2606 // Upper quadword shuffled.
2607 for (unsigned i = 4; i != 8; ++i) {
2608 SDValue Arg = N->getOperand(i);
2609 if (Arg.getOpcode() == ISD::UNDEF) continue;
2610 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2611 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2612 if (Val < 4 || Val > 7)
2619 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2620 /// values in ther permute mask.
2621 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2622 SDValue &V2, SDValue &Mask,
2623 SelectionDAG &DAG) {
2624 MVT VT = Op.getValueType();
2625 MVT MaskVT = Mask.getValueType();
2626 MVT EltVT = MaskVT.getVectorElementType();
2627 unsigned NumElems = Mask.getNumOperands();
2628 SmallVector<SDValue, 8> MaskVec;
2630 for (unsigned i = 0; i != NumElems; ++i) {
2631 SDValue Arg = Mask.getOperand(i);
2632 if (Arg.getOpcode() == ISD::UNDEF) {
2633 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2636 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2637 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2639 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2641 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2645 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2646 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2649 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2650 /// the two vector operands have swapped position.
2652 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2653 MVT MaskVT = Mask.getValueType();
2654 MVT EltVT = MaskVT.getVectorElementType();
2655 unsigned NumElems = Mask.getNumOperands();
2656 SmallVector<SDValue, 8> MaskVec;
2657 for (unsigned i = 0; i != NumElems; ++i) {
2658 SDValue Arg = Mask.getOperand(i);
2659 if (Arg.getOpcode() == ISD::UNDEF) {
2660 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2663 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2664 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2666 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2668 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2670 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2674 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2675 /// match movhlps. The lower half elements should come from upper half of
2676 /// V1 (and in order), and the upper half elements should come from the upper
2677 /// half of V2 (and in order).
2678 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2679 unsigned NumElems = Mask->getNumOperands();
2682 for (unsigned i = 0, e = 2; i != e; ++i)
2683 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2685 for (unsigned i = 2; i != 4; ++i)
2686 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2691 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2692 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2694 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2695 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2696 N = N->getOperand(0).getNode();
2697 if (ISD::isNON_EXTLoad(N)) {
2699 *LD = cast<LoadSDNode>(N);
2706 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2707 /// match movlp{s|d}. The lower half elements should come from lower half of
2708 /// V1 (and in order), and the upper half elements should come from the upper
2709 /// half of V2 (and in order). And since V1 will become the source of the
2710 /// MOVLP, it must be either a vector load or a scalar load to vector.
2711 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2712 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2714 // Is V2 is a vector load, don't do this transformation. We will try to use
2715 // load folding shufps op.
2716 if (ISD::isNON_EXTLoad(V2))
2719 unsigned NumElems = Mask->getNumOperands();
2720 if (NumElems != 2 && NumElems != 4)
2722 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2723 if (!isUndefOrEqual(Mask->getOperand(i), i))
2725 for (unsigned i = NumElems/2; i != NumElems; ++i)
2726 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2731 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2733 static bool isSplatVector(SDNode *N) {
2734 if (N->getOpcode() != ISD::BUILD_VECTOR)
2737 SDValue SplatValue = N->getOperand(0);
2738 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2739 if (N->getOperand(i) != SplatValue)
2744 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2746 static bool isUndefShuffle(SDNode *N) {
2747 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2750 SDValue V1 = N->getOperand(0);
2751 SDValue V2 = N->getOperand(1);
2752 SDValue Mask = N->getOperand(2);
2753 unsigned NumElems = Mask.getNumOperands();
2754 for (unsigned i = 0; i != NumElems; ++i) {
2755 SDValue Arg = Mask.getOperand(i);
2756 if (Arg.getOpcode() != ISD::UNDEF) {
2757 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2758 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2760 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2767 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2769 static inline bool isZeroNode(SDValue Elt) {
2770 return ((isa<ConstantSDNode>(Elt) &&
2771 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2772 (isa<ConstantFPSDNode>(Elt) &&
2773 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2776 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2777 /// to an zero vector.
2778 static bool isZeroShuffle(SDNode *N) {
2779 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2782 SDValue V1 = N->getOperand(0);
2783 SDValue V2 = N->getOperand(1);
2784 SDValue Mask = N->getOperand(2);
2785 unsigned NumElems = Mask.getNumOperands();
2786 for (unsigned i = 0; i != NumElems; ++i) {
2787 SDValue Arg = Mask.getOperand(i);
2788 if (Arg.getOpcode() == ISD::UNDEF)
2791 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2792 if (Idx < NumElems) {
2793 unsigned Opc = V1.getNode()->getOpcode();
2794 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2796 if (Opc != ISD::BUILD_VECTOR ||
2797 !isZeroNode(V1.getNode()->getOperand(Idx)))
2799 } else if (Idx >= NumElems) {
2800 unsigned Opc = V2.getNode()->getOpcode();
2801 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2803 if (Opc != ISD::BUILD_VECTOR ||
2804 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2811 /// getZeroVector - Returns a vector of specified type with all zero elements.
2813 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2814 assert(VT.isVector() && "Expected a vector type");
2816 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2817 // type. This ensures they get CSE'd.
2819 if (VT.getSizeInBits() == 64) { // MMX
2820 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2821 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2822 } else if (HasSSE2) { // SSE2
2823 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2824 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2826 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2827 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2829 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2832 /// getOnesVector - Returns a vector of specified type with all bits set.
2834 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2835 assert(VT.isVector() && "Expected a vector type");
2837 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2838 // type. This ensures they get CSE'd.
2839 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2841 if (VT.getSizeInBits() == 64) // MMX
2842 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2844 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2845 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2849 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2850 /// that point to V2 points to its first element.
2851 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2852 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2854 bool Changed = false;
2855 SmallVector<SDValue, 8> MaskVec;
2856 unsigned NumElems = Mask.getNumOperands();
2857 for (unsigned i = 0; i != NumElems; ++i) {
2858 SDValue Arg = Mask.getOperand(i);
2859 if (Arg.getOpcode() != ISD::UNDEF) {
2860 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2861 if (Val > NumElems) {
2862 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2866 MaskVec.push_back(Arg);
2870 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2871 &MaskVec[0], MaskVec.size());
2875 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2876 /// operation of specified width.
2877 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2878 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2879 MVT BaseVT = MaskVT.getVectorElementType();
2881 SmallVector<SDValue, 8> MaskVec;
2882 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2883 for (unsigned i = 1; i != NumElems; ++i)
2884 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2885 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2888 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2889 /// of specified width.
2890 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2891 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2892 MVT BaseVT = MaskVT.getVectorElementType();
2893 SmallVector<SDValue, 8> MaskVec;
2894 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2895 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2896 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2898 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2901 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2902 /// of specified width.
2903 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2904 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2905 MVT BaseVT = MaskVT.getVectorElementType();
2906 unsigned Half = NumElems/2;
2907 SmallVector<SDValue, 8> MaskVec;
2908 for (unsigned i = 0; i != Half; ++i) {
2909 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2910 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2912 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2915 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2916 /// element #0 of a vector with the specified index, leaving the rest of the
2917 /// elements in place.
2918 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2919 SelectionDAG &DAG) {
2920 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2921 MVT BaseVT = MaskVT.getVectorElementType();
2922 SmallVector<SDValue, 8> MaskVec;
2923 // Element #0 of the result gets the elt we are replacing.
2924 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2925 for (unsigned i = 1; i != NumElems; ++i)
2926 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2927 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2930 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2931 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2932 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2933 MVT VT = Op.getValueType();
2936 SDValue V1 = Op.getOperand(0);
2937 SDValue Mask = Op.getOperand(2);
2938 unsigned NumElems = Mask.getNumOperands();
2939 // Special handling of v4f32 -> v4i32.
2940 if (VT != MVT::v4f32) {
2941 Mask = getUnpacklMask(NumElems, DAG);
2942 while (NumElems > 4) {
2943 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2946 Mask = getZeroVector(MVT::v4i32, true, DAG);
2949 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2950 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2951 DAG.getNode(ISD::UNDEF, PVT), Mask);
2952 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2955 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2956 /// vector of zero or undef vector. This produces a shuffle where the low
2957 /// element of V2 is swizzled into the zero/undef vector, landing at element
2958 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2959 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2960 bool isZero, bool HasSSE2,
2961 SelectionDAG &DAG) {
2962 MVT VT = V2.getValueType();
2964 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2965 unsigned NumElems = V2.getValueType().getVectorNumElements();
2966 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2967 MVT EVT = MaskVT.getVectorElementType();
2968 SmallVector<SDValue, 16> MaskVec;
2969 for (unsigned i = 0; i != NumElems; ++i)
2970 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2971 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2973 MaskVec.push_back(DAG.getConstant(i, EVT));
2974 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2975 &MaskVec[0], MaskVec.size());
2976 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2979 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2980 /// a shuffle that is zero.
2982 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2983 unsigned NumElems, bool Low,
2984 SelectionDAG &DAG) {
2985 unsigned NumZeros = 0;
2986 for (unsigned i = 0; i < NumElems; ++i) {
2987 unsigned Index = Low ? i : NumElems-i-1;
2988 SDValue Idx = Mask.getOperand(Index);
2989 if (Idx.getOpcode() == ISD::UNDEF) {
2993 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
2994 if (Elt.getNode() && isZeroNode(Elt))
3002 /// isVectorShift - Returns true if the shuffle can be implemented as a
3003 /// logical left or right shift of a vector.
3004 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3005 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3006 unsigned NumElems = Mask.getNumOperands();
3009 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3012 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3017 bool SeenV1 = false;
3018 bool SeenV2 = false;
3019 for (unsigned i = NumZeros; i < NumElems; ++i) {
3020 unsigned Val = isLeft ? (i - NumZeros) : i;
3021 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3022 if (Idx.getOpcode() == ISD::UNDEF)
3024 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3025 if (Index < NumElems)
3034 if (SeenV1 && SeenV2)
3037 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3043 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3045 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3046 unsigned NumNonZero, unsigned NumZero,
3047 SelectionDAG &DAG, TargetLowering &TLI) {
3053 for (unsigned i = 0; i < 16; ++i) {
3054 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3055 if (ThisIsNonZero && First) {
3057 V = getZeroVector(MVT::v8i16, true, DAG);
3059 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3064 SDValue ThisElt(0, 0), LastElt(0, 0);
3065 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3066 if (LastIsNonZero) {
3067 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3069 if (ThisIsNonZero) {
3070 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3071 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3072 ThisElt, DAG.getConstant(8, MVT::i8));
3074 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3078 if (ThisElt.getNode())
3079 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3080 DAG.getIntPtrConstant(i/2));
3084 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3087 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3089 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3090 unsigned NumNonZero, unsigned NumZero,
3091 SelectionDAG &DAG, TargetLowering &TLI) {
3097 for (unsigned i = 0; i < 8; ++i) {
3098 bool isNonZero = (NonZeros & (1 << i)) != 0;
3102 V = getZeroVector(MVT::v8i16, true, DAG);
3104 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3107 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3108 DAG.getIntPtrConstant(i));
3115 /// getVShift - Return a vector logical shift node.
3117 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3118 unsigned NumBits, SelectionDAG &DAG,
3119 const TargetLowering &TLI) {
3120 bool isMMX = VT.getSizeInBits() == 64;
3121 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3122 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3123 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3124 return DAG.getNode(ISD::BIT_CONVERT, VT,
3125 DAG.getNode(Opc, ShVT, SrcOp,
3126 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3130 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3131 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3132 if (ISD::isBuildVectorAllZeros(Op.getNode())
3133 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3134 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3135 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3136 // eliminated on x86-32 hosts.
3137 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3140 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3141 return getOnesVector(Op.getValueType(), DAG);
3142 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3145 MVT VT = Op.getValueType();
3146 MVT EVT = VT.getVectorElementType();
3147 unsigned EVTBits = EVT.getSizeInBits();
3149 unsigned NumElems = Op.getNumOperands();
3150 unsigned NumZero = 0;
3151 unsigned NumNonZero = 0;
3152 unsigned NonZeros = 0;
3153 bool IsAllConstants = true;
3154 SmallSet<SDValue, 8> Values;
3155 for (unsigned i = 0; i < NumElems; ++i) {
3156 SDValue Elt = Op.getOperand(i);
3157 if (Elt.getOpcode() == ISD::UNDEF)
3160 if (Elt.getOpcode() != ISD::Constant &&
3161 Elt.getOpcode() != ISD::ConstantFP)
3162 IsAllConstants = false;
3163 if (isZeroNode(Elt))
3166 NonZeros |= (1 << i);
3171 if (NumNonZero == 0) {
3172 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3173 return DAG.getNode(ISD::UNDEF, VT);
3176 // Special case for single non-zero, non-undef, element.
3177 if (NumNonZero == 1 && NumElems <= 4) {
3178 unsigned Idx = CountTrailingZeros_32(NonZeros);
3179 SDValue Item = Op.getOperand(Idx);
3181 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3182 // the value are obviously zero, truncate the value to i32 and do the
3183 // insertion that way. Only do this if the value is non-constant or if the
3184 // value is a constant being inserted into element 0. It is cheaper to do
3185 // a constant pool load than it is to do a movd + shuffle.
3186 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3187 (!IsAllConstants || Idx == 0)) {
3188 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3189 // Handle MMX and SSE both.
3190 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3191 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3193 // Truncate the value (which may itself be a constant) to i32, and
3194 // convert it to a vector with movd (S2V+shuffle to zero extend).
3195 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3196 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3197 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3198 Subtarget->hasSSE2(), DAG);
3200 // Now we have our 32-bit value zero extended in the low element of
3201 // a vector. If Idx != 0, swizzle it into place.
3204 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3205 getSwapEltZeroMask(VecElts, Idx, DAG)
3207 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3209 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3213 // If we have a constant or non-constant insertion into the low element of
3214 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3215 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3216 // depending on what the source datatype is. Because we can only get here
3217 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3219 // Don't do this for i64 values on x86-32.
3220 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3221 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3222 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3223 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3224 Subtarget->hasSSE2(), DAG);
3227 // Is it a vector logical left shift?
3228 if (NumElems == 2 && Idx == 1 &&
3229 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3230 unsigned NumBits = VT.getSizeInBits();
3231 return getVShift(true, VT,
3232 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3233 NumBits/2, DAG, *this);
3236 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3239 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3240 // is a non-constant being inserted into an element other than the low one,
3241 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3242 // movd/movss) to move this into the low element, then shuffle it into
3244 if (EVTBits == 32) {
3245 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3247 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3248 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3249 Subtarget->hasSSE2(), DAG);
3250 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3251 MVT MaskEVT = MaskVT.getVectorElementType();
3252 SmallVector<SDValue, 8> MaskVec;
3253 for (unsigned i = 0; i < NumElems; i++)
3254 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3255 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3256 &MaskVec[0], MaskVec.size());
3257 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3258 DAG.getNode(ISD::UNDEF, VT), Mask);
3262 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3263 if (Values.size() == 1)
3266 // A vector full of immediates; various special cases are already
3267 // handled, so this is best done with a single constant-pool load.
3271 // Let legalizer expand 2-wide build_vectors.
3272 if (EVTBits == 64) {
3273 if (NumNonZero == 1) {
3274 // One half is zero or undef.
3275 unsigned Idx = CountTrailingZeros_32(NonZeros);
3276 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3277 Op.getOperand(Idx));
3278 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3279 Subtarget->hasSSE2(), DAG);
3284 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3285 if (EVTBits == 8 && NumElems == 16) {
3286 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3288 if (V.getNode()) return V;
3291 if (EVTBits == 16 && NumElems == 8) {
3292 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3294 if (V.getNode()) return V;
3297 // If element VT is == 32 bits, turn it into a number of shuffles.
3298 SmallVector<SDValue, 8> V;
3300 if (NumElems == 4 && NumZero > 0) {
3301 for (unsigned i = 0; i < 4; ++i) {
3302 bool isZero = !(NonZeros & (1 << i));
3304 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3306 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3309 for (unsigned i = 0; i < 2; ++i) {
3310 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3313 V[i] = V[i*2]; // Must be a zero vector.
3316 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3317 getMOVLMask(NumElems, DAG));
3320 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3321 getMOVLMask(NumElems, DAG));
3324 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3325 getUnpacklMask(NumElems, DAG));
3330 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3331 MVT EVT = MaskVT.getVectorElementType();
3332 SmallVector<SDValue, 8> MaskVec;
3333 bool Reverse = (NonZeros & 0x3) == 2;
3334 for (unsigned i = 0; i < 2; ++i)
3336 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3338 MaskVec.push_back(DAG.getConstant(i, EVT));
3339 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3340 for (unsigned i = 0; i < 2; ++i)
3342 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3344 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3345 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3346 &MaskVec[0], MaskVec.size());
3347 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3350 if (Values.size() > 2) {
3351 // Expand into a number of unpckl*.
3353 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3354 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3355 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3356 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3357 for (unsigned i = 0; i < NumElems; ++i)
3358 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3360 while (NumElems != 0) {
3361 for (unsigned i = 0; i < NumElems; ++i)
3362 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3373 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3374 SDValue PermMask, SelectionDAG &DAG,
3375 TargetLowering &TLI) {
3377 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3378 MVT MaskEVT = MaskVT.getVectorElementType();
3379 MVT PtrVT = TLI.getPointerTy();
3380 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3381 PermMask.getNode()->op_end());
3383 // First record which half of which vector the low elements come from.
3384 SmallVector<unsigned, 4> LowQuad(4);
3385 for (unsigned i = 0; i < 4; ++i) {
3386 SDValue Elt = MaskElts[i];
3387 if (Elt.getOpcode() == ISD::UNDEF)
3389 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3390 int QuadIdx = EltIdx / 4;
3394 int BestLowQuad = -1;
3395 unsigned MaxQuad = 1;
3396 for (unsigned i = 0; i < 4; ++i) {
3397 if (LowQuad[i] > MaxQuad) {
3399 MaxQuad = LowQuad[i];
3403 // Record which half of which vector the high elements come from.
3404 SmallVector<unsigned, 4> HighQuad(4);
3405 for (unsigned i = 4; i < 8; ++i) {
3406 SDValue Elt = MaskElts[i];
3407 if (Elt.getOpcode() == ISD::UNDEF)
3409 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3410 int QuadIdx = EltIdx / 4;
3411 ++HighQuad[QuadIdx];
3414 int BestHighQuad = -1;
3416 for (unsigned i = 0; i < 4; ++i) {
3417 if (HighQuad[i] > MaxQuad) {
3419 MaxQuad = HighQuad[i];
3423 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3424 if (BestLowQuad != -1 || BestHighQuad != -1) {
3425 // First sort the 4 chunks in order using shufpd.
3426 SmallVector<SDValue, 8> MaskVec;
3428 if (BestLowQuad != -1)
3429 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3431 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3433 if (BestHighQuad != -1)
3434 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3436 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3438 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3439 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3440 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3441 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3442 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3444 // Now sort high and low parts separately.
3445 BitVector InOrder(8);
3446 if (BestLowQuad != -1) {
3447 // Sort lower half in order using PSHUFLW.
3449 bool AnyOutOrder = false;
3451 for (unsigned i = 0; i != 4; ++i) {
3452 SDValue Elt = MaskElts[i];
3453 if (Elt.getOpcode() == ISD::UNDEF) {
3454 MaskVec.push_back(Elt);
3457 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3461 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3463 // If this element is in the right place after this shuffle, then
3465 if ((int)(EltIdx / 4) == BestLowQuad)
3470 for (unsigned i = 4; i != 8; ++i)
3471 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3472 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3473 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3477 if (BestHighQuad != -1) {
3478 // Sort high half in order using PSHUFHW if possible.
3481 for (unsigned i = 0; i != 4; ++i)
3482 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3484 bool AnyOutOrder = false;
3485 for (unsigned i = 4; i != 8; ++i) {
3486 SDValue Elt = MaskElts[i];
3487 if (Elt.getOpcode() == ISD::UNDEF) {
3488 MaskVec.push_back(Elt);
3491 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3495 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3497 // If this element is in the right place after this shuffle, then
3499 if ((int)(EltIdx / 4) == BestHighQuad)
3505 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3506 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3510 // The other elements are put in the right place using pextrw and pinsrw.
3511 for (unsigned i = 0; i != 8; ++i) {
3514 SDValue Elt = MaskElts[i];
3515 if (Elt.getOpcode() == ISD::UNDEF)
3517 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3518 SDValue ExtOp = (EltIdx < 8)
3519 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3520 DAG.getConstant(EltIdx, PtrVT))
3521 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3522 DAG.getConstant(EltIdx - 8, PtrVT));
3523 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3524 DAG.getConstant(i, PtrVT));
3530 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3531 // few as possible. First, let's find out how many elements are already in the
3533 unsigned V1InOrder = 0;
3534 unsigned V1FromV1 = 0;
3535 unsigned V2InOrder = 0;
3536 unsigned V2FromV2 = 0;
3537 SmallVector<SDValue, 8> V1Elts;
3538 SmallVector<SDValue, 8> V2Elts;
3539 for (unsigned i = 0; i < 8; ++i) {
3540 SDValue Elt = MaskElts[i];
3541 if (Elt.getOpcode() == ISD::UNDEF) {
3542 V1Elts.push_back(Elt);
3543 V2Elts.push_back(Elt);
3548 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3550 V1Elts.push_back(Elt);
3551 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3553 } else if (EltIdx == i+8) {
3554 V1Elts.push_back(Elt);
3555 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3557 } else if (EltIdx < 8) {
3558 V1Elts.push_back(Elt);
3561 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3566 if (V2InOrder > V1InOrder) {
3567 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3569 std::swap(V1Elts, V2Elts);
3570 std::swap(V1FromV1, V2FromV2);
3573 if ((V1FromV1 + V1InOrder) != 8) {
3574 // Some elements are from V2.
3576 // If there are elements that are from V1 but out of place,
3577 // then first sort them in place
3578 SmallVector<SDValue, 8> MaskVec;
3579 for (unsigned i = 0; i < 8; ++i) {
3580 SDValue Elt = V1Elts[i];
3581 if (Elt.getOpcode() == ISD::UNDEF) {
3582 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3585 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3587 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3589 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3591 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3592 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3596 for (unsigned i = 0; i < 8; ++i) {
3597 SDValue Elt = V1Elts[i];
3598 if (Elt.getOpcode() == ISD::UNDEF)
3600 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3603 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3604 DAG.getConstant(EltIdx - 8, PtrVT));
3605 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3606 DAG.getConstant(i, PtrVT));
3610 // All elements are from V1.
3612 for (unsigned i = 0; i < 8; ++i) {
3613 SDValue Elt = V1Elts[i];
3614 if (Elt.getOpcode() == ISD::UNDEF)
3616 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3617 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3618 DAG.getConstant(EltIdx, PtrVT));
3619 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3620 DAG.getConstant(i, PtrVT));
3626 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3627 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3628 /// done when every pair / quad of shuffle mask elements point to elements in
3629 /// the right sequence. e.g.
3630 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3632 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3634 SDValue PermMask, SelectionDAG &DAG,
3635 TargetLowering &TLI) {
3636 unsigned NumElems = PermMask.getNumOperands();
3637 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3638 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3639 MVT MaskEltVT = MaskVT.getVectorElementType();
3641 switch (VT.getSimpleVT()) {
3642 default: assert(false && "Unexpected!");
3643 case MVT::v4f32: NewVT = MVT::v2f64; break;
3644 case MVT::v4i32: NewVT = MVT::v2i64; break;
3645 case MVT::v8i16: NewVT = MVT::v4i32; break;
3646 case MVT::v16i8: NewVT = MVT::v4i32; break;
3649 if (NewWidth == 2) {
3655 unsigned Scale = NumElems / NewWidth;
3656 SmallVector<SDValue, 8> MaskVec;
3657 for (unsigned i = 0; i < NumElems; i += Scale) {
3658 unsigned StartIdx = ~0U;
3659 for (unsigned j = 0; j < Scale; ++j) {
3660 SDValue Elt = PermMask.getOperand(i+j);
3661 if (Elt.getOpcode() == ISD::UNDEF)
3663 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3664 if (StartIdx == ~0U)
3665 StartIdx = EltIdx - (EltIdx % Scale);
3666 if (EltIdx != StartIdx + j)
3669 if (StartIdx == ~0U)
3670 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3672 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3675 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3676 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3677 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3678 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3679 &MaskVec[0], MaskVec.size()));
3682 /// getVZextMovL - Return a zero-extending vector move low node.
3684 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3685 SDValue SrcOp, SelectionDAG &DAG,
3686 const X86Subtarget *Subtarget) {
3687 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3688 LoadSDNode *LD = NULL;
3689 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3690 LD = dyn_cast<LoadSDNode>(SrcOp);
3692 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3694 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3695 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3696 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3697 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3698 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3700 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3701 return DAG.getNode(ISD::BIT_CONVERT, VT,
3702 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3703 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3710 return DAG.getNode(ISD::BIT_CONVERT, VT,
3711 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3712 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3715 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3718 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3719 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3720 MVT MaskVT = PermMask.getValueType();
3721 MVT MaskEVT = MaskVT.getVectorElementType();
3722 SmallVector<std::pair<int, int>, 8> Locs;
3724 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3727 for (unsigned i = 0; i != 4; ++i) {
3728 SDValue Elt = PermMask.getOperand(i);
3729 if (Elt.getOpcode() == ISD::UNDEF) {
3730 Locs[i] = std::make_pair(-1, -1);
3732 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3733 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3735 Locs[i] = std::make_pair(0, NumLo);
3739 Locs[i] = std::make_pair(1, NumHi);
3741 Mask1[2+NumHi] = Elt;
3747 if (NumLo <= 2 && NumHi <= 2) {
3748 // If no more than two elements come from either vector. This can be
3749 // implemented with two shuffles. First shuffle gather the elements.
3750 // The second shuffle, which takes the first shuffle as both of its
3751 // vector operands, put the elements into the right order.
3752 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3753 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3754 &Mask1[0], Mask1.size()));
3756 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3757 for (unsigned i = 0; i != 4; ++i) {
3758 if (Locs[i].first == -1)
3761 unsigned Idx = (i < 2) ? 0 : 4;
3762 Idx += Locs[i].first * 2 + Locs[i].second;
3763 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3767 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3768 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3769 &Mask2[0], Mask2.size()));
3770 } else if (NumLo == 3 || NumHi == 3) {
3771 // Otherwise, we must have three elements from one vector, call it X, and
3772 // one element from the other, call it Y. First, use a shufps to build an
3773 // intermediate vector with the one element from Y and the element from X
3774 // that will be in the same half in the final destination (the indexes don't
3775 // matter). Then, use a shufps to build the final vector, taking the half
3776 // containing the element from Y from the intermediate, and the other half
3779 // Normalize it so the 3 elements come from V1.
3780 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3784 // Find the element from V2.
3786 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3787 SDValue Elt = PermMask.getOperand(HiIndex);
3788 if (Elt.getOpcode() == ISD::UNDEF)
3790 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3795 Mask1[0] = PermMask.getOperand(HiIndex);
3796 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3797 Mask1[2] = PermMask.getOperand(HiIndex^1);
3798 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3799 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3800 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3803 Mask1[0] = PermMask.getOperand(0);
3804 Mask1[1] = PermMask.getOperand(1);
3805 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3806 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3807 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3808 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3810 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3811 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3812 Mask1[2] = PermMask.getOperand(2);
3813 Mask1[3] = PermMask.getOperand(3);
3814 if (Mask1[2].getOpcode() != ISD::UNDEF)
3816 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3818 if (Mask1[3].getOpcode() != ISD::UNDEF)
3820 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3822 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3823 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3827 // Break it into (shuffle shuffle_hi, shuffle_lo).
3829 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3830 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3831 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3832 unsigned MaskIdx = 0;
3835 for (unsigned i = 0; i != 4; ++i) {
3842 SDValue Elt = PermMask.getOperand(i);
3843 if (Elt.getOpcode() == ISD::UNDEF) {
3844 Locs[i] = std::make_pair(-1, -1);
3845 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3846 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3847 (*MaskPtr)[LoIdx] = Elt;
3850 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3851 (*MaskPtr)[HiIdx] = Elt;
3856 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3857 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3858 &LoMask[0], LoMask.size()));
3859 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3860 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3861 &HiMask[0], HiMask.size()));
3862 SmallVector<SDValue, 8> MaskOps;
3863 for (unsigned i = 0; i != 4; ++i) {
3864 if (Locs[i].first == -1) {
3865 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3867 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3868 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3871 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3872 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3873 &MaskOps[0], MaskOps.size()));
3877 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3878 SDValue V1 = Op.getOperand(0);
3879 SDValue V2 = Op.getOperand(1);
3880 SDValue PermMask = Op.getOperand(2);
3881 MVT VT = Op.getValueType();
3882 unsigned NumElems = PermMask.getNumOperands();
3883 bool isMMX = VT.getSizeInBits() == 64;
3884 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3885 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3886 bool V1IsSplat = false;
3887 bool V2IsSplat = false;
3889 if (isUndefShuffle(Op.getNode()))
3890 return DAG.getNode(ISD::UNDEF, VT);
3892 if (isZeroShuffle(Op.getNode()))
3893 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3895 if (isIdentityMask(PermMask.getNode()))
3897 else if (isIdentityMask(PermMask.getNode(), true))
3900 if (isSplatMask(PermMask.getNode())) {
3901 if (isMMX || NumElems < 4) return Op;
3902 // Promote it to a v4{if}32 splat.
3903 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3906 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3908 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3909 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3910 if (NewOp.getNode())
3911 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3912 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3913 // FIXME: Figure out a cleaner way to do this.
3914 // Try to make use of movq to zero out the top part.
3915 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3916 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3918 if (NewOp.getNode()) {
3919 SDValue NewV1 = NewOp.getOperand(0);
3920 SDValue NewV2 = NewOp.getOperand(1);
3921 SDValue NewMask = NewOp.getOperand(2);
3922 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
3923 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3924 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3927 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3928 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3930 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
3931 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3936 // Check if this can be converted into a logical shift.
3937 bool isLeft = false;
3940 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3941 if (isShift && ShVal.hasOneUse()) {
3942 // If the shifted value has multiple uses, it may be cheaper to use
3943 // v_set0 + movlhps or movhlps, etc.
3944 MVT EVT = VT.getVectorElementType();
3945 ShAmt *= EVT.getSizeInBits();
3946 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3949 if (X86::isMOVLMask(PermMask.getNode())) {
3952 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3953 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3958 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
3959 X86::isMOVSLDUPMask(PermMask.getNode()) ||
3960 X86::isMOVHLPSMask(PermMask.getNode()) ||
3961 X86::isMOVHPMask(PermMask.getNode()) ||
3962 X86::isMOVLPMask(PermMask.getNode())))
3965 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
3966 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
3967 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3970 // No better options. Use a vshl / vsrl.
3971 MVT EVT = VT.getVectorElementType();
3972 ShAmt *= EVT.getSizeInBits();
3973 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3976 bool Commuted = false;
3977 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3978 // 1,1,1,1 -> v8i16 though.
3979 V1IsSplat = isSplatVector(V1.getNode());
3980 V2IsSplat = isSplatVector(V2.getNode());
3982 // Canonicalize the splat or undef, if present, to be on the RHS.
3983 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3984 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3985 std::swap(V1IsSplat, V2IsSplat);
3986 std::swap(V1IsUndef, V2IsUndef);
3990 // FIXME: Figure out a cleaner way to do this.
3991 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
3992 if (V2IsUndef) return V1;
3993 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3995 // V2 is a splat, so the mask may be malformed. That is, it may point
3996 // to any V2 element. The instruction selectior won't like this. Get
3997 // a corrected mask and commute to form a proper MOVS{S|D}.
3998 SDValue NewMask = getMOVLMask(NumElems, DAG);
3999 if (NewMask.getNode() != PermMask.getNode())
4000 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4005 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4006 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4007 X86::isUNPCKLMask(PermMask.getNode()) ||
4008 X86::isUNPCKHMask(PermMask.getNode()))
4012 // Normalize mask so all entries that point to V2 points to its first
4013 // element then try to match unpck{h|l} again. If match, return a
4014 // new vector_shuffle with the corrected mask.
4015 SDValue NewMask = NormalizeMask(PermMask, DAG);
4016 if (NewMask.getNode() != PermMask.getNode()) {
4017 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4018 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4019 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4020 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4021 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4022 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4027 // Normalize the node to match x86 shuffle ops if needed
4028 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4029 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4032 // Commute is back and try unpck* again.
4033 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4034 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4035 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4036 X86::isUNPCKLMask(PermMask.getNode()) ||
4037 X86::isUNPCKHMask(PermMask.getNode()))
4041 // Try PSHUF* first, then SHUFP*.
4042 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4043 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4044 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4045 if (V2.getOpcode() != ISD::UNDEF)
4046 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4047 DAG.getNode(ISD::UNDEF, VT), PermMask);
4052 if (Subtarget->hasSSE2() &&
4053 (X86::isPSHUFDMask(PermMask.getNode()) ||
4054 X86::isPSHUFHWMask(PermMask.getNode()) ||
4055 X86::isPSHUFLWMask(PermMask.getNode()))) {
4057 if (VT == MVT::v4f32) {
4059 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4060 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4061 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4062 } else if (V2.getOpcode() != ISD::UNDEF)
4063 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4064 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4066 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4070 // Binary or unary shufps.
4071 if (X86::isSHUFPMask(PermMask.getNode()) ||
4072 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4076 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4077 if (VT == MVT::v8i16) {
4078 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4079 if (NewOp.getNode())
4083 // Handle all 4 wide cases with a number of shuffles except for MMX.
4084 if (NumElems == 4 && !isMMX)
4085 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4091 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4092 SelectionDAG &DAG) {
4093 MVT VT = Op.getValueType();
4094 if (VT.getSizeInBits() == 8) {
4095 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4096 Op.getOperand(0), Op.getOperand(1));
4097 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4098 DAG.getValueType(VT));
4099 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4100 } else if (VT.getSizeInBits() == 16) {
4101 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4102 Op.getOperand(0), Op.getOperand(1));
4103 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4104 DAG.getValueType(VT));
4105 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4106 } else if (VT == MVT::f32) {
4107 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4108 // the result back to FR32 register. It's only worth matching if the
4109 // result has a single use which is a store or a bitcast to i32.
4110 if (!Op.hasOneUse())
4112 SDNode *User = *Op.getNode()->use_begin();
4113 if (User->getOpcode() != ISD::STORE &&
4114 (User->getOpcode() != ISD::BIT_CONVERT ||
4115 User->getValueType(0) != MVT::i32))
4117 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4118 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4120 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4127 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4128 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4131 if (Subtarget->hasSSE41()) {
4132 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4137 MVT VT = Op.getValueType();
4138 // TODO: handle v16i8.
4139 if (VT.getSizeInBits() == 16) {
4140 SDValue Vec = Op.getOperand(0);
4141 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4143 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4144 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4145 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4147 // Transform it so it match pextrw which produces a 32-bit result.
4148 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4149 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4150 Op.getOperand(0), Op.getOperand(1));
4151 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4152 DAG.getValueType(VT));
4153 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4154 } else if (VT.getSizeInBits() == 32) {
4155 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4158 // SHUFPS the element to the lowest double word, then movss.
4159 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4160 SmallVector<SDValue, 8> IdxVec;
4162 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4164 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4166 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4168 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4169 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4170 &IdxVec[0], IdxVec.size());
4171 SDValue Vec = Op.getOperand(0);
4172 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4173 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4174 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4175 DAG.getIntPtrConstant(0));
4176 } else if (VT.getSizeInBits() == 64) {
4177 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4178 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4179 // to match extract_elt for f64.
4180 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4184 // UNPCKHPD the element to the lowest double word, then movsd.
4185 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4186 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4187 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4188 SmallVector<SDValue, 8> IdxVec;
4189 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4191 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4192 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4193 &IdxVec[0], IdxVec.size());
4194 SDValue Vec = Op.getOperand(0);
4195 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4196 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4197 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4198 DAG.getIntPtrConstant(0));
4205 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4206 MVT VT = Op.getValueType();
4207 MVT EVT = VT.getVectorElementType();
4209 SDValue N0 = Op.getOperand(0);
4210 SDValue N1 = Op.getOperand(1);
4211 SDValue N2 = Op.getOperand(2);
4213 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4214 isa<ConstantSDNode>(N2)) {
4215 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4217 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4219 if (N1.getValueType() != MVT::i32)
4220 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4221 if (N2.getValueType() != MVT::i32)
4222 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4223 return DAG.getNode(Opc, VT, N0, N1, N2);
4224 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4225 // Bits [7:6] of the constant are the source select. This will always be
4226 // zero here. The DAG Combiner may combine an extract_elt index into these
4227 // bits. For example (insert (extract, 3), 2) could be matched by putting
4228 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4229 // Bits [5:4] of the constant are the destination select. This is the
4230 // value of the incoming immediate.
4231 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4232 // combine either bitwise AND or insert of float 0.0 to set these bits.
4233 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4234 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4240 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4241 MVT VT = Op.getValueType();
4242 MVT EVT = VT.getVectorElementType();
4244 if (Subtarget->hasSSE41())
4245 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4250 SDValue N0 = Op.getOperand(0);
4251 SDValue N1 = Op.getOperand(1);
4252 SDValue N2 = Op.getOperand(2);
4254 if (EVT.getSizeInBits() == 16) {
4255 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4256 // as its second argument.
4257 if (N1.getValueType() != MVT::i32)
4258 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4259 if (N2.getValueType() != MVT::i32)
4260 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4261 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4267 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4268 if (Op.getValueType() == MVT::v2f32)
4269 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4270 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4271 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4272 Op.getOperand(0))));
4274 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4275 MVT VT = MVT::v2i32;
4276 switch (Op.getValueType().getSimpleVT()) {
4283 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4284 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4287 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4288 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4289 // one of the above mentioned nodes. It has to be wrapped because otherwise
4290 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4291 // be used to form addressing mode. These wrapped nodes will be selected
4294 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4295 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4296 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4298 CP->getAlignment());
4299 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4300 // With PIC, the address is actually $g + Offset.
4301 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4302 !Subtarget->isPICStyleRIPRel()) {
4303 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4304 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4312 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4313 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4314 SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4315 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4316 // With PIC, the address is actually $g + Offset.
4317 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4318 !Subtarget->isPICStyleRIPRel()) {
4319 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4320 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4324 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4325 // load the value at address GV, not the value of GV itself. This means that
4326 // the GlobalAddress must be in the base or index register of the address, not
4327 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4328 // The same applies for external symbols during PIC codegen
4329 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4330 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4331 PseudoSourceValue::getGOT(), 0);
4336 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4338 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4341 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4342 DAG.getNode(X86ISD::GlobalBaseReg,
4344 InFlag = Chain.getValue(1);
4346 // emit leal symbol@TLSGD(,%ebx,1), %eax
4347 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4348 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4349 GA->getValueType(0),
4351 SDValue Ops[] = { Chain, TGA, InFlag };
4352 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4353 InFlag = Result.getValue(2);
4354 Chain = Result.getValue(1);
4356 // call ___tls_get_addr. This function receives its argument in
4357 // the register EAX.
4358 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4359 InFlag = Chain.getValue(1);
4361 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4362 SDValue Ops1[] = { Chain,
4363 DAG.getTargetExternalSymbol("___tls_get_addr",
4365 DAG.getRegister(X86::EAX, PtrVT),
4366 DAG.getRegister(X86::EBX, PtrVT),
4368 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4369 InFlag = Chain.getValue(1);
4371 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4374 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4376 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4378 SDValue InFlag, Chain;
4380 // emit leaq symbol@TLSGD(%rip), %rdi
4381 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4382 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4383 GA->getValueType(0),
4385 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4386 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4387 Chain = Result.getValue(1);
4388 InFlag = Result.getValue(2);
4390 // call __tls_get_addr. This function receives its argument in
4391 // the register RDI.
4392 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4393 InFlag = Chain.getValue(1);
4395 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4396 SDValue Ops1[] = { Chain,
4397 DAG.getTargetExternalSymbol("__tls_get_addr",
4399 DAG.getRegister(X86::RDI, PtrVT),
4401 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4402 InFlag = Chain.getValue(1);
4404 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4407 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4408 // "local exec" model.
4409 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4411 // Get the Thread Pointer
4412 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4413 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4415 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4416 GA->getValueType(0),
4418 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4420 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4421 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4422 PseudoSourceValue::getGOT(), 0);
4424 // The address of the thread local variable is the add of the thread
4425 // pointer with the offset of the variable.
4426 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4430 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4431 // TODO: implement the "local dynamic" model
4432 // TODO: implement the "initial exec"model for pic executables
4433 assert(Subtarget->isTargetELF() &&
4434 "TLS not implemented for non-ELF targets");
4435 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4436 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4437 // otherwise use the "Local Exec"TLS Model
4438 if (Subtarget->is64Bit()) {
4439 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4441 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4442 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4444 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4449 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4450 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4451 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4452 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4453 // With PIC, the address is actually $g + Offset.
4454 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4455 !Subtarget->isPICStyleRIPRel()) {
4456 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4457 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4464 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4465 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4466 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4467 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4468 // With PIC, the address is actually $g + Offset.
4469 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4470 !Subtarget->isPICStyleRIPRel()) {
4471 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4472 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4479 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4480 /// take a 2 x i32 value to shift plus a shift amount.
4481 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4482 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4483 MVT VT = Op.getValueType();
4484 unsigned VTBits = VT.getSizeInBits();
4485 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4486 SDValue ShOpLo = Op.getOperand(0);
4487 SDValue ShOpHi = Op.getOperand(1);
4488 SDValue ShAmt = Op.getOperand(2);
4489 SDValue Tmp1 = isSRA ?
4490 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4491 DAG.getConstant(0, VT);
4494 if (Op.getOpcode() == ISD::SHL_PARTS) {
4495 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4496 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4498 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4499 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4502 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4503 DAG.getConstant(VTBits, MVT::i8));
4504 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4505 AndNode, DAG.getConstant(0, MVT::i8));
4508 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4509 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4510 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4512 if (Op.getOpcode() == ISD::SHL_PARTS) {
4513 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4514 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4516 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4517 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4520 SDValue Ops[2] = { Lo, Hi };
4521 return DAG.getMergeValues(Ops, 2);
4524 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4525 MVT SrcVT = Op.getOperand(0).getValueType();
4526 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4527 "Unknown SINT_TO_FP to lower!");
4529 // These are really Legal; caller falls through into that case.
4530 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4532 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4533 Subtarget->is64Bit())
4536 unsigned Size = SrcVT.getSizeInBits()/8;
4537 MachineFunction &MF = DAG.getMachineFunction();
4538 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4539 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4540 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4542 PseudoSourceValue::getFixedStack(SSFI), 0);
4546 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4548 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4550 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4551 SmallVector<SDValue, 8> Ops;
4552 Ops.push_back(Chain);
4553 Ops.push_back(StackSlot);
4554 Ops.push_back(DAG.getValueType(SrcVT));
4555 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4556 Tys, &Ops[0], Ops.size());
4559 Chain = Result.getValue(1);
4560 SDValue InFlag = Result.getValue(2);
4562 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4563 // shouldn't be necessary except that RFP cannot be live across
4564 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4565 MachineFunction &MF = DAG.getMachineFunction();
4566 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4567 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4568 Tys = DAG.getVTList(MVT::Other);
4569 SmallVector<SDValue, 8> Ops;
4570 Ops.push_back(Chain);
4571 Ops.push_back(Result);
4572 Ops.push_back(StackSlot);
4573 Ops.push_back(DAG.getValueType(Op.getValueType()));
4574 Ops.push_back(InFlag);
4575 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4576 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4577 PseudoSourceValue::getFixedStack(SSFI), 0);
4583 std::pair<SDValue,SDValue> X86TargetLowering::
4584 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4585 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4586 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4587 "Unknown FP_TO_SINT to lower!");
4589 // These are really Legal.
4590 if (Op.getValueType() == MVT::i32 &&
4591 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4592 return std::make_pair(SDValue(), SDValue());
4593 if (Subtarget->is64Bit() &&
4594 Op.getValueType() == MVT::i64 &&
4595 Op.getOperand(0).getValueType() != MVT::f80)
4596 return std::make_pair(SDValue(), SDValue());
4598 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4600 MachineFunction &MF = DAG.getMachineFunction();
4601 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4602 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4603 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4605 switch (Op.getValueType().getSimpleVT()) {
4606 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4607 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4608 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4609 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4612 SDValue Chain = DAG.getEntryNode();
4613 SDValue Value = Op.getOperand(0);
4614 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4615 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4616 Chain = DAG.getStore(Chain, Value, StackSlot,
4617 PseudoSourceValue::getFixedStack(SSFI), 0);
4618 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4620 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4622 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4623 Chain = Value.getValue(1);
4624 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4625 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4628 // Build the FP_TO_INT*_IN_MEM
4629 SDValue Ops[] = { Chain, Value, StackSlot };
4630 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4632 return std::make_pair(FIST, StackSlot);
4635 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4636 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4637 SDValue FIST = Vals.first, StackSlot = Vals.second;
4638 if (FIST.getNode() == 0) return SDValue();
4641 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4644 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4645 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4646 SDValue FIST = Vals.first, StackSlot = Vals.second;
4647 if (FIST.getNode() == 0) return 0;
4649 MVT VT = N->getValueType(0);
4651 // Return a load from the stack slot.
4652 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4654 // Use MERGE_VALUES to drop the chain result value and get a node with one
4655 // result. This requires turning off getMergeValues simplification, since
4656 // otherwise it will give us Res back.
4657 return DAG.getMergeValues(&Res, 1, false).getNode();
4660 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4661 MVT VT = Op.getValueType();
4664 EltVT = VT.getVectorElementType();
4665 std::vector<Constant*> CV;
4666 if (EltVT == MVT::f64) {
4667 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4671 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4677 Constant *C = ConstantVector::get(CV);
4678 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4679 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4680 PseudoSourceValue::getConstantPool(), 0,
4682 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4685 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4686 MVT VT = Op.getValueType();
4688 unsigned EltNum = 1;
4689 if (VT.isVector()) {
4690 EltVT = VT.getVectorElementType();
4691 EltNum = VT.getVectorNumElements();
4693 std::vector<Constant*> CV;
4694 if (EltVT == MVT::f64) {
4695 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4699 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4705 Constant *C = ConstantVector::get(CV);
4706 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4707 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4708 PseudoSourceValue::getConstantPool(), 0,
4710 if (VT.isVector()) {
4711 return DAG.getNode(ISD::BIT_CONVERT, VT,
4712 DAG.getNode(ISD::XOR, MVT::v2i64,
4713 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4714 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4716 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4720 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4721 SDValue Op0 = Op.getOperand(0);
4722 SDValue Op1 = Op.getOperand(1);
4723 MVT VT = Op.getValueType();
4724 MVT SrcVT = Op1.getValueType();
4726 // If second operand is smaller, extend it first.
4727 if (SrcVT.bitsLT(VT)) {
4728 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4731 // And if it is bigger, shrink it first.
4732 if (SrcVT.bitsGT(VT)) {
4733 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4737 // At this point the operands and the result should have the same
4738 // type, and that won't be f80 since that is not custom lowered.
4740 // First get the sign bit of second operand.
4741 std::vector<Constant*> CV;
4742 if (SrcVT == MVT::f64) {
4743 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4744 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4746 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4747 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4748 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4749 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4751 Constant *C = ConstantVector::get(CV);
4752 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4753 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4754 PseudoSourceValue::getConstantPool(), 0,
4756 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4758 // Shift sign bit right or left if the two operands have different types.
4759 if (SrcVT.bitsGT(VT)) {
4760 // Op0 is MVT::f32, Op1 is MVT::f64.
4761 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4762 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4763 DAG.getConstant(32, MVT::i32));
4764 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4765 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4766 DAG.getIntPtrConstant(0));
4769 // Clear first operand sign bit.
4771 if (VT == MVT::f64) {
4772 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4773 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4775 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4776 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4777 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4778 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4780 C = ConstantVector::get(CV);
4781 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4782 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4783 PseudoSourceValue::getConstantPool(), 0,
4785 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4787 // Or the value with the sign bit.
4788 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4791 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4792 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4794 SDValue Op0 = Op.getOperand(0);
4795 SDValue Op1 = Op.getOperand(1);
4796 SDValue CC = Op.getOperand(2);
4797 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4798 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4801 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4803 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4804 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4805 DAG.getConstant(X86CC, MVT::i8), Cond);
4808 assert(isFP && "Illegal integer SetCC!");
4810 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4811 switch (SetCCOpcode) {
4812 default: assert(false && "Illegal floating point SetCC!");
4813 case ISD::SETOEQ: { // !PF & ZF
4814 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4815 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4816 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4817 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4818 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4820 case ISD::SETUNE: { // PF | !ZF
4821 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4822 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4823 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4824 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4825 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4830 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4832 SDValue Op0 = Op.getOperand(0);
4833 SDValue Op1 = Op.getOperand(1);
4834 SDValue CC = Op.getOperand(2);
4835 MVT VT = Op.getValueType();
4836 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4837 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4841 MVT VT0 = Op0.getValueType();
4842 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4843 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4846 switch (SetCCOpcode) {
4849 case ISD::SETEQ: SSECC = 0; break;
4851 case ISD::SETGT: Swap = true; // Fallthrough
4853 case ISD::SETOLT: SSECC = 1; break;
4855 case ISD::SETGE: Swap = true; // Fallthrough
4857 case ISD::SETOLE: SSECC = 2; break;
4858 case ISD::SETUO: SSECC = 3; break;
4860 case ISD::SETNE: SSECC = 4; break;
4861 case ISD::SETULE: Swap = true;
4862 case ISD::SETUGE: SSECC = 5; break;
4863 case ISD::SETULT: Swap = true;
4864 case ISD::SETUGT: SSECC = 6; break;
4865 case ISD::SETO: SSECC = 7; break;
4868 std::swap(Op0, Op1);
4870 // In the two special cases we can't handle, emit two comparisons.
4872 if (SetCCOpcode == ISD::SETUEQ) {
4874 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4875 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4876 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4878 else if (SetCCOpcode == ISD::SETONE) {
4880 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4881 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4882 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4884 assert(0 && "Illegal FP comparison");
4886 // Handle all other FP comparisons here.
4887 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4890 // We are handling one of the integer comparisons here. Since SSE only has
4891 // GT and EQ comparisons for integer, swapping operands and multiple
4892 // operations may be required for some comparisons.
4893 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4894 bool Swap = false, Invert = false, FlipSigns = false;
4896 switch (VT.getSimpleVT()) {
4898 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4899 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4900 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4901 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4904 switch (SetCCOpcode) {
4906 case ISD::SETNE: Invert = true;
4907 case ISD::SETEQ: Opc = EQOpc; break;
4908 case ISD::SETLT: Swap = true;
4909 case ISD::SETGT: Opc = GTOpc; break;
4910 case ISD::SETGE: Swap = true;
4911 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
4912 case ISD::SETULT: Swap = true;
4913 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4914 case ISD::SETUGE: Swap = true;
4915 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4918 std::swap(Op0, Op1);
4920 // Since SSE has no unsigned integer comparisons, we need to flip the sign
4921 // bits of the inputs before performing those operations.
4923 MVT EltVT = VT.getVectorElementType();
4924 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4925 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4926 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4928 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4929 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4932 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4934 // If the logical-not of the result is required, perform that now.
4936 MVT EltVT = VT.getVectorElementType();
4937 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4938 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4939 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4941 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4946 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4947 bool addTest = true;
4948 SDValue Cond = Op.getOperand(0);
4951 if (Cond.getOpcode() == ISD::SETCC)
4952 Cond = LowerSETCC(Cond, DAG);
4954 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4955 // setting operand in place of the X86ISD::SETCC.
4956 if (Cond.getOpcode() == X86ISD::SETCC) {
4957 CC = Cond.getOperand(0);
4959 SDValue Cmp = Cond.getOperand(1);
4960 unsigned Opc = Cmp.getOpcode();
4961 MVT VT = Op.getValueType();
4963 bool IllegalFPCMov = false;
4964 if (VT.isFloatingPoint() && !VT.isVector() &&
4965 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4966 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4968 if ((Opc == X86ISD::CMP ||
4969 Opc == X86ISD::COMI ||
4970 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4977 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4978 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4981 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4983 SmallVector<SDValue, 4> Ops;
4984 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4985 // condition is true.
4986 Ops.push_back(Op.getOperand(2));
4987 Ops.push_back(Op.getOperand(1));
4989 Ops.push_back(Cond);
4990 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4993 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4994 bool addTest = true;
4995 SDValue Chain = Op.getOperand(0);
4996 SDValue Cond = Op.getOperand(1);
4997 SDValue Dest = Op.getOperand(2);
5000 if (Cond.getOpcode() == ISD::SETCC)
5001 Cond = LowerSETCC(Cond, DAG);
5003 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5004 // setting operand in place of the X86ISD::SETCC.
5005 if (Cond.getOpcode() == X86ISD::SETCC) {
5006 CC = Cond.getOperand(0);
5008 SDValue Cmp = Cond.getOperand(1);
5009 unsigned Opc = Cmp.getOpcode();
5010 if (Opc == X86ISD::CMP ||
5011 Opc == X86ISD::COMI ||
5012 Opc == X86ISD::UCOMI) {
5019 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5020 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5022 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5023 Chain, Op.getOperand(2), CC, Cond);
5027 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5028 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5029 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5030 // that the guard pages used by the OS virtual memory manager are allocated in
5031 // correct sequence.
5033 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5034 SelectionDAG &DAG) {
5035 assert(Subtarget->isTargetCygMing() &&
5036 "This should be used only on Cygwin/Mingw targets");
5039 SDValue Chain = Op.getOperand(0);
5040 SDValue Size = Op.getOperand(1);
5041 // FIXME: Ensure alignment here
5045 MVT IntPtr = getPointerTy();
5046 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5048 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
5050 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5051 Flag = Chain.getValue(1);
5053 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5054 SDValue Ops[] = { Chain,
5055 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5056 DAG.getRegister(X86::EAX, IntPtr),
5057 DAG.getRegister(X86StackPtr, SPTy),
5059 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5060 Flag = Chain.getValue(1);
5062 Chain = DAG.getCALLSEQ_END(Chain,
5063 DAG.getIntPtrConstant(0),
5064 DAG.getIntPtrConstant(0),
5067 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5069 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5070 return DAG.getMergeValues(Ops1, 2);
5074 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5076 SDValue Dst, SDValue Src,
5077 SDValue Size, unsigned Align,
5078 const Value *DstSV, uint64_t DstSVOff) {
5079 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5081 /// If not DWORD aligned or size is more than the threshold, call the library.
5082 /// The libc version is likely to be faster for these cases. It can use the
5083 /// address value and run time information about the CPU.
5084 if ((Align & 3) != 0 ||
5086 ConstantSize->getZExtValue() >
5087 getSubtarget()->getMaxInlineSizeThreshold()) {
5088 SDValue InFlag(0, 0);
5090 // Check to see if there is a specialized entry-point for memory zeroing.
5091 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5092 if (const char *bzeroEntry =
5093 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5094 MVT IntPtr = getPointerTy();
5095 const Type *IntPtrTy = TD->getIntPtrType();
5096 TargetLowering::ArgListTy Args;
5097 TargetLowering::ArgListEntry Entry;
5099 Entry.Ty = IntPtrTy;
5100 Args.push_back(Entry);
5102 Args.push_back(Entry);
5103 std::pair<SDValue,SDValue> CallResult =
5104 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5105 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5107 return CallResult.second;
5110 // Otherwise have the target-independent code call memset.
5114 uint64_t SizeVal = ConstantSize->getZExtValue();
5115 SDValue InFlag(0, 0);
5118 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5119 unsigned BytesLeft = 0;
5120 bool TwoRepStos = false;
5123 uint64_t Val = ValC->getZExtValue() & 255;
5125 // If the value is a constant, then we can potentially use larger sets.
5126 switch (Align & 3) {
5127 case 2: // WORD aligned
5130 Val = (Val << 8) | Val;
5132 case 0: // DWORD aligned
5135 Val = (Val << 8) | Val;
5136 Val = (Val << 16) | Val;
5137 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5140 Val = (Val << 32) | Val;
5143 default: // Byte aligned
5146 Count = DAG.getIntPtrConstant(SizeVal);
5150 if (AVT.bitsGT(MVT::i8)) {
5151 unsigned UBytes = AVT.getSizeInBits() / 8;
5152 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5153 BytesLeft = SizeVal % UBytes;
5156 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5158 InFlag = Chain.getValue(1);
5161 Count = DAG.getIntPtrConstant(SizeVal);
5162 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5163 InFlag = Chain.getValue(1);
5166 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5168 InFlag = Chain.getValue(1);
5169 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5171 InFlag = Chain.getValue(1);
5173 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5174 SmallVector<SDValue, 8> Ops;
5175 Ops.push_back(Chain);
5176 Ops.push_back(DAG.getValueType(AVT));
5177 Ops.push_back(InFlag);
5178 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5181 InFlag = Chain.getValue(1);
5183 MVT CVT = Count.getValueType();
5184 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5185 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5186 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5188 InFlag = Chain.getValue(1);
5189 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5191 Ops.push_back(Chain);
5192 Ops.push_back(DAG.getValueType(MVT::i8));
5193 Ops.push_back(InFlag);
5194 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5195 } else if (BytesLeft) {
5196 // Handle the last 1 - 7 bytes.
5197 unsigned Offset = SizeVal - BytesLeft;
5198 MVT AddrVT = Dst.getValueType();
5199 MVT SizeVT = Size.getValueType();
5201 Chain = DAG.getMemset(Chain,
5202 DAG.getNode(ISD::ADD, AddrVT, Dst,
5203 DAG.getConstant(Offset, AddrVT)),
5205 DAG.getConstant(BytesLeft, SizeVT),
5206 Align, DstSV, DstSVOff + Offset);
5209 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5214 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5215 SDValue Chain, SDValue Dst, SDValue Src,
5216 SDValue Size, unsigned Align,
5218 const Value *DstSV, uint64_t DstSVOff,
5219 const Value *SrcSV, uint64_t SrcSVOff) {
5220 // This requires the copy size to be a constant, preferrably
5221 // within a subtarget-specific limit.
5222 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5225 uint64_t SizeVal = ConstantSize->getZExtValue();
5226 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5229 /// If not DWORD aligned, call the library.
5230 if ((Align & 3) != 0)
5235 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5238 unsigned UBytes = AVT.getSizeInBits() / 8;
5239 unsigned CountVal = SizeVal / UBytes;
5240 SDValue Count = DAG.getIntPtrConstant(CountVal);
5241 unsigned BytesLeft = SizeVal % UBytes;
5243 SDValue InFlag(0, 0);
5244 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5246 InFlag = Chain.getValue(1);
5247 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5249 InFlag = Chain.getValue(1);
5250 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5252 InFlag = Chain.getValue(1);
5254 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5255 SmallVector<SDValue, 8> Ops;
5256 Ops.push_back(Chain);
5257 Ops.push_back(DAG.getValueType(AVT));
5258 Ops.push_back(InFlag);
5259 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5261 SmallVector<SDValue, 4> Results;
5262 Results.push_back(RepMovs);
5264 // Handle the last 1 - 7 bytes.
5265 unsigned Offset = SizeVal - BytesLeft;
5266 MVT DstVT = Dst.getValueType();
5267 MVT SrcVT = Src.getValueType();
5268 MVT SizeVT = Size.getValueType();
5269 Results.push_back(DAG.getMemcpy(Chain,
5270 DAG.getNode(ISD::ADD, DstVT, Dst,
5271 DAG.getConstant(Offset, DstVT)),
5272 DAG.getNode(ISD::ADD, SrcVT, Src,
5273 DAG.getConstant(Offset, SrcVT)),
5274 DAG.getConstant(BytesLeft, SizeVT),
5275 Align, AlwaysInline,
5276 DstSV, DstSVOff + Offset,
5277 SrcSV, SrcSVOff + Offset));
5280 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5283 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5284 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5285 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5286 SDValue TheChain = N->getOperand(0);
5287 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5288 if (Subtarget->is64Bit()) {
5289 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5290 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5291 MVT::i64, rax.getValue(2));
5292 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5293 DAG.getConstant(32, MVT::i8));
5295 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5298 return DAG.getMergeValues(Ops, 2).getNode();
5301 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5302 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5303 MVT::i32, eax.getValue(2));
5304 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5305 SDValue Ops[] = { eax, edx };
5306 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5308 // Use a MERGE_VALUES to return the value and chain.
5309 Ops[1] = edx.getValue(1);
5310 return DAG.getMergeValues(Ops, 2).getNode();
5313 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5314 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5316 if (!Subtarget->is64Bit()) {
5317 // vastart just stores the address of the VarArgsFrameIndex slot into the
5318 // memory location argument.
5319 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5320 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5324 // gp_offset (0 - 6 * 8)
5325 // fp_offset (48 - 48 + 8 * 16)
5326 // overflow_arg_area (point to parameters coming in memory).
5328 SmallVector<SDValue, 8> MemOps;
5329 SDValue FIN = Op.getOperand(1);
5331 SDValue Store = DAG.getStore(Op.getOperand(0),
5332 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5334 MemOps.push_back(Store);
5337 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5338 Store = DAG.getStore(Op.getOperand(0),
5339 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5341 MemOps.push_back(Store);
5343 // Store ptr to overflow_arg_area
5344 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5345 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5346 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5347 MemOps.push_back(Store);
5349 // Store ptr to reg_save_area.
5350 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5351 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5352 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5353 MemOps.push_back(Store);
5354 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5357 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5358 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5359 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5360 SDValue Chain = Op.getOperand(0);
5361 SDValue SrcPtr = Op.getOperand(1);
5362 SDValue SrcSV = Op.getOperand(2);
5364 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5369 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5370 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5371 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5372 SDValue Chain = Op.getOperand(0);
5373 SDValue DstPtr = Op.getOperand(1);
5374 SDValue SrcPtr = Op.getOperand(2);
5375 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5376 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5378 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5379 DAG.getIntPtrConstant(24), 8, false,
5380 DstSV, 0, SrcSV, 0);
5384 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5385 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5387 default: return SDValue(); // Don't custom lower most intrinsics.
5388 // Comparison intrinsics.
5389 case Intrinsic::x86_sse_comieq_ss:
5390 case Intrinsic::x86_sse_comilt_ss:
5391 case Intrinsic::x86_sse_comile_ss:
5392 case Intrinsic::x86_sse_comigt_ss:
5393 case Intrinsic::x86_sse_comige_ss:
5394 case Intrinsic::x86_sse_comineq_ss:
5395 case Intrinsic::x86_sse_ucomieq_ss:
5396 case Intrinsic::x86_sse_ucomilt_ss:
5397 case Intrinsic::x86_sse_ucomile_ss:
5398 case Intrinsic::x86_sse_ucomigt_ss:
5399 case Intrinsic::x86_sse_ucomige_ss:
5400 case Intrinsic::x86_sse_ucomineq_ss:
5401 case Intrinsic::x86_sse2_comieq_sd:
5402 case Intrinsic::x86_sse2_comilt_sd:
5403 case Intrinsic::x86_sse2_comile_sd:
5404 case Intrinsic::x86_sse2_comigt_sd:
5405 case Intrinsic::x86_sse2_comige_sd:
5406 case Intrinsic::x86_sse2_comineq_sd:
5407 case Intrinsic::x86_sse2_ucomieq_sd:
5408 case Intrinsic::x86_sse2_ucomilt_sd:
5409 case Intrinsic::x86_sse2_ucomile_sd:
5410 case Intrinsic::x86_sse2_ucomigt_sd:
5411 case Intrinsic::x86_sse2_ucomige_sd:
5412 case Intrinsic::x86_sse2_ucomineq_sd: {
5414 ISD::CondCode CC = ISD::SETCC_INVALID;
5417 case Intrinsic::x86_sse_comieq_ss:
5418 case Intrinsic::x86_sse2_comieq_sd:
5422 case Intrinsic::x86_sse_comilt_ss:
5423 case Intrinsic::x86_sse2_comilt_sd:
5427 case Intrinsic::x86_sse_comile_ss:
5428 case Intrinsic::x86_sse2_comile_sd:
5432 case Intrinsic::x86_sse_comigt_ss:
5433 case Intrinsic::x86_sse2_comigt_sd:
5437 case Intrinsic::x86_sse_comige_ss:
5438 case Intrinsic::x86_sse2_comige_sd:
5442 case Intrinsic::x86_sse_comineq_ss:
5443 case Intrinsic::x86_sse2_comineq_sd:
5447 case Intrinsic::x86_sse_ucomieq_ss:
5448 case Intrinsic::x86_sse2_ucomieq_sd:
5449 Opc = X86ISD::UCOMI;
5452 case Intrinsic::x86_sse_ucomilt_ss:
5453 case Intrinsic::x86_sse2_ucomilt_sd:
5454 Opc = X86ISD::UCOMI;
5457 case Intrinsic::x86_sse_ucomile_ss:
5458 case Intrinsic::x86_sse2_ucomile_sd:
5459 Opc = X86ISD::UCOMI;
5462 case Intrinsic::x86_sse_ucomigt_ss:
5463 case Intrinsic::x86_sse2_ucomigt_sd:
5464 Opc = X86ISD::UCOMI;
5467 case Intrinsic::x86_sse_ucomige_ss:
5468 case Intrinsic::x86_sse2_ucomige_sd:
5469 Opc = X86ISD::UCOMI;
5472 case Intrinsic::x86_sse_ucomineq_ss:
5473 case Intrinsic::x86_sse2_ucomineq_sd:
5474 Opc = X86ISD::UCOMI;
5480 SDValue LHS = Op.getOperand(1);
5481 SDValue RHS = Op.getOperand(2);
5482 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5484 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5485 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5486 DAG.getConstant(X86CC, MVT::i8), Cond);
5487 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5490 // Fix vector shift instructions where the last operand is a non-immediate
5492 case Intrinsic::x86_sse2_pslli_w:
5493 case Intrinsic::x86_sse2_pslli_d:
5494 case Intrinsic::x86_sse2_pslli_q:
5495 case Intrinsic::x86_sse2_psrli_w:
5496 case Intrinsic::x86_sse2_psrli_d:
5497 case Intrinsic::x86_sse2_psrli_q:
5498 case Intrinsic::x86_sse2_psrai_w:
5499 case Intrinsic::x86_sse2_psrai_d:
5500 case Intrinsic::x86_mmx_pslli_w:
5501 case Intrinsic::x86_mmx_pslli_d:
5502 case Intrinsic::x86_mmx_pslli_q:
5503 case Intrinsic::x86_mmx_psrli_w:
5504 case Intrinsic::x86_mmx_psrli_d:
5505 case Intrinsic::x86_mmx_psrli_q:
5506 case Intrinsic::x86_mmx_psrai_w:
5507 case Intrinsic::x86_mmx_psrai_d: {
5508 SDValue ShAmt = Op.getOperand(2);
5509 if (isa<ConstantSDNode>(ShAmt))
5512 unsigned NewIntNo = 0;
5513 MVT ShAmtVT = MVT::v4i32;
5515 case Intrinsic::x86_sse2_pslli_w:
5516 NewIntNo = Intrinsic::x86_sse2_psll_w;
5518 case Intrinsic::x86_sse2_pslli_d:
5519 NewIntNo = Intrinsic::x86_sse2_psll_d;
5521 case Intrinsic::x86_sse2_pslli_q:
5522 NewIntNo = Intrinsic::x86_sse2_psll_q;
5524 case Intrinsic::x86_sse2_psrli_w:
5525 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5527 case Intrinsic::x86_sse2_psrli_d:
5528 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5530 case Intrinsic::x86_sse2_psrli_q:
5531 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5533 case Intrinsic::x86_sse2_psrai_w:
5534 NewIntNo = Intrinsic::x86_sse2_psra_w;
5536 case Intrinsic::x86_sse2_psrai_d:
5537 NewIntNo = Intrinsic::x86_sse2_psra_d;
5540 ShAmtVT = MVT::v2i32;
5542 case Intrinsic::x86_mmx_pslli_w:
5543 NewIntNo = Intrinsic::x86_mmx_psll_w;
5545 case Intrinsic::x86_mmx_pslli_d:
5546 NewIntNo = Intrinsic::x86_mmx_psll_d;
5548 case Intrinsic::x86_mmx_pslli_q:
5549 NewIntNo = Intrinsic::x86_mmx_psll_q;
5551 case Intrinsic::x86_mmx_psrli_w:
5552 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5554 case Intrinsic::x86_mmx_psrli_d:
5555 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5557 case Intrinsic::x86_mmx_psrli_q:
5558 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5560 case Intrinsic::x86_mmx_psrai_w:
5561 NewIntNo = Intrinsic::x86_mmx_psra_w;
5563 case Intrinsic::x86_mmx_psrai_d:
5564 NewIntNo = Intrinsic::x86_mmx_psra_d;
5566 default: abort(); // Can't reach here.
5571 MVT VT = Op.getValueType();
5572 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5573 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5574 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5575 DAG.getConstant(NewIntNo, MVT::i32),
5576 Op.getOperand(1), ShAmt);
5581 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5582 // Depths > 0 not supported yet!
5583 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5586 // Just load the return address
5587 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5588 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5591 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5592 // Depths > 0 not supported yet!
5593 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5596 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5597 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5598 DAG.getIntPtrConstant(TD->getPointerSize()));
5601 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5602 SelectionDAG &DAG) {
5603 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5606 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5608 MachineFunction &MF = DAG.getMachineFunction();
5609 SDValue Chain = Op.getOperand(0);
5610 SDValue Offset = Op.getOperand(1);
5611 SDValue Handler = Op.getOperand(2);
5613 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5615 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5617 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5618 DAG.getIntPtrConstant(-TD->getPointerSize()));
5619 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5620 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5621 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5622 MF.getRegInfo().addLiveOut(StoreAddrReg);
5624 return DAG.getNode(X86ISD::EH_RETURN,
5626 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5629 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5630 SelectionDAG &DAG) {
5631 SDValue Root = Op.getOperand(0);
5632 SDValue Trmp = Op.getOperand(1); // trampoline
5633 SDValue FPtr = Op.getOperand(2); // nested function
5634 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5636 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5638 const X86InstrInfo *TII =
5639 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5641 if (Subtarget->is64Bit()) {
5642 SDValue OutChains[6];
5644 // Large code-model.
5646 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5647 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5649 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5650 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5652 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5654 // Load the pointer to the nested function into R11.
5655 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5656 SDValue Addr = Trmp;
5657 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5660 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5661 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5663 // Load the 'nest' parameter value into R10.
5664 // R10 is specified in X86CallingConv.td
5665 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5666 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5667 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5670 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5671 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5673 // Jump to the nested function.
5674 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5675 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5676 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5679 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5680 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5681 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5685 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5686 return DAG.getMergeValues(Ops, 2);
5688 const Function *Func =
5689 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5690 unsigned CC = Func->getCallingConv();
5695 assert(0 && "Unsupported calling convention");
5696 case CallingConv::C:
5697 case CallingConv::X86_StdCall: {
5698 // Pass 'nest' parameter in ECX.
5699 // Must be kept in sync with X86CallingConv.td
5702 // Check that ECX wasn't needed by an 'inreg' parameter.
5703 const FunctionType *FTy = Func->getFunctionType();
5704 const PAListPtr &Attrs = Func->getParamAttrs();
5706 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5707 unsigned InRegCount = 0;
5710 for (FunctionType::param_iterator I = FTy->param_begin(),
5711 E = FTy->param_end(); I != E; ++I, ++Idx)
5712 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5713 // FIXME: should only count parameters that are lowered to integers.
5714 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5716 if (InRegCount > 2) {
5717 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5723 case CallingConv::X86_FastCall:
5724 case CallingConv::Fast:
5725 // Pass 'nest' parameter in EAX.
5726 // Must be kept in sync with X86CallingConv.td
5731 SDValue OutChains[4];
5734 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5735 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5737 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5738 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5739 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5742 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5743 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5745 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5746 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5747 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5748 TrmpAddr, 5, false, 1);
5750 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5751 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5754 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5755 return DAG.getMergeValues(Ops, 2);
5759 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5761 The rounding mode is in bits 11:10 of FPSR, and has the following
5768 FLT_ROUNDS, on the other hand, expects the following:
5775 To perform the conversion, we do:
5776 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5779 MachineFunction &MF = DAG.getMachineFunction();
5780 const TargetMachine &TM = MF.getTarget();
5781 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5782 unsigned StackAlignment = TFI.getStackAlignment();
5783 MVT VT = Op.getValueType();
5785 // Save FP Control Word to stack slot
5786 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5787 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5789 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5790 DAG.getEntryNode(), StackSlot);
5792 // Load FP Control Word from stack slot
5793 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5795 // Transform as necessary
5797 DAG.getNode(ISD::SRL, MVT::i16,
5798 DAG.getNode(ISD::AND, MVT::i16,
5799 CWD, DAG.getConstant(0x800, MVT::i16)),
5800 DAG.getConstant(11, MVT::i8));
5802 DAG.getNode(ISD::SRL, MVT::i16,
5803 DAG.getNode(ISD::AND, MVT::i16,
5804 CWD, DAG.getConstant(0x400, MVT::i16)),
5805 DAG.getConstant(9, MVT::i8));
5808 DAG.getNode(ISD::AND, MVT::i16,
5809 DAG.getNode(ISD::ADD, MVT::i16,
5810 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5811 DAG.getConstant(1, MVT::i16)),
5812 DAG.getConstant(3, MVT::i16));
5815 return DAG.getNode((VT.getSizeInBits() < 16 ?
5816 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5819 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5820 MVT VT = Op.getValueType();
5822 unsigned NumBits = VT.getSizeInBits();
5824 Op = Op.getOperand(0);
5825 if (VT == MVT::i8) {
5826 // Zero extend to i32 since there is not an i8 bsr.
5828 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5831 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5832 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5833 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5835 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5836 SmallVector<SDValue, 4> Ops;
5838 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5839 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5840 Ops.push_back(Op.getValue(1));
5841 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5843 // Finally xor with NumBits-1.
5844 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5847 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5851 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5852 MVT VT = Op.getValueType();
5854 unsigned NumBits = VT.getSizeInBits();
5856 Op = Op.getOperand(0);
5857 if (VT == MVT::i8) {
5859 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5862 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5863 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5864 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5866 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5867 SmallVector<SDValue, 4> Ops;
5869 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5870 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5871 Ops.push_back(Op.getValue(1));
5872 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5875 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5879 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5880 MVT T = Op.getValueType();
5883 switch(T.getSimpleVT()) {
5885 assert(false && "Invalid value type!");
5886 case MVT::i8: Reg = X86::AL; size = 1; break;
5887 case MVT::i16: Reg = X86::AX; size = 2; break;
5888 case MVT::i32: Reg = X86::EAX; size = 4; break;
5890 if (Subtarget->is64Bit()) {
5891 Reg = X86::RAX; size = 8;
5892 } else //Should go away when LowerType stuff lands
5893 return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
5896 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5897 Op.getOperand(2), SDValue());
5898 SDValue Ops[] = { cpIn.getValue(0),
5901 DAG.getTargetConstant(size, MVT::i8),
5903 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5904 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5906 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5910 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
5911 SelectionDAG &DAG) {
5912 MVT T = Op->getValueType(0);
5913 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5914 SDValue cpInL, cpInH;
5915 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5916 DAG.getConstant(0, MVT::i32));
5917 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5918 DAG.getConstant(1, MVT::i32));
5919 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5921 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5922 cpInH, cpInL.getValue(1));
5923 SDValue swapInL, swapInH;
5924 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5925 DAG.getConstant(0, MVT::i32));
5926 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5927 DAG.getConstant(1, MVT::i32));
5928 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5929 swapInL, cpInH.getValue(1));
5930 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5931 swapInH, swapInL.getValue(1));
5932 SDValue Ops[] = { swapInH.getValue(0),
5934 swapInH.getValue(1)};
5935 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5936 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5937 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5938 Result.getValue(1));
5939 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5940 cpOutL.getValue(2));
5941 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5942 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5943 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5944 return DAG.getMergeValues(Vals, 2).getNode();
5947 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op,
5948 SelectionDAG &DAG) {
5949 MVT T = Op->getValueType(0);
5950 SDValue negOp = DAG.getNode(ISD::SUB, T,
5951 DAG.getConstant(0, T), Op->getOperand(2));
5952 return DAG.getAtomic((T==MVT::i8 ? ISD::ATOMIC_LOAD_ADD_8:
5953 T==MVT::i16 ? ISD::ATOMIC_LOAD_ADD_16:
5954 T==MVT::i32 ? ISD::ATOMIC_LOAD_ADD_32:
5955 T==MVT::i64 ? ISD::ATOMIC_LOAD_ADD_64: 0),
5956 Op->getOperand(0), Op->getOperand(1), negOp,
5957 cast<AtomicSDNode>(Op)->getSrcValue(),
5958 cast<AtomicSDNode>(Op)->getAlignment()).getNode();
5961 /// LowerOperation - Provide custom lowering hooks for some operations.
5963 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5964 switch (Op.getOpcode()) {
5965 default: assert(0 && "Should not custom lower this!");
5966 case ISD::ATOMIC_CMP_SWAP_8: return LowerCMP_SWAP(Op,DAG);
5967 case ISD::ATOMIC_CMP_SWAP_16: return LowerCMP_SWAP(Op,DAG);
5968 case ISD::ATOMIC_CMP_SWAP_32: return LowerCMP_SWAP(Op,DAG);
5969 case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
5970 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5971 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5972 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5973 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5974 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5975 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5976 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5977 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5978 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5979 case ISD::SHL_PARTS:
5980 case ISD::SRA_PARTS:
5981 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5982 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5983 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5984 case ISD::FABS: return LowerFABS(Op, DAG);
5985 case ISD::FNEG: return LowerFNEG(Op, DAG);
5986 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5987 case ISD::SETCC: return LowerSETCC(Op, DAG);
5988 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
5989 case ISD::SELECT: return LowerSELECT(Op, DAG);
5990 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5991 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5992 case ISD::CALL: return LowerCALL(Op, DAG);
5993 case ISD::RET: return LowerRET(Op, DAG);
5994 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5995 case ISD::VASTART: return LowerVASTART(Op, DAG);
5996 case ISD::VAARG: return LowerVAARG(Op, DAG);
5997 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5998 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5999 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6000 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6001 case ISD::FRAME_TO_ARGS_OFFSET:
6002 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6003 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6004 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6005 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6006 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6007 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6008 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6010 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6011 case ISD::READCYCLECOUNTER:
6012 return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6016 /// ReplaceNodeResults - Replace a node with an illegal result type
6017 /// with a new node built out of custom code.
6018 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6019 switch (N->getOpcode()) {
6020 default: assert(0 && "Should not custom lower this!");
6021 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
6022 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
6023 case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6024 case ISD::ATOMIC_LOAD_SUB_8: return ExpandATOMIC_LOAD_SUB(N,DAG);
6025 case ISD::ATOMIC_LOAD_SUB_16: return ExpandATOMIC_LOAD_SUB(N,DAG);
6026 case ISD::ATOMIC_LOAD_SUB_32: return ExpandATOMIC_LOAD_SUB(N,DAG);
6027 case ISD::ATOMIC_LOAD_SUB_64: return ExpandATOMIC_LOAD_SUB(N,DAG);
6031 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6033 default: return NULL;
6034 case X86ISD::BSF: return "X86ISD::BSF";
6035 case X86ISD::BSR: return "X86ISD::BSR";
6036 case X86ISD::SHLD: return "X86ISD::SHLD";
6037 case X86ISD::SHRD: return "X86ISD::SHRD";
6038 case X86ISD::FAND: return "X86ISD::FAND";
6039 case X86ISD::FOR: return "X86ISD::FOR";
6040 case X86ISD::FXOR: return "X86ISD::FXOR";
6041 case X86ISD::FSRL: return "X86ISD::FSRL";
6042 case X86ISD::FILD: return "X86ISD::FILD";
6043 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6044 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6045 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6046 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6047 case X86ISD::FLD: return "X86ISD::FLD";
6048 case X86ISD::FST: return "X86ISD::FST";
6049 case X86ISD::CALL: return "X86ISD::CALL";
6050 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6051 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6052 case X86ISD::CMP: return "X86ISD::CMP";
6053 case X86ISD::COMI: return "X86ISD::COMI";
6054 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6055 case X86ISD::SETCC: return "X86ISD::SETCC";
6056 case X86ISD::CMOV: return "X86ISD::CMOV";
6057 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6058 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6059 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6060 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6061 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6062 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6063 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6064 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6065 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6066 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6067 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6068 case X86ISD::FMAX: return "X86ISD::FMAX";
6069 case X86ISD::FMIN: return "X86ISD::FMIN";
6070 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6071 case X86ISD::FRCP: return "X86ISD::FRCP";
6072 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6073 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6074 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6075 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6076 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6077 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6078 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6079 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6080 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6081 case X86ISD::VSHL: return "X86ISD::VSHL";
6082 case X86ISD::VSRL: return "X86ISD::VSRL";
6083 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6084 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6085 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6086 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6087 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6088 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6089 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6090 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6091 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6092 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6096 // isLegalAddressingMode - Return true if the addressing mode represented
6097 // by AM is legal for this target, for a load/store of the specified type.
6098 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6099 const Type *Ty) const {
6100 // X86 supports extremely general addressing modes.
6102 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6103 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6107 // We can only fold this if we don't need an extra load.
6108 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6111 // X86-64 only supports addr of globals in small code model.
6112 if (Subtarget->is64Bit()) {
6113 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6115 // If lower 4G is not available, then we must use rip-relative addressing.
6116 if (AM.BaseOffs || AM.Scale > 1)
6127 // These scales always work.
6132 // These scales are formed with basereg+scalereg. Only accept if there is
6137 default: // Other stuff never works.
6145 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6146 if (!Ty1->isInteger() || !Ty2->isInteger())
6148 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6149 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6150 if (NumBits1 <= NumBits2)
6152 return Subtarget->is64Bit() || NumBits1 < 64;
6155 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6156 if (!VT1.isInteger() || !VT2.isInteger())
6158 unsigned NumBits1 = VT1.getSizeInBits();
6159 unsigned NumBits2 = VT2.getSizeInBits();
6160 if (NumBits1 <= NumBits2)
6162 return Subtarget->is64Bit() || NumBits1 < 64;
6165 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6166 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6167 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6168 /// are assumed to be legal.
6170 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6171 // Only do shuffles on 128-bit vector types for now.
6172 if (VT.getSizeInBits() == 64) return false;
6173 return (Mask.getNode()->getNumOperands() <= 4 ||
6174 isIdentityMask(Mask.getNode()) ||
6175 isIdentityMask(Mask.getNode(), true) ||
6176 isSplatMask(Mask.getNode()) ||
6177 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6178 X86::isUNPCKLMask(Mask.getNode()) ||
6179 X86::isUNPCKHMask(Mask.getNode()) ||
6180 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6181 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6185 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6186 MVT EVT, SelectionDAG &DAG) const {
6187 unsigned NumElts = BVOps.size();
6188 // Only do shuffles on 128-bit vector types for now.
6189 if (EVT.getSizeInBits() * NumElts == 64) return false;
6190 if (NumElts == 2) return true;
6192 return (isMOVLMask(&BVOps[0], 4) ||
6193 isCommutedMOVL(&BVOps[0], 4, true) ||
6194 isSHUFPMask(&BVOps[0], 4) ||
6195 isCommutedSHUFP(&BVOps[0], 4));
6200 //===----------------------------------------------------------------------===//
6201 // X86 Scheduler Hooks
6202 //===----------------------------------------------------------------------===//
6204 // private utility function
6206 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6207 MachineBasicBlock *MBB,
6215 TargetRegisterClass *RC,
6217 // For the atomic bitwise operator, we generate
6220 // ld t1 = [bitinstr.addr]
6221 // op t2 = t1, [bitinstr.val]
6223 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6225 // fallthrough -->nextMBB
6226 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6227 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6228 MachineFunction::iterator MBBIter = MBB;
6231 /// First build the CFG
6232 MachineFunction *F = MBB->getParent();
6233 MachineBasicBlock *thisMBB = MBB;
6234 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6235 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6236 F->insert(MBBIter, newMBB);
6237 F->insert(MBBIter, nextMBB);
6239 // Move all successors to thisMBB to nextMBB
6240 nextMBB->transferSuccessors(thisMBB);
6242 // Update thisMBB to fall through to newMBB
6243 thisMBB->addSuccessor(newMBB);
6245 // newMBB jumps to itself and fall through to nextMBB
6246 newMBB->addSuccessor(nextMBB);
6247 newMBB->addSuccessor(newMBB);
6249 // Insert instructions into newMBB based on incoming instruction
6250 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6251 MachineOperand& destOper = bInstr->getOperand(0);
6252 MachineOperand* argOpers[6];
6253 int numArgs = bInstr->getNumOperands() - 1;
6254 for (int i=0; i < numArgs; ++i)
6255 argOpers[i] = &bInstr->getOperand(i+1);
6257 // x86 address has 4 operands: base, index, scale, and displacement
6258 int lastAddrIndx = 3; // [0,3]
6261 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6262 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6263 for (int i=0; i <= lastAddrIndx; ++i)
6264 (*MIB).addOperand(*argOpers[i]);
6266 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6268 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6273 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6274 assert((argOpers[valArgIndx]->isRegister() ||
6275 argOpers[valArgIndx]->isImmediate()) &&
6277 if (argOpers[valArgIndx]->isRegister())
6278 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6280 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6282 (*MIB).addOperand(*argOpers[valArgIndx]);
6284 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6287 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6288 for (int i=0; i <= lastAddrIndx; ++i)
6289 (*MIB).addOperand(*argOpers[i]);
6291 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6292 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6294 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6298 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6300 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6304 // private utility function
6306 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6307 MachineBasicBlock *MBB,
6309 // For the atomic min/max operator, we generate
6312 // ld t1 = [min/max.addr]
6313 // mov t2 = [min/max.val]
6315 // cmov[cond] t2 = t1
6317 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6319 // fallthrough -->nextMBB
6321 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6322 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6323 MachineFunction::iterator MBBIter = MBB;
6326 /// First build the CFG
6327 MachineFunction *F = MBB->getParent();
6328 MachineBasicBlock *thisMBB = MBB;
6329 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6330 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6331 F->insert(MBBIter, newMBB);
6332 F->insert(MBBIter, nextMBB);
6334 // Move all successors to thisMBB to nextMBB
6335 nextMBB->transferSuccessors(thisMBB);
6337 // Update thisMBB to fall through to newMBB
6338 thisMBB->addSuccessor(newMBB);
6340 // newMBB jumps to newMBB and fall through to nextMBB
6341 newMBB->addSuccessor(nextMBB);
6342 newMBB->addSuccessor(newMBB);
6344 // Insert instructions into newMBB based on incoming instruction
6345 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6346 MachineOperand& destOper = mInstr->getOperand(0);
6347 MachineOperand* argOpers[6];
6348 int numArgs = mInstr->getNumOperands() - 1;
6349 for (int i=0; i < numArgs; ++i)
6350 argOpers[i] = &mInstr->getOperand(i+1);
6352 // x86 address has 4 operands: base, index, scale, and displacement
6353 int lastAddrIndx = 3; // [0,3]
6356 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6357 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6358 for (int i=0; i <= lastAddrIndx; ++i)
6359 (*MIB).addOperand(*argOpers[i]);
6361 // We only support register and immediate values
6362 assert((argOpers[valArgIndx]->isRegister() ||
6363 argOpers[valArgIndx]->isImmediate()) &&
6366 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6367 if (argOpers[valArgIndx]->isRegister())
6368 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6370 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6371 (*MIB).addOperand(*argOpers[valArgIndx]);
6373 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6376 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6381 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6382 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6386 // Cmp and exchange if none has modified the memory location
6387 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6388 for (int i=0; i <= lastAddrIndx; ++i)
6389 (*MIB).addOperand(*argOpers[i]);
6391 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6392 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6394 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6395 MIB.addReg(X86::EAX);
6398 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6400 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6406 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6407 MachineBasicBlock *BB) {
6408 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6409 switch (MI->getOpcode()) {
6410 default: assert(false && "Unexpected instr type to insert");
6411 case X86::CMOV_FR32:
6412 case X86::CMOV_FR64:
6413 case X86::CMOV_V4F32:
6414 case X86::CMOV_V2F64:
6415 case X86::CMOV_V2I64: {
6416 // To "insert" a SELECT_CC instruction, we actually have to insert the
6417 // diamond control-flow pattern. The incoming instruction knows the
6418 // destination vreg to set, the condition code register to branch on, the
6419 // true/false values to select between, and a branch opcode to use.
6420 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6421 MachineFunction::iterator It = BB;
6427 // cmpTY ccX, r1, r2
6429 // fallthrough --> copy0MBB
6430 MachineBasicBlock *thisMBB = BB;
6431 MachineFunction *F = BB->getParent();
6432 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6433 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6435 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6436 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6437 F->insert(It, copy0MBB);
6438 F->insert(It, sinkMBB);
6439 // Update machine-CFG edges by transferring all successors of the current
6440 // block to the new block which will contain the Phi node for the select.
6441 sinkMBB->transferSuccessors(BB);
6443 // Add the true and fallthrough blocks as its successors.
6444 BB->addSuccessor(copy0MBB);
6445 BB->addSuccessor(sinkMBB);
6448 // %FalseValue = ...
6449 // # fallthrough to sinkMBB
6452 // Update machine-CFG edges
6453 BB->addSuccessor(sinkMBB);
6456 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6459 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6460 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6461 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6463 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6467 case X86::FP32_TO_INT16_IN_MEM:
6468 case X86::FP32_TO_INT32_IN_MEM:
6469 case X86::FP32_TO_INT64_IN_MEM:
6470 case X86::FP64_TO_INT16_IN_MEM:
6471 case X86::FP64_TO_INT32_IN_MEM:
6472 case X86::FP64_TO_INT64_IN_MEM:
6473 case X86::FP80_TO_INT16_IN_MEM:
6474 case X86::FP80_TO_INT32_IN_MEM:
6475 case X86::FP80_TO_INT64_IN_MEM: {
6476 // Change the floating point control register to use "round towards zero"
6477 // mode when truncating to an integer value.
6478 MachineFunction *F = BB->getParent();
6479 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6480 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6482 // Load the old value of the high byte of the control word...
6484 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6485 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6487 // Set the high part to be round to zero...
6488 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6491 // Reload the modified control word now...
6492 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6494 // Restore the memory image of control word to original value
6495 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6498 // Get the X86 opcode to use.
6500 switch (MI->getOpcode()) {
6501 default: assert(0 && "illegal opcode!");
6502 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6503 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6504 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6505 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6506 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6507 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6508 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6509 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6510 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6514 MachineOperand &Op = MI->getOperand(0);
6515 if (Op.isRegister()) {
6516 AM.BaseType = X86AddressMode::RegBase;
6517 AM.Base.Reg = Op.getReg();
6519 AM.BaseType = X86AddressMode::FrameIndexBase;
6520 AM.Base.FrameIndex = Op.getIndex();
6522 Op = MI->getOperand(1);
6523 if (Op.isImmediate())
6524 AM.Scale = Op.getImm();
6525 Op = MI->getOperand(2);
6526 if (Op.isImmediate())
6527 AM.IndexReg = Op.getImm();
6528 Op = MI->getOperand(3);
6529 if (Op.isGlobalAddress()) {
6530 AM.GV = Op.getGlobal();
6532 AM.Disp = Op.getImm();
6534 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6535 .addReg(MI->getOperand(4).getReg());
6537 // Reload the original control word now.
6538 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6540 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6543 case X86::ATOMAND32:
6544 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6545 X86::AND32ri, X86::MOV32rm,
6546 X86::LCMPXCHG32, X86::MOV32rr,
6547 X86::NOT32r, X86::EAX,
6548 X86::GR32RegisterClass);
6550 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6551 X86::OR32ri, X86::MOV32rm,
6552 X86::LCMPXCHG32, X86::MOV32rr,
6553 X86::NOT32r, X86::EAX,
6554 X86::GR32RegisterClass);
6555 case X86::ATOMXOR32:
6556 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6557 X86::XOR32ri, X86::MOV32rm,
6558 X86::LCMPXCHG32, X86::MOV32rr,
6559 X86::NOT32r, X86::EAX,
6560 X86::GR32RegisterClass);
6561 case X86::ATOMNAND32:
6562 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6563 X86::AND32ri, X86::MOV32rm,
6564 X86::LCMPXCHG32, X86::MOV32rr,
6565 X86::NOT32r, X86::EAX,
6566 X86::GR32RegisterClass, true);
6567 case X86::ATOMMIN32:
6568 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6569 case X86::ATOMMAX32:
6570 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6571 case X86::ATOMUMIN32:
6572 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6573 case X86::ATOMUMAX32:
6574 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6576 case X86::ATOMAND16:
6577 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6578 X86::AND16ri, X86::MOV16rm,
6579 X86::LCMPXCHG16, X86::MOV16rr,
6580 X86::NOT16r, X86::AX,
6581 X86::GR16RegisterClass);
6583 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
6584 X86::OR16ri, X86::MOV16rm,
6585 X86::LCMPXCHG16, X86::MOV16rr,
6586 X86::NOT16r, X86::AX,
6587 X86::GR16RegisterClass);
6588 case X86::ATOMXOR16:
6589 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6590 X86::XOR16ri, X86::MOV16rm,
6591 X86::LCMPXCHG16, X86::MOV16rr,
6592 X86::NOT16r, X86::AX,
6593 X86::GR16RegisterClass);
6594 case X86::ATOMNAND16:
6595 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6596 X86::AND16ri, X86::MOV16rm,
6597 X86::LCMPXCHG16, X86::MOV16rr,
6598 X86::NOT16r, X86::AX,
6599 X86::GR16RegisterClass, true);
6600 case X86::ATOMMIN16:
6601 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6602 case X86::ATOMMAX16:
6603 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6604 case X86::ATOMUMIN16:
6605 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6606 case X86::ATOMUMAX16:
6607 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6610 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6611 X86::AND8ri, X86::MOV8rm,
6612 X86::LCMPXCHG8, X86::MOV8rr,
6613 X86::NOT8r, X86::AL,
6614 X86::GR8RegisterClass);
6616 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
6617 X86::OR8ri, X86::MOV8rm,
6618 X86::LCMPXCHG8, X86::MOV8rr,
6619 X86::NOT8r, X86::AL,
6620 X86::GR8RegisterClass);
6622 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6623 X86::XOR8ri, X86::MOV8rm,
6624 X86::LCMPXCHG8, X86::MOV8rr,
6625 X86::NOT8r, X86::AL,
6626 X86::GR8RegisterClass);
6627 case X86::ATOMNAND8:
6628 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6629 X86::AND8ri, X86::MOV8rm,
6630 X86::LCMPXCHG8, X86::MOV8rr,
6631 X86::NOT8r, X86::AL,
6632 X86::GR8RegisterClass, true);
6633 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6634 case X86::ATOMAND64:
6635 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6636 X86::AND64ri32, X86::MOV64rm,
6637 X86::LCMPXCHG64, X86::MOV64rr,
6638 X86::NOT64r, X86::RAX,
6639 X86::GR64RegisterClass);
6641 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
6642 X86::OR64ri32, X86::MOV64rm,
6643 X86::LCMPXCHG64, X86::MOV64rr,
6644 X86::NOT64r, X86::RAX,
6645 X86::GR64RegisterClass);
6646 case X86::ATOMXOR64:
6647 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
6648 X86::XOR64ri32, X86::MOV64rm,
6649 X86::LCMPXCHG64, X86::MOV64rr,
6650 X86::NOT64r, X86::RAX,
6651 X86::GR64RegisterClass);
6652 case X86::ATOMNAND64:
6653 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6654 X86::AND64ri32, X86::MOV64rm,
6655 X86::LCMPXCHG64, X86::MOV64rr,
6656 X86::NOT64r, X86::RAX,
6657 X86::GR64RegisterClass, true);
6658 case X86::ATOMMIN64:
6659 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
6660 case X86::ATOMMAX64:
6661 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
6662 case X86::ATOMUMIN64:
6663 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
6664 case X86::ATOMUMAX64:
6665 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
6669 //===----------------------------------------------------------------------===//
6670 // X86 Optimization Hooks
6671 //===----------------------------------------------------------------------===//
6673 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6677 const SelectionDAG &DAG,
6678 unsigned Depth) const {
6679 unsigned Opc = Op.getOpcode();
6680 assert((Opc >= ISD::BUILTIN_OP_END ||
6681 Opc == ISD::INTRINSIC_WO_CHAIN ||
6682 Opc == ISD::INTRINSIC_W_CHAIN ||
6683 Opc == ISD::INTRINSIC_VOID) &&
6684 "Should use MaskedValueIsZero if you don't know whether Op"
6685 " is a target node!");
6687 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6691 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6692 Mask.getBitWidth() - 1);
6697 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6698 /// node is a GlobalAddress + offset.
6699 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6700 GlobalValue* &GA, int64_t &Offset) const{
6701 if (N->getOpcode() == X86ISD::Wrapper) {
6702 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6703 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6707 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6710 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6711 const TargetLowering &TLI) {
6714 if (TLI.isGAPlusOffset(Base, GV, Offset))
6715 return (GV->getAlignment() >= N && (Offset % N) == 0);
6716 // DAG combine handles the stack object case.
6720 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6721 unsigned NumElems, MVT EVT,
6723 SelectionDAG &DAG, MachineFrameInfo *MFI,
6724 const TargetLowering &TLI) {
6726 for (unsigned i = 0; i < NumElems; ++i) {
6727 SDValue Idx = PermMask.getOperand(i);
6728 if (Idx.getOpcode() == ISD::UNDEF) {
6734 SDValue Elt = DAG.getShuffleScalarElt(N, i);
6735 if (!Elt.getNode() ||
6736 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6739 Base = Elt.getNode();
6740 if (Base->getOpcode() == ISD::UNDEF)
6744 if (Elt.getOpcode() == ISD::UNDEF)
6747 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
6748 EVT.getSizeInBits()/8, i, MFI))
6754 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6755 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6756 /// if the load addresses are consecutive, non-overlapping, and in the right
6758 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6759 const TargetLowering &TLI) {
6760 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6761 MVT VT = N->getValueType(0);
6762 MVT EVT = VT.getVectorElementType();
6763 SDValue PermMask = N->getOperand(2);
6764 unsigned NumElems = PermMask.getNumOperands();
6765 SDNode *Base = NULL;
6766 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6770 LoadSDNode *LD = cast<LoadSDNode>(Base);
6771 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
6772 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6773 LD->getSrcValueOffset(), LD->isVolatile());
6774 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6775 LD->getSrcValueOffset(), LD->isVolatile(),
6776 LD->getAlignment());
6779 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6780 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6781 const X86Subtarget *Subtarget,
6782 const TargetLowering &TLI) {
6783 unsigned NumOps = N->getNumOperands();
6785 // Ignore single operand BUILD_VECTOR.
6789 MVT VT = N->getValueType(0);
6790 MVT EVT = VT.getVectorElementType();
6791 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6792 // We are looking for load i64 and zero extend. We want to transform
6793 // it before legalizer has a chance to expand it. Also look for i64
6794 // BUILD_PAIR bit casted to f64.
6796 // This must be an insertion into a zero vector.
6797 SDValue HighElt = N->getOperand(1);
6798 if (!isZeroNode(HighElt))
6801 // Value must be a load.
6802 SDNode *Base = N->getOperand(0).getNode();
6803 if (!isa<LoadSDNode>(Base)) {
6804 if (Base->getOpcode() != ISD::BIT_CONVERT)
6806 Base = Base->getOperand(0).getNode();
6807 if (!isa<LoadSDNode>(Base))
6811 // Transform it into VZEXT_LOAD addr.
6812 LoadSDNode *LD = cast<LoadSDNode>(Base);
6814 // Load must not be an extload.
6815 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6818 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6821 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6822 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6823 const X86Subtarget *Subtarget) {
6824 SDValue Cond = N->getOperand(0);
6826 // If we have SSE[12] support, try to form min/max nodes.
6827 if (Subtarget->hasSSE2() &&
6828 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6829 if (Cond.getOpcode() == ISD::SETCC) {
6830 // Get the LHS/RHS of the select.
6831 SDValue LHS = N->getOperand(1);
6832 SDValue RHS = N->getOperand(2);
6833 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6835 unsigned Opcode = 0;
6836 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6839 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6842 if (!UnsafeFPMath) break;
6844 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6846 Opcode = X86ISD::FMIN;
6849 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6852 if (!UnsafeFPMath) break;
6854 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6856 Opcode = X86ISD::FMAX;
6859 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6862 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6865 if (!UnsafeFPMath) break;
6867 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6869 Opcode = X86ISD::FMIN;
6872 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6875 if (!UnsafeFPMath) break;
6877 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6879 Opcode = X86ISD::FMAX;
6885 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6893 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6894 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6895 const X86Subtarget *Subtarget) {
6896 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6897 // the FP state in cases where an emms may be missing.
6898 // A preferable solution to the general problem is to figure out the right
6899 // places to insert EMMS. This qualifies as a quick hack.
6900 StoreSDNode *St = cast<StoreSDNode>(N);
6901 if (St->getValue().getValueType().isVector() &&
6902 St->getValue().getValueType().getSizeInBits() == 64 &&
6903 isa<LoadSDNode>(St->getValue()) &&
6904 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6905 St->getChain().hasOneUse() && !St->isVolatile()) {
6906 SDNode* LdVal = St->getValue().getNode();
6908 int TokenFactorIndex = -1;
6909 SmallVector<SDValue, 8> Ops;
6910 SDNode* ChainVal = St->getChain().getNode();
6911 // Must be a store of a load. We currently handle two cases: the load
6912 // is a direct child, and it's under an intervening TokenFactor. It is
6913 // possible to dig deeper under nested TokenFactors.
6914 if (ChainVal == LdVal)
6915 Ld = cast<LoadSDNode>(St->getChain());
6916 else if (St->getValue().hasOneUse() &&
6917 ChainVal->getOpcode() == ISD::TokenFactor) {
6918 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6919 if (ChainVal->getOperand(i).getNode() == LdVal) {
6920 TokenFactorIndex = i;
6921 Ld = cast<LoadSDNode>(St->getValue());
6923 Ops.push_back(ChainVal->getOperand(i));
6927 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6928 if (Subtarget->is64Bit()) {
6929 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6930 Ld->getBasePtr(), Ld->getSrcValue(),
6931 Ld->getSrcValueOffset(), Ld->isVolatile(),
6932 Ld->getAlignment());
6933 SDValue NewChain = NewLd.getValue(1);
6934 if (TokenFactorIndex != -1) {
6935 Ops.push_back(NewChain);
6936 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6939 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6940 St->getSrcValue(), St->getSrcValueOffset(),
6941 St->isVolatile(), St->getAlignment());
6944 // Otherwise, lower to two 32-bit copies.
6945 SDValue LoAddr = Ld->getBasePtr();
6946 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6947 DAG.getConstant(4, MVT::i32));
6949 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6950 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6951 Ld->isVolatile(), Ld->getAlignment());
6952 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6953 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6955 MinAlign(Ld->getAlignment(), 4));
6957 SDValue NewChain = LoLd.getValue(1);
6958 if (TokenFactorIndex != -1) {
6959 Ops.push_back(LoLd);
6960 Ops.push_back(HiLd);
6961 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6965 LoAddr = St->getBasePtr();
6966 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6967 DAG.getConstant(4, MVT::i32));
6969 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6970 St->getSrcValue(), St->getSrcValueOffset(),
6971 St->isVolatile(), St->getAlignment());
6972 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6974 St->getSrcValueOffset() + 4,
6976 MinAlign(St->getAlignment(), 4));
6977 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6983 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6984 /// X86ISD::FXOR nodes.
6985 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6986 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6987 // F[X]OR(0.0, x) -> x
6988 // F[X]OR(x, 0.0) -> x
6989 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6990 if (C->getValueAPF().isPosZero())
6991 return N->getOperand(1);
6992 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6993 if (C->getValueAPF().isPosZero())
6994 return N->getOperand(0);
6998 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6999 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7000 // FAND(0.0, x) -> 0.0
7001 // FAND(x, 0.0) -> 0.0
7002 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7003 if (C->getValueAPF().isPosZero())
7004 return N->getOperand(0);
7005 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7006 if (C->getValueAPF().isPosZero())
7007 return N->getOperand(1);
7012 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7013 DAGCombinerInfo &DCI) const {
7014 SelectionDAG &DAG = DCI.DAG;
7015 switch (N->getOpcode()) {
7017 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7018 case ISD::BUILD_VECTOR:
7019 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7020 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7021 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7023 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7024 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7030 //===----------------------------------------------------------------------===//
7031 // X86 Inline Assembly Support
7032 //===----------------------------------------------------------------------===//
7034 /// getConstraintType - Given a constraint letter, return the type of
7035 /// constraint it is for this target.
7036 X86TargetLowering::ConstraintType
7037 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7038 if (Constraint.size() == 1) {
7039 switch (Constraint[0]) {
7050 return C_RegisterClass;
7055 return TargetLowering::getConstraintType(Constraint);
7058 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7059 /// with another that has more specific requirements based on the type of the
7060 /// corresponding operand.
7061 const char *X86TargetLowering::
7062 LowerXConstraint(MVT ConstraintVT) const {
7063 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7064 // 'f' like normal targets.
7065 if (ConstraintVT.isFloatingPoint()) {
7066 if (Subtarget->hasSSE2())
7068 if (Subtarget->hasSSE1())
7072 return TargetLowering::LowerXConstraint(ConstraintVT);
7075 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7076 /// vector. If it is invalid, don't add anything to Ops.
7077 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7079 std::vector<SDValue>&Ops,
7080 SelectionDAG &DAG) const {
7081 SDValue Result(0, 0);
7083 switch (Constraint) {
7086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7087 if (C->getZExtValue() <= 31) {
7088 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7095 if (C->getZExtValue() <= 255) {
7096 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7102 // Literal immediates are always ok.
7103 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7104 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7108 // If we are in non-pic codegen mode, we allow the address of a global (with
7109 // an optional displacement) to be used with 'i'.
7110 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7113 // Match either (GA) or (GA+C)
7115 Offset = GA->getOffset();
7116 } else if (Op.getOpcode() == ISD::ADD) {
7117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7118 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7120 Offset = GA->getOffset()+C->getZExtValue();
7122 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7123 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7125 Offset = GA->getOffset()+C->getZExtValue();
7132 // If addressing this global requires a load (e.g. in PIC mode), we can't
7134 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
7138 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7144 // Otherwise, not valid for this mode.
7149 if (Result.getNode()) {
7150 Ops.push_back(Result);
7153 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7156 std::vector<unsigned> X86TargetLowering::
7157 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7159 if (Constraint.size() == 1) {
7160 // FIXME: not handling fp-stack yet!
7161 switch (Constraint[0]) { // GCC X86 Constraint Letters
7162 default: break; // Unknown constraint letter
7163 case 'A': // EAX/EDX
7164 if (VT == MVT::i32 || VT == MVT::i64)
7165 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7167 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7170 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7171 else if (VT == MVT::i16)
7172 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7173 else if (VT == MVT::i8)
7174 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7175 else if (VT == MVT::i64)
7176 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7181 return std::vector<unsigned>();
7184 std::pair<unsigned, const TargetRegisterClass*>
7185 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7187 // First, see if this is a constraint that directly corresponds to an LLVM
7189 if (Constraint.size() == 1) {
7190 // GCC Constraint Letters
7191 switch (Constraint[0]) {
7193 case 'r': // GENERAL_REGS
7194 case 'R': // LEGACY_REGS
7195 case 'l': // INDEX_REGS
7196 if (VT == MVT::i64 && Subtarget->is64Bit())
7197 return std::make_pair(0U, X86::GR64RegisterClass);
7199 return std::make_pair(0U, X86::GR32RegisterClass);
7200 else if (VT == MVT::i16)
7201 return std::make_pair(0U, X86::GR16RegisterClass);
7202 else if (VT == MVT::i8)
7203 return std::make_pair(0U, X86::GR8RegisterClass);
7205 case 'f': // FP Stack registers.
7206 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7207 // value to the correct fpstack register class.
7208 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7209 return std::make_pair(0U, X86::RFP32RegisterClass);
7210 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7211 return std::make_pair(0U, X86::RFP64RegisterClass);
7212 return std::make_pair(0U, X86::RFP80RegisterClass);
7213 case 'y': // MMX_REGS if MMX allowed.
7214 if (!Subtarget->hasMMX()) break;
7215 return std::make_pair(0U, X86::VR64RegisterClass);
7217 case 'Y': // SSE_REGS if SSE2 allowed
7218 if (!Subtarget->hasSSE2()) break;
7220 case 'x': // SSE_REGS if SSE1 allowed
7221 if (!Subtarget->hasSSE1()) break;
7223 switch (VT.getSimpleVT()) {
7225 // Scalar SSE types.
7228 return std::make_pair(0U, X86::FR32RegisterClass);
7231 return std::make_pair(0U, X86::FR64RegisterClass);
7239 return std::make_pair(0U, X86::VR128RegisterClass);
7245 // Use the default implementation in TargetLowering to convert the register
7246 // constraint into a member of a register class.
7247 std::pair<unsigned, const TargetRegisterClass*> Res;
7248 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7250 // Not found as a standard register?
7251 if (Res.second == 0) {
7252 // GCC calls "st(0)" just plain "st".
7253 if (StringsEqualNoCase("{st}", Constraint)) {
7254 Res.first = X86::ST0;
7255 Res.second = X86::RFP80RegisterClass;
7261 // Otherwise, check to see if this is a register class of the wrong value
7262 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7263 // turn into {ax},{dx}.
7264 if (Res.second->hasType(VT))
7265 return Res; // Correct type already, nothing to do.
7267 // All of the single-register GCC register classes map their values onto
7268 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7269 // really want an 8-bit or 32-bit register, map to the appropriate register
7270 // class and return the appropriate register.
7271 if (Res.second == X86::GR16RegisterClass) {
7272 if (VT == MVT::i8) {
7273 unsigned DestReg = 0;
7274 switch (Res.first) {
7276 case X86::AX: DestReg = X86::AL; break;
7277 case X86::DX: DestReg = X86::DL; break;
7278 case X86::CX: DestReg = X86::CL; break;
7279 case X86::BX: DestReg = X86::BL; break;
7282 Res.first = DestReg;
7283 Res.second = Res.second = X86::GR8RegisterClass;
7285 } else if (VT == MVT::i32) {
7286 unsigned DestReg = 0;
7287 switch (Res.first) {
7289 case X86::AX: DestReg = X86::EAX; break;
7290 case X86::DX: DestReg = X86::EDX; break;
7291 case X86::CX: DestReg = X86::ECX; break;
7292 case X86::BX: DestReg = X86::EBX; break;
7293 case X86::SI: DestReg = X86::ESI; break;
7294 case X86::DI: DestReg = X86::EDI; break;
7295 case X86::BP: DestReg = X86::EBP; break;
7296 case X86::SP: DestReg = X86::ESP; break;
7299 Res.first = DestReg;
7300 Res.second = Res.second = X86::GR32RegisterClass;
7302 } else if (VT == MVT::i64) {
7303 unsigned DestReg = 0;
7304 switch (Res.first) {
7306 case X86::AX: DestReg = X86::RAX; break;
7307 case X86::DX: DestReg = X86::RDX; break;
7308 case X86::CX: DestReg = X86::RCX; break;
7309 case X86::BX: DestReg = X86::RBX; break;
7310 case X86::SI: DestReg = X86::RSI; break;
7311 case X86::DI: DestReg = X86::RDI; break;
7312 case X86::BP: DestReg = X86::RBP; break;
7313 case X86::SP: DestReg = X86::RSP; break;
7316 Res.first = DestReg;
7317 Res.second = Res.second = X86::GR64RegisterClass;
7320 } else if (Res.second == X86::FR32RegisterClass ||
7321 Res.second == X86::FR64RegisterClass ||
7322 Res.second == X86::VR128RegisterClass) {
7323 // Handle references to XMM physical registers that got mapped into the
7324 // wrong class. This can happen with constraints like {xmm0} where the
7325 // target independent register mapper will just pick the first match it can
7326 // find, ignoring the required type.
7328 Res.second = X86::FR32RegisterClass;
7329 else if (VT == MVT::f64)
7330 Res.second = X86::FR64RegisterClass;
7331 else if (X86::VR128RegisterClass->hasType(VT))
7332 Res.second = X86::VR128RegisterClass;