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 "X86FastISel.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/VectorExtras.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
44 // Forward declarations.
45 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
47 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
48 : TargetLowering(TM) {
49 Subtarget = &TM.getSubtarget<X86Subtarget>();
50 X86ScalarSSEf64 = Subtarget->hasSSE2();
51 X86ScalarSSEf32 = Subtarget->hasSSE1();
52 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
56 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 if (!Subtarget->is64Bit())
263 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
266 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
267 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
270 if (Subtarget->is64Bit())
271 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
272 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
273 if (Subtarget->is64Bit()) {
274 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
275 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
276 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
277 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
279 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
280 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
281 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
282 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
283 if (Subtarget->is64Bit()) {
284 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
285 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
286 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
289 if (Subtarget->hasSSE1())
290 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
292 if (!Subtarget->hasSSE2())
293 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
295 // Expand certain atomics
296 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i8, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i16, Custom);
298 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i32, Custom);
299 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i64, Custom);
301 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i8, Expand);
302 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i16, Expand);
303 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i32, Expand);
304 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i64, Expand);
306 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
307 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
308 // FIXME - use subtarget debug flags
309 if (!Subtarget->isTargetDarwin() &&
310 !Subtarget->isTargetELF() &&
311 !Subtarget->isTargetCygMing()) {
312 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
313 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
316 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
317 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
318 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
319 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
320 if (Subtarget->is64Bit()) {
322 setExceptionPointerRegister(X86::RAX);
323 setExceptionSelectorRegister(X86::RDX);
325 setExceptionPointerRegister(X86::EAX);
326 setExceptionSelectorRegister(X86::EDX);
328 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
330 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
332 setOperationAction(ISD::TRAP, MVT::Other, Legal);
334 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
335 setOperationAction(ISD::VASTART , MVT::Other, Custom);
336 setOperationAction(ISD::VAEND , MVT::Other, Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::VAARG , MVT::Other, Custom);
339 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
341 setOperationAction(ISD::VAARG , MVT::Other, Expand);
342 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
345 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
346 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
349 if (Subtarget->isTargetCygMing())
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
352 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
354 if (X86ScalarSSEf64) {
355 // f32 and f64 use SSE.
356 // Set up the FP register classes.
357 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
358 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
360 // Use ANDPD to simulate FABS.
361 setOperationAction(ISD::FABS , MVT::f64, Custom);
362 setOperationAction(ISD::FABS , MVT::f32, Custom);
364 // Use XORP to simulate FNEG.
365 setOperationAction(ISD::FNEG , MVT::f64, Custom);
366 setOperationAction(ISD::FNEG , MVT::f32, Custom);
368 // Use ANDPD and ORPD to simulate FCOPYSIGN.
369 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
370 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
372 // We don't support sin/cos/fmod
373 setOperationAction(ISD::FSIN , MVT::f64, Expand);
374 setOperationAction(ISD::FCOS , MVT::f64, Expand);
375 setOperationAction(ISD::FSIN , MVT::f32, Expand);
376 setOperationAction(ISD::FCOS , MVT::f32, Expand);
378 // Expand FP immediates into loads from the stack, except for the special
380 addLegalFPImmediate(APFloat(+0.0)); // xorpd
381 addLegalFPImmediate(APFloat(+0.0f)); // xorps
383 // Floating truncations from f80 and extensions to f80 go through memory.
384 // If optimizing, we lie about this though and handle it in
385 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
387 setConvertAction(MVT::f32, MVT::f80, Expand);
388 setConvertAction(MVT::f64, MVT::f80, Expand);
389 setConvertAction(MVT::f80, MVT::f32, Expand);
390 setConvertAction(MVT::f80, MVT::f64, Expand);
392 } else if (X86ScalarSSEf32) {
393 // Use SSE for f32, x87 for f64.
394 // Set up the FP register classes.
395 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
396 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
398 // Use ANDPS to simulate FABS.
399 setOperationAction(ISD::FABS , MVT::f32, Custom);
401 // Use XORP to simulate FNEG.
402 setOperationAction(ISD::FNEG , MVT::f32, Custom);
404 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
406 // Use ANDPS and ORPS to simulate FCOPYSIGN.
407 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
410 // We don't support sin/cos/fmod
411 setOperationAction(ISD::FSIN , MVT::f32, Expand);
412 setOperationAction(ISD::FCOS , MVT::f32, Expand);
414 // Special cases we handle for FP constants.
415 addLegalFPImmediate(APFloat(+0.0f)); // xorps
416 addLegalFPImmediate(APFloat(+0.0)); // FLD0
417 addLegalFPImmediate(APFloat(+1.0)); // FLD1
418 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
419 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
421 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
422 // this though and handle it in InstructionSelectPreprocess so that
423 // dagcombine2 can hack on these.
425 setConvertAction(MVT::f32, MVT::f64, Expand);
426 setConvertAction(MVT::f32, MVT::f80, Expand);
427 setConvertAction(MVT::f80, MVT::f32, Expand);
428 setConvertAction(MVT::f64, MVT::f32, Expand);
429 // And x87->x87 truncations also.
430 setConvertAction(MVT::f80, MVT::f64, Expand);
434 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
435 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
438 // f32 and f64 in x87.
439 // Set up the FP register classes.
440 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
441 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
443 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
444 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
445 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
446 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
448 // Floating truncations go through memory. If optimizing, we lie about
449 // this though and handle it in InstructionSelectPreprocess so that
450 // dagcombine2 can hack on these.
452 setConvertAction(MVT::f80, MVT::f32, Expand);
453 setConvertAction(MVT::f64, MVT::f32, Expand);
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
461 addLegalFPImmediate(APFloat(+0.0)); // FLD0
462 addLegalFPImmediate(APFloat(+1.0)); // FLD1
463 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
464 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
465 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
466 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
467 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
468 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
471 // Long double always uses X87.
472 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
473 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
474 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
476 APFloat TmpFlt(+0.0);
477 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
478 addLegalFPImmediate(TmpFlt); // FLD0
480 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
481 APFloat TmpFlt2(+1.0);
482 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
483 addLegalFPImmediate(TmpFlt2); // FLD1
484 TmpFlt2.changeSign();
485 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
489 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
490 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
493 // Always use a library call for pow.
494 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
495 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
496 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
498 // First set operation action for all vector types to expand. Then we
499 // will selectively turn on ones that can be effectively codegen'd.
500 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
501 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
502 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
503 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
504 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
505 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
506 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
507 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
508 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
509 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
510 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
511 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
512 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
542 if (Subtarget->hasMMX()) {
543 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
544 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
545 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
546 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
547 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
549 // FIXME: add MMX packed arithmetics
551 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
552 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
553 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
554 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
556 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
557 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
558 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
559 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
561 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
562 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
564 setOperationAction(ISD::AND, MVT::v8i8, Promote);
565 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
566 setOperationAction(ISD::AND, MVT::v4i16, Promote);
567 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
568 setOperationAction(ISD::AND, MVT::v2i32, Promote);
569 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
570 setOperationAction(ISD::AND, MVT::v1i64, Legal);
572 setOperationAction(ISD::OR, MVT::v8i8, Promote);
573 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
574 setOperationAction(ISD::OR, MVT::v4i16, Promote);
575 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
576 setOperationAction(ISD::OR, MVT::v2i32, Promote);
577 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
578 setOperationAction(ISD::OR, MVT::v1i64, Legal);
580 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
581 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
582 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
583 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
584 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
585 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
586 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
588 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
589 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
590 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
591 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
592 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
593 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
594 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
595 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
596 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
598 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
599 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
600 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
601 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
602 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
604 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
605 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
606 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
610 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
611 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
612 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
614 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
617 if (Subtarget->hasSSE1()) {
618 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
620 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
621 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
622 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
623 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
624 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
625 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
626 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
627 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
628 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
630 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
631 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
634 if (Subtarget->hasSSE2()) {
635 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
636 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
637 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
638 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
639 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
641 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
642 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
643 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
644 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
645 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
646 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
647 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
648 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
649 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
650 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
651 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
652 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
653 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
654 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
655 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
657 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
658 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
659 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
660 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
662 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
663 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
664 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
665 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
666 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
668 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
669 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
670 MVT VT = (MVT::SimpleValueType)i;
671 // Do not attempt to custom lower non-power-of-2 vectors
672 if (!isPowerOf2_32(VT.getVectorNumElements()))
674 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
676 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
678 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
679 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
680 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
681 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
682 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
683 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
684 if (Subtarget->is64Bit()) {
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
686 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
689 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
690 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
691 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
692 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
693 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
694 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
695 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
696 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
698 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
699 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
700 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
703 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
705 // Custom lower v2i64 and v2f64 selects.
706 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
707 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
708 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
709 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
713 if (Subtarget->hasSSE41()) {
714 // FIXME: Do we need to handle scalar-to-vector here?
715 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
716 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
718 // i8 and i16 vectors are custom , because the source register and source
719 // source memory operand types are not the same width. f32 vectors are
720 // custom since the immediate controlling the insert encodes additional
722 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
723 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
724 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
725 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
728 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
729 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
732 if (Subtarget->is64Bit()) {
733 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
734 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
738 if (Subtarget->hasSSE42()) {
739 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
742 // We want to custom lower some of our intrinsics.
743 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
745 // We have target-specific dag combine patterns for the following nodes:
746 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
747 setTargetDAGCombine(ISD::BUILD_VECTOR);
748 setTargetDAGCombine(ISD::SELECT);
749 setTargetDAGCombine(ISD::STORE);
751 computeRegisterProperties();
753 // FIXME: These should be based on subtarget info. Plus, the values should
754 // be smaller when we are in optimizing for size mode.
755 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
756 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
757 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
758 allowUnalignedMemoryAccesses = true; // x86 supports it!
759 setPrefLoopAlignment(16);
763 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
768 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
769 /// the desired ByVal argument alignment.
770 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
773 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
774 if (VTy->getBitWidth() == 128)
776 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
777 unsigned EltAlign = 0;
778 getMaxByValAlign(ATy->getElementType(), EltAlign);
779 if (EltAlign > MaxAlign)
781 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
782 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
783 unsigned EltAlign = 0;
784 getMaxByValAlign(STy->getElementType(i), EltAlign);
785 if (EltAlign > MaxAlign)
794 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
795 /// function arguments in the caller parameter area. For X86, aggregates
796 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
797 /// are at 4-byte boundaries.
798 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
799 if (Subtarget->is64Bit()) {
800 // Max of 8 and alignment of type.
801 unsigned TyAlign = getTargetData()->getABITypeAlignment(Ty);
808 if (Subtarget->hasSSE1())
809 getMaxByValAlign(Ty, Align);
813 /// getOptimalMemOpType - Returns the target specific optimal type for load
814 /// and store operations as a result of memset, memcpy, and memmove
815 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
818 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
819 bool isSrcConst, bool isSrcStr) const {
820 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
822 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
824 if (Subtarget->is64Bit() && Size >= 8)
830 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
832 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
833 SelectionDAG &DAG) const {
834 if (usesGlobalOffsetTable())
835 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
836 if (!Subtarget->isPICStyleRIPRel())
837 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
841 //===----------------------------------------------------------------------===//
842 // Return Value Calling Convention Implementation
843 //===----------------------------------------------------------------------===//
845 #include "X86GenCallingConv.inc"
847 /// LowerRET - Lower an ISD::RET node.
848 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
849 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
851 SmallVector<CCValAssign, 16> RVLocs;
852 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
853 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
854 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
855 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
857 // If this is the first return lowered for this function, add the regs to the
858 // liveout set for the function.
859 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
860 for (unsigned i = 0; i != RVLocs.size(); ++i)
861 if (RVLocs[i].isRegLoc())
862 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
864 SDValue Chain = Op.getOperand(0);
866 // Handle tail call return.
867 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
868 if (Chain.getOpcode() == X86ISD::TAILCALL) {
869 SDValue TailCall = Chain;
870 SDValue TargetAddress = TailCall.getOperand(1);
871 SDValue StackAdjustment = TailCall.getOperand(2);
872 assert(((TargetAddress.getOpcode() == ISD::Register &&
873 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
874 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
875 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
876 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
877 "Expecting an global address, external symbol, or register");
878 assert(StackAdjustment.getOpcode() == ISD::Constant &&
879 "Expecting a const value");
881 SmallVector<SDValue,8> Operands;
882 Operands.push_back(Chain.getOperand(0));
883 Operands.push_back(TargetAddress);
884 Operands.push_back(StackAdjustment);
885 // Copy registers used by the call. Last operand is a flag so it is not
887 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
888 Operands.push_back(Chain.getOperand(i));
890 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
897 SmallVector<SDValue, 6> RetOps;
898 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
899 // Operand #1 = Bytes To Pop
900 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
902 // Copy the result values into the output registers.
903 for (unsigned i = 0; i != RVLocs.size(); ++i) {
904 CCValAssign &VA = RVLocs[i];
905 assert(VA.isRegLoc() && "Can only return in registers!");
906 SDValue ValToCopy = Op.getOperand(i*2+1);
908 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
909 // the RET instruction and handled by the FP Stackifier.
910 if (RVLocs[i].getLocReg() == X86::ST0 ||
911 RVLocs[i].getLocReg() == X86::ST1) {
912 // If this is a copy from an xmm register to ST(0), use an FPExtend to
913 // change the value to the FP stack register class.
914 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
915 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
916 RetOps.push_back(ValToCopy);
917 // Don't emit a copytoreg.
921 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
922 Flag = Chain.getValue(1);
925 // The x86-64 ABI for returning structs by value requires that we copy
926 // the sret argument into %rax for the return. We saved the argument into
927 // a virtual register in the entry block, so now we copy the value out
929 if (Subtarget->is64Bit() &&
930 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
931 MachineFunction &MF = DAG.getMachineFunction();
932 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
933 unsigned Reg = FuncInfo->getSRetReturnReg();
935 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
936 FuncInfo->setSRetReturnReg(Reg);
938 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
940 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
941 Flag = Chain.getValue(1);
944 RetOps[0] = Chain; // Update chain.
946 // Add the flag if we have it.
948 RetOps.push_back(Flag);
950 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
954 /// LowerCallResult - Lower the result values of an ISD::CALL into the
955 /// appropriate copies out of appropriate physical registers. This assumes that
956 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
957 /// being lowered. The returns a SDNode with the same number of values as the
959 SDNode *X86TargetLowering::
960 LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall,
961 unsigned CallingConv, SelectionDAG &DAG) {
963 // Assign locations to each value returned by this call.
964 SmallVector<CCValAssign, 16> RVLocs;
965 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
966 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
967 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
969 SmallVector<SDValue, 8> ResultVals;
971 // Copy all of the result registers out of their specified physreg.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 MVT CopyVT = RVLocs[i].getValVT();
975 // If this is a call to a function that returns an fp value on the floating
976 // point stack, but where we prefer to use the value in xmm registers, copy
977 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
978 if ((RVLocs[i].getLocReg() == X86::ST0 ||
979 RVLocs[i].getLocReg() == X86::ST1) &&
980 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
984 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
985 CopyVT, InFlag).getValue(1);
986 SDValue Val = Chain.getValue(0);
987 InFlag = Chain.getValue(2);
989 if (CopyVT != RVLocs[i].getValVT()) {
990 // Round the F80 the right size, which also moves to the appropriate xmm
992 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
993 // This truncation won't change the value.
994 DAG.getIntPtrConstant(1));
997 ResultVals.push_back(Val);
1000 // Merge everything together with a MERGE_VALUES node.
1001 ResultVals.push_back(Chain);
1002 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1003 ResultVals.size()).Val;
1007 //===----------------------------------------------------------------------===//
1008 // C & StdCall & Fast Calling Convention implementation
1009 //===----------------------------------------------------------------------===//
1010 // StdCall calling convention seems to be standard for many Windows' API
1011 // routines and around. It differs from C calling convention just a little:
1012 // callee should clean up the stack, not caller. Symbols should be also
1013 // decorated in some fancy way :) It doesn't support any vector arguments.
1014 // For info on fast calling convention see Fast Calling Convention (tail call)
1015 // implementation LowerX86_32FastCCCallTo.
1017 /// AddLiveIn - This helper function adds the specified physical register to the
1018 /// MachineFunction as a live in value. It also creates a corresponding virtual
1019 /// register for it.
1020 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1021 const TargetRegisterClass *RC) {
1022 assert(RC->contains(PReg) && "Not the correct regclass!");
1023 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1024 MF.getRegInfo().addLiveIn(PReg, VReg);
1028 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1030 static bool CallIsStructReturn(SDValue Op) {
1031 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1035 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1038 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1039 /// return semantics.
1040 static bool ArgsAreStructReturn(SDValue Op) {
1041 unsigned NumArgs = Op.Val->getNumValues() - 1;
1045 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1048 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1049 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1051 bool X86TargetLowering::IsCalleePop(SDValue Op) {
1052 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1056 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1059 case CallingConv::X86_StdCall:
1060 return !Subtarget->is64Bit();
1061 case CallingConv::X86_FastCall:
1062 return !Subtarget->is64Bit();
1063 case CallingConv::Fast:
1064 return PerformTailCallOpt;
1068 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1069 /// FORMAL_ARGUMENTS node.
1070 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDValue Op) const {
1071 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1073 if (Subtarget->is64Bit()) {
1074 if (Subtarget->isTargetWin64())
1075 return CC_X86_Win64_C;
1077 if (CC == CallingConv::Fast && PerformTailCallOpt)
1078 return CC_X86_64_TailCall;
1084 if (CC == CallingConv::X86_FastCall)
1085 return CC_X86_32_FastCall;
1086 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1087 return CC_X86_32_TailCall;
1092 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1093 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1095 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1096 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1097 if (CC == CallingConv::X86_FastCall)
1099 else if (CC == CallingConv::X86_StdCall)
1105 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1106 /// in a register before calling.
1107 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1108 return !IsTailCall && !Is64Bit &&
1109 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1110 Subtarget->isPICStyleGOT();
1113 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1114 /// address to be loaded in a register.
1116 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1117 return !Is64Bit && IsTailCall &&
1118 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1119 Subtarget->isPICStyleGOT();
1122 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1123 /// by "Src" to address "Dst" with size and alignment information specified by
1124 /// the specific parameter attribute. The copy will be passed as a byval
1125 /// function parameter.
1127 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1128 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1129 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1130 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1131 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1134 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1135 const CCValAssign &VA,
1136 MachineFrameInfo *MFI,
1138 SDValue Root, unsigned i) {
1139 // Create the nodes corresponding to a load from this parameter slot.
1140 ISD::ArgFlagsTy Flags =
1141 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1142 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1143 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1145 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1146 // changed with more analysis.
1147 // In case of tail call optimization mark all arguments mutable. Since they
1148 // could be overwritten by lowering of arguments in case of a tail call.
1149 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1150 VA.getLocMemOffset(), isImmutable);
1151 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1152 if (Flags.isByVal())
1154 return DAG.getLoad(VA.getValVT(), Root, FIN,
1155 PseudoSourceValue::getFixedStack(FI), 0);
1159 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1160 MachineFunction &MF = DAG.getMachineFunction();
1161 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1163 const Function* Fn = MF.getFunction();
1164 if (Fn->hasExternalLinkage() &&
1165 Subtarget->isTargetCygMing() &&
1166 Fn->getName() == "main")
1167 FuncInfo->setForceFramePointer(true);
1169 // Decorate the function name.
1170 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1172 MachineFrameInfo *MFI = MF.getFrameInfo();
1173 SDValue Root = Op.getOperand(0);
1174 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1175 unsigned CC = MF.getFunction()->getCallingConv();
1176 bool Is64Bit = Subtarget->is64Bit();
1177 bool IsWin64 = Subtarget->isTargetWin64();
1179 assert(!(isVarArg && CC == CallingConv::Fast) &&
1180 "Var args not supported with calling convention fastcc");
1182 // Assign locations to all of the incoming arguments.
1183 SmallVector<CCValAssign, 16> ArgLocs;
1184 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1185 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1187 SmallVector<SDValue, 8> ArgValues;
1188 unsigned LastVal = ~0U;
1189 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1190 CCValAssign &VA = ArgLocs[i];
1191 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1193 assert(VA.getValNo() != LastVal &&
1194 "Don't support value assigned to multiple locs yet");
1195 LastVal = VA.getValNo();
1197 if (VA.isRegLoc()) {
1198 MVT RegVT = VA.getLocVT();
1199 TargetRegisterClass *RC;
1200 if (RegVT == MVT::i32)
1201 RC = X86::GR32RegisterClass;
1202 else if (Is64Bit && RegVT == MVT::i64)
1203 RC = X86::GR64RegisterClass;
1204 else if (RegVT == MVT::f32)
1205 RC = X86::FR32RegisterClass;
1206 else if (RegVT == MVT::f64)
1207 RC = X86::FR64RegisterClass;
1208 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1209 RC = X86::VR128RegisterClass;
1210 else if (RegVT.isVector()) {
1211 assert(RegVT.getSizeInBits() == 64);
1213 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1215 // Darwin calling convention passes MMX values in either GPRs or
1216 // XMMs in x86-64. Other targets pass them in memory.
1217 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1218 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1221 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1226 assert(0 && "Unknown argument type!");
1229 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1230 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1232 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1233 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1235 if (VA.getLocInfo() == CCValAssign::SExt)
1236 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1237 DAG.getValueType(VA.getValVT()));
1238 else if (VA.getLocInfo() == CCValAssign::ZExt)
1239 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1240 DAG.getValueType(VA.getValVT()));
1242 if (VA.getLocInfo() != CCValAssign::Full)
1243 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1245 // Handle MMX values passed in GPRs.
1246 if (Is64Bit && RegVT != VA.getLocVT()) {
1247 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1248 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1249 else if (RC == X86::VR128RegisterClass) {
1250 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1251 DAG.getConstant(0, MVT::i64));
1252 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1256 ArgValues.push_back(ArgValue);
1258 assert(VA.isMemLoc());
1259 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1263 // The x86-64 ABI for returning structs by value requires that we copy
1264 // the sret argument into %rax for the return. Save the argument into
1265 // a virtual register so that we can access it from the return points.
1266 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1267 MachineFunction &MF = DAG.getMachineFunction();
1268 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1269 unsigned Reg = FuncInfo->getSRetReturnReg();
1271 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1272 FuncInfo->setSRetReturnReg(Reg);
1274 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1275 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1278 unsigned StackSize = CCInfo.getNextStackOffset();
1279 // align stack specially for tail calls
1280 if (CC == CallingConv::Fast)
1281 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1283 // If the function takes variable number of arguments, make a frame index for
1284 // the start of the first vararg value... for expansion of llvm.va_start.
1286 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1287 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1290 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1292 // FIXME: We should really autogenerate these arrays
1293 static const unsigned GPR64ArgRegsWin64[] = {
1294 X86::RCX, X86::RDX, X86::R8, X86::R9
1296 static const unsigned XMMArgRegsWin64[] = {
1297 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1299 static const unsigned GPR64ArgRegs64Bit[] = {
1300 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1302 static const unsigned XMMArgRegs64Bit[] = {
1303 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1304 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1306 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1309 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1310 GPR64ArgRegs = GPR64ArgRegsWin64;
1311 XMMArgRegs = XMMArgRegsWin64;
1313 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1314 GPR64ArgRegs = GPR64ArgRegs64Bit;
1315 XMMArgRegs = XMMArgRegs64Bit;
1317 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1319 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1322 // For X86-64, if there are vararg parameters that are passed via
1323 // registers, then we must store them to their spots on the stack so they
1324 // may be loaded by deferencing the result of va_next.
1325 VarArgsGPOffset = NumIntRegs * 8;
1326 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1327 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1328 TotalNumXMMRegs * 16, 16);
1330 // Store the integer parameter registers.
1331 SmallVector<SDValue, 8> MemOps;
1332 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1333 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1334 DAG.getIntPtrConstant(VarArgsGPOffset));
1335 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1336 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1337 X86::GR64RegisterClass);
1338 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1340 DAG.getStore(Val.getValue(1), Val, FIN,
1341 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1342 MemOps.push_back(Store);
1343 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1344 DAG.getIntPtrConstant(8));
1347 // Now store the XMM (fp + vector) parameter registers.
1348 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1349 DAG.getIntPtrConstant(VarArgsFPOffset));
1350 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1351 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1352 X86::VR128RegisterClass);
1353 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
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(16));
1361 if (!MemOps.empty())
1362 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1363 &MemOps[0], MemOps.size());
1367 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1368 // arguments and the arguments after the retaddr has been pushed are
1370 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1371 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1372 (StackSize & 7) == 0)
1375 ArgValues.push_back(Root);
1377 // Some CCs need callee pop.
1378 if (IsCalleePop(Op)) {
1379 BytesToPopOnReturn = StackSize; // Callee pops everything.
1380 BytesCallerReserves = 0;
1382 BytesToPopOnReturn = 0; // Callee pops nothing.
1383 // If this is an sret function, the return should pop the hidden pointer.
1384 if (!Is64Bit && ArgsAreStructReturn(Op))
1385 BytesToPopOnReturn = 4;
1386 BytesCallerReserves = StackSize;
1390 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1391 if (CC == CallingConv::X86_FastCall)
1392 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1395 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1397 // Return the new list of results.
1398 return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
1399 ArgValues.size()).getValue(Op.ResNo);
1403 X86TargetLowering::LowerMemOpCallTo(SDValue Op, SelectionDAG &DAG,
1404 const SDValue &StackPtr,
1405 const CCValAssign &VA,
1408 unsigned LocMemOffset = VA.getLocMemOffset();
1409 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1410 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1411 ISD::ArgFlagsTy Flags =
1412 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1413 if (Flags.isByVal()) {
1414 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1416 return DAG.getStore(Chain, Arg, PtrOff,
1417 PseudoSourceValue::getStack(), LocMemOffset);
1420 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1421 /// optimization is performed and it is required.
1423 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1424 SDValue &OutRetAddr,
1429 if (!IsTailCall || FPDiff==0) return Chain;
1431 // Adjust the Return address stack slot.
1432 MVT VT = getPointerTy();
1433 OutRetAddr = getReturnAddressFrameIndex(DAG);
1434 // Load the "old" Return address.
1435 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1436 return SDValue(OutRetAddr.Val, 1);
1439 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1440 /// optimization is performed and it is required (FPDiff!=0).
1442 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1443 SDValue Chain, SDValue RetAddrFrIdx,
1444 bool Is64Bit, int FPDiff) {
1445 // Store the return address to the appropriate stack slot.
1446 if (!FPDiff) return Chain;
1447 // Calculate the new stack slot for the return address.
1448 int SlotSize = Is64Bit ? 8 : 4;
1449 int NewReturnAddrFI =
1450 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1451 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1452 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1453 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1454 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1458 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1459 MachineFunction &MF = DAG.getMachineFunction();
1460 SDValue Chain = Op.getOperand(0);
1461 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1462 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1463 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1464 && CC == CallingConv::Fast && PerformTailCallOpt;
1465 SDValue Callee = Op.getOperand(4);
1466 bool Is64Bit = Subtarget->is64Bit();
1467 bool IsStructRet = CallIsStructReturn(Op);
1469 assert(!(isVarArg && CC == CallingConv::Fast) &&
1470 "Var args not supported with calling convention fastcc");
1472 // Analyze operands of the call, assigning locations to each operand.
1473 SmallVector<CCValAssign, 16> ArgLocs;
1474 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1475 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1477 // Get a count of how many bytes are to be pushed on the stack.
1478 unsigned NumBytes = CCInfo.getNextStackOffset();
1479 if (CC == CallingConv::Fast)
1480 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1482 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1483 // arguments and the arguments after the retaddr has been pushed are aligned.
1484 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1485 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1486 (NumBytes & 7) == 0)
1491 // Lower arguments at fp - stackoffset + fpdiff.
1492 unsigned NumBytesCallerPushed =
1493 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1494 FPDiff = NumBytesCallerPushed - NumBytes;
1496 // Set the delta of movement of the returnaddr stackslot.
1497 // But only set if delta is greater than previous delta.
1498 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1499 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1502 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1504 SDValue RetAddrFrIdx;
1505 // Load return adress for tail calls.
1506 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1509 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1510 SmallVector<SDValue, 8> MemOpChains;
1513 // Walk the register/memloc assignments, inserting copies/loads. In the case
1514 // of tail call optimization arguments are handle later.
1515 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1516 CCValAssign &VA = ArgLocs[i];
1517 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1518 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1519 getArgFlags().isByVal();
1521 // Promote the value if needed.
1522 switch (VA.getLocInfo()) {
1523 default: assert(0 && "Unknown loc info!");
1524 case CCValAssign::Full: break;
1525 case CCValAssign::SExt:
1526 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1528 case CCValAssign::ZExt:
1529 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1531 case CCValAssign::AExt:
1532 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1536 if (VA.isRegLoc()) {
1538 MVT RegVT = VA.getLocVT();
1539 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1540 switch (VA.getLocReg()) {
1543 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1545 // Special case: passing MMX values in GPR registers.
1546 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1549 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1550 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1551 // Special case: passing MMX values in XMM registers.
1552 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1553 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1554 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1555 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1556 getMOVLMask(2, DAG));
1561 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1563 if (!IsTailCall || (IsTailCall && isByVal)) {
1564 assert(VA.isMemLoc());
1565 if (StackPtr.Val == 0)
1566 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1568 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1574 if (!MemOpChains.empty())
1575 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1576 &MemOpChains[0], MemOpChains.size());
1578 // Build a sequence of copy-to-reg nodes chained together with token chain
1579 // and flag operands which copy the outgoing args into registers.
1581 // Tail call byval lowering might overwrite argument registers so in case of
1582 // tail call optimization the copies to registers are lowered later.
1584 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1587 InFlag = Chain.getValue(1);
1590 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1592 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1593 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1594 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1596 InFlag = Chain.getValue(1);
1598 // If we are tail calling and generating PIC/GOT style code load the address
1599 // of the callee into ecx. The value in ecx is used as target of the tail
1600 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1601 // calls on PIC/GOT architectures. Normally we would just put the address of
1602 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1603 // restored (since ebx is callee saved) before jumping to the target@PLT.
1604 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1605 // Note: The actual moving to ecx is done further down.
1606 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1607 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1608 !G->getGlobal()->hasProtectedVisibility())
1609 Callee = LowerGlobalAddress(Callee, DAG);
1610 else if (isa<ExternalSymbolSDNode>(Callee))
1611 Callee = LowerExternalSymbol(Callee,DAG);
1614 if (Is64Bit && isVarArg) {
1615 // From AMD64 ABI document:
1616 // For calls that may call functions that use varargs or stdargs
1617 // (prototype-less calls or calls to functions containing ellipsis (...) in
1618 // the declaration) %al is used as hidden argument to specify the number
1619 // of SSE registers used. The contents of %al do not need to match exactly
1620 // the number of registers, but must be an ubound on the number of SSE
1621 // registers used and is in the range 0 - 8 inclusive.
1623 // FIXME: Verify this on Win64
1624 // Count the number of XMM registers allocated.
1625 static const unsigned XMMArgRegs[] = {
1626 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1627 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1629 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1631 Chain = DAG.getCopyToReg(Chain, X86::AL,
1632 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1633 InFlag = Chain.getValue(1);
1637 // For tail calls lower the arguments to the 'real' stack slot.
1639 SmallVector<SDValue, 8> MemOpChains2;
1642 // Do not flag preceeding copytoreg stuff together with the following stuff.
1644 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1645 CCValAssign &VA = ArgLocs[i];
1646 if (!VA.isRegLoc()) {
1647 assert(VA.isMemLoc());
1648 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1649 SDValue FlagsOp = Op.getOperand(6+2*VA.getValNo());
1650 ISD::ArgFlagsTy Flags =
1651 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1652 // Create frame index.
1653 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1654 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1655 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1656 FIN = DAG.getFrameIndex(FI, getPointerTy());
1658 if (Flags.isByVal()) {
1659 // Copy relative to framepointer.
1660 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1661 if (StackPtr.Val == 0)
1662 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1663 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1665 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1668 // Store relative to framepointer.
1669 MemOpChains2.push_back(
1670 DAG.getStore(Chain, Arg, FIN,
1671 PseudoSourceValue::getFixedStack(FI), 0));
1676 if (!MemOpChains2.empty())
1677 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1678 &MemOpChains2[0], MemOpChains2.size());
1680 // Copy arguments to their registers.
1681 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1682 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1684 InFlag = Chain.getValue(1);
1688 // Store the return address to the appropriate stack slot.
1689 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1693 // If the callee is a GlobalAddress node (quite common, every direct call is)
1694 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1695 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696 // We should use extra load for direct calls to dllimported functions in
1698 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1699 getTargetMachine(), true))
1700 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1701 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1702 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1703 } else if (IsTailCall) {
1704 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1706 Chain = DAG.getCopyToReg(Chain,
1707 DAG.getRegister(Opc, getPointerTy()),
1709 Callee = DAG.getRegister(Opc, getPointerTy());
1710 // Add register as live out.
1711 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1714 // Returns a chain & a flag for retval copy to use.
1715 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1716 SmallVector<SDValue, 8> Ops;
1719 Ops.push_back(Chain);
1720 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1721 Ops.push_back(DAG.getIntPtrConstant(0));
1723 Ops.push_back(InFlag);
1724 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1725 InFlag = Chain.getValue(1);
1727 // Returns a chain & a flag for retval copy to use.
1728 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1732 Ops.push_back(Chain);
1733 Ops.push_back(Callee);
1736 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1738 // Add argument registers to the end of the list so that they are known live
1740 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1741 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1742 RegsToPass[i].second.getValueType()));
1744 // Add an implicit use GOT pointer in EBX.
1745 if (!IsTailCall && !Is64Bit &&
1746 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1747 Subtarget->isPICStyleGOT())
1748 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1750 // Add an implicit use of AL for x86 vararg functions.
1751 if (Is64Bit && isVarArg)
1752 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1755 Ops.push_back(InFlag);
1758 assert(InFlag.Val &&
1759 "Flag must be set. Depend on flag being set in LowerRET");
1760 Chain = DAG.getNode(X86ISD::TAILCALL,
1761 Op.Val->getVTList(), &Ops[0], Ops.size());
1763 return SDValue(Chain.Val, Op.ResNo);
1766 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1767 InFlag = Chain.getValue(1);
1769 // Create the CALLSEQ_END node.
1770 unsigned NumBytesForCalleeToPush;
1771 if (IsCalleePop(Op))
1772 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1773 else if (!Is64Bit && IsStructRet)
1774 // If this is is a call to a struct-return function, the callee
1775 // pops the hidden struct pointer, so we have to push it back.
1776 // This is common for Darwin/X86, Linux & Mingw32 targets.
1777 NumBytesForCalleeToPush = 4;
1779 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1781 // Returns a flag for retval copy to use.
1782 Chain = DAG.getCALLSEQ_END(Chain,
1783 DAG.getIntPtrConstant(NumBytes),
1784 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1786 InFlag = Chain.getValue(1);
1788 // Handle result values, copying them out of physregs into vregs that we
1790 return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1794 //===----------------------------------------------------------------------===//
1795 // Fast Calling Convention (tail call) implementation
1796 //===----------------------------------------------------------------------===//
1798 // Like std call, callee cleans arguments, convention except that ECX is
1799 // reserved for storing the tail called function address. Only 2 registers are
1800 // free for argument passing (inreg). Tail call optimization is performed
1802 // * tailcallopt is enabled
1803 // * caller/callee are fastcc
1804 // On X86_64 architecture with GOT-style position independent code only local
1805 // (within module) calls are supported at the moment.
1806 // To keep the stack aligned according to platform abi the function
1807 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1808 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1809 // If a tail called function callee has more arguments than the caller the
1810 // caller needs to make sure that there is room to move the RETADDR to. This is
1811 // achieved by reserving an area the size of the argument delta right after the
1812 // original REtADDR, but before the saved framepointer or the spilled registers
1813 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1825 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1826 /// for a 16 byte align requirement.
1827 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1828 SelectionDAG& DAG) {
1829 if (PerformTailCallOpt) {
1830 MachineFunction &MF = DAG.getMachineFunction();
1831 const TargetMachine &TM = MF.getTarget();
1832 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1833 unsigned StackAlignment = TFI.getStackAlignment();
1834 uint64_t AlignMask = StackAlignment - 1;
1835 int64_t Offset = StackSize;
1836 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1837 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1838 // Number smaller than 12 so just add the difference.
1839 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1841 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1842 Offset = ((~AlignMask) & Offset) + StackAlignment +
1843 (StackAlignment-SlotSize);
1850 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1851 /// following the call is a return. A function is eligible if caller/callee
1852 /// calling conventions match, currently only fastcc supports tail calls, and
1853 /// the function CALL is immediatly followed by a RET.
1854 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Call,
1856 SelectionDAG& DAG) const {
1857 if (!PerformTailCallOpt)
1860 if (CheckTailCallReturnConstraints(Call, Ret)) {
1861 MachineFunction &MF = DAG.getMachineFunction();
1862 unsigned CallerCC = MF.getFunction()->getCallingConv();
1863 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1864 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1865 SDValue Callee = Call.getOperand(4);
1866 // On x86/32Bit PIC/GOT tail calls are supported.
1867 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1868 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1871 // Can only do local tail calls (in same module, hidden or protected) on
1872 // x86_64 PIC/GOT at the moment.
1873 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1874 return G->getGlobal()->hasHiddenVisibility()
1875 || G->getGlobal()->hasProtectedVisibility();
1882 FastISel *X86TargetLowering::createFastISel(MachineFunction &mf) {
1883 return X86::createFastISel(mf);
1887 //===----------------------------------------------------------------------===//
1888 // Other Lowering Hooks
1889 //===----------------------------------------------------------------------===//
1892 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1893 MachineFunction &MF = DAG.getMachineFunction();
1894 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1895 int ReturnAddrIndex = FuncInfo->getRAIndex();
1897 if (ReturnAddrIndex == 0) {
1898 // Set up a frame object for the return address.
1899 if (Subtarget->is64Bit())
1900 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1902 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1904 FuncInfo->setRAIndex(ReturnAddrIndex);
1907 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1912 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1913 /// specific condition code. It returns a false if it cannot do a direct
1914 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1916 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1917 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1918 SelectionDAG &DAG) {
1919 X86CC = X86::COND_INVALID;
1921 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1922 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1923 // X > -1 -> X == 0, jump !sign.
1924 RHS = DAG.getConstant(0, RHS.getValueType());
1925 X86CC = X86::COND_NS;
1927 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1928 // X < 0 -> X == 0, jump on sign.
1929 X86CC = X86::COND_S;
1931 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1933 RHS = DAG.getConstant(0, RHS.getValueType());
1934 X86CC = X86::COND_LE;
1939 switch (SetCCOpcode) {
1941 case ISD::SETEQ: X86CC = X86::COND_E; break;
1942 case ISD::SETGT: X86CC = X86::COND_G; break;
1943 case ISD::SETGE: X86CC = X86::COND_GE; break;
1944 case ISD::SETLT: X86CC = X86::COND_L; break;
1945 case ISD::SETLE: X86CC = X86::COND_LE; break;
1946 case ISD::SETNE: X86CC = X86::COND_NE; break;
1947 case ISD::SETULT: X86CC = X86::COND_B; break;
1948 case ISD::SETUGT: X86CC = X86::COND_A; break;
1949 case ISD::SETULE: X86CC = X86::COND_BE; break;
1950 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1953 // On a floating point condition, the flags are set as follows:
1955 // 0 | 0 | 0 | X > Y
1956 // 0 | 0 | 1 | X < Y
1957 // 1 | 0 | 0 | X == Y
1958 // 1 | 1 | 1 | unordered
1960 switch (SetCCOpcode) {
1963 case ISD::SETEQ: X86CC = X86::COND_E; break;
1964 case ISD::SETOLT: Flip = true; // Fallthrough
1966 case ISD::SETGT: X86CC = X86::COND_A; break;
1967 case ISD::SETOLE: Flip = true; // Fallthrough
1969 case ISD::SETGE: X86CC = X86::COND_AE; break;
1970 case ISD::SETUGT: Flip = true; // Fallthrough
1972 case ISD::SETLT: X86CC = X86::COND_B; break;
1973 case ISD::SETUGE: Flip = true; // Fallthrough
1975 case ISD::SETLE: X86CC = X86::COND_BE; break;
1977 case ISD::SETNE: X86CC = X86::COND_NE; break;
1978 case ISD::SETUO: X86CC = X86::COND_P; break;
1979 case ISD::SETO: X86CC = X86::COND_NP; break;
1982 std::swap(LHS, RHS);
1985 return X86CC != X86::COND_INVALID;
1988 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1989 /// code. Current x86 isa includes the following FP cmov instructions:
1990 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1991 static bool hasFPCMov(unsigned X86CC) {
2007 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2008 /// true if Op is undef or if its value falls within the specified range (L, H].
2009 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2010 if (Op.getOpcode() == ISD::UNDEF)
2013 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2014 return (Val >= Low && Val < Hi);
2017 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2018 /// true if Op is undef or if its value equal to the specified value.
2019 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2020 if (Op.getOpcode() == ISD::UNDEF)
2022 return cast<ConstantSDNode>(Op)->getValue() == Val;
2025 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2026 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2027 bool X86::isPSHUFDMask(SDNode *N) {
2028 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2030 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2033 // Check if the value doesn't reference the second vector.
2034 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2035 SDValue Arg = N->getOperand(i);
2036 if (Arg.getOpcode() == ISD::UNDEF) continue;
2037 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2038 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2045 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2046 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2047 bool X86::isPSHUFHWMask(SDNode *N) {
2048 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2050 if (N->getNumOperands() != 8)
2053 // Lower quadword copied in order.
2054 for (unsigned i = 0; i != 4; ++i) {
2055 SDValue Arg = N->getOperand(i);
2056 if (Arg.getOpcode() == ISD::UNDEF) continue;
2057 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2058 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2062 // Upper quadword shuffled.
2063 for (unsigned i = 4; i != 8; ++i) {
2064 SDValue Arg = N->getOperand(i);
2065 if (Arg.getOpcode() == ISD::UNDEF) continue;
2066 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2067 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2068 if (Val < 4 || Val > 7)
2075 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2076 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2077 bool X86::isPSHUFLWMask(SDNode *N) {
2078 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2080 if (N->getNumOperands() != 8)
2083 // Upper quadword copied in order.
2084 for (unsigned i = 4; i != 8; ++i)
2085 if (!isUndefOrEqual(N->getOperand(i), i))
2088 // Lower quadword shuffled.
2089 for (unsigned i = 0; i != 4; ++i)
2090 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2096 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2097 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2098 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2099 if (NumElems != 2 && NumElems != 4) return false;
2101 unsigned Half = NumElems / 2;
2102 for (unsigned i = 0; i < Half; ++i)
2103 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2105 for (unsigned i = Half; i < NumElems; ++i)
2106 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2112 bool X86::isSHUFPMask(SDNode *N) {
2113 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2114 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2117 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2118 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2119 /// half elements to come from vector 1 (which would equal the dest.) and
2120 /// the upper half to come from vector 2.
2121 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2122 if (NumOps != 2 && NumOps != 4) return false;
2124 unsigned Half = NumOps / 2;
2125 for (unsigned i = 0; i < Half; ++i)
2126 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2128 for (unsigned i = Half; i < NumOps; ++i)
2129 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2134 static bool isCommutedSHUFP(SDNode *N) {
2135 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2136 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2139 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2140 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2141 bool X86::isMOVHLPSMask(SDNode *N) {
2142 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2144 if (N->getNumOperands() != 4)
2147 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2148 return isUndefOrEqual(N->getOperand(0), 6) &&
2149 isUndefOrEqual(N->getOperand(1), 7) &&
2150 isUndefOrEqual(N->getOperand(2), 2) &&
2151 isUndefOrEqual(N->getOperand(3), 3);
2154 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2155 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2157 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2158 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2160 if (N->getNumOperands() != 4)
2163 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2164 return isUndefOrEqual(N->getOperand(0), 2) &&
2165 isUndefOrEqual(N->getOperand(1), 3) &&
2166 isUndefOrEqual(N->getOperand(2), 2) &&
2167 isUndefOrEqual(N->getOperand(3), 3);
2170 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2171 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2172 bool X86::isMOVLPMask(SDNode *N) {
2173 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2175 unsigned NumElems = N->getNumOperands();
2176 if (NumElems != 2 && NumElems != 4)
2179 for (unsigned i = 0; i < NumElems/2; ++i)
2180 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2183 for (unsigned i = NumElems/2; i < NumElems; ++i)
2184 if (!isUndefOrEqual(N->getOperand(i), i))
2190 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2191 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2193 bool X86::isMOVHPMask(SDNode *N) {
2194 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2196 unsigned NumElems = N->getNumOperands();
2197 if (NumElems != 2 && NumElems != 4)
2200 for (unsigned i = 0; i < NumElems/2; ++i)
2201 if (!isUndefOrEqual(N->getOperand(i), i))
2204 for (unsigned i = 0; i < NumElems/2; ++i) {
2205 SDValue Arg = N->getOperand(i + NumElems/2);
2206 if (!isUndefOrEqual(Arg, i + NumElems))
2213 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2214 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2215 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2216 bool V2IsSplat = false) {
2217 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2220 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2221 SDValue BitI = Elts[i];
2222 SDValue BitI1 = Elts[i+1];
2223 if (!isUndefOrEqual(BitI, j))
2226 if (isUndefOrEqual(BitI1, NumElts))
2229 if (!isUndefOrEqual(BitI1, j + NumElts))
2237 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2238 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2239 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2242 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2243 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2244 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2245 bool V2IsSplat = false) {
2246 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2249 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2250 SDValue BitI = Elts[i];
2251 SDValue BitI1 = Elts[i+1];
2252 if (!isUndefOrEqual(BitI, j + NumElts/2))
2255 if (isUndefOrEqual(BitI1, NumElts))
2258 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2266 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2267 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2268 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2271 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2272 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2274 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2275 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2277 unsigned NumElems = N->getNumOperands();
2278 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2281 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2282 SDValue BitI = N->getOperand(i);
2283 SDValue BitI1 = N->getOperand(i+1);
2285 if (!isUndefOrEqual(BitI, j))
2287 if (!isUndefOrEqual(BitI1, j))
2294 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2295 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2297 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2298 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2300 unsigned NumElems = N->getNumOperands();
2301 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2304 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2305 SDValue BitI = N->getOperand(i);
2306 SDValue BitI1 = N->getOperand(i + 1);
2308 if (!isUndefOrEqual(BitI, j))
2310 if (!isUndefOrEqual(BitI1, j))
2317 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2318 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2319 /// MOVSD, and MOVD, i.e. setting the lowest element.
2320 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2321 if (NumElts != 2 && NumElts != 4)
2324 if (!isUndefOrEqual(Elts[0], NumElts))
2327 for (unsigned i = 1; i < NumElts; ++i) {
2328 if (!isUndefOrEqual(Elts[i], i))
2335 bool X86::isMOVLMask(SDNode *N) {
2336 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2337 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2340 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2341 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2342 /// element of vector 2 and the other elements to come from vector 1 in order.
2343 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2344 bool V2IsSplat = false,
2345 bool V2IsUndef = false) {
2346 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2349 if (!isUndefOrEqual(Ops[0], 0))
2352 for (unsigned i = 1; i < NumOps; ++i) {
2353 SDValue Arg = Ops[i];
2354 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2355 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2356 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2363 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2364 bool V2IsUndef = false) {
2365 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2366 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2367 V2IsSplat, V2IsUndef);
2370 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2371 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2372 bool X86::isMOVSHDUPMask(SDNode *N) {
2373 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2375 if (N->getNumOperands() != 4)
2378 // Expect 1, 1, 3, 3
2379 for (unsigned i = 0; i < 2; ++i) {
2380 SDValue Arg = N->getOperand(i);
2381 if (Arg.getOpcode() == ISD::UNDEF) continue;
2382 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2383 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2384 if (Val != 1) return false;
2388 for (unsigned i = 2; i < 4; ++i) {
2389 SDValue Arg = N->getOperand(i);
2390 if (Arg.getOpcode() == ISD::UNDEF) continue;
2391 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2392 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2393 if (Val != 3) return false;
2397 // Don't use movshdup if it can be done with a shufps.
2401 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2402 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2403 bool X86::isMOVSLDUPMask(SDNode *N) {
2404 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2406 if (N->getNumOperands() != 4)
2409 // Expect 0, 0, 2, 2
2410 for (unsigned i = 0; i < 2; ++i) {
2411 SDValue Arg = N->getOperand(i);
2412 if (Arg.getOpcode() == ISD::UNDEF) continue;
2413 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2414 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2415 if (Val != 0) return false;
2419 for (unsigned i = 2; i < 4; ++i) {
2420 SDValue Arg = N->getOperand(i);
2421 if (Arg.getOpcode() == ISD::UNDEF) continue;
2422 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2423 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2424 if (Val != 2) return false;
2428 // Don't use movshdup if it can be done with a shufps.
2432 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2433 /// specifies a identity operation on the LHS or RHS.
2434 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2435 unsigned NumElems = N->getNumOperands();
2436 for (unsigned i = 0; i < NumElems; ++i)
2437 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2442 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2443 /// a splat of a single element.
2444 static bool isSplatMask(SDNode *N) {
2445 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2447 // This is a splat operation if each element of the permute is the same, and
2448 // if the value doesn't reference the second vector.
2449 unsigned NumElems = N->getNumOperands();
2450 SDValue ElementBase;
2452 for (; i != NumElems; ++i) {
2453 SDValue Elt = N->getOperand(i);
2454 if (isa<ConstantSDNode>(Elt)) {
2460 if (!ElementBase.Val)
2463 for (; i != NumElems; ++i) {
2464 SDValue Arg = N->getOperand(i);
2465 if (Arg.getOpcode() == ISD::UNDEF) continue;
2466 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2467 if (Arg != ElementBase) return false;
2470 // Make sure it is a splat of the first vector operand.
2471 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2474 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2475 /// a splat of a single element and it's a 2 or 4 element mask.
2476 bool X86::isSplatMask(SDNode *N) {
2477 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2479 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2480 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2482 return ::isSplatMask(N);
2485 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2486 /// specifies a splat of zero element.
2487 bool X86::isSplatLoMask(SDNode *N) {
2488 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2490 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2491 if (!isUndefOrEqual(N->getOperand(i), 0))
2496 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2497 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2499 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2500 unsigned NumOperands = N->getNumOperands();
2501 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2503 for (unsigned i = 0; i < NumOperands; ++i) {
2505 SDValue Arg = N->getOperand(NumOperands-i-1);
2506 if (Arg.getOpcode() != ISD::UNDEF)
2507 Val = cast<ConstantSDNode>(Arg)->getValue();
2508 if (Val >= NumOperands) Val -= NumOperands;
2510 if (i != NumOperands - 1)
2517 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2518 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2520 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2522 // 8 nodes, but we only care about the last 4.
2523 for (unsigned i = 7; i >= 4; --i) {
2525 SDValue Arg = N->getOperand(i);
2526 if (Arg.getOpcode() != ISD::UNDEF)
2527 Val = cast<ConstantSDNode>(Arg)->getValue();
2536 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2537 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2539 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2541 // 8 nodes, but we only care about the first 4.
2542 for (int i = 3; i >= 0; --i) {
2544 SDValue Arg = N->getOperand(i);
2545 if (Arg.getOpcode() != ISD::UNDEF)
2546 Val = cast<ConstantSDNode>(Arg)->getValue();
2555 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2556 /// specifies a 8 element shuffle that can be broken into a pair of
2557 /// PSHUFHW and PSHUFLW.
2558 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2559 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2561 if (N->getNumOperands() != 8)
2564 // Lower quadword shuffled.
2565 for (unsigned i = 0; i != 4; ++i) {
2566 SDValue Arg = N->getOperand(i);
2567 if (Arg.getOpcode() == ISD::UNDEF) continue;
2568 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2569 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2574 // Upper quadword shuffled.
2575 for (unsigned i = 4; i != 8; ++i) {
2576 SDValue Arg = N->getOperand(i);
2577 if (Arg.getOpcode() == ISD::UNDEF) continue;
2578 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2579 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2580 if (Val < 4 || Val > 7)
2587 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2588 /// values in ther permute mask.
2589 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2590 SDValue &V2, SDValue &Mask,
2591 SelectionDAG &DAG) {
2592 MVT VT = Op.getValueType();
2593 MVT MaskVT = Mask.getValueType();
2594 MVT EltVT = MaskVT.getVectorElementType();
2595 unsigned NumElems = Mask.getNumOperands();
2596 SmallVector<SDValue, 8> MaskVec;
2598 for (unsigned i = 0; i != NumElems; ++i) {
2599 SDValue Arg = Mask.getOperand(i);
2600 if (Arg.getOpcode() == ISD::UNDEF) {
2601 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2604 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2605 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2607 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2609 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2613 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2614 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2617 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2618 /// the two vector operands have swapped position.
2620 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2621 MVT MaskVT = Mask.getValueType();
2622 MVT EltVT = MaskVT.getVectorElementType();
2623 unsigned NumElems = Mask.getNumOperands();
2624 SmallVector<SDValue, 8> MaskVec;
2625 for (unsigned i = 0; i != NumElems; ++i) {
2626 SDValue Arg = Mask.getOperand(i);
2627 if (Arg.getOpcode() == ISD::UNDEF) {
2628 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2631 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2632 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2634 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2636 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2638 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2642 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2643 /// match movhlps. The lower half elements should come from upper half of
2644 /// V1 (and in order), and the upper half elements should come from the upper
2645 /// half of V2 (and in order).
2646 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2647 unsigned NumElems = Mask->getNumOperands();
2650 for (unsigned i = 0, e = 2; i != e; ++i)
2651 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2653 for (unsigned i = 2; i != 4; ++i)
2654 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2659 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2660 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2662 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2663 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2664 N = N->getOperand(0).Val;
2665 if (ISD::isNON_EXTLoad(N)) {
2667 *LD = cast<LoadSDNode>(N);
2674 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2675 /// match movlp{s|d}. The lower half elements should come from lower half of
2676 /// V1 (and in order), and the upper half elements should come from the upper
2677 /// half of V2 (and in order). And since V1 will become the source of the
2678 /// MOVLP, it must be either a vector load or a scalar load to vector.
2679 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2680 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2682 // Is V2 is a vector load, don't do this transformation. We will try to use
2683 // load folding shufps op.
2684 if (ISD::isNON_EXTLoad(V2))
2687 unsigned NumElems = Mask->getNumOperands();
2688 if (NumElems != 2 && NumElems != 4)
2690 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2691 if (!isUndefOrEqual(Mask->getOperand(i), i))
2693 for (unsigned i = NumElems/2; i != NumElems; ++i)
2694 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2699 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2701 static bool isSplatVector(SDNode *N) {
2702 if (N->getOpcode() != ISD::BUILD_VECTOR)
2705 SDValue SplatValue = N->getOperand(0);
2706 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2707 if (N->getOperand(i) != SplatValue)
2712 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2714 static bool isUndefShuffle(SDNode *N) {
2715 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2718 SDValue V1 = N->getOperand(0);
2719 SDValue V2 = N->getOperand(1);
2720 SDValue Mask = N->getOperand(2);
2721 unsigned NumElems = Mask.getNumOperands();
2722 for (unsigned i = 0; i != NumElems; ++i) {
2723 SDValue Arg = Mask.getOperand(i);
2724 if (Arg.getOpcode() != ISD::UNDEF) {
2725 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2726 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2728 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2735 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2737 static inline bool isZeroNode(SDValue Elt) {
2738 return ((isa<ConstantSDNode>(Elt) &&
2739 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2740 (isa<ConstantFPSDNode>(Elt) &&
2741 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2744 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2745 /// to an zero vector.
2746 static bool isZeroShuffle(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)
2759 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2760 if (Idx < NumElems) {
2761 unsigned Opc = V1.Val->getOpcode();
2762 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2764 if (Opc != ISD::BUILD_VECTOR ||
2765 !isZeroNode(V1.Val->getOperand(Idx)))
2767 } else if (Idx >= NumElems) {
2768 unsigned Opc = V2.Val->getOpcode();
2769 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2771 if (Opc != ISD::BUILD_VECTOR ||
2772 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2779 /// getZeroVector - Returns a vector of specified type with all zero elements.
2781 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2782 assert(VT.isVector() && "Expected a vector type");
2784 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2785 // type. This ensures they get CSE'd.
2787 if (VT.getSizeInBits() == 64) { // MMX
2788 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2789 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2790 } else if (HasSSE2) { // SSE2
2791 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2792 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2794 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2795 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2797 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2800 /// getOnesVector - Returns a vector of specified type with all bits set.
2802 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2803 assert(VT.isVector() && "Expected a vector type");
2805 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2806 // type. This ensures they get CSE'd.
2807 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2809 if (VT.getSizeInBits() == 64) // MMX
2810 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2812 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2813 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2817 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2818 /// that point to V2 points to its first element.
2819 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2820 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2822 bool Changed = false;
2823 SmallVector<SDValue, 8> MaskVec;
2824 unsigned NumElems = Mask.getNumOperands();
2825 for (unsigned i = 0; i != NumElems; ++i) {
2826 SDValue Arg = Mask.getOperand(i);
2827 if (Arg.getOpcode() != ISD::UNDEF) {
2828 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2829 if (Val > NumElems) {
2830 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2834 MaskVec.push_back(Arg);
2838 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2839 &MaskVec[0], MaskVec.size());
2843 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2844 /// operation of specified width.
2845 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2846 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2847 MVT BaseVT = MaskVT.getVectorElementType();
2849 SmallVector<SDValue, 8> MaskVec;
2850 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2851 for (unsigned i = 1; i != NumElems; ++i)
2852 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2853 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2856 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2857 /// of specified width.
2858 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2859 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2860 MVT BaseVT = MaskVT.getVectorElementType();
2861 SmallVector<SDValue, 8> MaskVec;
2862 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2863 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2864 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2866 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2869 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2870 /// of specified width.
2871 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2872 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2873 MVT BaseVT = MaskVT.getVectorElementType();
2874 unsigned Half = NumElems/2;
2875 SmallVector<SDValue, 8> MaskVec;
2876 for (unsigned i = 0; i != Half; ++i) {
2877 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2878 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2880 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2883 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2884 /// element #0 of a vector with the specified index, leaving the rest of the
2885 /// elements in place.
2886 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2887 SelectionDAG &DAG) {
2888 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2889 MVT BaseVT = MaskVT.getVectorElementType();
2890 SmallVector<SDValue, 8> MaskVec;
2891 // Element #0 of the result gets the elt we are replacing.
2892 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2893 for (unsigned i = 1; i != NumElems; ++i)
2894 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2895 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2898 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2899 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2900 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2901 MVT VT = Op.getValueType();
2904 SDValue V1 = Op.getOperand(0);
2905 SDValue Mask = Op.getOperand(2);
2906 unsigned NumElems = Mask.getNumOperands();
2907 // Special handling of v4f32 -> v4i32.
2908 if (VT != MVT::v4f32) {
2909 Mask = getUnpacklMask(NumElems, DAG);
2910 while (NumElems > 4) {
2911 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2914 Mask = getZeroVector(MVT::v4i32, true, DAG);
2917 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2918 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2919 DAG.getNode(ISD::UNDEF, PVT), Mask);
2920 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2923 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2924 /// vector of zero or undef vector. This produces a shuffle where the low
2925 /// element of V2 is swizzled into the zero/undef vector, landing at element
2926 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2927 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2928 bool isZero, bool HasSSE2,
2929 SelectionDAG &DAG) {
2930 MVT VT = V2.getValueType();
2932 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2933 unsigned NumElems = V2.getValueType().getVectorNumElements();
2934 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2935 MVT EVT = MaskVT.getVectorElementType();
2936 SmallVector<SDValue, 16> MaskVec;
2937 for (unsigned i = 0; i != NumElems; ++i)
2938 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2939 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2941 MaskVec.push_back(DAG.getConstant(i, EVT));
2942 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2943 &MaskVec[0], MaskVec.size());
2944 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2947 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2948 /// a shuffle that is zero.
2950 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2951 unsigned NumElems, bool Low,
2952 SelectionDAG &DAG) {
2953 unsigned NumZeros = 0;
2954 for (unsigned i = 0; i < NumElems; ++i) {
2955 unsigned Index = Low ? i : NumElems-i-1;
2956 SDValue Idx = Mask.getOperand(Index);
2957 if (Idx.getOpcode() == ISD::UNDEF) {
2961 SDValue Elt = DAG.getShuffleScalarElt(Op.Val, Index);
2962 if (Elt.Val && isZeroNode(Elt))
2970 /// isVectorShift - Returns true if the shuffle can be implemented as a
2971 /// logical left or right shift of a vector.
2972 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
2973 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2974 unsigned NumElems = Mask.getNumOperands();
2977 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
2980 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
2985 bool SeenV1 = false;
2986 bool SeenV2 = false;
2987 for (unsigned i = NumZeros; i < NumElems; ++i) {
2988 unsigned Val = isLeft ? (i - NumZeros) : i;
2989 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
2990 if (Idx.getOpcode() == ISD::UNDEF)
2992 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2993 if (Index < NumElems)
3002 if (SeenV1 && SeenV2)
3005 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3011 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3013 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3014 unsigned NumNonZero, unsigned NumZero,
3015 SelectionDAG &DAG, TargetLowering &TLI) {
3021 for (unsigned i = 0; i < 16; ++i) {
3022 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3023 if (ThisIsNonZero && First) {
3025 V = getZeroVector(MVT::v8i16, true, DAG);
3027 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3032 SDValue ThisElt(0, 0), LastElt(0, 0);
3033 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3034 if (LastIsNonZero) {
3035 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3037 if (ThisIsNonZero) {
3038 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3039 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3040 ThisElt, DAG.getConstant(8, MVT::i8));
3042 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3047 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3048 DAG.getIntPtrConstant(i/2));
3052 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3055 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3057 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3058 unsigned NumNonZero, unsigned NumZero,
3059 SelectionDAG &DAG, TargetLowering &TLI) {
3065 for (unsigned i = 0; i < 8; ++i) {
3066 bool isNonZero = (NonZeros & (1 << i)) != 0;
3070 V = getZeroVector(MVT::v8i16, true, DAG);
3072 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3075 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3076 DAG.getIntPtrConstant(i));
3083 /// getVShift - Return a vector logical shift node.
3085 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3086 unsigned NumBits, SelectionDAG &DAG,
3087 const TargetLowering &TLI) {
3088 bool isMMX = VT.getSizeInBits() == 64;
3089 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3090 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3091 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3092 return DAG.getNode(ISD::BIT_CONVERT, VT,
3093 DAG.getNode(Opc, ShVT, SrcOp,
3094 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3098 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3099 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3100 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3101 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3102 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3103 // eliminated on x86-32 hosts.
3104 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3107 if (ISD::isBuildVectorAllOnes(Op.Val))
3108 return getOnesVector(Op.getValueType(), DAG);
3109 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3112 MVT VT = Op.getValueType();
3113 MVT EVT = VT.getVectorElementType();
3114 unsigned EVTBits = EVT.getSizeInBits();
3116 unsigned NumElems = Op.getNumOperands();
3117 unsigned NumZero = 0;
3118 unsigned NumNonZero = 0;
3119 unsigned NonZeros = 0;
3120 bool IsAllConstants = true;
3121 SmallSet<SDValue, 8> Values;
3122 for (unsigned i = 0; i < NumElems; ++i) {
3123 SDValue Elt = Op.getOperand(i);
3124 if (Elt.getOpcode() == ISD::UNDEF)
3127 if (Elt.getOpcode() != ISD::Constant &&
3128 Elt.getOpcode() != ISD::ConstantFP)
3129 IsAllConstants = false;
3130 if (isZeroNode(Elt))
3133 NonZeros |= (1 << i);
3138 if (NumNonZero == 0) {
3139 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3140 return DAG.getNode(ISD::UNDEF, VT);
3143 // Special case for single non-zero, non-undef, element.
3144 if (NumNonZero == 1 && NumElems <= 4) {
3145 unsigned Idx = CountTrailingZeros_32(NonZeros);
3146 SDValue Item = Op.getOperand(Idx);
3148 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3149 // the value are obviously zero, truncate the value to i32 and do the
3150 // insertion that way. Only do this if the value is non-constant or if the
3151 // value is a constant being inserted into element 0. It is cheaper to do
3152 // a constant pool load than it is to do a movd + shuffle.
3153 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3154 (!IsAllConstants || Idx == 0)) {
3155 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3156 // Handle MMX and SSE both.
3157 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3158 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3160 // Truncate the value (which may itself be a constant) to i32, and
3161 // convert it to a vector with movd (S2V+shuffle to zero extend).
3162 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3163 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3164 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3165 Subtarget->hasSSE2(), DAG);
3167 // Now we have our 32-bit value zero extended in the low element of
3168 // a vector. If Idx != 0, swizzle it into place.
3171 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3172 getSwapEltZeroMask(VecElts, Idx, DAG)
3174 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3176 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3180 // If we have a constant or non-constant insertion into the low element of
3181 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3182 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3183 // depending on what the source datatype is. Because we can only get here
3184 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3186 // Don't do this for i64 values on x86-32.
3187 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3188 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3189 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3190 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3191 Subtarget->hasSSE2(), DAG);
3194 // Is it a vector logical left shift?
3195 if (NumElems == 2 && Idx == 1 &&
3196 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3197 unsigned NumBits = VT.getSizeInBits();
3198 return getVShift(true, VT,
3199 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3200 NumBits/2, DAG, *this);
3203 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3206 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3207 // is a non-constant being inserted into an element other than the low one,
3208 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3209 // movd/movss) to move this into the low element, then shuffle it into
3211 if (EVTBits == 32) {
3212 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3214 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3215 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3216 Subtarget->hasSSE2(), DAG);
3217 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3218 MVT MaskEVT = MaskVT.getVectorElementType();
3219 SmallVector<SDValue, 8> MaskVec;
3220 for (unsigned i = 0; i < NumElems; i++)
3221 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3222 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3223 &MaskVec[0], MaskVec.size());
3224 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3225 DAG.getNode(ISD::UNDEF, VT), Mask);
3229 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3230 if (Values.size() == 1)
3233 // A vector full of immediates; various special cases are already
3234 // handled, so this is best done with a single constant-pool load.
3238 // Let legalizer expand 2-wide build_vectors.
3239 if (EVTBits == 64) {
3240 if (NumNonZero == 1) {
3241 // One half is zero or undef.
3242 unsigned Idx = CountTrailingZeros_32(NonZeros);
3243 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3244 Op.getOperand(Idx));
3245 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3246 Subtarget->hasSSE2(), DAG);
3251 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3252 if (EVTBits == 8 && NumElems == 16) {
3253 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3255 if (V.Val) return V;
3258 if (EVTBits == 16 && NumElems == 8) {
3259 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3261 if (V.Val) return V;
3264 // If element VT is == 32 bits, turn it into a number of shuffles.
3265 SmallVector<SDValue, 8> V;
3267 if (NumElems == 4 && NumZero > 0) {
3268 for (unsigned i = 0; i < 4; ++i) {
3269 bool isZero = !(NonZeros & (1 << i));
3271 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3273 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3276 for (unsigned i = 0; i < 2; ++i) {
3277 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3280 V[i] = V[i*2]; // Must be a zero vector.
3283 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3284 getMOVLMask(NumElems, DAG));
3287 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3288 getMOVLMask(NumElems, DAG));
3291 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3292 getUnpacklMask(NumElems, DAG));
3297 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3298 MVT EVT = MaskVT.getVectorElementType();
3299 SmallVector<SDValue, 8> MaskVec;
3300 bool Reverse = (NonZeros & 0x3) == 2;
3301 for (unsigned i = 0; i < 2; ++i)
3303 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3305 MaskVec.push_back(DAG.getConstant(i, EVT));
3306 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3307 for (unsigned i = 0; i < 2; ++i)
3309 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3311 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3312 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3313 &MaskVec[0], MaskVec.size());
3314 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3317 if (Values.size() > 2) {
3318 // Expand into a number of unpckl*.
3320 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3321 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3322 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3323 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3324 for (unsigned i = 0; i < NumElems; ++i)
3325 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3327 while (NumElems != 0) {
3328 for (unsigned i = 0; i < NumElems; ++i)
3329 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3340 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3341 SDValue PermMask, SelectionDAG &DAG,
3342 TargetLowering &TLI) {
3344 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3345 MVT MaskEVT = MaskVT.getVectorElementType();
3346 MVT PtrVT = TLI.getPointerTy();
3347 SmallVector<SDValue, 8> MaskElts(PermMask.Val->op_begin(),
3348 PermMask.Val->op_end());
3350 // First record which half of which vector the low elements come from.
3351 SmallVector<unsigned, 4> LowQuad(4);
3352 for (unsigned i = 0; i < 4; ++i) {
3353 SDValue Elt = MaskElts[i];
3354 if (Elt.getOpcode() == ISD::UNDEF)
3356 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3357 int QuadIdx = EltIdx / 4;
3361 int BestLowQuad = -1;
3362 unsigned MaxQuad = 1;
3363 for (unsigned i = 0; i < 4; ++i) {
3364 if (LowQuad[i] > MaxQuad) {
3366 MaxQuad = LowQuad[i];
3370 // Record which half of which vector the high elements come from.
3371 SmallVector<unsigned, 4> HighQuad(4);
3372 for (unsigned i = 4; i < 8; ++i) {
3373 SDValue Elt = MaskElts[i];
3374 if (Elt.getOpcode() == ISD::UNDEF)
3376 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3377 int QuadIdx = EltIdx / 4;
3378 ++HighQuad[QuadIdx];
3381 int BestHighQuad = -1;
3383 for (unsigned i = 0; i < 4; ++i) {
3384 if (HighQuad[i] > MaxQuad) {
3386 MaxQuad = HighQuad[i];
3390 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3391 if (BestLowQuad != -1 || BestHighQuad != -1) {
3392 // First sort the 4 chunks in order using shufpd.
3393 SmallVector<SDValue, 8> MaskVec;
3395 if (BestLowQuad != -1)
3396 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3398 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3400 if (BestHighQuad != -1)
3401 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3403 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3405 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3406 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3407 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3408 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3409 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3411 // Now sort high and low parts separately.
3412 BitVector InOrder(8);
3413 if (BestLowQuad != -1) {
3414 // Sort lower half in order using PSHUFLW.
3416 bool AnyOutOrder = false;
3418 for (unsigned i = 0; i != 4; ++i) {
3419 SDValue Elt = MaskElts[i];
3420 if (Elt.getOpcode() == ISD::UNDEF) {
3421 MaskVec.push_back(Elt);
3424 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3428 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3430 // If this element is in the right place after this shuffle, then
3432 if ((int)(EltIdx / 4) == BestLowQuad)
3437 for (unsigned i = 4; i != 8; ++i)
3438 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3439 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3440 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3444 if (BestHighQuad != -1) {
3445 // Sort high half in order using PSHUFHW if possible.
3448 for (unsigned i = 0; i != 4; ++i)
3449 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3451 bool AnyOutOrder = false;
3452 for (unsigned i = 4; i != 8; ++i) {
3453 SDValue Elt = MaskElts[i];
3454 if (Elt.getOpcode() == ISD::UNDEF) {
3455 MaskVec.push_back(Elt);
3458 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3462 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3464 // If this element is in the right place after this shuffle, then
3466 if ((int)(EltIdx / 4) == BestHighQuad)
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 // The other elements are put in the right place using pextrw and pinsrw.
3478 for (unsigned i = 0; i != 8; ++i) {
3481 SDValue Elt = MaskElts[i];
3482 if (Elt.getOpcode() == ISD::UNDEF)
3484 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3485 SDValue ExtOp = (EltIdx < 8)
3486 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3487 DAG.getConstant(EltIdx, PtrVT))
3488 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3489 DAG.getConstant(EltIdx - 8, PtrVT));
3490 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3491 DAG.getConstant(i, PtrVT));
3497 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3498 // few as possible. First, let's find out how many elements are already in the
3500 unsigned V1InOrder = 0;
3501 unsigned V1FromV1 = 0;
3502 unsigned V2InOrder = 0;
3503 unsigned V2FromV2 = 0;
3504 SmallVector<SDValue, 8> V1Elts;
3505 SmallVector<SDValue, 8> V2Elts;
3506 for (unsigned i = 0; i < 8; ++i) {
3507 SDValue Elt = MaskElts[i];
3508 if (Elt.getOpcode() == ISD::UNDEF) {
3509 V1Elts.push_back(Elt);
3510 V2Elts.push_back(Elt);
3515 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3517 V1Elts.push_back(Elt);
3518 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3520 } else if (EltIdx == i+8) {
3521 V1Elts.push_back(Elt);
3522 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3524 } else if (EltIdx < 8) {
3525 V1Elts.push_back(Elt);
3528 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3533 if (V2InOrder > V1InOrder) {
3534 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3536 std::swap(V1Elts, V2Elts);
3537 std::swap(V1FromV1, V2FromV2);
3540 if ((V1FromV1 + V1InOrder) != 8) {
3541 // Some elements are from V2.
3543 // If there are elements that are from V1 but out of place,
3544 // then first sort them in place
3545 SmallVector<SDValue, 8> MaskVec;
3546 for (unsigned i = 0; i < 8; ++i) {
3547 SDValue Elt = V1Elts[i];
3548 if (Elt.getOpcode() == ISD::UNDEF) {
3549 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3552 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3554 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3556 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3558 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3559 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3563 for (unsigned i = 0; i < 8; ++i) {
3564 SDValue Elt = V1Elts[i];
3565 if (Elt.getOpcode() == ISD::UNDEF)
3567 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3570 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3571 DAG.getConstant(EltIdx - 8, PtrVT));
3572 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3573 DAG.getConstant(i, PtrVT));
3577 // All elements are from V1.
3579 for (unsigned i = 0; i < 8; ++i) {
3580 SDValue Elt = V1Elts[i];
3581 if (Elt.getOpcode() == ISD::UNDEF)
3583 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3584 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3585 DAG.getConstant(EltIdx, PtrVT));
3586 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3587 DAG.getConstant(i, PtrVT));
3593 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3594 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3595 /// done when every pair / quad of shuffle mask elements point to elements in
3596 /// the right sequence. e.g.
3597 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3599 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3601 SDValue PermMask, SelectionDAG &DAG,
3602 TargetLowering &TLI) {
3603 unsigned NumElems = PermMask.getNumOperands();
3604 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3605 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3606 MVT MaskEltVT = MaskVT.getVectorElementType();
3608 switch (VT.getSimpleVT()) {
3609 default: assert(false && "Unexpected!");
3610 case MVT::v4f32: NewVT = MVT::v2f64; break;
3611 case MVT::v4i32: NewVT = MVT::v2i64; break;
3612 case MVT::v8i16: NewVT = MVT::v4i32; break;
3613 case MVT::v16i8: NewVT = MVT::v4i32; break;
3616 if (NewWidth == 2) {
3622 unsigned Scale = NumElems / NewWidth;
3623 SmallVector<SDValue, 8> MaskVec;
3624 for (unsigned i = 0; i < NumElems; i += Scale) {
3625 unsigned StartIdx = ~0U;
3626 for (unsigned j = 0; j < Scale; ++j) {
3627 SDValue Elt = PermMask.getOperand(i+j);
3628 if (Elt.getOpcode() == ISD::UNDEF)
3630 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3631 if (StartIdx == ~0U)
3632 StartIdx = EltIdx - (EltIdx % Scale);
3633 if (EltIdx != StartIdx + j)
3636 if (StartIdx == ~0U)
3637 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3639 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3642 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3643 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3644 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3645 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3646 &MaskVec[0], MaskVec.size()));
3649 /// getVZextMovL - Return a zero-extending vector move low node.
3651 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3652 SDValue SrcOp, SelectionDAG &DAG,
3653 const X86Subtarget *Subtarget) {
3654 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3655 LoadSDNode *LD = NULL;
3656 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3657 LD = dyn_cast<LoadSDNode>(SrcOp);
3659 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3661 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3662 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3663 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3664 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3665 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3667 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3668 return DAG.getNode(ISD::BIT_CONVERT, VT,
3669 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3670 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3671 SrcOp.getOperand(0).getOperand(0))));
3676 return DAG.getNode(ISD::BIT_CONVERT, VT,
3677 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3678 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3681 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3684 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3685 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3686 MVT MaskVT = PermMask.getValueType();
3687 MVT MaskEVT = MaskVT.getVectorElementType();
3688 SmallVector<std::pair<int, int>, 8> Locs;
3690 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3693 for (unsigned i = 0; i != 4; ++i) {
3694 SDValue Elt = PermMask.getOperand(i);
3695 if (Elt.getOpcode() == ISD::UNDEF) {
3696 Locs[i] = std::make_pair(-1, -1);
3698 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3699 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3701 Locs[i] = std::make_pair(0, NumLo);
3705 Locs[i] = std::make_pair(1, NumHi);
3707 Mask1[2+NumHi] = Elt;
3713 if (NumLo <= 2 && NumHi <= 2) {
3714 // If no more than two elements come from either vector. This can be
3715 // implemented with two shuffles. First shuffle gather the elements.
3716 // The second shuffle, which takes the first shuffle as both of its
3717 // vector operands, put the elements into the right order.
3718 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3719 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3720 &Mask1[0], Mask1.size()));
3722 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3723 for (unsigned i = 0; i != 4; ++i) {
3724 if (Locs[i].first == -1)
3727 unsigned Idx = (i < 2) ? 0 : 4;
3728 Idx += Locs[i].first * 2 + Locs[i].second;
3729 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3733 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3734 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3735 &Mask2[0], Mask2.size()));
3736 } else if (NumLo == 3 || NumHi == 3) {
3737 // Otherwise, we must have three elements from one vector, call it X, and
3738 // one element from the other, call it Y. First, use a shufps to build an
3739 // intermediate vector with the one element from Y and the element from X
3740 // that will be in the same half in the final destination (the indexes don't
3741 // matter). Then, use a shufps to build the final vector, taking the half
3742 // containing the element from Y from the intermediate, and the other half
3745 // Normalize it so the 3 elements come from V1.
3746 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3750 // Find the element from V2.
3752 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3753 SDValue Elt = PermMask.getOperand(HiIndex);
3754 if (Elt.getOpcode() == ISD::UNDEF)
3756 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3761 Mask1[0] = PermMask.getOperand(HiIndex);
3762 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3763 Mask1[2] = PermMask.getOperand(HiIndex^1);
3764 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3765 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3766 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3769 Mask1[0] = PermMask.getOperand(0);
3770 Mask1[1] = PermMask.getOperand(1);
3771 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3772 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3773 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3774 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3776 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3777 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3778 Mask1[2] = PermMask.getOperand(2);
3779 Mask1[3] = PermMask.getOperand(3);
3780 if (Mask1[2].getOpcode() != ISD::UNDEF)
3781 Mask1[2] = DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getValue()+4,
3783 if (Mask1[3].getOpcode() != ISD::UNDEF)
3784 Mask1[3] = DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getValue()+4,
3786 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3787 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3791 // Break it into (shuffle shuffle_hi, shuffle_lo).
3793 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3794 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3795 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3796 unsigned MaskIdx = 0;
3799 for (unsigned i = 0; i != 4; ++i) {
3806 SDValue Elt = PermMask.getOperand(i);
3807 if (Elt.getOpcode() == ISD::UNDEF) {
3808 Locs[i] = std::make_pair(-1, -1);
3809 } else if (cast<ConstantSDNode>(Elt)->getValue() < 4) {
3810 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3811 (*MaskPtr)[LoIdx] = Elt;
3814 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3815 (*MaskPtr)[HiIdx] = Elt;
3820 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3821 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3822 &LoMask[0], LoMask.size()));
3823 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3824 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3825 &HiMask[0], HiMask.size()));
3826 SmallVector<SDValue, 8> MaskOps;
3827 for (unsigned i = 0; i != 4; ++i) {
3828 if (Locs[i].first == -1) {
3829 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3831 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3832 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3835 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3836 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3837 &MaskOps[0], MaskOps.size()));
3841 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3842 SDValue V1 = Op.getOperand(0);
3843 SDValue V2 = Op.getOperand(1);
3844 SDValue PermMask = Op.getOperand(2);
3845 MVT VT = Op.getValueType();
3846 unsigned NumElems = PermMask.getNumOperands();
3847 bool isMMX = VT.getSizeInBits() == 64;
3848 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3849 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3850 bool V1IsSplat = false;
3851 bool V2IsSplat = false;
3853 if (isUndefShuffle(Op.Val))
3854 return DAG.getNode(ISD::UNDEF, VT);
3856 if (isZeroShuffle(Op.Val))
3857 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3859 if (isIdentityMask(PermMask.Val))
3861 else if (isIdentityMask(PermMask.Val, true))
3864 if (isSplatMask(PermMask.Val)) {
3865 if (isMMX || NumElems < 4) return Op;
3866 // Promote it to a v4{if}32 splat.
3867 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3870 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3872 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3873 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3875 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3876 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3877 // FIXME: Figure out a cleaner way to do this.
3878 // Try to make use of movq to zero out the top part.
3879 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3880 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3883 SDValue NewV1 = NewOp.getOperand(0);
3884 SDValue NewV2 = NewOp.getOperand(1);
3885 SDValue NewMask = NewOp.getOperand(2);
3886 if (isCommutedMOVL(NewMask.Val, true, false)) {
3887 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3888 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3891 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3892 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3894 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3895 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3900 // Check if this can be converted into a logical shift.
3901 bool isLeft = false;
3904 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3905 if (isShift && ShVal.hasOneUse()) {
3906 // If the shifted value has multiple uses, it may be cheaper to use
3907 // v_set0 + movlhps or movhlps, etc.
3908 MVT EVT = VT.getVectorElementType();
3909 ShAmt *= EVT.getSizeInBits();
3910 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3913 if (X86::isMOVLMask(PermMask.Val)) {
3916 if (ISD::isBuildVectorAllZeros(V1.Val))
3917 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3922 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.Val) ||
3923 X86::isMOVSLDUPMask(PermMask.Val) ||
3924 X86::isMOVHLPSMask(PermMask.Val) ||
3925 X86::isMOVHPMask(PermMask.Val) ||
3926 X86::isMOVLPMask(PermMask.Val)))
3929 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3930 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3931 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3934 // No better options. Use a vshl / vsrl.
3935 MVT EVT = VT.getVectorElementType();
3936 ShAmt *= EVT.getSizeInBits();
3937 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3940 bool Commuted = false;
3941 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3942 // 1,1,1,1 -> v8i16 though.
3943 V1IsSplat = isSplatVector(V1.Val);
3944 V2IsSplat = isSplatVector(V2.Val);
3946 // Canonicalize the splat or undef, if present, to be on the RHS.
3947 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3948 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3949 std::swap(V1IsSplat, V2IsSplat);
3950 std::swap(V1IsUndef, V2IsUndef);
3954 // FIXME: Figure out a cleaner way to do this.
3955 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3956 if (V2IsUndef) return V1;
3957 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3959 // V2 is a splat, so the mask may be malformed. That is, it may point
3960 // to any V2 element. The instruction selectior won't like this. Get
3961 // a corrected mask and commute to form a proper MOVS{S|D}.
3962 SDValue NewMask = getMOVLMask(NumElems, DAG);
3963 if (NewMask.Val != PermMask.Val)
3964 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3969 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3970 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3971 X86::isUNPCKLMask(PermMask.Val) ||
3972 X86::isUNPCKHMask(PermMask.Val))
3976 // Normalize mask so all entries that point to V2 points to its first
3977 // element then try to match unpck{h|l} again. If match, return a
3978 // new vector_shuffle with the corrected mask.
3979 SDValue NewMask = NormalizeMask(PermMask, DAG);
3980 if (NewMask.Val != PermMask.Val) {
3981 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3982 SDValue NewMask = getUnpacklMask(NumElems, DAG);
3983 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3984 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3985 SDValue NewMask = getUnpackhMask(NumElems, DAG);
3986 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3991 // Normalize the node to match x86 shuffle ops if needed
3992 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3993 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3996 // Commute is back and try unpck* again.
3997 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3998 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3999 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
4000 X86::isUNPCKLMask(PermMask.Val) ||
4001 X86::isUNPCKHMask(PermMask.Val))
4005 // Try PSHUF* first, then SHUFP*.
4006 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4007 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4008 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
4009 if (V2.getOpcode() != ISD::UNDEF)
4010 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4011 DAG.getNode(ISD::UNDEF, VT), PermMask);
4016 if (Subtarget->hasSSE2() &&
4017 (X86::isPSHUFDMask(PermMask.Val) ||
4018 X86::isPSHUFHWMask(PermMask.Val) ||
4019 X86::isPSHUFLWMask(PermMask.Val))) {
4021 if (VT == MVT::v4f32) {
4023 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4024 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4025 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4026 } else if (V2.getOpcode() != ISD::UNDEF)
4027 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4028 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4030 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4034 // Binary or unary shufps.
4035 if (X86::isSHUFPMask(PermMask.Val) ||
4036 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
4040 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4041 if (VT == MVT::v8i16) {
4042 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4047 // Handle all 4 wide cases with a number of shuffles except for MMX.
4048 if (NumElems == 4 && !isMMX)
4049 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4055 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4056 SelectionDAG &DAG) {
4057 MVT VT = Op.getValueType();
4058 if (VT.getSizeInBits() == 8) {
4059 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4060 Op.getOperand(0), Op.getOperand(1));
4061 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4062 DAG.getValueType(VT));
4063 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4064 } else if (VT.getSizeInBits() == 16) {
4065 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4066 Op.getOperand(0), Op.getOperand(1));
4067 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4068 DAG.getValueType(VT));
4069 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4070 } else if (VT == MVT::f32) {
4071 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4072 // the result back to FR32 register. It's only worth matching if the
4073 // result has a single use which is a store or a bitcast to i32.
4074 if (!Op.hasOneUse())
4076 SDNode *User = *Op.Val->use_begin();
4077 if (User->getOpcode() != ISD::STORE &&
4078 (User->getOpcode() != ISD::BIT_CONVERT ||
4079 User->getValueType(0) != MVT::i32))
4081 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4082 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4084 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4091 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4092 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4095 if (Subtarget->hasSSE41()) {
4096 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4101 MVT VT = Op.getValueType();
4102 // TODO: handle v16i8.
4103 if (VT.getSizeInBits() == 16) {
4104 SDValue Vec = Op.getOperand(0);
4105 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4107 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4108 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4109 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4111 // Transform it so it match pextrw which produces a 32-bit result.
4112 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4113 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4114 Op.getOperand(0), Op.getOperand(1));
4115 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4116 DAG.getValueType(VT));
4117 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4118 } else if (VT.getSizeInBits() == 32) {
4119 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4122 // SHUFPS the element to the lowest double word, then movss.
4123 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4124 SmallVector<SDValue, 8> IdxVec;
4126 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4128 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4130 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4132 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4133 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4134 &IdxVec[0], IdxVec.size());
4135 SDValue Vec = Op.getOperand(0);
4136 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4137 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4138 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4139 DAG.getIntPtrConstant(0));
4140 } else if (VT.getSizeInBits() == 64) {
4141 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4142 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4143 // to match extract_elt for f64.
4144 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4148 // UNPCKHPD the element to the lowest double word, then movsd.
4149 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4150 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4151 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4152 SmallVector<SDValue, 8> IdxVec;
4153 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4155 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4156 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4157 &IdxVec[0], IdxVec.size());
4158 SDValue Vec = Op.getOperand(0);
4159 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4160 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4161 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4162 DAG.getIntPtrConstant(0));
4169 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4170 MVT VT = Op.getValueType();
4171 MVT EVT = VT.getVectorElementType();
4173 SDValue N0 = Op.getOperand(0);
4174 SDValue N1 = Op.getOperand(1);
4175 SDValue N2 = Op.getOperand(2);
4177 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4178 isa<ConstantSDNode>(N2)) {
4179 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4181 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4183 if (N1.getValueType() != MVT::i32)
4184 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4185 if (N2.getValueType() != MVT::i32)
4186 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4187 return DAG.getNode(Opc, VT, N0, N1, N2);
4188 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4189 // Bits [7:6] of the constant are the source select. This will always be
4190 // zero here. The DAG Combiner may combine an extract_elt index into these
4191 // bits. For example (insert (extract, 3), 2) could be matched by putting
4192 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4193 // Bits [5:4] of the constant are the destination select. This is the
4194 // value of the incoming immediate.
4195 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4196 // combine either bitwise AND or insert of float 0.0 to set these bits.
4197 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4198 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4204 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4205 MVT VT = Op.getValueType();
4206 MVT EVT = VT.getVectorElementType();
4208 if (Subtarget->hasSSE41())
4209 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4214 SDValue N0 = Op.getOperand(0);
4215 SDValue N1 = Op.getOperand(1);
4216 SDValue N2 = Op.getOperand(2);
4218 if (EVT.getSizeInBits() == 16) {
4219 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4220 // as its second argument.
4221 if (N1.getValueType() != MVT::i32)
4222 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4223 if (N2.getValueType() != MVT::i32)
4224 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4225 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4231 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4232 if (Op.getValueType() == MVT::v2f32)
4233 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4234 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4235 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4236 Op.getOperand(0))));
4238 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4239 MVT VT = MVT::v2i32;
4240 switch (Op.getValueType().getSimpleVT()) {
4247 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4248 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4251 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4252 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4253 // one of the above mentioned nodes. It has to be wrapped because otherwise
4254 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4255 // be used to form addressing mode. These wrapped nodes will be selected
4258 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4259 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4260 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4262 CP->getAlignment());
4263 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4264 // With PIC, the address is actually $g + Offset.
4265 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4266 !Subtarget->isPICStyleRIPRel()) {
4267 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4268 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4276 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4277 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4278 SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4279 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4280 // With PIC, the address is actually $g + Offset.
4281 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4282 !Subtarget->isPICStyleRIPRel()) {
4283 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4284 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4288 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4289 // load the value at address GV, not the value of GV itself. This means that
4290 // the GlobalAddress must be in the base or index register of the address, not
4291 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4292 // The same applies for external symbols during PIC codegen
4293 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4294 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4295 PseudoSourceValue::getGOT(), 0);
4300 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4302 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4305 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4306 DAG.getNode(X86ISD::GlobalBaseReg,
4308 InFlag = Chain.getValue(1);
4310 // emit leal symbol@TLSGD(,%ebx,1), %eax
4311 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4312 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4313 GA->getValueType(0),
4315 SDValue Ops[] = { Chain, TGA, InFlag };
4316 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4317 InFlag = Result.getValue(2);
4318 Chain = Result.getValue(1);
4320 // call ___tls_get_addr. This function receives its argument in
4321 // the register EAX.
4322 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4323 InFlag = Chain.getValue(1);
4325 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4326 SDValue Ops1[] = { Chain,
4327 DAG.getTargetExternalSymbol("___tls_get_addr",
4329 DAG.getRegister(X86::EAX, PtrVT),
4330 DAG.getRegister(X86::EBX, PtrVT),
4332 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4333 InFlag = Chain.getValue(1);
4335 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4338 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4340 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4342 SDValue InFlag, Chain;
4344 // emit leaq symbol@TLSGD(%rip), %rdi
4345 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4346 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4347 GA->getValueType(0),
4349 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4350 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4351 Chain = Result.getValue(1);
4352 InFlag = Result.getValue(2);
4354 // call __tls_get_addr. This function receives its argument in
4355 // the register RDI.
4356 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4357 InFlag = Chain.getValue(1);
4359 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4360 SDValue Ops1[] = { Chain,
4361 DAG.getTargetExternalSymbol("__tls_get_addr",
4363 DAG.getRegister(X86::RDI, PtrVT),
4365 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4366 InFlag = Chain.getValue(1);
4368 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4371 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4372 // "local exec" model.
4373 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4375 // Get the Thread Pointer
4376 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4377 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4379 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4380 GA->getValueType(0),
4382 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4384 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4385 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4386 PseudoSourceValue::getGOT(), 0);
4388 // The address of the thread local variable is the add of the thread
4389 // pointer with the offset of the variable.
4390 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4394 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4395 // TODO: implement the "local dynamic" model
4396 // TODO: implement the "initial exec"model for pic executables
4397 assert(Subtarget->isTargetELF() &&
4398 "TLS not implemented for non-ELF targets");
4399 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4400 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4401 // otherwise use the "Local Exec"TLS Model
4402 if (Subtarget->is64Bit()) {
4403 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4405 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4406 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4408 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4413 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4414 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4415 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4416 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4417 // With PIC, the address is actually $g + Offset.
4418 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4419 !Subtarget->isPICStyleRIPRel()) {
4420 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4421 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4428 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4429 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4430 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4431 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4432 // With PIC, the address is actually $g + Offset.
4433 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4434 !Subtarget->isPICStyleRIPRel()) {
4435 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4436 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4443 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4444 /// take a 2 x i32 value to shift plus a shift amount.
4445 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4446 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4447 MVT VT = Op.getValueType();
4448 unsigned VTBits = VT.getSizeInBits();
4449 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4450 SDValue ShOpLo = Op.getOperand(0);
4451 SDValue ShOpHi = Op.getOperand(1);
4452 SDValue ShAmt = Op.getOperand(2);
4453 SDValue Tmp1 = isSRA ?
4454 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4455 DAG.getConstant(0, VT);
4458 if (Op.getOpcode() == ISD::SHL_PARTS) {
4459 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4460 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4462 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4463 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4466 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4467 DAG.getConstant(VTBits, MVT::i8));
4468 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4469 AndNode, DAG.getConstant(0, MVT::i8));
4472 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4473 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4474 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4476 if (Op.getOpcode() == ISD::SHL_PARTS) {
4477 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4478 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4480 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4481 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4484 SDValue Ops[2] = { Lo, Hi };
4485 return DAG.getMergeValues(Ops, 2);
4488 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4489 MVT SrcVT = Op.getOperand(0).getValueType();
4490 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4491 "Unknown SINT_TO_FP to lower!");
4493 // These are really Legal; caller falls through into that case.
4494 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4496 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4497 Subtarget->is64Bit())
4500 unsigned Size = SrcVT.getSizeInBits()/8;
4501 MachineFunction &MF = DAG.getMachineFunction();
4502 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4503 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4504 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4506 PseudoSourceValue::getFixedStack(SSFI), 0);
4510 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4512 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4514 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4515 SmallVector<SDValue, 8> Ops;
4516 Ops.push_back(Chain);
4517 Ops.push_back(StackSlot);
4518 Ops.push_back(DAG.getValueType(SrcVT));
4519 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4520 Tys, &Ops[0], Ops.size());
4523 Chain = Result.getValue(1);
4524 SDValue InFlag = Result.getValue(2);
4526 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4527 // shouldn't be necessary except that RFP cannot be live across
4528 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4529 MachineFunction &MF = DAG.getMachineFunction();
4530 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4531 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4532 Tys = DAG.getVTList(MVT::Other);
4533 SmallVector<SDValue, 8> Ops;
4534 Ops.push_back(Chain);
4535 Ops.push_back(Result);
4536 Ops.push_back(StackSlot);
4537 Ops.push_back(DAG.getValueType(Op.getValueType()));
4538 Ops.push_back(InFlag);
4539 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4540 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4541 PseudoSourceValue::getFixedStack(SSFI), 0);
4547 std::pair<SDValue,SDValue> X86TargetLowering::
4548 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4549 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4550 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4551 "Unknown FP_TO_SINT to lower!");
4553 // These are really Legal.
4554 if (Op.getValueType() == MVT::i32 &&
4555 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4556 return std::make_pair(SDValue(), SDValue());
4557 if (Subtarget->is64Bit() &&
4558 Op.getValueType() == MVT::i64 &&
4559 Op.getOperand(0).getValueType() != MVT::f80)
4560 return std::make_pair(SDValue(), SDValue());
4562 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4564 MachineFunction &MF = DAG.getMachineFunction();
4565 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4566 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4567 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4569 switch (Op.getValueType().getSimpleVT()) {
4570 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4571 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4572 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4573 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4576 SDValue Chain = DAG.getEntryNode();
4577 SDValue Value = Op.getOperand(0);
4578 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4579 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4580 Chain = DAG.getStore(Chain, Value, StackSlot,
4581 PseudoSourceValue::getFixedStack(SSFI), 0);
4582 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4584 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4586 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4587 Chain = Value.getValue(1);
4588 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4589 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4592 // Build the FP_TO_INT*_IN_MEM
4593 SDValue Ops[] = { Chain, Value, StackSlot };
4594 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4596 return std::make_pair(FIST, StackSlot);
4599 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4600 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4601 SDValue FIST = Vals.first, StackSlot = Vals.second;
4602 if (FIST.Val == 0) return SDValue();
4605 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4608 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4609 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4610 SDValue FIST = Vals.first, StackSlot = Vals.second;
4611 if (FIST.Val == 0) return 0;
4613 MVT VT = N->getValueType(0);
4615 // Return a load from the stack slot.
4616 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4618 // Use MERGE_VALUES to drop the chain result value and get a node with one
4619 // result. This requires turning off getMergeValues simplification, since
4620 // otherwise it will give us Res back.
4621 return DAG.getMergeValues(&Res, 1, false).Val;
4624 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4625 MVT VT = Op.getValueType();
4628 EltVT = VT.getVectorElementType();
4629 std::vector<Constant*> CV;
4630 if (EltVT == MVT::f64) {
4631 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4635 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4641 Constant *C = ConstantVector::get(CV);
4642 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4643 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4644 PseudoSourceValue::getConstantPool(), 0,
4646 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4649 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4650 MVT VT = Op.getValueType();
4652 unsigned EltNum = 1;
4653 if (VT.isVector()) {
4654 EltVT = VT.getVectorElementType();
4655 EltNum = VT.getVectorNumElements();
4657 std::vector<Constant*> CV;
4658 if (EltVT == MVT::f64) {
4659 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4663 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4669 Constant *C = ConstantVector::get(CV);
4670 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4671 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4672 PseudoSourceValue::getConstantPool(), 0,
4674 if (VT.isVector()) {
4675 return DAG.getNode(ISD::BIT_CONVERT, VT,
4676 DAG.getNode(ISD::XOR, MVT::v2i64,
4677 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4678 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4680 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4684 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4685 SDValue Op0 = Op.getOperand(0);
4686 SDValue Op1 = Op.getOperand(1);
4687 MVT VT = Op.getValueType();
4688 MVT SrcVT = Op1.getValueType();
4690 // If second operand is smaller, extend it first.
4691 if (SrcVT.bitsLT(VT)) {
4692 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4695 // And if it is bigger, shrink it first.
4696 if (SrcVT.bitsGT(VT)) {
4697 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4701 // At this point the operands and the result should have the same
4702 // type, and that won't be f80 since that is not custom lowered.
4704 // First get the sign bit of second operand.
4705 std::vector<Constant*> CV;
4706 if (SrcVT == MVT::f64) {
4707 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4708 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4710 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4711 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4712 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4713 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4715 Constant *C = ConstantVector::get(CV);
4716 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4717 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4718 PseudoSourceValue::getConstantPool(), 0,
4720 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4722 // Shift sign bit right or left if the two operands have different types.
4723 if (SrcVT.bitsGT(VT)) {
4724 // Op0 is MVT::f32, Op1 is MVT::f64.
4725 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4726 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4727 DAG.getConstant(32, MVT::i32));
4728 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4729 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4730 DAG.getIntPtrConstant(0));
4733 // Clear first operand sign bit.
4735 if (VT == MVT::f64) {
4736 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4737 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4739 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4740 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4741 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4742 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4744 C = ConstantVector::get(CV);
4745 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4746 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4747 PseudoSourceValue::getConstantPool(), 0,
4749 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4751 // Or the value with the sign bit.
4752 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4755 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4756 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4758 SDValue Op0 = Op.getOperand(0);
4759 SDValue Op1 = Op.getOperand(1);
4760 SDValue CC = Op.getOperand(2);
4761 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4762 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4765 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4767 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4768 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4769 DAG.getConstant(X86CC, MVT::i8), Cond);
4772 assert(isFP && "Illegal integer SetCC!");
4774 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4775 switch (SetCCOpcode) {
4776 default: assert(false && "Illegal floating point SetCC!");
4777 case ISD::SETOEQ: { // !PF & ZF
4778 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4779 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4780 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4781 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4782 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4784 case ISD::SETUNE: { // PF | !ZF
4785 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4786 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4787 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4788 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4789 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4794 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4796 SDValue Op0 = Op.getOperand(0);
4797 SDValue Op1 = Op.getOperand(1);
4798 SDValue CC = Op.getOperand(2);
4799 MVT VT = Op.getValueType();
4800 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4801 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4805 MVT VT0 = Op0.getValueType();
4806 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4807 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4810 switch (SetCCOpcode) {
4813 case ISD::SETEQ: SSECC = 0; break;
4815 case ISD::SETGT: Swap = true; // Fallthrough
4817 case ISD::SETOLT: SSECC = 1; break;
4819 case ISD::SETGE: Swap = true; // Fallthrough
4821 case ISD::SETOLE: SSECC = 2; break;
4822 case ISD::SETUO: SSECC = 3; break;
4824 case ISD::SETNE: SSECC = 4; break;
4825 case ISD::SETULE: Swap = true;
4826 case ISD::SETUGE: SSECC = 5; break;
4827 case ISD::SETULT: Swap = true;
4828 case ISD::SETUGT: SSECC = 6; break;
4829 case ISD::SETO: SSECC = 7; break;
4832 std::swap(Op0, Op1);
4834 // In the two special cases we can't handle, emit two comparisons.
4836 if (SetCCOpcode == ISD::SETUEQ) {
4838 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4839 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4840 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4842 else if (SetCCOpcode == ISD::SETONE) {
4844 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4845 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4846 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4848 assert(0 && "Illegal FP comparison");
4850 // Handle all other FP comparisons here.
4851 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4854 // We are handling one of the integer comparisons here. Since SSE only has
4855 // GT and EQ comparisons for integer, swapping operands and multiple
4856 // operations may be required for some comparisons.
4857 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4858 bool Swap = false, Invert = false, FlipSigns = false;
4860 switch (VT.getSimpleVT()) {
4862 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4863 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4864 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4865 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4868 switch (SetCCOpcode) {
4870 case ISD::SETNE: Invert = true;
4871 case ISD::SETEQ: Opc = EQOpc; break;
4872 case ISD::SETLT: Swap = true;
4873 case ISD::SETGT: Opc = GTOpc; break;
4874 case ISD::SETGE: Swap = true;
4875 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
4876 case ISD::SETULT: Swap = true;
4877 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4878 case ISD::SETUGE: Swap = true;
4879 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4882 std::swap(Op0, Op1);
4884 // Since SSE has no unsigned integer comparisons, we need to flip the sign
4885 // bits of the inputs before performing those operations.
4887 MVT EltVT = VT.getVectorElementType();
4888 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4889 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4890 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4892 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4893 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4896 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4898 // If the logical-not of the result is required, perform that now.
4900 MVT EltVT = VT.getVectorElementType();
4901 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4902 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4903 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4905 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4910 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4911 bool addTest = true;
4912 SDValue Cond = Op.getOperand(0);
4915 if (Cond.getOpcode() == ISD::SETCC)
4916 Cond = LowerSETCC(Cond, DAG);
4918 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4919 // setting operand in place of the X86ISD::SETCC.
4920 if (Cond.getOpcode() == X86ISD::SETCC) {
4921 CC = Cond.getOperand(0);
4923 SDValue Cmp = Cond.getOperand(1);
4924 unsigned Opc = Cmp.getOpcode();
4925 MVT VT = Op.getValueType();
4927 bool IllegalFPCMov = false;
4928 if (VT.isFloatingPoint() && !VT.isVector() &&
4929 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4930 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4932 if ((Opc == X86ISD::CMP ||
4933 Opc == X86ISD::COMI ||
4934 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4941 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4942 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4945 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4947 SmallVector<SDValue, 4> Ops;
4948 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4949 // condition is true.
4950 Ops.push_back(Op.getOperand(2));
4951 Ops.push_back(Op.getOperand(1));
4953 Ops.push_back(Cond);
4954 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4957 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4958 bool addTest = true;
4959 SDValue Chain = Op.getOperand(0);
4960 SDValue Cond = Op.getOperand(1);
4961 SDValue Dest = Op.getOperand(2);
4964 if (Cond.getOpcode() == ISD::SETCC)
4965 Cond = LowerSETCC(Cond, DAG);
4967 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4968 // setting operand in place of the X86ISD::SETCC.
4969 if (Cond.getOpcode() == X86ISD::SETCC) {
4970 CC = Cond.getOperand(0);
4972 SDValue Cmp = Cond.getOperand(1);
4973 unsigned Opc = Cmp.getOpcode();
4974 if (Opc == X86ISD::CMP ||
4975 Opc == X86ISD::COMI ||
4976 Opc == X86ISD::UCOMI) {
4983 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4984 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4986 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4987 Chain, Op.getOperand(2), CC, Cond);
4991 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4992 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4993 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4994 // that the guard pages used by the OS virtual memory manager are allocated in
4995 // correct sequence.
4997 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4998 SelectionDAG &DAG) {
4999 assert(Subtarget->isTargetCygMing() &&
5000 "This should be used only on Cygwin/Mingw targets");
5003 SDValue Chain = Op.getOperand(0);
5004 SDValue Size = Op.getOperand(1);
5005 // FIXME: Ensure alignment here
5009 MVT IntPtr = getPointerTy();
5010 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5012 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
5014 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5015 Flag = Chain.getValue(1);
5017 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5018 SDValue Ops[] = { Chain,
5019 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5020 DAG.getRegister(X86::EAX, IntPtr),
5021 DAG.getRegister(X86StackPtr, SPTy),
5023 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5024 Flag = Chain.getValue(1);
5026 Chain = DAG.getCALLSEQ_END(Chain,
5027 DAG.getIntPtrConstant(0),
5028 DAG.getIntPtrConstant(0),
5031 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5033 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5034 return DAG.getMergeValues(Ops1, 2);
5038 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5040 SDValue Dst, SDValue Src,
5041 SDValue Size, unsigned Align,
5042 const Value *DstSV, uint64_t DstSVOff) {
5043 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5045 /// If not DWORD aligned or size is more than the threshold, call the library.
5046 /// The libc version is likely to be faster for these cases. It can use the
5047 /// address value and run time information about the CPU.
5048 if ((Align & 3) != 0 ||
5050 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
5051 SDValue InFlag(0, 0);
5053 // Check to see if there is a specialized entry-point for memory zeroing.
5054 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5055 if (const char *bzeroEntry =
5056 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5057 MVT IntPtr = getPointerTy();
5058 const Type *IntPtrTy = getTargetData()->getIntPtrType();
5059 TargetLowering::ArgListTy Args;
5060 TargetLowering::ArgListEntry Entry;
5062 Entry.Ty = IntPtrTy;
5063 Args.push_back(Entry);
5065 Args.push_back(Entry);
5066 std::pair<SDValue,SDValue> CallResult =
5067 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5068 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5070 return CallResult.second;
5073 // Otherwise have the target-independent code call memset.
5077 uint64_t SizeVal = ConstantSize->getValue();
5078 SDValue InFlag(0, 0);
5081 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5082 unsigned BytesLeft = 0;
5083 bool TwoRepStos = false;
5086 uint64_t Val = ValC->getValue() & 255;
5088 // If the value is a constant, then we can potentially use larger sets.
5089 switch (Align & 3) {
5090 case 2: // WORD aligned
5093 Val = (Val << 8) | Val;
5095 case 0: // DWORD aligned
5098 Val = (Val << 8) | Val;
5099 Val = (Val << 16) | Val;
5100 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5103 Val = (Val << 32) | Val;
5106 default: // Byte aligned
5109 Count = DAG.getIntPtrConstant(SizeVal);
5113 if (AVT.bitsGT(MVT::i8)) {
5114 unsigned UBytes = AVT.getSizeInBits() / 8;
5115 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5116 BytesLeft = SizeVal % UBytes;
5119 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5121 InFlag = Chain.getValue(1);
5124 Count = DAG.getIntPtrConstant(SizeVal);
5125 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5126 InFlag = Chain.getValue(1);
5129 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5131 InFlag = Chain.getValue(1);
5132 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5134 InFlag = Chain.getValue(1);
5136 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5137 SmallVector<SDValue, 8> Ops;
5138 Ops.push_back(Chain);
5139 Ops.push_back(DAG.getValueType(AVT));
5140 Ops.push_back(InFlag);
5141 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5144 InFlag = Chain.getValue(1);
5146 MVT CVT = Count.getValueType();
5147 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5148 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5149 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5151 InFlag = Chain.getValue(1);
5152 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5154 Ops.push_back(Chain);
5155 Ops.push_back(DAG.getValueType(MVT::i8));
5156 Ops.push_back(InFlag);
5157 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5158 } else if (BytesLeft) {
5159 // Handle the last 1 - 7 bytes.
5160 unsigned Offset = SizeVal - BytesLeft;
5161 MVT AddrVT = Dst.getValueType();
5162 MVT SizeVT = Size.getValueType();
5164 Chain = DAG.getMemset(Chain,
5165 DAG.getNode(ISD::ADD, AddrVT, Dst,
5166 DAG.getConstant(Offset, AddrVT)),
5168 DAG.getConstant(BytesLeft, SizeVT),
5169 Align, DstSV, DstSVOff + Offset);
5172 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5177 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5178 SDValue Chain, SDValue Dst, SDValue Src,
5179 SDValue Size, unsigned Align,
5181 const Value *DstSV, uint64_t DstSVOff,
5182 const Value *SrcSV, uint64_t SrcSVOff) {
5183 // This requires the copy size to be a constant, preferrably
5184 // within a subtarget-specific limit.
5185 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5188 uint64_t SizeVal = ConstantSize->getValue();
5189 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5192 /// If not DWORD aligned, call the library.
5193 if ((Align & 3) != 0)
5198 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5201 unsigned UBytes = AVT.getSizeInBits() / 8;
5202 unsigned CountVal = SizeVal / UBytes;
5203 SDValue Count = DAG.getIntPtrConstant(CountVal);
5204 unsigned BytesLeft = SizeVal % UBytes;
5206 SDValue InFlag(0, 0);
5207 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5209 InFlag = Chain.getValue(1);
5210 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5212 InFlag = Chain.getValue(1);
5213 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5215 InFlag = Chain.getValue(1);
5217 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5218 SmallVector<SDValue, 8> Ops;
5219 Ops.push_back(Chain);
5220 Ops.push_back(DAG.getValueType(AVT));
5221 Ops.push_back(InFlag);
5222 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5224 SmallVector<SDValue, 4> Results;
5225 Results.push_back(RepMovs);
5227 // Handle the last 1 - 7 bytes.
5228 unsigned Offset = SizeVal - BytesLeft;
5229 MVT DstVT = Dst.getValueType();
5230 MVT SrcVT = Src.getValueType();
5231 MVT SizeVT = Size.getValueType();
5232 Results.push_back(DAG.getMemcpy(Chain,
5233 DAG.getNode(ISD::ADD, DstVT, Dst,
5234 DAG.getConstant(Offset, DstVT)),
5235 DAG.getNode(ISD::ADD, SrcVT, Src,
5236 DAG.getConstant(Offset, SrcVT)),
5237 DAG.getConstant(BytesLeft, SizeVT),
5238 Align, AlwaysInline,
5239 DstSV, DstSVOff + Offset,
5240 SrcSV, SrcSVOff + Offset));
5243 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5246 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5247 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5248 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5249 SDValue TheChain = N->getOperand(0);
5250 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5251 if (Subtarget->is64Bit()) {
5252 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5253 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5254 MVT::i64, rax.getValue(2));
5255 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5256 DAG.getConstant(32, MVT::i8));
5258 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5261 return DAG.getMergeValues(Ops, 2).Val;
5264 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5265 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5266 MVT::i32, eax.getValue(2));
5267 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5268 SDValue Ops[] = { eax, edx };
5269 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5271 // Use a MERGE_VALUES to return the value and chain.
5272 Ops[1] = edx.getValue(1);
5273 return DAG.getMergeValues(Ops, 2).Val;
5276 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5277 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5279 if (!Subtarget->is64Bit()) {
5280 // vastart just stores the address of the VarArgsFrameIndex slot into the
5281 // memory location argument.
5282 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5283 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5287 // gp_offset (0 - 6 * 8)
5288 // fp_offset (48 - 48 + 8 * 16)
5289 // overflow_arg_area (point to parameters coming in memory).
5291 SmallVector<SDValue, 8> MemOps;
5292 SDValue FIN = Op.getOperand(1);
5294 SDValue Store = DAG.getStore(Op.getOperand(0),
5295 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5297 MemOps.push_back(Store);
5300 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5301 Store = DAG.getStore(Op.getOperand(0),
5302 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5304 MemOps.push_back(Store);
5306 // Store ptr to overflow_arg_area
5307 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5308 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5309 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5310 MemOps.push_back(Store);
5312 // Store ptr to reg_save_area.
5313 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5314 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5315 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5316 MemOps.push_back(Store);
5317 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5320 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5321 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5322 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5323 SDValue Chain = Op.getOperand(0);
5324 SDValue SrcPtr = Op.getOperand(1);
5325 SDValue SrcSV = Op.getOperand(2);
5327 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5332 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5333 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5334 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5335 SDValue Chain = Op.getOperand(0);
5336 SDValue DstPtr = Op.getOperand(1);
5337 SDValue SrcPtr = Op.getOperand(2);
5338 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5339 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5341 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5342 DAG.getIntPtrConstant(24), 8, false,
5343 DstSV, 0, SrcSV, 0);
5347 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5348 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5350 default: return SDValue(); // Don't custom lower most intrinsics.
5351 // Comparison intrinsics.
5352 case Intrinsic::x86_sse_comieq_ss:
5353 case Intrinsic::x86_sse_comilt_ss:
5354 case Intrinsic::x86_sse_comile_ss:
5355 case Intrinsic::x86_sse_comigt_ss:
5356 case Intrinsic::x86_sse_comige_ss:
5357 case Intrinsic::x86_sse_comineq_ss:
5358 case Intrinsic::x86_sse_ucomieq_ss:
5359 case Intrinsic::x86_sse_ucomilt_ss:
5360 case Intrinsic::x86_sse_ucomile_ss:
5361 case Intrinsic::x86_sse_ucomigt_ss:
5362 case Intrinsic::x86_sse_ucomige_ss:
5363 case Intrinsic::x86_sse_ucomineq_ss:
5364 case Intrinsic::x86_sse2_comieq_sd:
5365 case Intrinsic::x86_sse2_comilt_sd:
5366 case Intrinsic::x86_sse2_comile_sd:
5367 case Intrinsic::x86_sse2_comigt_sd:
5368 case Intrinsic::x86_sse2_comige_sd:
5369 case Intrinsic::x86_sse2_comineq_sd:
5370 case Intrinsic::x86_sse2_ucomieq_sd:
5371 case Intrinsic::x86_sse2_ucomilt_sd:
5372 case Intrinsic::x86_sse2_ucomile_sd:
5373 case Intrinsic::x86_sse2_ucomigt_sd:
5374 case Intrinsic::x86_sse2_ucomige_sd:
5375 case Intrinsic::x86_sse2_ucomineq_sd: {
5377 ISD::CondCode CC = ISD::SETCC_INVALID;
5380 case Intrinsic::x86_sse_comieq_ss:
5381 case Intrinsic::x86_sse2_comieq_sd:
5385 case Intrinsic::x86_sse_comilt_ss:
5386 case Intrinsic::x86_sse2_comilt_sd:
5390 case Intrinsic::x86_sse_comile_ss:
5391 case Intrinsic::x86_sse2_comile_sd:
5395 case Intrinsic::x86_sse_comigt_ss:
5396 case Intrinsic::x86_sse2_comigt_sd:
5400 case Intrinsic::x86_sse_comige_ss:
5401 case Intrinsic::x86_sse2_comige_sd:
5405 case Intrinsic::x86_sse_comineq_ss:
5406 case Intrinsic::x86_sse2_comineq_sd:
5410 case Intrinsic::x86_sse_ucomieq_ss:
5411 case Intrinsic::x86_sse2_ucomieq_sd:
5412 Opc = X86ISD::UCOMI;
5415 case Intrinsic::x86_sse_ucomilt_ss:
5416 case Intrinsic::x86_sse2_ucomilt_sd:
5417 Opc = X86ISD::UCOMI;
5420 case Intrinsic::x86_sse_ucomile_ss:
5421 case Intrinsic::x86_sse2_ucomile_sd:
5422 Opc = X86ISD::UCOMI;
5425 case Intrinsic::x86_sse_ucomigt_ss:
5426 case Intrinsic::x86_sse2_ucomigt_sd:
5427 Opc = X86ISD::UCOMI;
5430 case Intrinsic::x86_sse_ucomige_ss:
5431 case Intrinsic::x86_sse2_ucomige_sd:
5432 Opc = X86ISD::UCOMI;
5435 case Intrinsic::x86_sse_ucomineq_ss:
5436 case Intrinsic::x86_sse2_ucomineq_sd:
5437 Opc = X86ISD::UCOMI;
5443 SDValue LHS = Op.getOperand(1);
5444 SDValue RHS = Op.getOperand(2);
5445 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5447 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5448 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5449 DAG.getConstant(X86CC, MVT::i8), Cond);
5450 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5453 // Fix vector shift instructions where the last operand is a non-immediate
5455 case Intrinsic::x86_sse2_pslli_w:
5456 case Intrinsic::x86_sse2_pslli_d:
5457 case Intrinsic::x86_sse2_pslli_q:
5458 case Intrinsic::x86_sse2_psrli_w:
5459 case Intrinsic::x86_sse2_psrli_d:
5460 case Intrinsic::x86_sse2_psrli_q:
5461 case Intrinsic::x86_sse2_psrai_w:
5462 case Intrinsic::x86_sse2_psrai_d:
5463 case Intrinsic::x86_mmx_pslli_w:
5464 case Intrinsic::x86_mmx_pslli_d:
5465 case Intrinsic::x86_mmx_pslli_q:
5466 case Intrinsic::x86_mmx_psrli_w:
5467 case Intrinsic::x86_mmx_psrli_d:
5468 case Intrinsic::x86_mmx_psrli_q:
5469 case Intrinsic::x86_mmx_psrai_w:
5470 case Intrinsic::x86_mmx_psrai_d: {
5471 SDValue ShAmt = Op.getOperand(2);
5472 if (isa<ConstantSDNode>(ShAmt))
5475 unsigned NewIntNo = 0;
5476 MVT ShAmtVT = MVT::v4i32;
5478 case Intrinsic::x86_sse2_pslli_w:
5479 NewIntNo = Intrinsic::x86_sse2_psll_w;
5481 case Intrinsic::x86_sse2_pslli_d:
5482 NewIntNo = Intrinsic::x86_sse2_psll_d;
5484 case Intrinsic::x86_sse2_pslli_q:
5485 NewIntNo = Intrinsic::x86_sse2_psll_q;
5487 case Intrinsic::x86_sse2_psrli_w:
5488 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5490 case Intrinsic::x86_sse2_psrli_d:
5491 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5493 case Intrinsic::x86_sse2_psrli_q:
5494 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5496 case Intrinsic::x86_sse2_psrai_w:
5497 NewIntNo = Intrinsic::x86_sse2_psra_w;
5499 case Intrinsic::x86_sse2_psrai_d:
5500 NewIntNo = Intrinsic::x86_sse2_psra_d;
5503 ShAmtVT = MVT::v2i32;
5505 case Intrinsic::x86_mmx_pslli_w:
5506 NewIntNo = Intrinsic::x86_mmx_psll_w;
5508 case Intrinsic::x86_mmx_pslli_d:
5509 NewIntNo = Intrinsic::x86_mmx_psll_d;
5511 case Intrinsic::x86_mmx_pslli_q:
5512 NewIntNo = Intrinsic::x86_mmx_psll_q;
5514 case Intrinsic::x86_mmx_psrli_w:
5515 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5517 case Intrinsic::x86_mmx_psrli_d:
5518 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5520 case Intrinsic::x86_mmx_psrli_q:
5521 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5523 case Intrinsic::x86_mmx_psrai_w:
5524 NewIntNo = Intrinsic::x86_mmx_psra_w;
5526 case Intrinsic::x86_mmx_psrai_d:
5527 NewIntNo = Intrinsic::x86_mmx_psra_d;
5529 default: abort(); // Can't reach here.
5534 MVT VT = Op.getValueType();
5535 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5536 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5537 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5538 DAG.getConstant(NewIntNo, MVT::i32),
5539 Op.getOperand(1), ShAmt);
5544 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5545 // Depths > 0 not supported yet!
5546 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5549 // Just load the return address
5550 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5551 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5554 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5555 // Depths > 0 not supported yet!
5556 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5559 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5560 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5561 DAG.getIntPtrConstant(!Subtarget->is64Bit() ? 4 : 8));
5564 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5565 SelectionDAG &DAG) {
5566 // Is not yet supported on x86-64
5567 if (Subtarget->is64Bit())
5570 return DAG.getIntPtrConstant(8);
5573 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5575 assert(!Subtarget->is64Bit() &&
5576 "Lowering of eh_return builtin is not supported yet on x86-64");
5578 MachineFunction &MF = DAG.getMachineFunction();
5579 SDValue Chain = Op.getOperand(0);
5580 SDValue Offset = Op.getOperand(1);
5581 SDValue Handler = Op.getOperand(2);
5583 SDValue Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5586 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5587 DAG.getIntPtrConstant(-4UL));
5588 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5589 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5590 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5591 MF.getRegInfo().addLiveOut(X86::ECX);
5593 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5594 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5597 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5598 SelectionDAG &DAG) {
5599 SDValue Root = Op.getOperand(0);
5600 SDValue Trmp = Op.getOperand(1); // trampoline
5601 SDValue FPtr = Op.getOperand(2); // nested function
5602 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5604 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5606 const X86InstrInfo *TII =
5607 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5609 if (Subtarget->is64Bit()) {
5610 SDValue OutChains[6];
5612 // Large code-model.
5614 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5615 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5617 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5618 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5620 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5622 // Load the pointer to the nested function into R11.
5623 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5624 SDValue Addr = Trmp;
5625 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5628 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5629 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5631 // Load the 'nest' parameter value into R10.
5632 // R10 is specified in X86CallingConv.td
5633 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5634 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5635 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5638 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5639 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5641 // Jump to the nested function.
5642 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5643 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5644 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5647 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5648 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5649 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5653 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5654 return DAG.getMergeValues(Ops, 2);
5656 const Function *Func =
5657 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5658 unsigned CC = Func->getCallingConv();
5663 assert(0 && "Unsupported calling convention");
5664 case CallingConv::C:
5665 case CallingConv::X86_StdCall: {
5666 // Pass 'nest' parameter in ECX.
5667 // Must be kept in sync with X86CallingConv.td
5670 // Check that ECX wasn't needed by an 'inreg' parameter.
5671 const FunctionType *FTy = Func->getFunctionType();
5672 const PAListPtr &Attrs = Func->getParamAttrs();
5674 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5675 unsigned InRegCount = 0;
5678 for (FunctionType::param_iterator I = FTy->param_begin(),
5679 E = FTy->param_end(); I != E; ++I, ++Idx)
5680 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5681 // FIXME: should only count parameters that are lowered to integers.
5682 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5684 if (InRegCount > 2) {
5685 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5691 case CallingConv::X86_FastCall:
5692 // Pass 'nest' parameter in EAX.
5693 // Must be kept in sync with X86CallingConv.td
5698 SDValue OutChains[4];
5701 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5702 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5704 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5705 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5706 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5709 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5710 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5712 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5713 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5714 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5715 TrmpAddr, 5, false, 1);
5717 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5718 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5721 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5722 return DAG.getMergeValues(Ops, 2);
5726 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5728 The rounding mode is in bits 11:10 of FPSR, and has the following
5735 FLT_ROUNDS, on the other hand, expects the following:
5742 To perform the conversion, we do:
5743 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5746 MachineFunction &MF = DAG.getMachineFunction();
5747 const TargetMachine &TM = MF.getTarget();
5748 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5749 unsigned StackAlignment = TFI.getStackAlignment();
5750 MVT VT = Op.getValueType();
5752 // Save FP Control Word to stack slot
5753 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5754 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5756 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5757 DAG.getEntryNode(), StackSlot);
5759 // Load FP Control Word from stack slot
5760 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5762 // Transform as necessary
5764 DAG.getNode(ISD::SRL, MVT::i16,
5765 DAG.getNode(ISD::AND, MVT::i16,
5766 CWD, DAG.getConstant(0x800, MVT::i16)),
5767 DAG.getConstant(11, MVT::i8));
5769 DAG.getNode(ISD::SRL, MVT::i16,
5770 DAG.getNode(ISD::AND, MVT::i16,
5771 CWD, DAG.getConstant(0x400, MVT::i16)),
5772 DAG.getConstant(9, MVT::i8));
5775 DAG.getNode(ISD::AND, MVT::i16,
5776 DAG.getNode(ISD::ADD, MVT::i16,
5777 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5778 DAG.getConstant(1, MVT::i16)),
5779 DAG.getConstant(3, MVT::i16));
5782 return DAG.getNode((VT.getSizeInBits() < 16 ?
5783 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5786 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5787 MVT VT = Op.getValueType();
5789 unsigned NumBits = VT.getSizeInBits();
5791 Op = Op.getOperand(0);
5792 if (VT == MVT::i8) {
5793 // Zero extend to i32 since there is not an i8 bsr.
5795 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5798 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5799 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5800 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5802 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5803 SmallVector<SDValue, 4> Ops;
5805 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5806 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5807 Ops.push_back(Op.getValue(1));
5808 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5810 // Finally xor with NumBits-1.
5811 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5814 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5818 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5819 MVT VT = Op.getValueType();
5821 unsigned NumBits = VT.getSizeInBits();
5823 Op = Op.getOperand(0);
5824 if (VT == MVT::i8) {
5826 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5829 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5830 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5831 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5833 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5834 SmallVector<SDValue, 4> Ops;
5836 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5837 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5838 Ops.push_back(Op.getValue(1));
5839 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5842 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5846 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5847 MVT T = Op.getValueType();
5850 switch(T.getSimpleVT()) {
5852 assert(false && "Invalid value type!");
5853 case MVT::i8: Reg = X86::AL; size = 1; break;
5854 case MVT::i16: Reg = X86::AX; size = 2; break;
5855 case MVT::i32: Reg = X86::EAX; size = 4; break;
5857 if (Subtarget->is64Bit()) {
5858 Reg = X86::RAX; size = 8;
5859 } else //Should go away when LowerType stuff lands
5860 return SDValue(ExpandATOMIC_CMP_SWAP(Op.Val, DAG), 0);
5863 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5864 Op.getOperand(3), SDValue());
5865 SDValue Ops[] = { cpIn.getValue(0),
5868 DAG.getTargetConstant(size, MVT::i8),
5870 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5871 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5873 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5877 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op, SelectionDAG &DAG) {
5878 MVT T = Op->getValueType(0);
5879 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5880 SDValue cpInL, cpInH;
5881 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5882 DAG.getConstant(0, MVT::i32));
5883 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5884 DAG.getConstant(1, MVT::i32));
5885 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5887 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5888 cpInH, cpInL.getValue(1));
5889 SDValue swapInL, swapInH;
5890 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5891 DAG.getConstant(0, MVT::i32));
5892 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5893 DAG.getConstant(1, MVT::i32));
5894 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5895 swapInL, cpInH.getValue(1));
5896 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5897 swapInH, swapInL.getValue(1));
5898 SDValue Ops[] = { swapInH.getValue(0),
5900 swapInH.getValue(1)};
5901 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5902 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5903 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5904 Result.getValue(1));
5905 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5906 cpOutL.getValue(2));
5907 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5908 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5909 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5910 return DAG.getMergeValues(Vals, 2).Val;
5913 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op, SelectionDAG &DAG) {
5914 MVT T = Op->getValueType(0);
5915 SDValue negOp = DAG.getNode(ISD::SUB, T,
5916 DAG.getConstant(0, T), Op->getOperand(2));
5917 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, Op->getOperand(0),
5918 Op->getOperand(1), negOp,
5919 cast<AtomicSDNode>(Op)->getSrcValue(),
5920 cast<AtomicSDNode>(Op)->getAlignment()).Val;
5923 /// LowerOperation - Provide custom lowering hooks for some operations.
5925 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5926 switch (Op.getOpcode()) {
5927 default: assert(0 && "Should not custom lower this!");
5928 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
5929 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5930 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5931 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5932 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5933 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5934 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5935 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5936 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5937 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5938 case ISD::SHL_PARTS:
5939 case ISD::SRA_PARTS:
5940 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5941 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5942 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5943 case ISD::FABS: return LowerFABS(Op, DAG);
5944 case ISD::FNEG: return LowerFNEG(Op, DAG);
5945 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5946 case ISD::SETCC: return LowerSETCC(Op, DAG);
5947 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
5948 case ISD::SELECT: return LowerSELECT(Op, DAG);
5949 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5950 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5951 case ISD::CALL: return LowerCALL(Op, DAG);
5952 case ISD::RET: return LowerRET(Op, DAG);
5953 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5954 case ISD::VASTART: return LowerVASTART(Op, DAG);
5955 case ISD::VAARG: return LowerVAARG(Op, DAG);
5956 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5957 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5958 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5959 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5960 case ISD::FRAME_TO_ARGS_OFFSET:
5961 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5962 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5963 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5964 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5965 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5966 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5967 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5969 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5970 case ISD::READCYCLECOUNTER:
5971 return SDValue(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5975 /// ReplaceNodeResults - Replace a node with an illegal result type
5976 /// with a new node built out of custom code.
5977 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
5978 switch (N->getOpcode()) {
5979 default: assert(0 && "Should not custom lower this!");
5980 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5981 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5982 case ISD::ATOMIC_CMP_SWAP: return ExpandATOMIC_CMP_SWAP(N, DAG);
5983 case ISD::ATOMIC_LOAD_SUB: return ExpandATOMIC_LOAD_SUB(N,DAG);
5987 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5989 default: return NULL;
5990 case X86ISD::BSF: return "X86ISD::BSF";
5991 case X86ISD::BSR: return "X86ISD::BSR";
5992 case X86ISD::SHLD: return "X86ISD::SHLD";
5993 case X86ISD::SHRD: return "X86ISD::SHRD";
5994 case X86ISD::FAND: return "X86ISD::FAND";
5995 case X86ISD::FOR: return "X86ISD::FOR";
5996 case X86ISD::FXOR: return "X86ISD::FXOR";
5997 case X86ISD::FSRL: return "X86ISD::FSRL";
5998 case X86ISD::FILD: return "X86ISD::FILD";
5999 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6000 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6001 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6002 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6003 case X86ISD::FLD: return "X86ISD::FLD";
6004 case X86ISD::FST: return "X86ISD::FST";
6005 case X86ISD::CALL: return "X86ISD::CALL";
6006 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6007 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6008 case X86ISD::CMP: return "X86ISD::CMP";
6009 case X86ISD::COMI: return "X86ISD::COMI";
6010 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6011 case X86ISD::SETCC: return "X86ISD::SETCC";
6012 case X86ISD::CMOV: return "X86ISD::CMOV";
6013 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6014 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6015 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6016 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6017 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6018 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6019 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6020 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6021 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6022 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6023 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6024 case X86ISD::FMAX: return "X86ISD::FMAX";
6025 case X86ISD::FMIN: return "X86ISD::FMIN";
6026 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6027 case X86ISD::FRCP: return "X86ISD::FRCP";
6028 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6029 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6030 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6031 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6032 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6033 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6034 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6035 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6036 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6037 case X86ISD::VSHL: return "X86ISD::VSHL";
6038 case X86ISD::VSRL: return "X86ISD::VSRL";
6039 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6040 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6041 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6042 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6043 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6044 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6045 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6046 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6047 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6048 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6052 // isLegalAddressingMode - Return true if the addressing mode represented
6053 // by AM is legal for this target, for a load/store of the specified type.
6054 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6055 const Type *Ty) const {
6056 // X86 supports extremely general addressing modes.
6058 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6059 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6063 // We can only fold this if we don't need an extra load.
6064 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6067 // X86-64 only supports addr of globals in small code model.
6068 if (Subtarget->is64Bit()) {
6069 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6071 // If lower 4G is not available, then we must use rip-relative addressing.
6072 if (AM.BaseOffs || AM.Scale > 1)
6083 // These scales always work.
6088 // These scales are formed with basereg+scalereg. Only accept if there is
6093 default: // Other stuff never works.
6101 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6102 if (!Ty1->isInteger() || !Ty2->isInteger())
6104 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6105 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6106 if (NumBits1 <= NumBits2)
6108 return Subtarget->is64Bit() || NumBits1 < 64;
6111 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6112 if (!VT1.isInteger() || !VT2.isInteger())
6114 unsigned NumBits1 = VT1.getSizeInBits();
6115 unsigned NumBits2 = VT2.getSizeInBits();
6116 if (NumBits1 <= NumBits2)
6118 return Subtarget->is64Bit() || NumBits1 < 64;
6121 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6122 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6123 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6124 /// are assumed to be legal.
6126 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6127 // Only do shuffles on 128-bit vector types for now.
6128 if (VT.getSizeInBits() == 64) return false;
6129 return (Mask.Val->getNumOperands() <= 4 ||
6130 isIdentityMask(Mask.Val) ||
6131 isIdentityMask(Mask.Val, true) ||
6132 isSplatMask(Mask.Val) ||
6133 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
6134 X86::isUNPCKLMask(Mask.Val) ||
6135 X86::isUNPCKHMask(Mask.Val) ||
6136 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
6137 X86::isUNPCKH_v_undef_Mask(Mask.Val));
6141 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6142 MVT EVT, SelectionDAG &DAG) const {
6143 unsigned NumElts = BVOps.size();
6144 // Only do shuffles on 128-bit vector types for now.
6145 if (EVT.getSizeInBits() * NumElts == 64) return false;
6146 if (NumElts == 2) return true;
6148 return (isMOVLMask(&BVOps[0], 4) ||
6149 isCommutedMOVL(&BVOps[0], 4, true) ||
6150 isSHUFPMask(&BVOps[0], 4) ||
6151 isCommutedSHUFP(&BVOps[0], 4));
6156 //===----------------------------------------------------------------------===//
6157 // X86 Scheduler Hooks
6158 //===----------------------------------------------------------------------===//
6160 // private utility function
6162 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6163 MachineBasicBlock *MBB,
6171 TargetRegisterClass *RC,
6173 // For the atomic bitwise operator, we generate
6176 // ld t1 = [bitinstr.addr]
6177 // op t2 = t1, [bitinstr.val]
6179 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6181 // fallthrough -->nextMBB
6182 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6183 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6184 MachineFunction::iterator MBBIter = MBB;
6187 /// First build the CFG
6188 MachineFunction *F = MBB->getParent();
6189 MachineBasicBlock *thisMBB = MBB;
6190 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6191 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6192 F->insert(MBBIter, newMBB);
6193 F->insert(MBBIter, nextMBB);
6195 // Move all successors to thisMBB to nextMBB
6196 nextMBB->transferSuccessors(thisMBB);
6198 // Update thisMBB to fall through to newMBB
6199 thisMBB->addSuccessor(newMBB);
6201 // newMBB jumps to itself and fall through to nextMBB
6202 newMBB->addSuccessor(nextMBB);
6203 newMBB->addSuccessor(newMBB);
6205 // Insert instructions into newMBB based on incoming instruction
6206 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6207 MachineOperand& destOper = bInstr->getOperand(0);
6208 MachineOperand* argOpers[6];
6209 int numArgs = bInstr->getNumOperands() - 1;
6210 for (int i=0; i < numArgs; ++i)
6211 argOpers[i] = &bInstr->getOperand(i+1);
6213 // x86 address has 4 operands: base, index, scale, and displacement
6214 int lastAddrIndx = 3; // [0,3]
6217 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6218 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6219 for (int i=0; i <= lastAddrIndx; ++i)
6220 (*MIB).addOperand(*argOpers[i]);
6222 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6224 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6229 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6230 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6231 && "invalid operand");
6232 if (argOpers[valArgIndx]->isReg())
6233 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6235 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6237 (*MIB).addOperand(*argOpers[valArgIndx]);
6239 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6242 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6243 for (int i=0; i <= lastAddrIndx; ++i)
6244 (*MIB).addOperand(*argOpers[i]);
6246 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6247 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6249 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6253 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6255 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6259 // private utility function
6261 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6262 MachineBasicBlock *MBB,
6264 // For the atomic min/max operator, we generate
6267 // ld t1 = [min/max.addr]
6268 // mov t2 = [min/max.val]
6270 // cmov[cond] t2 = t1
6272 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6274 // fallthrough -->nextMBB
6276 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6277 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6278 MachineFunction::iterator MBBIter = MBB;
6281 /// First build the CFG
6282 MachineFunction *F = MBB->getParent();
6283 MachineBasicBlock *thisMBB = MBB;
6284 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6285 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6286 F->insert(MBBIter, newMBB);
6287 F->insert(MBBIter, nextMBB);
6289 // Move all successors to thisMBB to nextMBB
6290 nextMBB->transferSuccessors(thisMBB);
6292 // Update thisMBB to fall through to newMBB
6293 thisMBB->addSuccessor(newMBB);
6295 // newMBB jumps to newMBB and fall through to nextMBB
6296 newMBB->addSuccessor(nextMBB);
6297 newMBB->addSuccessor(newMBB);
6299 // Insert instructions into newMBB based on incoming instruction
6300 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6301 MachineOperand& destOper = mInstr->getOperand(0);
6302 MachineOperand* argOpers[6];
6303 int numArgs = mInstr->getNumOperands() - 1;
6304 for (int i=0; i < numArgs; ++i)
6305 argOpers[i] = &mInstr->getOperand(i+1);
6307 // x86 address has 4 operands: base, index, scale, and displacement
6308 int lastAddrIndx = 3; // [0,3]
6311 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6312 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6313 for (int i=0; i <= lastAddrIndx; ++i)
6314 (*MIB).addOperand(*argOpers[i]);
6316 // We only support register and immediate values
6317 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6318 && "invalid operand");
6320 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6321 if (argOpers[valArgIndx]->isReg())
6322 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6324 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6325 (*MIB).addOperand(*argOpers[valArgIndx]);
6327 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6330 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6335 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6336 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6340 // Cmp and exchange if none has modified the memory location
6341 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6342 for (int i=0; i <= lastAddrIndx; ++i)
6343 (*MIB).addOperand(*argOpers[i]);
6345 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6346 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6348 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6349 MIB.addReg(X86::EAX);
6352 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6354 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6360 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6361 MachineBasicBlock *BB) {
6362 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6363 switch (MI->getOpcode()) {
6364 default: assert(false && "Unexpected instr type to insert");
6365 case X86::CMOV_FR32:
6366 case X86::CMOV_FR64:
6367 case X86::CMOV_V4F32:
6368 case X86::CMOV_V2F64:
6369 case X86::CMOV_V2I64: {
6370 // To "insert" a SELECT_CC instruction, we actually have to insert the
6371 // diamond control-flow pattern. The incoming instruction knows the
6372 // destination vreg to set, the condition code register to branch on, the
6373 // true/false values to select between, and a branch opcode to use.
6374 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6375 MachineFunction::iterator It = BB;
6381 // cmpTY ccX, r1, r2
6383 // fallthrough --> copy0MBB
6384 MachineBasicBlock *thisMBB = BB;
6385 MachineFunction *F = BB->getParent();
6386 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6387 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6389 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6390 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6391 F->insert(It, copy0MBB);
6392 F->insert(It, sinkMBB);
6393 // Update machine-CFG edges by transferring all successors of the current
6394 // block to the new block which will contain the Phi node for the select.
6395 sinkMBB->transferSuccessors(BB);
6397 // Add the true and fallthrough blocks as its successors.
6398 BB->addSuccessor(copy0MBB);
6399 BB->addSuccessor(sinkMBB);
6402 // %FalseValue = ...
6403 // # fallthrough to sinkMBB
6406 // Update machine-CFG edges
6407 BB->addSuccessor(sinkMBB);
6410 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6413 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6414 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6415 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6417 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6421 case X86::FP32_TO_INT16_IN_MEM:
6422 case X86::FP32_TO_INT32_IN_MEM:
6423 case X86::FP32_TO_INT64_IN_MEM:
6424 case X86::FP64_TO_INT16_IN_MEM:
6425 case X86::FP64_TO_INT32_IN_MEM:
6426 case X86::FP64_TO_INT64_IN_MEM:
6427 case X86::FP80_TO_INT16_IN_MEM:
6428 case X86::FP80_TO_INT32_IN_MEM:
6429 case X86::FP80_TO_INT64_IN_MEM: {
6430 // Change the floating point control register to use "round towards zero"
6431 // mode when truncating to an integer value.
6432 MachineFunction *F = BB->getParent();
6433 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6434 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6436 // Load the old value of the high byte of the control word...
6438 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6439 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6441 // Set the high part to be round to zero...
6442 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6445 // Reload the modified control word now...
6446 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6448 // Restore the memory image of control word to original value
6449 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6452 // Get the X86 opcode to use.
6454 switch (MI->getOpcode()) {
6455 default: assert(0 && "illegal opcode!");
6456 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6457 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6458 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6459 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6460 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6461 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6462 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6463 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6464 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6468 MachineOperand &Op = MI->getOperand(0);
6469 if (Op.isRegister()) {
6470 AM.BaseType = X86AddressMode::RegBase;
6471 AM.Base.Reg = Op.getReg();
6473 AM.BaseType = X86AddressMode::FrameIndexBase;
6474 AM.Base.FrameIndex = Op.getIndex();
6476 Op = MI->getOperand(1);
6477 if (Op.isImmediate())
6478 AM.Scale = Op.getImm();
6479 Op = MI->getOperand(2);
6480 if (Op.isImmediate())
6481 AM.IndexReg = Op.getImm();
6482 Op = MI->getOperand(3);
6483 if (Op.isGlobalAddress()) {
6484 AM.GV = Op.getGlobal();
6486 AM.Disp = Op.getImm();
6488 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6489 .addReg(MI->getOperand(4).getReg());
6491 // Reload the original control word now.
6492 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6494 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6497 case X86::ATOMAND32:
6498 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6499 X86::AND32ri, X86::MOV32rm,
6500 X86::LCMPXCHG32, X86::MOV32rr,
6501 X86::NOT32r, X86::EAX,
6502 X86::GR32RegisterClass);
6504 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6505 X86::OR32ri, X86::MOV32rm,
6506 X86::LCMPXCHG32, X86::MOV32rr,
6507 X86::NOT32r, X86::EAX,
6508 X86::GR32RegisterClass);
6509 case X86::ATOMXOR32:
6510 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6511 X86::XOR32ri, X86::MOV32rm,
6512 X86::LCMPXCHG32, X86::MOV32rr,
6513 X86::NOT32r, X86::EAX,
6514 X86::GR32RegisterClass);
6515 case X86::ATOMNAND32:
6516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6517 X86::AND32ri, X86::MOV32rm,
6518 X86::LCMPXCHG32, X86::MOV32rr,
6519 X86::NOT32r, X86::EAX,
6520 X86::GR32RegisterClass, true);
6521 case X86::ATOMMIN32:
6522 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6523 case X86::ATOMMAX32:
6524 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6525 case X86::ATOMUMIN32:
6526 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6527 case X86::ATOMUMAX32:
6528 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6530 case X86::ATOMAND16:
6531 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6532 X86::AND16ri, X86::MOV16rm,
6533 X86::LCMPXCHG16, X86::MOV16rr,
6534 X86::NOT16r, X86::AX,
6535 X86::GR16RegisterClass);
6537 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
6538 X86::OR16ri, X86::MOV16rm,
6539 X86::LCMPXCHG16, X86::MOV16rr,
6540 X86::NOT16r, X86::AX,
6541 X86::GR16RegisterClass);
6542 case X86::ATOMXOR16:
6543 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6544 X86::XOR16ri, X86::MOV16rm,
6545 X86::LCMPXCHG16, X86::MOV16rr,
6546 X86::NOT16r, X86::AX,
6547 X86::GR16RegisterClass);
6548 case X86::ATOMNAND16:
6549 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6550 X86::AND16ri, X86::MOV16rm,
6551 X86::LCMPXCHG16, X86::MOV16rr,
6552 X86::NOT16r, X86::AX,
6553 X86::GR16RegisterClass, true);
6554 case X86::ATOMMIN16:
6555 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6556 case X86::ATOMMAX16:
6557 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6558 case X86::ATOMUMIN16:
6559 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6560 case X86::ATOMUMAX16:
6561 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6564 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6565 X86::AND8ri, X86::MOV8rm,
6566 X86::LCMPXCHG8, X86::MOV8rr,
6567 X86::NOT8r, X86::AL,
6568 X86::GR8RegisterClass);
6570 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
6571 X86::OR8ri, X86::MOV8rm,
6572 X86::LCMPXCHG8, X86::MOV8rr,
6573 X86::NOT8r, X86::AL,
6574 X86::GR8RegisterClass);
6576 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6577 X86::XOR8ri, X86::MOV8rm,
6578 X86::LCMPXCHG8, X86::MOV8rr,
6579 X86::NOT8r, X86::AL,
6580 X86::GR8RegisterClass);
6581 case X86::ATOMNAND8:
6582 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6583 X86::AND8ri, X86::MOV8rm,
6584 X86::LCMPXCHG8, X86::MOV8rr,
6585 X86::NOT8r, X86::AL,
6586 X86::GR8RegisterClass, true);
6587 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6588 case X86::ATOMAND64:
6589 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6590 X86::AND64ri32, X86::MOV64rm,
6591 X86::LCMPXCHG64, X86::MOV64rr,
6592 X86::NOT64r, X86::RAX,
6593 X86::GR64RegisterClass);
6595 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
6596 X86::OR64ri32, X86::MOV64rm,
6597 X86::LCMPXCHG64, X86::MOV64rr,
6598 X86::NOT64r, X86::RAX,
6599 X86::GR64RegisterClass);
6600 case X86::ATOMXOR64:
6601 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
6602 X86::XOR64ri32, X86::MOV64rm,
6603 X86::LCMPXCHG64, X86::MOV64rr,
6604 X86::NOT64r, X86::RAX,
6605 X86::GR64RegisterClass);
6606 case X86::ATOMNAND64:
6607 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6608 X86::AND64ri32, X86::MOV64rm,
6609 X86::LCMPXCHG64, X86::MOV64rr,
6610 X86::NOT64r, X86::RAX,
6611 X86::GR64RegisterClass, true);
6612 case X86::ATOMMIN64:
6613 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
6614 case X86::ATOMMAX64:
6615 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
6616 case X86::ATOMUMIN64:
6617 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
6618 case X86::ATOMUMAX64:
6619 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
6623 //===----------------------------------------------------------------------===//
6624 // X86 Optimization Hooks
6625 //===----------------------------------------------------------------------===//
6627 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6631 const SelectionDAG &DAG,
6632 unsigned Depth) const {
6633 unsigned Opc = Op.getOpcode();
6634 assert((Opc >= ISD::BUILTIN_OP_END ||
6635 Opc == ISD::INTRINSIC_WO_CHAIN ||
6636 Opc == ISD::INTRINSIC_W_CHAIN ||
6637 Opc == ISD::INTRINSIC_VOID) &&
6638 "Should use MaskedValueIsZero if you don't know whether Op"
6639 " is a target node!");
6641 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6645 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6646 Mask.getBitWidth() - 1);
6651 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6652 /// node is a GlobalAddress + offset.
6653 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6654 GlobalValue* &GA, int64_t &Offset) const{
6655 if (N->getOpcode() == X86ISD::Wrapper) {
6656 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6657 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6661 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6664 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6665 const TargetLowering &TLI) {
6668 if (TLI.isGAPlusOffset(Base, GV, Offset))
6669 return (GV->getAlignment() >= N && (Offset % N) == 0);
6670 // DAG combine handles the stack object case.
6674 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6675 unsigned NumElems, MVT EVT,
6677 SelectionDAG &DAG, MachineFrameInfo *MFI,
6678 const TargetLowering &TLI) {
6680 for (unsigned i = 0; i < NumElems; ++i) {
6681 SDValue Idx = PermMask.getOperand(i);
6682 if (Idx.getOpcode() == ISD::UNDEF) {
6688 SDValue Elt = DAG.getShuffleScalarElt(N, i);
6690 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6694 if (Base->getOpcode() == ISD::UNDEF)
6698 if (Elt.getOpcode() == ISD::UNDEF)
6701 if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6702 EVT.getSizeInBits()/8, i, MFI))
6708 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6709 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6710 /// if the load addresses are consecutive, non-overlapping, and in the right
6712 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6713 const TargetLowering &TLI) {
6714 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6715 MVT VT = N->getValueType(0);
6716 MVT EVT = VT.getVectorElementType();
6717 SDValue PermMask = N->getOperand(2);
6718 unsigned NumElems = PermMask.getNumOperands();
6719 SDNode *Base = NULL;
6720 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6724 LoadSDNode *LD = cast<LoadSDNode>(Base);
6725 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6726 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6727 LD->getSrcValueOffset(), LD->isVolatile());
6728 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6729 LD->getSrcValueOffset(), LD->isVolatile(),
6730 LD->getAlignment());
6733 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6734 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6735 const X86Subtarget *Subtarget,
6736 const TargetLowering &TLI) {
6737 unsigned NumOps = N->getNumOperands();
6739 // Ignore single operand BUILD_VECTOR.
6743 MVT VT = N->getValueType(0);
6744 MVT EVT = VT.getVectorElementType();
6745 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6746 // We are looking for load i64 and zero extend. We want to transform
6747 // it before legalizer has a chance to expand it. Also look for i64
6748 // BUILD_PAIR bit casted to f64.
6750 // This must be an insertion into a zero vector.
6751 SDValue HighElt = N->getOperand(1);
6752 if (!isZeroNode(HighElt))
6755 // Value must be a load.
6756 SDNode *Base = N->getOperand(0).Val;
6757 if (!isa<LoadSDNode>(Base)) {
6758 if (Base->getOpcode() != ISD::BIT_CONVERT)
6760 Base = Base->getOperand(0).Val;
6761 if (!isa<LoadSDNode>(Base))
6765 // Transform it into VZEXT_LOAD addr.
6766 LoadSDNode *LD = cast<LoadSDNode>(Base);
6768 // Load must not be an extload.
6769 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6772 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6775 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6776 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6777 const X86Subtarget *Subtarget) {
6778 SDValue Cond = N->getOperand(0);
6780 // If we have SSE[12] support, try to form min/max nodes.
6781 if (Subtarget->hasSSE2() &&
6782 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6783 if (Cond.getOpcode() == ISD::SETCC) {
6784 // Get the LHS/RHS of the select.
6785 SDValue LHS = N->getOperand(1);
6786 SDValue RHS = N->getOperand(2);
6787 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6789 unsigned Opcode = 0;
6790 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6793 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6796 if (!UnsafeFPMath) break;
6798 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6800 Opcode = X86ISD::FMIN;
6803 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6806 if (!UnsafeFPMath) break;
6808 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6810 Opcode = X86ISD::FMAX;
6813 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6816 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6819 if (!UnsafeFPMath) break;
6821 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6823 Opcode = X86ISD::FMIN;
6826 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6829 if (!UnsafeFPMath) break;
6831 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6833 Opcode = X86ISD::FMAX;
6839 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6847 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6848 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6849 const X86Subtarget *Subtarget) {
6850 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6851 // the FP state in cases where an emms may be missing.
6852 // A preferable solution to the general problem is to figure out the right
6853 // places to insert EMMS. This qualifies as a quick hack.
6854 StoreSDNode *St = cast<StoreSDNode>(N);
6855 if (St->getValue().getValueType().isVector() &&
6856 St->getValue().getValueType().getSizeInBits() == 64 &&
6857 isa<LoadSDNode>(St->getValue()) &&
6858 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6859 St->getChain().hasOneUse() && !St->isVolatile()) {
6860 SDNode* LdVal = St->getValue().Val;
6862 int TokenFactorIndex = -1;
6863 SmallVector<SDValue, 8> Ops;
6864 SDNode* ChainVal = St->getChain().Val;
6865 // Must be a store of a load. We currently handle two cases: the load
6866 // is a direct child, and it's under an intervening TokenFactor. It is
6867 // possible to dig deeper under nested TokenFactors.
6868 if (ChainVal == LdVal)
6869 Ld = cast<LoadSDNode>(St->getChain());
6870 else if (St->getValue().hasOneUse() &&
6871 ChainVal->getOpcode() == ISD::TokenFactor) {
6872 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6873 if (ChainVal->getOperand(i).Val == LdVal) {
6874 TokenFactorIndex = i;
6875 Ld = cast<LoadSDNode>(St->getValue());
6877 Ops.push_back(ChainVal->getOperand(i));
6881 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6882 if (Subtarget->is64Bit()) {
6883 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6884 Ld->getBasePtr(), Ld->getSrcValue(),
6885 Ld->getSrcValueOffset(), Ld->isVolatile(),
6886 Ld->getAlignment());
6887 SDValue NewChain = NewLd.getValue(1);
6888 if (TokenFactorIndex != -1) {
6889 Ops.push_back(NewChain);
6890 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6893 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6894 St->getSrcValue(), St->getSrcValueOffset(),
6895 St->isVolatile(), St->getAlignment());
6898 // Otherwise, lower to two 32-bit copies.
6899 SDValue LoAddr = Ld->getBasePtr();
6900 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6901 DAG.getConstant(4, MVT::i32));
6903 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6904 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6905 Ld->isVolatile(), Ld->getAlignment());
6906 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6907 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6909 MinAlign(Ld->getAlignment(), 4));
6911 SDValue NewChain = LoLd.getValue(1);
6912 if (TokenFactorIndex != -1) {
6913 Ops.push_back(LoLd);
6914 Ops.push_back(HiLd);
6915 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6919 LoAddr = St->getBasePtr();
6920 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6921 DAG.getConstant(4, MVT::i32));
6923 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6924 St->getSrcValue(), St->getSrcValueOffset(),
6925 St->isVolatile(), St->getAlignment());
6926 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6927 St->getSrcValue(), St->getSrcValueOffset()+4,
6929 MinAlign(St->getAlignment(), 4));
6930 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6936 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6937 /// X86ISD::FXOR nodes.
6938 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6939 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6940 // F[X]OR(0.0, x) -> x
6941 // F[X]OR(x, 0.0) -> x
6942 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6943 if (C->getValueAPF().isPosZero())
6944 return N->getOperand(1);
6945 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6946 if (C->getValueAPF().isPosZero())
6947 return N->getOperand(0);
6951 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6952 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6953 // FAND(0.0, x) -> 0.0
6954 // FAND(x, 0.0) -> 0.0
6955 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6956 if (C->getValueAPF().isPosZero())
6957 return N->getOperand(0);
6958 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6959 if (C->getValueAPF().isPosZero())
6960 return N->getOperand(1);
6965 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
6966 DAGCombinerInfo &DCI) const {
6967 SelectionDAG &DAG = DCI.DAG;
6968 switch (N->getOpcode()) {
6970 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6971 case ISD::BUILD_VECTOR:
6972 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6973 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6974 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6976 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6977 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6983 //===----------------------------------------------------------------------===//
6984 // X86 Inline Assembly Support
6985 //===----------------------------------------------------------------------===//
6987 /// getConstraintType - Given a constraint letter, return the type of
6988 /// constraint it is for this target.
6989 X86TargetLowering::ConstraintType
6990 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6991 if (Constraint.size() == 1) {
6992 switch (Constraint[0]) {
7003 return C_RegisterClass;
7008 return TargetLowering::getConstraintType(Constraint);
7011 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7012 /// with another that has more specific requirements based on the type of the
7013 /// corresponding operand.
7014 const char *X86TargetLowering::
7015 LowerXConstraint(MVT ConstraintVT) const {
7016 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7017 // 'f' like normal targets.
7018 if (ConstraintVT.isFloatingPoint()) {
7019 if (Subtarget->hasSSE2())
7021 if (Subtarget->hasSSE1())
7025 return TargetLowering::LowerXConstraint(ConstraintVT);
7028 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7029 /// vector. If it is invalid, don't add anything to Ops.
7030 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7032 std::vector<SDValue>&Ops,
7033 SelectionDAG &DAG) const {
7034 SDValue Result(0, 0);
7036 switch (Constraint) {
7039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7040 if (C->getValue() <= 31) {
7041 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
7047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7048 if (C->getValue() <= 255) {
7049 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
7055 // Literal immediates are always ok.
7056 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7057 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
7061 // If we are in non-pic codegen mode, we allow the address of a global (with
7062 // an optional displacement) to be used with 'i'.
7063 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7066 // Match either (GA) or (GA+C)
7068 Offset = GA->getOffset();
7069 } else if (Op.getOpcode() == ISD::ADD) {
7070 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7071 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7073 Offset = GA->getOffset()+C->getValue();
7075 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7076 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7078 Offset = GA->getOffset()+C->getValue();
7085 // If addressing this global requires a load (e.g. in PIC mode), we can't
7087 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
7091 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7097 // Otherwise, not valid for this mode.
7103 Ops.push_back(Result);
7106 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7109 std::vector<unsigned> X86TargetLowering::
7110 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7112 if (Constraint.size() == 1) {
7113 // FIXME: not handling fp-stack yet!
7114 switch (Constraint[0]) { // GCC X86 Constraint Letters
7115 default: break; // Unknown constraint letter
7116 case 'A': // EAX/EDX
7117 if (VT == MVT::i32 || VT == MVT::i64)
7118 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7120 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7123 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7124 else if (VT == MVT::i16)
7125 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7126 else if (VT == MVT::i8)
7127 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7128 else if (VT == MVT::i64)
7129 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7134 return std::vector<unsigned>();
7137 std::pair<unsigned, const TargetRegisterClass*>
7138 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7140 // First, see if this is a constraint that directly corresponds to an LLVM
7142 if (Constraint.size() == 1) {
7143 // GCC Constraint Letters
7144 switch (Constraint[0]) {
7146 case 'r': // GENERAL_REGS
7147 case 'R': // LEGACY_REGS
7148 case 'l': // INDEX_REGS
7149 if (VT == MVT::i64 && Subtarget->is64Bit())
7150 return std::make_pair(0U, X86::GR64RegisterClass);
7152 return std::make_pair(0U, X86::GR32RegisterClass);
7153 else if (VT == MVT::i16)
7154 return std::make_pair(0U, X86::GR16RegisterClass);
7155 else if (VT == MVT::i8)
7156 return std::make_pair(0U, X86::GR8RegisterClass);
7158 case 'f': // FP Stack registers.
7159 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7160 // value to the correct fpstack register class.
7161 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7162 return std::make_pair(0U, X86::RFP32RegisterClass);
7163 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7164 return std::make_pair(0U, X86::RFP64RegisterClass);
7165 return std::make_pair(0U, X86::RFP80RegisterClass);
7166 case 'y': // MMX_REGS if MMX allowed.
7167 if (!Subtarget->hasMMX()) break;
7168 return std::make_pair(0U, X86::VR64RegisterClass);
7170 case 'Y': // SSE_REGS if SSE2 allowed
7171 if (!Subtarget->hasSSE2()) break;
7173 case 'x': // SSE_REGS if SSE1 allowed
7174 if (!Subtarget->hasSSE1()) break;
7176 switch (VT.getSimpleVT()) {
7178 // Scalar SSE types.
7181 return std::make_pair(0U, X86::FR32RegisterClass);
7184 return std::make_pair(0U, X86::FR64RegisterClass);
7192 return std::make_pair(0U, X86::VR128RegisterClass);
7198 // Use the default implementation in TargetLowering to convert the register
7199 // constraint into a member of a register class.
7200 std::pair<unsigned, const TargetRegisterClass*> Res;
7201 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7203 // Not found as a standard register?
7204 if (Res.second == 0) {
7205 // GCC calls "st(0)" just plain "st".
7206 if (StringsEqualNoCase("{st}", Constraint)) {
7207 Res.first = X86::ST0;
7208 Res.second = X86::RFP80RegisterClass;
7214 // Otherwise, check to see if this is a register class of the wrong value
7215 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7216 // turn into {ax},{dx}.
7217 if (Res.second->hasType(VT))
7218 return Res; // Correct type already, nothing to do.
7220 // All of the single-register GCC register classes map their values onto
7221 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7222 // really want an 8-bit or 32-bit register, map to the appropriate register
7223 // class and return the appropriate register.
7224 if (Res.second != X86::GR16RegisterClass)
7227 if (VT == MVT::i8) {
7228 unsigned DestReg = 0;
7229 switch (Res.first) {
7231 case X86::AX: DestReg = X86::AL; break;
7232 case X86::DX: DestReg = X86::DL; break;
7233 case X86::CX: DestReg = X86::CL; break;
7234 case X86::BX: DestReg = X86::BL; break;
7237 Res.first = DestReg;
7238 Res.second = Res.second = X86::GR8RegisterClass;
7240 } else if (VT == MVT::i32) {
7241 unsigned DestReg = 0;
7242 switch (Res.first) {
7244 case X86::AX: DestReg = X86::EAX; break;
7245 case X86::DX: DestReg = X86::EDX; break;
7246 case X86::CX: DestReg = X86::ECX; break;
7247 case X86::BX: DestReg = X86::EBX; break;
7248 case X86::SI: DestReg = X86::ESI; break;
7249 case X86::DI: DestReg = X86::EDI; break;
7250 case X86::BP: DestReg = X86::EBP; break;
7251 case X86::SP: DestReg = X86::ESP; break;
7254 Res.first = DestReg;
7255 Res.second = Res.second = X86::GR32RegisterClass;
7257 } else if (VT == MVT::i64) {
7258 unsigned DestReg = 0;
7259 switch (Res.first) {
7261 case X86::AX: DestReg = X86::RAX; break;
7262 case X86::DX: DestReg = X86::RDX; break;
7263 case X86::CX: DestReg = X86::RCX; break;
7264 case X86::BX: DestReg = X86::RBX; break;
7265 case X86::SI: DestReg = X86::RSI; break;
7266 case X86::DI: DestReg = X86::RDI; break;
7267 case X86::BP: DestReg = X86::RBP; break;
7268 case X86::SP: DestReg = X86::RSP; break;
7271 Res.first = DestReg;
7272 Res.second = Res.second = X86::GR64RegisterClass;