1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.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 SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
47 X86TargetLowering::X86TargetLowering(TargetMachine &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_LCS , MVT::i8, Custom);
297 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
298 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
299 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
300 setOperationAction(ISD::ATOMIC_LSS , MVT::i32, Expand);
302 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
303 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
304 // FIXME - use subtarget debug flags
305 if (!Subtarget->isTargetDarwin() &&
306 !Subtarget->isTargetELF() &&
307 !Subtarget->isTargetCygMing())
308 setOperationAction(ISD::LABEL, MVT::Other, Expand);
310 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
311 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
312 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
313 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
314 if (Subtarget->is64Bit()) {
316 setExceptionPointerRegister(X86::RAX);
317 setExceptionSelectorRegister(X86::RDX);
319 setExceptionPointerRegister(X86::EAX);
320 setExceptionSelectorRegister(X86::EDX);
322 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
324 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
326 setOperationAction(ISD::TRAP, MVT::Other, Legal);
328 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
329 setOperationAction(ISD::VASTART , MVT::Other, Custom);
330 setOperationAction(ISD::VAARG , MVT::Other, Expand);
331 setOperationAction(ISD::VAEND , MVT::Other, Expand);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
335 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
337 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
338 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
341 if (Subtarget->isTargetCygMing())
342 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
344 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
346 if (X86ScalarSSEf64) {
347 // f32 and f64 use SSE.
348 // Set up the FP register classes.
349 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
350 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
352 // Use ANDPD to simulate FABS.
353 setOperationAction(ISD::FABS , MVT::f64, Custom);
354 setOperationAction(ISD::FABS , MVT::f32, Custom);
356 // Use XORP to simulate FNEG.
357 setOperationAction(ISD::FNEG , MVT::f64, Custom);
358 setOperationAction(ISD::FNEG , MVT::f32, Custom);
360 // Use ANDPD and ORPD to simulate FCOPYSIGN.
361 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
362 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
364 // We don't support sin/cos/fmod
365 setOperationAction(ISD::FSIN , MVT::f64, Expand);
366 setOperationAction(ISD::FCOS , MVT::f64, Expand);
367 setOperationAction(ISD::FSIN , MVT::f32, Expand);
368 setOperationAction(ISD::FCOS , MVT::f32, Expand);
370 // Expand FP immediates into loads from the stack, except for the special
372 addLegalFPImmediate(APFloat(+0.0)); // xorpd
373 addLegalFPImmediate(APFloat(+0.0f)); // xorps
375 // Floating truncations from f80 and extensions to f80 go through memory.
376 // If optimizing, we lie about this though and handle it in
377 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
379 setConvertAction(MVT::f32, MVT::f80, Expand);
380 setConvertAction(MVT::f64, MVT::f80, Expand);
381 setConvertAction(MVT::f80, MVT::f32, Expand);
382 setConvertAction(MVT::f80, MVT::f64, Expand);
384 } else if (X86ScalarSSEf32) {
385 // Use SSE for f32, x87 for f64.
386 // Set up the FP register classes.
387 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
388 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
390 // Use ANDPS to simulate FABS.
391 setOperationAction(ISD::FABS , MVT::f32, Custom);
393 // Use XORP to simulate FNEG.
394 setOperationAction(ISD::FNEG , MVT::f32, Custom);
396 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
398 // Use ANDPS and ORPS to simulate FCOPYSIGN.
399 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
400 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
402 // We don't support sin/cos/fmod
403 setOperationAction(ISD::FSIN , MVT::f32, Expand);
404 setOperationAction(ISD::FCOS , MVT::f32, Expand);
406 // Special cases we handle for FP constants.
407 addLegalFPImmediate(APFloat(+0.0f)); // xorps
408 addLegalFPImmediate(APFloat(+0.0)); // FLD0
409 addLegalFPImmediate(APFloat(+1.0)); // FLD1
410 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
411 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
413 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
414 // this though and handle it in InstructionSelectPreprocess so that
415 // dagcombine2 can hack on these.
417 setConvertAction(MVT::f32, MVT::f64, Expand);
418 setConvertAction(MVT::f32, MVT::f80, Expand);
419 setConvertAction(MVT::f80, MVT::f32, Expand);
420 setConvertAction(MVT::f64, MVT::f32, Expand);
421 // And x87->x87 truncations also.
422 setConvertAction(MVT::f80, MVT::f64, Expand);
426 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
427 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
430 // f32 and f64 in x87.
431 // Set up the FP register classes.
432 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
433 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
435 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
436 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
440 // Floating truncations go through memory. If optimizing, we lie about
441 // this though and handle it in InstructionSelectPreprocess so that
442 // dagcombine2 can hack on these.
444 setConvertAction(MVT::f80, MVT::f32, Expand);
445 setConvertAction(MVT::f64, MVT::f32, Expand);
446 setConvertAction(MVT::f80, MVT::f64, Expand);
450 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
451 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
453 addLegalFPImmediate(APFloat(+0.0)); // FLD0
454 addLegalFPImmediate(APFloat(+1.0)); // FLD1
455 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
456 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
457 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
458 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
459 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
460 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
463 // Long double always uses X87.
464 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
465 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
466 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
468 APFloat TmpFlt(+0.0);
469 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
470 addLegalFPImmediate(TmpFlt); // FLD0
472 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
473 APFloat TmpFlt2(+1.0);
474 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
475 addLegalFPImmediate(TmpFlt2); // FLD1
476 TmpFlt2.changeSign();
477 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
481 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
482 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
485 // Always use a library call for pow.
486 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
487 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
488 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
490 // First set operation action for all vector types to expand. Then we
491 // will selectively turn on ones that can be effectively codegen'd.
492 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
493 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
494 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
529 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
530 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
533 if (Subtarget->hasMMX()) {
534 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
535 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
536 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
537 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
539 // FIXME: add MMX packed arithmetics
541 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
542 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
543 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
544 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
546 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
547 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
548 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
549 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
551 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
552 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
554 setOperationAction(ISD::AND, MVT::v8i8, Promote);
555 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
556 setOperationAction(ISD::AND, MVT::v4i16, Promote);
557 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
558 setOperationAction(ISD::AND, MVT::v2i32, Promote);
559 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
560 setOperationAction(ISD::AND, MVT::v1i64, Legal);
562 setOperationAction(ISD::OR, MVT::v8i8, Promote);
563 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
564 setOperationAction(ISD::OR, MVT::v4i16, Promote);
565 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
566 setOperationAction(ISD::OR, MVT::v2i32, Promote);
567 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
568 setOperationAction(ISD::OR, MVT::v1i64, Legal);
570 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
571 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
572 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
573 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
574 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
575 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
576 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
578 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
579 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
580 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
581 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
582 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
583 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
584 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
586 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
587 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
588 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
589 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
591 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
593 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
597 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
598 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
601 if (Subtarget->hasSSE1()) {
602 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
604 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
605 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
606 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
607 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
608 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
609 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
610 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
611 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
612 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
613 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
614 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
617 if (Subtarget->hasSSE2()) {
618 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
619 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
620 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
621 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
622 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
624 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
625 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
626 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
627 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
628 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
629 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
630 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
631 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
632 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
633 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
634 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
635 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
636 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
637 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
638 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
640 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
641 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
642 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
643 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
644 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
646 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
647 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
648 // Do not attempt to custom lower non-power-of-2 vectors
649 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
651 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
653 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
655 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
656 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
657 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
658 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
660 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
661 if (Subtarget->is64Bit()) {
662 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
666 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
667 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
668 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
669 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
670 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
671 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
672 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
673 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
674 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
675 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
676 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
677 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
680 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
682 // Custom lower v2i64 and v2f64 selects.
683 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
684 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
685 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
686 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
689 if (Subtarget->hasSSE41()) {
690 // FIXME: Do we need to handle scalar-to-vector here?
691 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
693 // i8 and i16 vectors are custom , because the source register and source
694 // source memory operand types are not the same width. f32 vectors are
695 // custom since the immediate controlling the insert encodes additional
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
698 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
699 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
700 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
707 if (Subtarget->is64Bit()) {
708 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
709 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
713 // We want to custom lower some of our intrinsics.
714 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
716 // We have target-specific dag combine patterns for the following nodes:
717 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
718 setTargetDAGCombine(ISD::SELECT);
719 setTargetDAGCombine(ISD::STORE);
721 computeRegisterProperties();
723 // FIXME: These should be based on subtarget info. Plus, the values should
724 // be smaller when we are in optimizing for size mode.
725 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
726 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
727 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
728 allowUnalignedMemoryAccesses = true; // x86 supports it!
729 setPrefLoopAlignment(16);
734 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
739 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
740 /// the desired ByVal argument alignment.
741 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
744 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
745 if (VTy->getBitWidth() == 128)
747 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
748 unsigned EltAlign = 0;
749 getMaxByValAlign(ATy->getElementType(), EltAlign);
750 if (EltAlign > MaxAlign)
752 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
753 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
754 unsigned EltAlign = 0;
755 getMaxByValAlign(STy->getElementType(i), EltAlign);
756 if (EltAlign > MaxAlign)
765 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
766 /// function arguments in the caller parameter area. For X86, aggregates
767 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
768 /// are at 4-byte boundaries.
769 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
770 if (Subtarget->is64Bit())
771 return getTargetData()->getABITypeAlignment(Ty);
773 if (Subtarget->hasSSE1())
774 getMaxByValAlign(Ty, Align);
778 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
780 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
781 SelectionDAG &DAG) const {
782 if (usesGlobalOffsetTable())
783 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
784 if (!Subtarget->isPICStyleRIPRel())
785 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
789 //===----------------------------------------------------------------------===//
790 // Return Value Calling Convention Implementation
791 //===----------------------------------------------------------------------===//
793 #include "X86GenCallingConv.inc"
795 /// LowerRET - Lower an ISD::RET node.
796 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
797 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
799 SmallVector<CCValAssign, 16> RVLocs;
800 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
801 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
802 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
803 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
805 // If this is the first return lowered for this function, add the regs to the
806 // liveout set for the function.
807 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
808 for (unsigned i = 0; i != RVLocs.size(); ++i)
809 if (RVLocs[i].isRegLoc())
810 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
812 SDOperand Chain = Op.getOperand(0);
814 // Handle tail call return.
815 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
816 if (Chain.getOpcode() == X86ISD::TAILCALL) {
817 SDOperand TailCall = Chain;
818 SDOperand TargetAddress = TailCall.getOperand(1);
819 SDOperand StackAdjustment = TailCall.getOperand(2);
820 assert(((TargetAddress.getOpcode() == ISD::Register &&
821 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
822 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
823 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
824 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
825 "Expecting an global address, external symbol, or register");
826 assert(StackAdjustment.getOpcode() == ISD::Constant &&
827 "Expecting a const value");
829 SmallVector<SDOperand,8> Operands;
830 Operands.push_back(Chain.getOperand(0));
831 Operands.push_back(TargetAddress);
832 Operands.push_back(StackAdjustment);
833 // Copy registers used by the call. Last operand is a flag so it is not
835 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
836 Operands.push_back(Chain.getOperand(i));
838 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
845 SmallVector<SDOperand, 6> RetOps;
846 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
847 // Operand #1 = Bytes To Pop
848 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
850 // Copy the result values into the output registers.
851 for (unsigned i = 0; i != RVLocs.size(); ++i) {
852 CCValAssign &VA = RVLocs[i];
853 assert(VA.isRegLoc() && "Can only return in registers!");
854 SDOperand ValToCopy = Op.getOperand(i*2+1);
856 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
857 // the RET instruction and handled by the FP Stackifier.
858 if (RVLocs[i].getLocReg() == X86::ST0 ||
859 RVLocs[i].getLocReg() == X86::ST1) {
860 // If this is a copy from an xmm register to ST(0), use an FPExtend to
861 // change the value to the FP stack register class.
862 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
863 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
864 RetOps.push_back(ValToCopy);
865 // Don't emit a copytoreg.
869 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
870 Flag = Chain.getValue(1);
873 // The x86-64 ABI for returning structs by value requires that we copy
874 // the sret argument into %rax for the return. We saved the argument into
875 // a virtual register in the entry block, so now we copy the value out
877 if (Subtarget->is64Bit() &&
878 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
879 MachineFunction &MF = DAG.getMachineFunction();
880 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
881 unsigned Reg = FuncInfo->getSRetReturnReg();
883 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
884 FuncInfo->setSRetReturnReg(Reg);
886 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
888 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
889 Flag = Chain.getValue(1);
892 RetOps[0] = Chain; // Update chain.
894 // Add the flag if we have it.
896 RetOps.push_back(Flag);
898 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
902 /// LowerCallResult - Lower the result values of an ISD::CALL into the
903 /// appropriate copies out of appropriate physical registers. This assumes that
904 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
905 /// being lowered. The returns a SDNode with the same number of values as the
907 SDNode *X86TargetLowering::
908 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
909 unsigned CallingConv, SelectionDAG &DAG) {
911 // Assign locations to each value returned by this call.
912 SmallVector<CCValAssign, 16> RVLocs;
913 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
914 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
915 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
917 SmallVector<SDOperand, 8> ResultVals;
919 // Copy all of the result registers out of their specified physreg.
920 for (unsigned i = 0; i != RVLocs.size(); ++i) {
921 MVT::ValueType CopyVT = RVLocs[i].getValVT();
923 // If this is a call to a function that returns an fp value on the floating
924 // point stack, but where we prefer to use the value in xmm registers, copy
925 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
926 if (RVLocs[i].getLocReg() == X86::ST0 &&
927 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
931 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
932 CopyVT, InFlag).getValue(1);
933 SDOperand Val = Chain.getValue(0);
934 InFlag = Chain.getValue(2);
936 if (CopyVT != RVLocs[i].getValVT()) {
937 // Round the F80 the right size, which also moves to the appropriate xmm
939 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
940 // This truncation won't change the value.
941 DAG.getIntPtrConstant(1));
944 ResultVals.push_back(Val);
947 // Merge everything together with a MERGE_VALUES node.
948 ResultVals.push_back(Chain);
949 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
950 &ResultVals[0], ResultVals.size()).Val;
954 //===----------------------------------------------------------------------===//
955 // C & StdCall & Fast Calling Convention implementation
956 //===----------------------------------------------------------------------===//
957 // StdCall calling convention seems to be standard for many Windows' API
958 // routines and around. It differs from C calling convention just a little:
959 // callee should clean up the stack, not caller. Symbols should be also
960 // decorated in some fancy way :) It doesn't support any vector arguments.
961 // For info on fast calling convention see Fast Calling Convention (tail call)
962 // implementation LowerX86_32FastCCCallTo.
964 /// AddLiveIn - This helper function adds the specified physical register to the
965 /// MachineFunction as a live in value. It also creates a corresponding virtual
967 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
968 const TargetRegisterClass *RC) {
969 assert(RC->contains(PReg) && "Not the correct regclass!");
970 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
971 MF.getRegInfo().addLiveIn(PReg, VReg);
975 /// CallIsStructReturn - Determines whether a CALL node uses struct return
977 static bool CallIsStructReturn(SDOperand Op) {
978 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
982 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
985 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
986 /// return semantics.
987 static bool ArgsAreStructReturn(SDOperand Op) {
988 unsigned NumArgs = Op.Val->getNumValues() - 1;
992 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
995 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
996 /// the callee to pop its own arguments. Callee pop is necessary to support tail
998 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
999 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1003 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1006 case CallingConv::X86_StdCall:
1007 return !Subtarget->is64Bit();
1008 case CallingConv::X86_FastCall:
1009 return !Subtarget->is64Bit();
1010 case CallingConv::Fast:
1011 return PerformTailCallOpt;
1015 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1016 /// FORMAL_ARGUMENTS node.
1017 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1018 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1020 if (Subtarget->is64Bit()) {
1021 if (Subtarget->isTargetWin64())
1022 return CC_X86_Win64_C;
1024 if (CC == CallingConv::Fast && PerformTailCallOpt)
1025 return CC_X86_64_TailCall;
1031 if (CC == CallingConv::X86_FastCall)
1032 return CC_X86_32_FastCall;
1033 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1034 return CC_X86_32_TailCall;
1039 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1040 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1042 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1043 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1044 if (CC == CallingConv::X86_FastCall)
1046 else if (CC == CallingConv::X86_StdCall)
1052 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1053 /// in a register before calling.
1054 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1055 return !IsTailCall && !Is64Bit &&
1056 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1057 Subtarget->isPICStyleGOT();
1060 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1061 /// address to be loaded in a register.
1063 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1064 return !Is64Bit && IsTailCall &&
1065 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1066 Subtarget->isPICStyleGOT();
1069 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1070 /// by "Src" to address "Dst" with size and alignment information specified by
1071 /// the specific parameter attribute. The copy will be passed as a byval
1072 /// function parameter.
1074 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1075 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1076 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1077 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1078 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1081 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1082 const CCValAssign &VA,
1083 MachineFrameInfo *MFI,
1085 SDOperand Root, unsigned i) {
1086 // Create the nodes corresponding to a load from this parameter slot.
1087 ISD::ArgFlagsTy Flags =
1088 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1089 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1090 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1092 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1093 // changed with more analysis.
1094 // In case of tail call optimization mark all arguments mutable. Since they
1095 // could be overwritten by lowering of arguments in case of a tail call.
1096 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1097 VA.getLocMemOffset(), isImmutable);
1098 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1099 if (Flags.isByVal())
1101 return DAG.getLoad(VA.getValVT(), Root, FIN,
1102 PseudoSourceValue::getFixedStack(), FI);
1106 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1107 MachineFunction &MF = DAG.getMachineFunction();
1108 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1110 const Function* Fn = MF.getFunction();
1111 if (Fn->hasExternalLinkage() &&
1112 Subtarget->isTargetCygMing() &&
1113 Fn->getName() == "main")
1114 FuncInfo->setForceFramePointer(true);
1116 // Decorate the function name.
1117 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1119 MachineFrameInfo *MFI = MF.getFrameInfo();
1120 SDOperand Root = Op.getOperand(0);
1121 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1122 unsigned CC = MF.getFunction()->getCallingConv();
1123 bool Is64Bit = Subtarget->is64Bit();
1124 bool IsWin64 = Subtarget->isTargetWin64();
1126 assert(!(isVarArg && CC == CallingConv::Fast) &&
1127 "Var args not supported with calling convention fastcc");
1129 // Assign locations to all of the incoming arguments.
1130 SmallVector<CCValAssign, 16> ArgLocs;
1131 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1132 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1134 SmallVector<SDOperand, 8> ArgValues;
1135 unsigned LastVal = ~0U;
1136 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1137 CCValAssign &VA = ArgLocs[i];
1138 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1140 assert(VA.getValNo() != LastVal &&
1141 "Don't support value assigned to multiple locs yet");
1142 LastVal = VA.getValNo();
1144 if (VA.isRegLoc()) {
1145 MVT::ValueType RegVT = VA.getLocVT();
1146 TargetRegisterClass *RC;
1147 if (RegVT == MVT::i32)
1148 RC = X86::GR32RegisterClass;
1149 else if (Is64Bit && RegVT == MVT::i64)
1150 RC = X86::GR64RegisterClass;
1151 else if (RegVT == MVT::f32)
1152 RC = X86::FR32RegisterClass;
1153 else if (RegVT == MVT::f64)
1154 RC = X86::FR64RegisterClass;
1155 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1156 RC = X86::VR128RegisterClass;
1157 else if (MVT::isVector(RegVT)) {
1158 assert(MVT::getSizeInBits(RegVT) == 64);
1160 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1162 // Darwin calling convention passes MMX values in either GPRs or
1163 // XMMs in x86-64. Other targets pass them in memory.
1164 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1165 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1168 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1173 assert(0 && "Unknown argument type!");
1176 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1177 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1179 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1180 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1182 if (VA.getLocInfo() == CCValAssign::SExt)
1183 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1184 DAG.getValueType(VA.getValVT()));
1185 else if (VA.getLocInfo() == CCValAssign::ZExt)
1186 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1187 DAG.getValueType(VA.getValVT()));
1189 if (VA.getLocInfo() != CCValAssign::Full)
1190 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1192 // Handle MMX values passed in GPRs.
1193 if (Is64Bit && RegVT != VA.getLocVT()) {
1194 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1195 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1196 else if (RC == X86::VR128RegisterClass) {
1197 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1198 DAG.getConstant(0, MVT::i64));
1199 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1203 ArgValues.push_back(ArgValue);
1205 assert(VA.isMemLoc());
1206 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1210 // The x86-64 ABI for returning structs by value requires that we copy
1211 // the sret argument into %rax for the return. Save the argument into
1212 // a virtual register so that we can access it from the return points.
1213 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1214 MachineFunction &MF = DAG.getMachineFunction();
1215 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1216 unsigned Reg = FuncInfo->getSRetReturnReg();
1218 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1219 FuncInfo->setSRetReturnReg(Reg);
1221 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1222 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1225 unsigned StackSize = CCInfo.getNextStackOffset();
1226 // align stack specially for tail calls
1227 if (CC == CallingConv::Fast)
1228 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1230 // If the function takes variable number of arguments, make a frame index for
1231 // the start of the first vararg value... for expansion of llvm.va_start.
1233 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1234 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1237 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1239 // FIXME: We should really autogenerate these arrays
1240 static const unsigned GPR64ArgRegsWin64[] = {
1241 X86::RCX, X86::RDX, X86::R8, X86::R9
1243 static const unsigned XMMArgRegsWin64[] = {
1244 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1246 static const unsigned GPR64ArgRegs64Bit[] = {
1247 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1249 static const unsigned XMMArgRegs64Bit[] = {
1250 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1251 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1253 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1256 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1257 GPR64ArgRegs = GPR64ArgRegsWin64;
1258 XMMArgRegs = XMMArgRegsWin64;
1260 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1261 GPR64ArgRegs = GPR64ArgRegs64Bit;
1262 XMMArgRegs = XMMArgRegs64Bit;
1264 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1266 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1269 // For X86-64, if there are vararg parameters that are passed via
1270 // registers, then we must store them to their spots on the stack so they
1271 // may be loaded by deferencing the result of va_next.
1272 VarArgsGPOffset = NumIntRegs * 8;
1273 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1274 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1275 TotalNumXMMRegs * 16, 16);
1277 // Store the integer parameter registers.
1278 SmallVector<SDOperand, 8> MemOps;
1279 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1280 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1281 DAG.getIntPtrConstant(VarArgsGPOffset));
1282 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1283 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1284 X86::GR64RegisterClass);
1285 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1287 DAG.getStore(Val.getValue(1), Val, FIN,
1288 PseudoSourceValue::getFixedStack(),
1290 MemOps.push_back(Store);
1291 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1292 DAG.getIntPtrConstant(8));
1295 // Now store the XMM (fp + vector) parameter registers.
1296 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1297 DAG.getIntPtrConstant(VarArgsFPOffset));
1298 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1299 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1300 X86::VR128RegisterClass);
1301 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1303 DAG.getStore(Val.getValue(1), Val, FIN,
1304 PseudoSourceValue::getFixedStack(),
1306 MemOps.push_back(Store);
1307 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1308 DAG.getIntPtrConstant(16));
1310 if (!MemOps.empty())
1311 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1312 &MemOps[0], MemOps.size());
1316 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1317 // arguments and the arguments after the retaddr has been pushed are
1319 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1320 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1321 (StackSize & 7) == 0)
1324 ArgValues.push_back(Root);
1326 // Some CCs need callee pop.
1327 if (IsCalleePop(Op)) {
1328 BytesToPopOnReturn = StackSize; // Callee pops everything.
1329 BytesCallerReserves = 0;
1331 BytesToPopOnReturn = 0; // Callee pops nothing.
1332 // If this is an sret function, the return should pop the hidden pointer.
1333 if (!Is64Bit && ArgsAreStructReturn(Op))
1334 BytesToPopOnReturn = 4;
1335 BytesCallerReserves = StackSize;
1339 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1340 if (CC == CallingConv::X86_FastCall)
1341 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1344 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1346 // Return the new list of results.
1347 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1348 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1352 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1353 const SDOperand &StackPtr,
1354 const CCValAssign &VA,
1357 unsigned LocMemOffset = VA.getLocMemOffset();
1358 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1359 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1360 ISD::ArgFlagsTy Flags =
1361 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1362 if (Flags.isByVal()) {
1363 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1365 return DAG.getStore(Chain, Arg, PtrOff,
1366 PseudoSourceValue::getStack(), LocMemOffset);
1369 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1370 /// optimization is performed and it is required.
1372 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1373 SDOperand &OutRetAddr,
1378 if (!IsTailCall || FPDiff==0) return Chain;
1380 // Adjust the Return address stack slot.
1381 MVT::ValueType VT = getPointerTy();
1382 OutRetAddr = getReturnAddressFrameIndex(DAG);
1383 // Load the "old" Return address.
1384 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1385 return SDOperand(OutRetAddr.Val, 1);
1388 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1389 /// optimization is performed and it is required (FPDiff!=0).
1391 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1392 SDOperand Chain, SDOperand RetAddrFrIdx,
1393 bool Is64Bit, int FPDiff) {
1394 // Store the return address to the appropriate stack slot.
1395 if (!FPDiff) return Chain;
1396 // Calculate the new stack slot for the return address.
1397 int SlotSize = Is64Bit ? 8 : 4;
1398 int NewReturnAddrFI =
1399 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1400 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1401 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1402 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1403 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1407 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1408 MachineFunction &MF = DAG.getMachineFunction();
1409 SDOperand Chain = Op.getOperand(0);
1410 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1411 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1412 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1413 && CC == CallingConv::Fast && PerformTailCallOpt;
1414 SDOperand Callee = Op.getOperand(4);
1415 bool Is64Bit = Subtarget->is64Bit();
1416 bool IsStructRet = CallIsStructReturn(Op);
1418 assert(!(isVarArg && CC == CallingConv::Fast) &&
1419 "Var args not supported with calling convention fastcc");
1421 // Analyze operands of the call, assigning locations to each operand.
1422 SmallVector<CCValAssign, 16> ArgLocs;
1423 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1424 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1426 // Get a count of how many bytes are to be pushed on the stack.
1427 unsigned NumBytes = CCInfo.getNextStackOffset();
1428 if (CC == CallingConv::Fast)
1429 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1431 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1432 // arguments and the arguments after the retaddr has been pushed are aligned.
1433 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1434 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1435 (NumBytes & 7) == 0)
1440 // Lower arguments at fp - stackoffset + fpdiff.
1441 unsigned NumBytesCallerPushed =
1442 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1443 FPDiff = NumBytesCallerPushed - NumBytes;
1445 // Set the delta of movement of the returnaddr stackslot.
1446 // But only set if delta is greater than previous delta.
1447 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1448 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1451 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1453 SDOperand RetAddrFrIdx;
1454 // Load return adress for tail calls.
1455 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1458 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1459 SmallVector<SDOperand, 8> MemOpChains;
1462 // Walk the register/memloc assignments, inserting copies/loads. In the case
1463 // of tail call optimization arguments are handle later.
1464 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1465 CCValAssign &VA = ArgLocs[i];
1466 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1467 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1468 getArgFlags().isByVal();
1470 // Promote the value if needed.
1471 switch (VA.getLocInfo()) {
1472 default: assert(0 && "Unknown loc info!");
1473 case CCValAssign::Full: break;
1474 case CCValAssign::SExt:
1475 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1477 case CCValAssign::ZExt:
1478 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1480 case CCValAssign::AExt:
1481 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1485 if (VA.isRegLoc()) {
1487 MVT::ValueType RegVT = VA.getLocVT();
1488 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1489 switch (VA.getLocReg()) {
1492 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1494 // Special case: passing MMX values in GPR registers.
1495 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1498 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1499 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1500 // Special case: passing MMX values in XMM registers.
1501 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1502 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1503 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1504 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1505 getMOVLMask(2, DAG));
1510 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1512 if (!IsTailCall || (IsTailCall && isByVal)) {
1513 assert(VA.isMemLoc());
1514 if (StackPtr.Val == 0)
1515 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1517 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1523 if (!MemOpChains.empty())
1524 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1525 &MemOpChains[0], MemOpChains.size());
1527 // Build a sequence of copy-to-reg nodes chained together with token chain
1528 // and flag operands which copy the outgoing args into registers.
1530 // Tail call byval lowering might overwrite argument registers so in case of
1531 // tail call optimization the copies to registers are lowered later.
1533 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1534 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1536 InFlag = Chain.getValue(1);
1539 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1541 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1542 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1543 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1545 InFlag = Chain.getValue(1);
1547 // If we are tail calling and generating PIC/GOT style code load the address
1548 // of the callee into ecx. The value in ecx is used as target of the tail
1549 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1550 // calls on PIC/GOT architectures. Normally we would just put the address of
1551 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1552 // restored (since ebx is callee saved) before jumping to the target@PLT.
1553 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1554 // Note: The actual moving to ecx is done further down.
1555 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1556 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1557 !G->getGlobal()->hasProtectedVisibility())
1558 Callee = LowerGlobalAddress(Callee, DAG);
1559 else if (isa<ExternalSymbolSDNode>(Callee))
1560 Callee = LowerExternalSymbol(Callee,DAG);
1563 if (Is64Bit && isVarArg) {
1564 // From AMD64 ABI document:
1565 // For calls that may call functions that use varargs or stdargs
1566 // (prototype-less calls or calls to functions containing ellipsis (...) in
1567 // the declaration) %al is used as hidden argument to specify the number
1568 // of SSE registers used. The contents of %al do not need to match exactly
1569 // the number of registers, but must be an ubound on the number of SSE
1570 // registers used and is in the range 0 - 8 inclusive.
1572 // FIXME: Verify this on Win64
1573 // Count the number of XMM registers allocated.
1574 static const unsigned XMMArgRegs[] = {
1575 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1576 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1578 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1580 Chain = DAG.getCopyToReg(Chain, X86::AL,
1581 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1582 InFlag = Chain.getValue(1);
1586 // For tail calls lower the arguments to the 'real' stack slot.
1588 SmallVector<SDOperand, 8> MemOpChains2;
1591 // Do not flag preceeding copytoreg stuff together with the following stuff.
1592 InFlag = SDOperand();
1593 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1594 CCValAssign &VA = ArgLocs[i];
1595 if (!VA.isRegLoc()) {
1596 assert(VA.isMemLoc());
1597 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1598 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1599 ISD::ArgFlagsTy Flags =
1600 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1601 // Create frame index.
1602 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1603 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1604 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1605 FIN = DAG.getFrameIndex(FI, getPointerTy());
1607 if (Flags.isByVal()) {
1608 // Copy relative to framepointer.
1609 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1610 if (StackPtr.Val == 0)
1611 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1612 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1614 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1617 // Store relative to framepointer.
1618 MemOpChains2.push_back(
1619 DAG.getStore(Chain, Arg, FIN,
1620 PseudoSourceValue::getFixedStack(), FI));
1625 if (!MemOpChains2.empty())
1626 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1627 &MemOpChains2[0], MemOpChains2.size());
1629 // Copy arguments to their registers.
1630 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1631 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1633 InFlag = Chain.getValue(1);
1635 InFlag =SDOperand();
1637 // Store the return address to the appropriate stack slot.
1638 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1642 // If the callee is a GlobalAddress node (quite common, every direct call is)
1643 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1644 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1645 // We should use extra load for direct calls to dllimported functions in
1647 if ((IsTailCall || !Is64Bit ||
1648 getTargetMachine().getCodeModel() != CodeModel::Large)
1649 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1650 getTargetMachine(), true))
1651 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1652 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1653 if (IsTailCall || !Is64Bit ||
1654 getTargetMachine().getCodeModel() != CodeModel::Large)
1655 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1656 } else if (IsTailCall) {
1657 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1659 Chain = DAG.getCopyToReg(Chain,
1660 DAG.getRegister(Opc, getPointerTy()),
1662 Callee = DAG.getRegister(Opc, getPointerTy());
1663 // Add register as live out.
1664 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1667 // Returns a chain & a flag for retval copy to use.
1668 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1669 SmallVector<SDOperand, 8> Ops;
1672 Ops.push_back(Chain);
1673 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1674 Ops.push_back(DAG.getIntPtrConstant(0));
1676 Ops.push_back(InFlag);
1677 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1678 InFlag = Chain.getValue(1);
1680 // Returns a chain & a flag for retval copy to use.
1681 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1685 Ops.push_back(Chain);
1686 Ops.push_back(Callee);
1689 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1691 // Add argument registers to the end of the list so that they are known live
1693 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1694 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1695 RegsToPass[i].second.getValueType()));
1697 // Add an implicit use GOT pointer in EBX.
1698 if (!IsTailCall && !Is64Bit &&
1699 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1700 Subtarget->isPICStyleGOT())
1701 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1703 // Add an implicit use of AL for x86 vararg functions.
1704 if (Is64Bit && isVarArg)
1705 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1708 Ops.push_back(InFlag);
1711 assert(InFlag.Val &&
1712 "Flag must be set. Depend on flag being set in LowerRET");
1713 Chain = DAG.getNode(X86ISD::TAILCALL,
1714 Op.Val->getVTList(), &Ops[0], Ops.size());
1716 return SDOperand(Chain.Val, Op.ResNo);
1719 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1720 InFlag = Chain.getValue(1);
1722 // Create the CALLSEQ_END node.
1723 unsigned NumBytesForCalleeToPush;
1724 if (IsCalleePop(Op))
1725 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1726 else if (!Is64Bit && IsStructRet)
1727 // If this is is a call to a struct-return function, the callee
1728 // pops the hidden struct pointer, so we have to push it back.
1729 // This is common for Darwin/X86, Linux & Mingw32 targets.
1730 NumBytesForCalleeToPush = 4;
1732 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1734 // Returns a flag for retval copy to use.
1735 Chain = DAG.getCALLSEQ_END(Chain,
1736 DAG.getIntPtrConstant(NumBytes),
1737 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1739 InFlag = Chain.getValue(1);
1741 // Handle result values, copying them out of physregs into vregs that we
1743 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1747 //===----------------------------------------------------------------------===//
1748 // Fast Calling Convention (tail call) implementation
1749 //===----------------------------------------------------------------------===//
1751 // Like std call, callee cleans arguments, convention except that ECX is
1752 // reserved for storing the tail called function address. Only 2 registers are
1753 // free for argument passing (inreg). Tail call optimization is performed
1755 // * tailcallopt is enabled
1756 // * caller/callee are fastcc
1757 // On X86_64 architecture with GOT-style position independent code only local
1758 // (within module) calls are supported at the moment.
1759 // To keep the stack aligned according to platform abi the function
1760 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1761 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1762 // If a tail called function callee has more arguments than the caller the
1763 // caller needs to make sure that there is room to move the RETADDR to. This is
1764 // achieved by reserving an area the size of the argument delta right after the
1765 // original REtADDR, but before the saved framepointer or the spilled registers
1766 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1778 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1779 /// for a 16 byte align requirement.
1780 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1781 SelectionDAG& DAG) {
1782 if (PerformTailCallOpt) {
1783 MachineFunction &MF = DAG.getMachineFunction();
1784 const TargetMachine &TM = MF.getTarget();
1785 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1786 unsigned StackAlignment = TFI.getStackAlignment();
1787 uint64_t AlignMask = StackAlignment - 1;
1788 int64_t Offset = StackSize;
1789 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1790 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1791 // Number smaller than 12 so just add the difference.
1792 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1794 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1795 Offset = ((~AlignMask) & Offset) + StackAlignment +
1796 (StackAlignment-SlotSize);
1803 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1804 /// following the call is a return. A function is eligible if caller/callee
1805 /// calling conventions match, currently only fastcc supports tail calls, and
1806 /// the function CALL is immediatly followed by a RET.
1807 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1809 SelectionDAG& DAG) const {
1810 if (!PerformTailCallOpt)
1813 if (CheckTailCallReturnConstraints(Call, Ret)) {
1814 MachineFunction &MF = DAG.getMachineFunction();
1815 unsigned CallerCC = MF.getFunction()->getCallingConv();
1816 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1817 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1818 SDOperand Callee = Call.getOperand(4);
1819 // On x86/32Bit PIC/GOT tail calls are supported.
1820 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1821 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1824 // Can only do local tail calls (in same module, hidden or protected) on
1825 // x86_64 PIC/GOT at the moment.
1826 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1827 return G->getGlobal()->hasHiddenVisibility()
1828 || G->getGlobal()->hasProtectedVisibility();
1835 //===----------------------------------------------------------------------===//
1836 // Other Lowering Hooks
1837 //===----------------------------------------------------------------------===//
1840 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1841 MachineFunction &MF = DAG.getMachineFunction();
1842 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843 int ReturnAddrIndex = FuncInfo->getRAIndex();
1845 if (ReturnAddrIndex == 0) {
1846 // Set up a frame object for the return address.
1847 if (Subtarget->is64Bit())
1848 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1850 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1852 FuncInfo->setRAIndex(ReturnAddrIndex);
1855 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1860 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1861 /// specific condition code. It returns a false if it cannot do a direct
1862 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1864 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1865 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1866 SelectionDAG &DAG) {
1867 X86CC = X86::COND_INVALID;
1869 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1870 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1871 // X > -1 -> X == 0, jump !sign.
1872 RHS = DAG.getConstant(0, RHS.getValueType());
1873 X86CC = X86::COND_NS;
1875 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1876 // X < 0 -> X == 0, jump on sign.
1877 X86CC = X86::COND_S;
1879 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1881 RHS = DAG.getConstant(0, RHS.getValueType());
1882 X86CC = X86::COND_LE;
1887 switch (SetCCOpcode) {
1889 case ISD::SETEQ: X86CC = X86::COND_E; break;
1890 case ISD::SETGT: X86CC = X86::COND_G; break;
1891 case ISD::SETGE: X86CC = X86::COND_GE; break;
1892 case ISD::SETLT: X86CC = X86::COND_L; break;
1893 case ISD::SETLE: X86CC = X86::COND_LE; break;
1894 case ISD::SETNE: X86CC = X86::COND_NE; break;
1895 case ISD::SETULT: X86CC = X86::COND_B; break;
1896 case ISD::SETUGT: X86CC = X86::COND_A; break;
1897 case ISD::SETULE: X86CC = X86::COND_BE; break;
1898 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1901 // On a floating point condition, the flags are set as follows:
1903 // 0 | 0 | 0 | X > Y
1904 // 0 | 0 | 1 | X < Y
1905 // 1 | 0 | 0 | X == Y
1906 // 1 | 1 | 1 | unordered
1908 switch (SetCCOpcode) {
1911 case ISD::SETEQ: X86CC = X86::COND_E; break;
1912 case ISD::SETOLT: Flip = true; // Fallthrough
1914 case ISD::SETGT: X86CC = X86::COND_A; break;
1915 case ISD::SETOLE: Flip = true; // Fallthrough
1917 case ISD::SETGE: X86CC = X86::COND_AE; break;
1918 case ISD::SETUGT: Flip = true; // Fallthrough
1920 case ISD::SETLT: X86CC = X86::COND_B; break;
1921 case ISD::SETUGE: Flip = true; // Fallthrough
1923 case ISD::SETLE: X86CC = X86::COND_BE; break;
1925 case ISD::SETNE: X86CC = X86::COND_NE; break;
1926 case ISD::SETUO: X86CC = X86::COND_P; break;
1927 case ISD::SETO: X86CC = X86::COND_NP; break;
1930 std::swap(LHS, RHS);
1933 return X86CC != X86::COND_INVALID;
1936 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1937 /// code. Current x86 isa includes the following FP cmov instructions:
1938 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1939 static bool hasFPCMov(unsigned X86CC) {
1955 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1956 /// true if Op is undef or if its value falls within the specified range (L, H].
1957 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1958 if (Op.getOpcode() == ISD::UNDEF)
1961 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1962 return (Val >= Low && Val < Hi);
1965 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1966 /// true if Op is undef or if its value equal to the specified value.
1967 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1968 if (Op.getOpcode() == ISD::UNDEF)
1970 return cast<ConstantSDNode>(Op)->getValue() == Val;
1973 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1974 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1975 bool X86::isPSHUFDMask(SDNode *N) {
1976 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1978 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1981 // Check if the value doesn't reference the second vector.
1982 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1983 SDOperand Arg = N->getOperand(i);
1984 if (Arg.getOpcode() == ISD::UNDEF) continue;
1985 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1986 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1993 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1994 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1995 bool X86::isPSHUFHWMask(SDNode *N) {
1996 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1998 if (N->getNumOperands() != 8)
2001 // Lower quadword copied in order.
2002 for (unsigned i = 0; i != 4; ++i) {
2003 SDOperand Arg = N->getOperand(i);
2004 if (Arg.getOpcode() == ISD::UNDEF) continue;
2005 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2006 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2010 // Upper quadword shuffled.
2011 for (unsigned i = 4; i != 8; ++i) {
2012 SDOperand Arg = N->getOperand(i);
2013 if (Arg.getOpcode() == ISD::UNDEF) continue;
2014 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2015 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2016 if (Val < 4 || Val > 7)
2023 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2024 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2025 bool X86::isPSHUFLWMask(SDNode *N) {
2026 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2028 if (N->getNumOperands() != 8)
2031 // Upper quadword copied in order.
2032 for (unsigned i = 4; i != 8; ++i)
2033 if (!isUndefOrEqual(N->getOperand(i), i))
2036 // Lower quadword shuffled.
2037 for (unsigned i = 0; i != 4; ++i)
2038 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2044 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2045 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2046 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2047 if (NumElems != 2 && NumElems != 4) return false;
2049 unsigned Half = NumElems / 2;
2050 for (unsigned i = 0; i < Half; ++i)
2051 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2053 for (unsigned i = Half; i < NumElems; ++i)
2054 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2060 bool X86::isSHUFPMask(SDNode *N) {
2061 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2062 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2065 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2066 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2067 /// half elements to come from vector 1 (which would equal the dest.) and
2068 /// the upper half to come from vector 2.
2069 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2070 if (NumOps != 2 && NumOps != 4) return false;
2072 unsigned Half = NumOps / 2;
2073 for (unsigned i = 0; i < Half; ++i)
2074 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2076 for (unsigned i = Half; i < NumOps; ++i)
2077 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2082 static bool isCommutedSHUFP(SDNode *N) {
2083 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2084 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2087 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2088 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2089 bool X86::isMOVHLPSMask(SDNode *N) {
2090 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2092 if (N->getNumOperands() != 4)
2095 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2096 return isUndefOrEqual(N->getOperand(0), 6) &&
2097 isUndefOrEqual(N->getOperand(1), 7) &&
2098 isUndefOrEqual(N->getOperand(2), 2) &&
2099 isUndefOrEqual(N->getOperand(3), 3);
2102 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2103 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2105 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2106 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2108 if (N->getNumOperands() != 4)
2111 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2112 return isUndefOrEqual(N->getOperand(0), 2) &&
2113 isUndefOrEqual(N->getOperand(1), 3) &&
2114 isUndefOrEqual(N->getOperand(2), 2) &&
2115 isUndefOrEqual(N->getOperand(3), 3);
2118 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2119 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2120 bool X86::isMOVLPMask(SDNode *N) {
2121 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2123 unsigned NumElems = N->getNumOperands();
2124 if (NumElems != 2 && NumElems != 4)
2127 for (unsigned i = 0; i < NumElems/2; ++i)
2128 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2131 for (unsigned i = NumElems/2; i < NumElems; ++i)
2132 if (!isUndefOrEqual(N->getOperand(i), i))
2138 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2139 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2141 bool X86::isMOVHPMask(SDNode *N) {
2142 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2144 unsigned NumElems = N->getNumOperands();
2145 if (NumElems != 2 && NumElems != 4)
2148 for (unsigned i = 0; i < NumElems/2; ++i)
2149 if (!isUndefOrEqual(N->getOperand(i), i))
2152 for (unsigned i = 0; i < NumElems/2; ++i) {
2153 SDOperand Arg = N->getOperand(i + NumElems/2);
2154 if (!isUndefOrEqual(Arg, i + NumElems))
2161 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2162 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2163 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2164 bool V2IsSplat = false) {
2165 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2168 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2169 SDOperand BitI = Elts[i];
2170 SDOperand BitI1 = Elts[i+1];
2171 if (!isUndefOrEqual(BitI, j))
2174 if (isUndefOrEqual(BitI1, NumElts))
2177 if (!isUndefOrEqual(BitI1, j + NumElts))
2185 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2186 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2187 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2190 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2191 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2192 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2193 bool V2IsSplat = false) {
2194 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2197 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2198 SDOperand BitI = Elts[i];
2199 SDOperand BitI1 = Elts[i+1];
2200 if (!isUndefOrEqual(BitI, j + NumElts/2))
2203 if (isUndefOrEqual(BitI1, NumElts))
2206 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2214 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2215 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2216 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2219 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2220 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2222 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2223 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2225 unsigned NumElems = N->getNumOperands();
2226 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2229 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2230 SDOperand BitI = N->getOperand(i);
2231 SDOperand BitI1 = N->getOperand(i+1);
2233 if (!isUndefOrEqual(BitI, j))
2235 if (!isUndefOrEqual(BitI1, j))
2242 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2243 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2245 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2246 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2248 unsigned NumElems = N->getNumOperands();
2249 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2252 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2253 SDOperand BitI = N->getOperand(i);
2254 SDOperand BitI1 = N->getOperand(i + 1);
2256 if (!isUndefOrEqual(BitI, j))
2258 if (!isUndefOrEqual(BitI1, j))
2265 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2266 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2267 /// MOVSD, and MOVD, i.e. setting the lowest element.
2268 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2269 if (NumElts != 2 && NumElts != 4)
2272 if (!isUndefOrEqual(Elts[0], NumElts))
2275 for (unsigned i = 1; i < NumElts; ++i) {
2276 if (!isUndefOrEqual(Elts[i], i))
2283 bool X86::isMOVLMask(SDNode *N) {
2284 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2288 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2289 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2290 /// element of vector 2 and the other elements to come from vector 1 in order.
2291 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2292 bool V2IsSplat = false,
2293 bool V2IsUndef = false) {
2294 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2297 if (!isUndefOrEqual(Ops[0], 0))
2300 for (unsigned i = 1; i < NumOps; ++i) {
2301 SDOperand Arg = Ops[i];
2302 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2303 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2304 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2311 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2312 bool V2IsUndef = false) {
2313 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2314 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2315 V2IsSplat, V2IsUndef);
2318 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2319 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2320 bool X86::isMOVSHDUPMask(SDNode *N) {
2321 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2323 if (N->getNumOperands() != 4)
2326 // Expect 1, 1, 3, 3
2327 for (unsigned i = 0; i < 2; ++i) {
2328 SDOperand Arg = N->getOperand(i);
2329 if (Arg.getOpcode() == ISD::UNDEF) continue;
2330 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2331 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2332 if (Val != 1) return false;
2336 for (unsigned i = 2; i < 4; ++i) {
2337 SDOperand Arg = N->getOperand(i);
2338 if (Arg.getOpcode() == ISD::UNDEF) continue;
2339 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2340 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2341 if (Val != 3) return false;
2345 // Don't use movshdup if it can be done with a shufps.
2349 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2350 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2351 bool X86::isMOVSLDUPMask(SDNode *N) {
2352 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2354 if (N->getNumOperands() != 4)
2357 // Expect 0, 0, 2, 2
2358 for (unsigned i = 0; i < 2; ++i) {
2359 SDOperand Arg = N->getOperand(i);
2360 if (Arg.getOpcode() == ISD::UNDEF) continue;
2361 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2362 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2363 if (Val != 0) return false;
2367 for (unsigned i = 2; i < 4; ++i) {
2368 SDOperand Arg = N->getOperand(i);
2369 if (Arg.getOpcode() == ISD::UNDEF) continue;
2370 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2371 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2372 if (Val != 2) return false;
2376 // Don't use movshdup if it can be done with a shufps.
2380 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2381 /// specifies a identity operation on the LHS or RHS.
2382 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2383 unsigned NumElems = N->getNumOperands();
2384 for (unsigned i = 0; i < NumElems; ++i)
2385 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2390 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2391 /// a splat of a single element.
2392 static bool isSplatMask(SDNode *N) {
2393 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2395 // This is a splat operation if each element of the permute is the same, and
2396 // if the value doesn't reference the second vector.
2397 unsigned NumElems = N->getNumOperands();
2398 SDOperand ElementBase;
2400 for (; i != NumElems; ++i) {
2401 SDOperand Elt = N->getOperand(i);
2402 if (isa<ConstantSDNode>(Elt)) {
2408 if (!ElementBase.Val)
2411 for (; i != NumElems; ++i) {
2412 SDOperand Arg = N->getOperand(i);
2413 if (Arg.getOpcode() == ISD::UNDEF) continue;
2414 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2415 if (Arg != ElementBase) return false;
2418 // Make sure it is a splat of the first vector operand.
2419 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2422 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2423 /// a splat of a single element and it's a 2 or 4 element mask.
2424 bool X86::isSplatMask(SDNode *N) {
2425 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2427 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2428 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2430 return ::isSplatMask(N);
2433 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2434 /// specifies a splat of zero element.
2435 bool X86::isSplatLoMask(SDNode *N) {
2436 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2438 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2439 if (!isUndefOrEqual(N->getOperand(i), 0))
2444 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2445 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2447 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2448 unsigned NumOperands = N->getNumOperands();
2449 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2451 for (unsigned i = 0; i < NumOperands; ++i) {
2453 SDOperand Arg = N->getOperand(NumOperands-i-1);
2454 if (Arg.getOpcode() != ISD::UNDEF)
2455 Val = cast<ConstantSDNode>(Arg)->getValue();
2456 if (Val >= NumOperands) Val -= NumOperands;
2458 if (i != NumOperands - 1)
2465 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2466 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2468 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2470 // 8 nodes, but we only care about the last 4.
2471 for (unsigned i = 7; i >= 4; --i) {
2473 SDOperand Arg = N->getOperand(i);
2474 if (Arg.getOpcode() != ISD::UNDEF)
2475 Val = cast<ConstantSDNode>(Arg)->getValue();
2484 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2485 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2487 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2489 // 8 nodes, but we only care about the first 4.
2490 for (int i = 3; i >= 0; --i) {
2492 SDOperand Arg = N->getOperand(i);
2493 if (Arg.getOpcode() != ISD::UNDEF)
2494 Val = cast<ConstantSDNode>(Arg)->getValue();
2503 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2504 /// specifies a 8 element shuffle that can be broken into a pair of
2505 /// PSHUFHW and PSHUFLW.
2506 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2507 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2509 if (N->getNumOperands() != 8)
2512 // Lower quadword shuffled.
2513 for (unsigned i = 0; i != 4; ++i) {
2514 SDOperand Arg = N->getOperand(i);
2515 if (Arg.getOpcode() == ISD::UNDEF) continue;
2516 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2517 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2522 // Upper quadword shuffled.
2523 for (unsigned i = 4; i != 8; ++i) {
2524 SDOperand Arg = N->getOperand(i);
2525 if (Arg.getOpcode() == ISD::UNDEF) continue;
2526 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2527 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2528 if (Val < 4 || Val > 7)
2535 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2536 /// values in ther permute mask.
2537 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2538 SDOperand &V2, SDOperand &Mask,
2539 SelectionDAG &DAG) {
2540 MVT::ValueType VT = Op.getValueType();
2541 MVT::ValueType MaskVT = Mask.getValueType();
2542 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2543 unsigned NumElems = Mask.getNumOperands();
2544 SmallVector<SDOperand, 8> MaskVec;
2546 for (unsigned i = 0; i != NumElems; ++i) {
2547 SDOperand Arg = Mask.getOperand(i);
2548 if (Arg.getOpcode() == ISD::UNDEF) {
2549 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2552 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2553 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2555 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2557 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2561 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2562 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2565 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2566 /// the two vector operands have swapped position.
2568 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2569 MVT::ValueType MaskVT = Mask.getValueType();
2570 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2571 unsigned NumElems = Mask.getNumOperands();
2572 SmallVector<SDOperand, 8> MaskVec;
2573 for (unsigned i = 0; i != NumElems; ++i) {
2574 SDOperand Arg = Mask.getOperand(i);
2575 if (Arg.getOpcode() == ISD::UNDEF) {
2576 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2579 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2580 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2582 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2584 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2586 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2590 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2591 /// match movhlps. The lower half elements should come from upper half of
2592 /// V1 (and in order), and the upper half elements should come from the upper
2593 /// half of V2 (and in order).
2594 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2595 unsigned NumElems = Mask->getNumOperands();
2598 for (unsigned i = 0, e = 2; i != e; ++i)
2599 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2601 for (unsigned i = 2; i != 4; ++i)
2602 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2607 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2608 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2610 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2611 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2612 N = N->getOperand(0).Val;
2613 if (ISD::isNON_EXTLoad(N)) {
2615 *LD = cast<LoadSDNode>(N);
2622 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2623 /// match movlp{s|d}. The lower half elements should come from lower half of
2624 /// V1 (and in order), and the upper half elements should come from the upper
2625 /// half of V2 (and in order). And since V1 will become the source of the
2626 /// MOVLP, it must be either a vector load or a scalar load to vector.
2627 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2628 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2630 // Is V2 is a vector load, don't do this transformation. We will try to use
2631 // load folding shufps op.
2632 if (ISD::isNON_EXTLoad(V2))
2635 unsigned NumElems = Mask->getNumOperands();
2636 if (NumElems != 2 && NumElems != 4)
2638 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2639 if (!isUndefOrEqual(Mask->getOperand(i), i))
2641 for (unsigned i = NumElems/2; i != NumElems; ++i)
2642 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2647 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2649 static bool isSplatVector(SDNode *N) {
2650 if (N->getOpcode() != ISD::BUILD_VECTOR)
2653 SDOperand SplatValue = N->getOperand(0);
2654 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2655 if (N->getOperand(i) != SplatValue)
2660 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2662 static bool isUndefShuffle(SDNode *N) {
2663 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2666 SDOperand V1 = N->getOperand(0);
2667 SDOperand V2 = N->getOperand(1);
2668 SDOperand Mask = N->getOperand(2);
2669 unsigned NumElems = Mask.getNumOperands();
2670 for (unsigned i = 0; i != NumElems; ++i) {
2671 SDOperand Arg = Mask.getOperand(i);
2672 if (Arg.getOpcode() != ISD::UNDEF) {
2673 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2674 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2676 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2683 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2685 static inline bool isZeroNode(SDOperand Elt) {
2686 return ((isa<ConstantSDNode>(Elt) &&
2687 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2688 (isa<ConstantFPSDNode>(Elt) &&
2689 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2692 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2693 /// to an zero vector.
2694 static bool isZeroShuffle(SDNode *N) {
2695 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2698 SDOperand V1 = N->getOperand(0);
2699 SDOperand V2 = N->getOperand(1);
2700 SDOperand Mask = N->getOperand(2);
2701 unsigned NumElems = Mask.getNumOperands();
2702 for (unsigned i = 0; i != NumElems; ++i) {
2703 SDOperand Arg = Mask.getOperand(i);
2704 if (Arg.getOpcode() == ISD::UNDEF)
2707 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2708 if (Idx < NumElems) {
2709 unsigned Opc = V1.Val->getOpcode();
2710 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2712 if (Opc != ISD::BUILD_VECTOR ||
2713 !isZeroNode(V1.Val->getOperand(Idx)))
2715 } else if (Idx >= NumElems) {
2716 unsigned Opc = V2.Val->getOpcode();
2717 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2719 if (Opc != ISD::BUILD_VECTOR ||
2720 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2727 /// getZeroVector - Returns a vector of specified type with all zero elements.
2729 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2730 assert(MVT::isVector(VT) && "Expected a vector type");
2732 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2733 // type. This ensures they get CSE'd.
2734 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2736 if (MVT::getSizeInBits(VT) == 64) // MMX
2737 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2739 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2740 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2743 /// getOnesVector - Returns a vector of specified type with all bits set.
2745 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2746 assert(MVT::isVector(VT) && "Expected a vector type");
2748 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2749 // type. This ensures they get CSE'd.
2750 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2752 if (MVT::getSizeInBits(VT) == 64) // MMX
2753 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2755 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2756 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2760 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2761 /// that point to V2 points to its first element.
2762 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2763 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2765 bool Changed = false;
2766 SmallVector<SDOperand, 8> MaskVec;
2767 unsigned NumElems = Mask.getNumOperands();
2768 for (unsigned i = 0; i != NumElems; ++i) {
2769 SDOperand Arg = Mask.getOperand(i);
2770 if (Arg.getOpcode() != ISD::UNDEF) {
2771 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2772 if (Val > NumElems) {
2773 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2777 MaskVec.push_back(Arg);
2781 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2782 &MaskVec[0], MaskVec.size());
2786 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2787 /// operation of specified width.
2788 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2789 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2790 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2792 SmallVector<SDOperand, 8> MaskVec;
2793 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2794 for (unsigned i = 1; i != NumElems; ++i)
2795 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2796 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2799 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2800 /// of specified width.
2801 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2802 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2803 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2804 SmallVector<SDOperand, 8> MaskVec;
2805 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2806 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2807 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2809 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2812 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2813 /// of specified width.
2814 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2815 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2816 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2817 unsigned Half = NumElems/2;
2818 SmallVector<SDOperand, 8> MaskVec;
2819 for (unsigned i = 0; i != Half; ++i) {
2820 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2821 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2823 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2826 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2827 /// element #0 of a vector with the specified index, leaving the rest of the
2828 /// elements in place.
2829 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2830 SelectionDAG &DAG) {
2831 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2832 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2833 SmallVector<SDOperand, 8> MaskVec;
2834 // Element #0 of the result gets the elt we are replacing.
2835 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2836 for (unsigned i = 1; i != NumElems; ++i)
2837 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2838 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2841 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2842 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2843 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2844 MVT::ValueType VT = Op.getValueType();
2847 SDOperand V1 = Op.getOperand(0);
2848 SDOperand Mask = Op.getOperand(2);
2849 unsigned NumElems = Mask.getNumOperands();
2850 // Special handling of v4f32 -> v4i32.
2851 if (VT != MVT::v4f32) {
2852 Mask = getUnpacklMask(NumElems, DAG);
2853 while (NumElems > 4) {
2854 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2857 Mask = getZeroVector(MVT::v4i32, DAG);
2860 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2861 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2862 DAG.getNode(ISD::UNDEF, PVT), Mask);
2863 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2866 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2867 /// vector of zero or undef vector. This produces a shuffle where the low
2868 /// element of V2 is swizzled into the zero/undef vector, landing at element
2869 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2870 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2871 bool isZero, SelectionDAG &DAG) {
2872 MVT::ValueType VT = V2.getValueType();
2873 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2874 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2875 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2876 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2877 SmallVector<SDOperand, 16> MaskVec;
2878 for (unsigned i = 0; i != NumElems; ++i)
2879 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2880 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2882 MaskVec.push_back(DAG.getConstant(i, EVT));
2883 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2884 &MaskVec[0], MaskVec.size());
2885 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2888 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2890 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2891 unsigned NumNonZero, unsigned NumZero,
2892 SelectionDAG &DAG, TargetLowering &TLI) {
2898 for (unsigned i = 0; i < 16; ++i) {
2899 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2900 if (ThisIsNonZero && First) {
2902 V = getZeroVector(MVT::v8i16, DAG);
2904 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2909 SDOperand ThisElt(0, 0), LastElt(0, 0);
2910 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2911 if (LastIsNonZero) {
2912 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2914 if (ThisIsNonZero) {
2915 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2916 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2917 ThisElt, DAG.getConstant(8, MVT::i8));
2919 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2924 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2925 DAG.getIntPtrConstant(i/2));
2929 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2932 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2934 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2935 unsigned NumNonZero, unsigned NumZero,
2936 SelectionDAG &DAG, TargetLowering &TLI) {
2942 for (unsigned i = 0; i < 8; ++i) {
2943 bool isNonZero = (NonZeros & (1 << i)) != 0;
2947 V = getZeroVector(MVT::v8i16, DAG);
2949 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2952 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2953 DAG.getIntPtrConstant(i));
2961 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2962 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2963 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2964 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2965 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2966 // eliminated on x86-32 hosts.
2967 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2970 if (ISD::isBuildVectorAllOnes(Op.Val))
2971 return getOnesVector(Op.getValueType(), DAG);
2972 return getZeroVector(Op.getValueType(), DAG);
2975 MVT::ValueType VT = Op.getValueType();
2976 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2977 unsigned EVTBits = MVT::getSizeInBits(EVT);
2979 unsigned NumElems = Op.getNumOperands();
2980 unsigned NumZero = 0;
2981 unsigned NumNonZero = 0;
2982 unsigned NonZeros = 0;
2983 bool IsAllConstants = true;
2984 SmallSet<SDOperand, 8> Values;
2985 for (unsigned i = 0; i < NumElems; ++i) {
2986 SDOperand Elt = Op.getOperand(i);
2987 if (Elt.getOpcode() == ISD::UNDEF)
2990 if (Elt.getOpcode() != ISD::Constant &&
2991 Elt.getOpcode() != ISD::ConstantFP)
2992 IsAllConstants = false;
2993 if (isZeroNode(Elt))
2996 NonZeros |= (1 << i);
3001 if (NumNonZero == 0) {
3002 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3003 return DAG.getNode(ISD::UNDEF, VT);
3006 // Special case for single non-zero, non-undef, element.
3007 if (NumNonZero == 1 && NumElems <= 4) {
3008 unsigned Idx = CountTrailingZeros_32(NonZeros);
3009 SDOperand Item = Op.getOperand(Idx);
3011 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3012 // the value are obviously zero, truncate the value to i32 and do the
3013 // insertion that way. Only do this if the value is non-constant or if the
3014 // value is a constant being inserted into element 0. It is cheaper to do
3015 // a constant pool load than it is to do a movd + shuffle.
3016 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3017 (!IsAllConstants || Idx == 0)) {
3018 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3019 // Handle MMX and SSE both.
3020 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3021 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3023 // Truncate the value (which may itself be a constant) to i32, and
3024 // convert it to a vector with movd (S2V+shuffle to zero extend).
3025 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3026 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3027 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3029 // Now we have our 32-bit value zero extended in the low element of
3030 // a vector. If Idx != 0, swizzle it into place.
3033 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3034 getSwapEltZeroMask(VecElts, Idx, DAG)
3036 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3038 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3042 // If we have a constant or non-constant insertion into the low element of
3043 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3044 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3045 // depending on what the source datatype is. Because we can only get here
3046 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3048 // Don't do this for i64 values on x86-32.
3049 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3050 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3051 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3052 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3055 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3058 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3059 // is a non-constant being inserted into an element other than the low one,
3060 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3061 // movd/movss) to move this into the low element, then shuffle it into
3063 if (EVTBits == 32) {
3064 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3066 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3067 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3068 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3069 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3070 SmallVector<SDOperand, 8> MaskVec;
3071 for (unsigned i = 0; i < NumElems; i++)
3072 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3073 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3074 &MaskVec[0], MaskVec.size());
3075 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3076 DAG.getNode(ISD::UNDEF, VT), Mask);
3080 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3081 if (Values.size() == 1)
3084 // A vector full of immediates; various special cases are already
3085 // handled, so this is best done with a single constant-pool load.
3089 // Let legalizer expand 2-wide build_vectors.
3090 if (EVTBits == 64) {
3091 if (NumNonZero == 1) {
3092 // One half is zero or undef.
3093 unsigned Idx = CountTrailingZeros_32(NonZeros);
3094 SDOperand V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3095 Op.getOperand(Idx));
3096 return getShuffleVectorZeroOrUndef(V2, Idx, true, DAG);
3101 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3102 if (EVTBits == 8 && NumElems == 16) {
3103 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3105 if (V.Val) return V;
3108 if (EVTBits == 16 && NumElems == 8) {
3109 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3111 if (V.Val) return V;
3114 // If element VT is == 32 bits, turn it into a number of shuffles.
3115 SmallVector<SDOperand, 8> V;
3117 if (NumElems == 4 && NumZero > 0) {
3118 for (unsigned i = 0; i < 4; ++i) {
3119 bool isZero = !(NonZeros & (1 << i));
3121 V[i] = getZeroVector(VT, DAG);
3123 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3126 for (unsigned i = 0; i < 2; ++i) {
3127 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3130 V[i] = V[i*2]; // Must be a zero vector.
3133 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3134 getMOVLMask(NumElems, DAG));
3137 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3138 getMOVLMask(NumElems, DAG));
3141 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3142 getUnpacklMask(NumElems, DAG));
3147 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3148 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3149 SmallVector<SDOperand, 8> MaskVec;
3150 bool Reverse = (NonZeros & 0x3) == 2;
3151 for (unsigned i = 0; i < 2; ++i)
3153 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3155 MaskVec.push_back(DAG.getConstant(i, EVT));
3156 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3157 for (unsigned i = 0; i < 2; ++i)
3159 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3161 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3162 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3163 &MaskVec[0], MaskVec.size());
3164 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3167 if (Values.size() > 2) {
3168 // Expand into a number of unpckl*.
3170 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3171 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3172 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3173 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3174 for (unsigned i = 0; i < NumElems; ++i)
3175 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3177 while (NumElems != 0) {
3178 for (unsigned i = 0; i < NumElems; ++i)
3179 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3190 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3191 SDOperand PermMask, SelectionDAG &DAG,
3192 TargetLowering &TLI) {
3194 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3195 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3196 MVT::ValueType PtrVT = TLI.getPointerTy();
3197 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3198 PermMask.Val->op_end());
3200 // First record which half of which vector the low elements come from.
3201 SmallVector<unsigned, 4> LowQuad(4);
3202 for (unsigned i = 0; i < 4; ++i) {
3203 SDOperand Elt = MaskElts[i];
3204 if (Elt.getOpcode() == ISD::UNDEF)
3206 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3207 int QuadIdx = EltIdx / 4;
3210 int BestLowQuad = -1;
3211 unsigned MaxQuad = 1;
3212 for (unsigned i = 0; i < 4; ++i) {
3213 if (LowQuad[i] > MaxQuad) {
3215 MaxQuad = LowQuad[i];
3219 // Record which half of which vector the high elements come from.
3220 SmallVector<unsigned, 4> HighQuad(4);
3221 for (unsigned i = 4; i < 8; ++i) {
3222 SDOperand Elt = MaskElts[i];
3223 if (Elt.getOpcode() == ISD::UNDEF)
3225 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3226 int QuadIdx = EltIdx / 4;
3227 ++HighQuad[QuadIdx];
3229 int BestHighQuad = -1;
3231 for (unsigned i = 0; i < 4; ++i) {
3232 if (HighQuad[i] > MaxQuad) {
3234 MaxQuad = HighQuad[i];
3238 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3239 if (BestLowQuad != -1 || BestHighQuad != -1) {
3240 // First sort the 4 chunks in order using shufpd.
3241 SmallVector<SDOperand, 8> MaskVec;
3242 if (BestLowQuad != -1)
3243 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3245 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3246 if (BestHighQuad != -1)
3247 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3249 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3250 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3251 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3252 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3253 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3254 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3256 // Now sort high and low parts separately.
3257 BitVector InOrder(8);
3258 if (BestLowQuad != -1) {
3259 // Sort lower half in order using PSHUFLW.
3261 bool AnyOutOrder = false;
3262 for (unsigned i = 0; i != 4; ++i) {
3263 SDOperand Elt = MaskElts[i];
3264 if (Elt.getOpcode() == ISD::UNDEF) {
3265 MaskVec.push_back(Elt);
3268 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3271 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3272 // If this element is in the right place after this shuffle, then
3274 if ((int)(EltIdx / 4) == BestLowQuad)
3279 for (unsigned i = 4; i != 8; ++i)
3280 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3281 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3282 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3286 if (BestHighQuad != -1) {
3287 // Sort high half in order using PSHUFHW if possible.
3289 for (unsigned i = 0; i != 4; ++i)
3290 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3291 bool AnyOutOrder = false;
3292 for (unsigned i = 4; i != 8; ++i) {
3293 SDOperand Elt = MaskElts[i];
3294 if (Elt.getOpcode() == ISD::UNDEF) {
3295 MaskVec.push_back(Elt);
3298 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3301 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3302 // If this element is in the right place after this shuffle, then
3304 if ((int)(EltIdx / 4) == BestHighQuad)
3309 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3310 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3314 // The other elements are put in the right place using pextrw and pinsrw.
3315 for (unsigned i = 0; i != 8; ++i) {
3318 SDOperand Elt = MaskElts[i];
3319 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3322 SDOperand ExtOp = (EltIdx < 8)
3323 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3324 DAG.getConstant(EltIdx, PtrVT))
3325 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3326 DAG.getConstant(EltIdx - 8, PtrVT));
3327 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3328 DAG.getConstant(i, PtrVT));
3333 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3334 ///as few as possible.
3335 // First, let's find out how many elements are already in the right order.
3336 unsigned V1InOrder = 0;
3337 unsigned V1FromV1 = 0;
3338 unsigned V2InOrder = 0;
3339 unsigned V2FromV2 = 0;
3340 SmallVector<SDOperand, 8> V1Elts;
3341 SmallVector<SDOperand, 8> V2Elts;
3342 for (unsigned i = 0; i < 8; ++i) {
3343 SDOperand Elt = MaskElts[i];
3344 if (Elt.getOpcode() == ISD::UNDEF) {
3345 V1Elts.push_back(Elt);
3346 V2Elts.push_back(Elt);
3351 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3353 V1Elts.push_back(Elt);
3354 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3356 } else if (EltIdx == i+8) {
3357 V1Elts.push_back(Elt);
3358 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3360 } else if (EltIdx < 8) {
3361 V1Elts.push_back(Elt);
3364 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3369 if (V2InOrder > V1InOrder) {
3370 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3372 std::swap(V1Elts, V2Elts);
3373 std::swap(V1FromV1, V2FromV2);
3376 if ((V1FromV1 + V1InOrder) != 8) {
3377 // Some elements are from V2.
3379 // If there are elements that are from V1 but out of place,
3380 // then first sort them in place
3381 SmallVector<SDOperand, 8> MaskVec;
3382 for (unsigned i = 0; i < 8; ++i) {
3383 SDOperand Elt = V1Elts[i];
3384 if (Elt.getOpcode() == ISD::UNDEF) {
3385 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3388 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3390 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3392 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3394 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3395 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3399 for (unsigned i = 0; i < 8; ++i) {
3400 SDOperand Elt = V1Elts[i];
3401 if (Elt.getOpcode() == ISD::UNDEF)
3403 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3406 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3407 DAG.getConstant(EltIdx - 8, PtrVT));
3408 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3409 DAG.getConstant(i, PtrVT));
3413 // All elements are from V1.
3415 for (unsigned i = 0; i < 8; ++i) {
3416 SDOperand Elt = V1Elts[i];
3417 if (Elt.getOpcode() == ISD::UNDEF)
3419 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3420 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3421 DAG.getConstant(EltIdx, PtrVT));
3422 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3423 DAG.getConstant(i, PtrVT));
3429 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3430 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3431 /// done when every pair / quad of shuffle mask elements point to elements in
3432 /// the right sequence. e.g.
3433 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3435 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3437 SDOperand PermMask, SelectionDAG &DAG,
3438 TargetLowering &TLI) {
3439 unsigned NumElems = PermMask.getNumOperands();
3440 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3441 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3442 MVT::ValueType NewVT = MaskVT;
3444 case MVT::v4f32: NewVT = MVT::v2f64; break;
3445 case MVT::v4i32: NewVT = MVT::v2i64; break;
3446 case MVT::v8i16: NewVT = MVT::v4i32; break;
3447 case MVT::v16i8: NewVT = MVT::v4i32; break;
3448 default: assert(false && "Unexpected!");
3451 if (NewWidth == 2) {
3452 if (MVT::isInteger(VT))
3457 unsigned Scale = NumElems / NewWidth;
3458 SmallVector<SDOperand, 8> MaskVec;
3459 for (unsigned i = 0; i < NumElems; i += Scale) {
3460 unsigned StartIdx = ~0U;
3461 for (unsigned j = 0; j < Scale; ++j) {
3462 SDOperand Elt = PermMask.getOperand(i+j);
3463 if (Elt.getOpcode() == ISD::UNDEF)
3465 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3466 if (StartIdx == ~0U)
3467 StartIdx = EltIdx - (EltIdx % Scale);
3468 if (EltIdx != StartIdx + j)
3471 if (StartIdx == ~0U)
3472 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3474 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3477 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3478 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3479 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3480 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3481 &MaskVec[0], MaskVec.size()));
3484 /// getZextVMoveL - Return a zero-extending vector move low node.
3486 static SDOperand getZextVMoveL(MVT::ValueType VT, MVT::ValueType OpVT,
3487 SDOperand SrcOp, SelectionDAG &DAG,
3488 const X86Subtarget *Subtarget) {
3489 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3490 LoadSDNode *LD = NULL;
3491 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3492 LD = dyn_cast<LoadSDNode>(SrcOp);
3494 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3496 MVT::ValueType EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3497 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3498 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3499 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3500 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3502 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3503 return DAG.getNode(ISD::BIT_CONVERT, VT,
3504 DAG.getNode(X86ISD::ZEXT_VMOVL, OpVT,
3505 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3506 SrcOp.getOperand(0).getOperand(0))));
3511 return DAG.getNode(ISD::BIT_CONVERT, VT,
3512 DAG.getNode(X86ISD::ZEXT_VMOVL, OpVT,
3513 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3517 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3518 SDOperand V1 = Op.getOperand(0);
3519 SDOperand V2 = Op.getOperand(1);
3520 SDOperand PermMask = Op.getOperand(2);
3521 MVT::ValueType VT = Op.getValueType();
3522 unsigned NumElems = PermMask.getNumOperands();
3523 bool isMMX = MVT::getSizeInBits(VT) == 64;
3524 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3525 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3526 bool V1IsSplat = false;
3527 bool V2IsSplat = false;
3529 if (isUndefShuffle(Op.Val))
3530 return DAG.getNode(ISD::UNDEF, VT);
3532 if (isZeroShuffle(Op.Val))
3533 return getZeroVector(VT, DAG);
3535 if (isIdentityMask(PermMask.Val))
3537 else if (isIdentityMask(PermMask.Val, true))
3540 if (isSplatMask(PermMask.Val)) {
3541 if (isMMX || NumElems < 4) return Op;
3542 // Promote it to a v4{if}32 splat.
3543 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3546 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3548 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3549 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3551 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3552 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3553 // FIXME: Figure out a cleaner way to do this.
3554 // Try to make use of movq to zero out the top part.
3555 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3556 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3559 SDOperand NewV1 = NewOp.getOperand(0);
3560 SDOperand NewV2 = NewOp.getOperand(1);
3561 SDOperand NewMask = NewOp.getOperand(2);
3562 if (isCommutedMOVL(NewMask.Val, true, false)) {
3563 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3564 return getZextVMoveL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3567 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3568 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3570 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3571 return getZextVMoveL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3576 if (X86::isMOVLMask(PermMask.Val)) {
3579 if (ISD::isBuildVectorAllZeros(V1.Val))
3580 return getZextVMoveL(VT, VT, V2, DAG, Subtarget);
3584 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3585 X86::isMOVSLDUPMask(PermMask.Val) ||
3586 X86::isMOVHLPSMask(PermMask.Val) ||
3587 X86::isMOVHPMask(PermMask.Val) ||
3588 X86::isMOVLPMask(PermMask.Val))
3591 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3592 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3593 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3595 bool Commuted = false;
3596 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3597 // 1,1,1,1 -> v8i16 though.
3598 V1IsSplat = isSplatVector(V1.Val);
3599 V2IsSplat = isSplatVector(V2.Val);
3601 // Canonicalize the splat or undef, if present, to be on the RHS.
3602 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3603 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3604 std::swap(V1IsSplat, V2IsSplat);
3605 std::swap(V1IsUndef, V2IsUndef);
3609 // FIXME: Figure out a cleaner way to do this.
3610 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3611 if (V2IsUndef) return V1;
3612 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3614 // V2 is a splat, so the mask may be malformed. That is, it may point
3615 // to any V2 element. The instruction selectior won't like this. Get
3616 // a corrected mask and commute to form a proper MOVS{S|D}.
3617 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3618 if (NewMask.Val != PermMask.Val)
3619 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3624 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3625 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3626 X86::isUNPCKLMask(PermMask.Val) ||
3627 X86::isUNPCKHMask(PermMask.Val))
3631 // Normalize mask so all entries that point to V2 points to its first
3632 // element then try to match unpck{h|l} again. If match, return a
3633 // new vector_shuffle with the corrected mask.
3634 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3635 if (NewMask.Val != PermMask.Val) {
3636 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3637 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3638 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3639 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3640 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3641 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3646 // Normalize the node to match x86 shuffle ops if needed
3647 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3648 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3651 // Commute is back and try unpck* again.
3652 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3653 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3654 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3655 X86::isUNPCKLMask(PermMask.Val) ||
3656 X86::isUNPCKHMask(PermMask.Val))
3660 // Try PSHUF* first, then SHUFP*.
3661 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3662 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3663 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3664 if (V2.getOpcode() != ISD::UNDEF)
3665 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3666 DAG.getNode(ISD::UNDEF, VT), PermMask);
3671 if (Subtarget->hasSSE2() &&
3672 (X86::isPSHUFDMask(PermMask.Val) ||
3673 X86::isPSHUFHWMask(PermMask.Val) ||
3674 X86::isPSHUFLWMask(PermMask.Val))) {
3675 MVT::ValueType RVT = VT;
3676 if (VT == MVT::v4f32) {
3678 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3679 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3680 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3681 } else if (V2.getOpcode() != ISD::UNDEF)
3682 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3683 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3685 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3689 // Binary or unary shufps.
3690 if (X86::isSHUFPMask(PermMask.Val) ||
3691 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3695 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3696 if (VT == MVT::v8i16) {
3697 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3702 // Handle all 4 wide cases with a number of shuffles.
3703 if (NumElems == 4 && !isMMX) {
3704 // Don't do this for MMX.
3705 MVT::ValueType MaskVT = PermMask.getValueType();
3706 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3707 SmallVector<std::pair<int, int>, 8> Locs;
3708 Locs.reserve(NumElems);
3709 SmallVector<SDOperand, 8> Mask1(NumElems,
3710 DAG.getNode(ISD::UNDEF, MaskEVT));
3711 SmallVector<SDOperand, 8> Mask2(NumElems,
3712 DAG.getNode(ISD::UNDEF, MaskEVT));
3715 // If no more than two elements come from either vector. This can be
3716 // implemented with two shuffles. First shuffle gather the elements.
3717 // The second shuffle, which takes the first shuffle as both of its
3718 // vector operands, put the elements into the right order.
3719 for (unsigned i = 0; i != NumElems; ++i) {
3720 SDOperand Elt = PermMask.getOperand(i);
3721 if (Elt.getOpcode() == ISD::UNDEF) {
3722 Locs[i] = std::make_pair(-1, -1);
3724 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3725 if (Val < NumElems) {
3726 Locs[i] = std::make_pair(0, NumLo);
3730 Locs[i] = std::make_pair(1, NumHi);
3731 if (2+NumHi < NumElems)
3732 Mask1[2+NumHi] = Elt;
3737 if (NumLo <= 2 && NumHi <= 2) {
3738 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3739 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3740 &Mask1[0], Mask1.size()));
3741 for (unsigned i = 0; i != NumElems; ++i) {
3742 if (Locs[i].first == -1)
3745 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3746 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3747 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3751 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3752 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3753 &Mask2[0], Mask2.size()));
3756 // Break it into (shuffle shuffle_hi, shuffle_lo).
3758 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3759 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3760 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3761 unsigned MaskIdx = 0;
3763 unsigned HiIdx = NumElems/2;
3764 for (unsigned i = 0; i != NumElems; ++i) {
3765 if (i == NumElems/2) {
3771 SDOperand Elt = PermMask.getOperand(i);
3772 if (Elt.getOpcode() == ISD::UNDEF) {
3773 Locs[i] = std::make_pair(-1, -1);
3774 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3775 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3776 (*MaskPtr)[LoIdx] = Elt;
3779 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3780 (*MaskPtr)[HiIdx] = Elt;
3785 SDOperand LoShuffle =
3786 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3787 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3788 &LoMask[0], LoMask.size()));
3789 SDOperand HiShuffle =
3790 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3791 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3792 &HiMask[0], HiMask.size()));
3793 SmallVector<SDOperand, 8> MaskOps;
3794 for (unsigned i = 0; i != NumElems; ++i) {
3795 if (Locs[i].first == -1) {
3796 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3798 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3799 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3802 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3803 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3804 &MaskOps[0], MaskOps.size()));
3811 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3812 SelectionDAG &DAG) {
3813 MVT::ValueType VT = Op.getValueType();
3814 if (MVT::getSizeInBits(VT) == 8) {
3815 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3816 Op.getOperand(0), Op.getOperand(1));
3817 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3818 DAG.getValueType(VT));
3819 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3820 } else if (MVT::getSizeInBits(VT) == 16) {
3821 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3822 Op.getOperand(0), Op.getOperand(1));
3823 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3824 DAG.getValueType(VT));
3825 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3826 } else if (VT == MVT::f32) {
3827 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3828 // the result back to FR32 register. It's only worth matching if the
3829 // result has a single use which is a store or a bitcast to i32.
3830 if (!Op.hasOneUse())
3832 SDNode *User = Op.Val->use_begin()->getUser();
3833 if (User->getOpcode() != ISD::STORE &&
3834 (User->getOpcode() != ISD::BIT_CONVERT ||
3835 User->getValueType(0) != MVT::i32))
3837 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3838 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3840 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3848 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3851 if (Subtarget->hasSSE41()) {
3852 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3857 MVT::ValueType VT = Op.getValueType();
3858 // TODO: handle v16i8.
3859 if (MVT::getSizeInBits(VT) == 16) {
3860 SDOperand Vec = Op.getOperand(0);
3861 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3863 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3864 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3865 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3867 // Transform it so it match pextrw which produces a 32-bit result.
3868 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3869 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3870 Op.getOperand(0), Op.getOperand(1));
3871 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3872 DAG.getValueType(VT));
3873 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3874 } else if (MVT::getSizeInBits(VT) == 32) {
3875 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3878 // SHUFPS the element to the lowest double word, then movss.
3879 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3880 SmallVector<SDOperand, 8> IdxVec;
3882 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3884 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3886 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3888 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3889 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3890 &IdxVec[0], IdxVec.size());
3891 SDOperand Vec = Op.getOperand(0);
3892 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3893 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3894 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3895 DAG.getIntPtrConstant(0));
3896 } else if (MVT::getSizeInBits(VT) == 64) {
3897 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3898 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3899 // to match extract_elt for f64.
3900 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3904 // UNPCKHPD the element to the lowest double word, then movsd.
3905 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3906 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3907 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3908 SmallVector<SDOperand, 8> IdxVec;
3909 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3911 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3912 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3913 &IdxVec[0], IdxVec.size());
3914 SDOperand Vec = Op.getOperand(0);
3915 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3916 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3917 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3918 DAG.getIntPtrConstant(0));
3925 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3926 MVT::ValueType VT = Op.getValueType();
3927 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3929 SDOperand N0 = Op.getOperand(0);
3930 SDOperand N1 = Op.getOperand(1);
3931 SDOperand N2 = Op.getOperand(2);
3933 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3934 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3936 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3938 if (N1.getValueType() != MVT::i32)
3939 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3940 if (N2.getValueType() != MVT::i32)
3941 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3942 return DAG.getNode(Opc, VT, N0, N1, N2);
3943 } else if (EVT == MVT::f32) {
3944 // Bits [7:6] of the constant are the source select. This will always be
3945 // zero here. The DAG Combiner may combine an extract_elt index into these
3946 // bits. For example (insert (extract, 3), 2) could be matched by putting
3947 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3948 // Bits [5:4] of the constant are the destination select. This is the
3949 // value of the incoming immediate.
3950 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3951 // combine either bitwise AND or insert of float 0.0 to set these bits.
3952 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3953 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3959 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3960 MVT::ValueType VT = Op.getValueType();
3961 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3963 if (Subtarget->hasSSE41())
3964 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3969 SDOperand N0 = Op.getOperand(0);
3970 SDOperand N1 = Op.getOperand(1);
3971 SDOperand N2 = Op.getOperand(2);
3973 if (MVT::getSizeInBits(EVT) == 16) {
3974 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3975 // as its second argument.
3976 if (N1.getValueType() != MVT::i32)
3977 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3978 if (N2.getValueType() != MVT::i32)
3979 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3980 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3986 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3987 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3988 MVT::ValueType VT = MVT::v2i32;
3989 switch (Op.getValueType()) {
3996 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3997 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4000 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4001 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4002 // one of the above mentioned nodes. It has to be wrapped because otherwise
4003 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4004 // be used to form addressing mode. These wrapped nodes will be selected
4007 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4008 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4009 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4011 CP->getAlignment());
4012 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4013 // With PIC, the address is actually $g + Offset.
4014 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4015 !Subtarget->isPICStyleRIPRel()) {
4016 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4017 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4025 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4026 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4027 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4028 // If it's a debug information descriptor, don't mess with it.
4029 if (DAG.isVerifiedDebugInfoDesc(Op))
4031 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4032 // With PIC, the address is actually $g + Offset.
4033 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4034 !Subtarget->isPICStyleRIPRel()) {
4035 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4036 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4040 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4041 // load the value at address GV, not the value of GV itself. This means that
4042 // the GlobalAddress must be in the base or index register of the address, not
4043 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4044 // The same applies for external symbols during PIC codegen
4045 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4046 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4047 PseudoSourceValue::getGOT(), 0);
4052 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4054 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4055 const MVT::ValueType PtrVT) {
4057 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4058 DAG.getNode(X86ISD::GlobalBaseReg,
4060 InFlag = Chain.getValue(1);
4062 // emit leal symbol@TLSGD(,%ebx,1), %eax
4063 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4064 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4065 GA->getValueType(0),
4067 SDOperand Ops[] = { Chain, TGA, InFlag };
4068 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4069 InFlag = Result.getValue(2);
4070 Chain = Result.getValue(1);
4072 // call ___tls_get_addr. This function receives its argument in
4073 // the register EAX.
4074 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4075 InFlag = Chain.getValue(1);
4077 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4078 SDOperand Ops1[] = { Chain,
4079 DAG.getTargetExternalSymbol("___tls_get_addr",
4081 DAG.getRegister(X86::EAX, PtrVT),
4082 DAG.getRegister(X86::EBX, PtrVT),
4084 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4085 InFlag = Chain.getValue(1);
4087 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4090 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4092 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4093 const MVT::ValueType PtrVT) {
4094 SDOperand InFlag, Chain;
4096 // emit leaq symbol@TLSGD(%rip), %rdi
4097 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4098 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4099 GA->getValueType(0),
4101 SDOperand Ops[] = { DAG.getEntryNode(), TGA};
4102 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4103 Chain = Result.getValue(1);
4104 InFlag = Result.getValue(2);
4106 // call ___tls_get_addr. This function receives its argument in
4107 // the register RDI.
4108 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4109 InFlag = Chain.getValue(1);
4111 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4112 SDOperand Ops1[] = { Chain,
4113 DAG.getTargetExternalSymbol("___tls_get_addr",
4115 DAG.getRegister(X86::RDI, PtrVT),
4117 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4118 InFlag = Chain.getValue(1);
4120 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4123 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4124 // "local exec" model.
4126 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4127 const MVT::ValueType PtrVT) {
4128 // Get the Thread Pointer
4129 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4130 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4132 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4133 GA->getValueType(0),
4135 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4137 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4138 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4139 PseudoSourceValue::getGOT(), 0);
4141 // The address of the thread local variable is the add of the thread
4142 // pointer with the offset of the variable.
4143 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4147 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4148 // TODO: implement the "local dynamic" model
4149 // TODO: implement the "initial exec"model for pic executables
4150 assert(Subtarget->isTargetELF() &&
4151 "TLS not implemented for non-ELF targets");
4152 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4153 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4154 // otherwise use the "Local Exec"TLS Model
4155 if (Subtarget->is64Bit()) {
4156 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4158 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4159 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4161 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4166 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4167 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4168 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4169 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4170 // With PIC, the address is actually $g + Offset.
4171 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4172 !Subtarget->isPICStyleRIPRel()) {
4173 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4174 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4181 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4182 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4183 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4184 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4185 // With PIC, the address is actually $g + Offset.
4186 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4187 !Subtarget->isPICStyleRIPRel()) {
4188 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4189 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4196 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4197 /// take a 2 x i32 value to shift plus a shift amount.
4198 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4199 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4200 MVT::ValueType VT = Op.getValueType();
4201 unsigned VTBits = MVT::getSizeInBits(VT);
4202 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4203 SDOperand ShOpLo = Op.getOperand(0);
4204 SDOperand ShOpHi = Op.getOperand(1);
4205 SDOperand ShAmt = Op.getOperand(2);
4206 SDOperand Tmp1 = isSRA ?
4207 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4208 DAG.getConstant(0, VT);
4210 SDOperand Tmp2, Tmp3;
4211 if (Op.getOpcode() == ISD::SHL_PARTS) {
4212 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4213 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4215 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4216 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4219 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4220 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4221 DAG.getConstant(VTBits, MVT::i8));
4222 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4223 AndNode, DAG.getConstant(0, MVT::i8));
4226 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4227 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4228 SmallVector<SDOperand, 4> Ops;
4229 if (Op.getOpcode() == ISD::SHL_PARTS) {
4230 Ops.push_back(Tmp2);
4231 Ops.push_back(Tmp3);
4233 Ops.push_back(Cond);
4234 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4237 Ops.push_back(Tmp3);
4238 Ops.push_back(Tmp1);
4240 Ops.push_back(Cond);
4241 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4243 Ops.push_back(Tmp2);
4244 Ops.push_back(Tmp3);
4246 Ops.push_back(Cond);
4247 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4250 Ops.push_back(Tmp3);
4251 Ops.push_back(Tmp1);
4253 Ops.push_back(Cond);
4254 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4257 VTs = DAG.getNodeValueTypes(VT, VT);
4261 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4264 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4265 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4266 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4267 "Unknown SINT_TO_FP to lower!");
4269 // These are really Legal; caller falls through into that case.
4270 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4272 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4273 Subtarget->is64Bit())
4276 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4277 MachineFunction &MF = DAG.getMachineFunction();
4278 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4279 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4280 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4282 PseudoSourceValue::getFixedStack(),
4287 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4289 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4291 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4292 SmallVector<SDOperand, 8> Ops;
4293 Ops.push_back(Chain);
4294 Ops.push_back(StackSlot);
4295 Ops.push_back(DAG.getValueType(SrcVT));
4296 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4297 Tys, &Ops[0], Ops.size());
4300 Chain = Result.getValue(1);
4301 SDOperand InFlag = Result.getValue(2);
4303 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4304 // shouldn't be necessary except that RFP cannot be live across
4305 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4306 MachineFunction &MF = DAG.getMachineFunction();
4307 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4308 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4309 Tys = DAG.getVTList(MVT::Other);
4310 SmallVector<SDOperand, 8> Ops;
4311 Ops.push_back(Chain);
4312 Ops.push_back(Result);
4313 Ops.push_back(StackSlot);
4314 Ops.push_back(DAG.getValueType(Op.getValueType()));
4315 Ops.push_back(InFlag);
4316 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4317 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4318 PseudoSourceValue::getFixedStack(), SSFI);
4324 std::pair<SDOperand,SDOperand> X86TargetLowering::
4325 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4326 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4327 "Unknown FP_TO_SINT to lower!");
4329 // These are really Legal.
4330 if (Op.getValueType() == MVT::i32 &&
4331 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4332 return std::make_pair(SDOperand(), SDOperand());
4333 if (Subtarget->is64Bit() &&
4334 Op.getValueType() == MVT::i64 &&
4335 Op.getOperand(0).getValueType() != MVT::f80)
4336 return std::make_pair(SDOperand(), SDOperand());
4338 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4340 MachineFunction &MF = DAG.getMachineFunction();
4341 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4342 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4343 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4345 switch (Op.getValueType()) {
4346 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4347 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4348 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4349 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4352 SDOperand Chain = DAG.getEntryNode();
4353 SDOperand Value = Op.getOperand(0);
4354 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4355 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4356 Chain = DAG.getStore(Chain, Value, StackSlot,
4357 PseudoSourceValue::getFixedStack(), SSFI);
4358 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4360 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4362 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4363 Chain = Value.getValue(1);
4364 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4365 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4368 // Build the FP_TO_INT*_IN_MEM
4369 SDOperand Ops[] = { Chain, Value, StackSlot };
4370 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4372 return std::make_pair(FIST, StackSlot);
4375 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4376 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4377 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4378 if (FIST.Val == 0) return SDOperand();
4381 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4384 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4385 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4386 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4387 if (FIST.Val == 0) return 0;
4389 // Return an i64 load from the stack slot.
4390 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4392 // Use a MERGE_VALUES node to drop the chain result value.
4393 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4396 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4397 MVT::ValueType VT = Op.getValueType();
4398 MVT::ValueType EltVT = VT;
4399 if (MVT::isVector(VT))
4400 EltVT = MVT::getVectorElementType(VT);
4401 std::vector<Constant*> CV;
4402 if (EltVT == MVT::f64) {
4403 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4407 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4413 Constant *C = ConstantVector::get(CV);
4414 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4415 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4416 PseudoSourceValue::getConstantPool(), 0,
4418 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4421 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4422 MVT::ValueType VT = Op.getValueType();
4423 MVT::ValueType EltVT = VT;
4424 unsigned EltNum = 1;
4425 if (MVT::isVector(VT)) {
4426 EltVT = MVT::getVectorElementType(VT);
4427 EltNum = MVT::getVectorNumElements(VT);
4429 std::vector<Constant*> CV;
4430 if (EltVT == MVT::f64) {
4431 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4435 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4441 Constant *C = ConstantVector::get(CV);
4442 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4443 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4444 PseudoSourceValue::getConstantPool(), 0,
4446 if (MVT::isVector(VT)) {
4447 return DAG.getNode(ISD::BIT_CONVERT, VT,
4448 DAG.getNode(ISD::XOR, MVT::v2i64,
4449 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4450 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4452 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4456 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4457 SDOperand Op0 = Op.getOperand(0);
4458 SDOperand Op1 = Op.getOperand(1);
4459 MVT::ValueType VT = Op.getValueType();
4460 MVT::ValueType SrcVT = Op1.getValueType();
4462 // If second operand is smaller, extend it first.
4463 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4464 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4467 // And if it is bigger, shrink it first.
4468 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4469 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4473 // At this point the operands and the result should have the same
4474 // type, and that won't be f80 since that is not custom lowered.
4476 // First get the sign bit of second operand.
4477 std::vector<Constant*> CV;
4478 if (SrcVT == MVT::f64) {
4479 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4480 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4482 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4483 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4484 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4485 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4487 Constant *C = ConstantVector::get(CV);
4488 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4489 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4490 PseudoSourceValue::getConstantPool(), 0,
4492 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4494 // Shift sign bit right or left if the two operands have different types.
4495 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4496 // Op0 is MVT::f32, Op1 is MVT::f64.
4497 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4498 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4499 DAG.getConstant(32, MVT::i32));
4500 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4501 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4502 DAG.getIntPtrConstant(0));
4505 // Clear first operand sign bit.
4507 if (VT == MVT::f64) {
4508 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4509 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4511 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4512 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4513 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4514 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4516 C = ConstantVector::get(CV);
4517 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4518 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4519 PseudoSourceValue::getConstantPool(), 0,
4521 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4523 // Or the value with the sign bit.
4524 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4527 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4528 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4530 SDOperand Op0 = Op.getOperand(0);
4531 SDOperand Op1 = Op.getOperand(1);
4532 SDOperand CC = Op.getOperand(2);
4533 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4534 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4537 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4539 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4540 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4541 DAG.getConstant(X86CC, MVT::i8), Cond);
4544 assert(isFP && "Illegal integer SetCC!");
4546 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4547 switch (SetCCOpcode) {
4548 default: assert(false && "Illegal floating point SetCC!");
4549 case ISD::SETOEQ: { // !PF & ZF
4550 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4551 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4552 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4553 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4554 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4556 case ISD::SETUNE: { // PF | !ZF
4557 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4558 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4559 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4560 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4561 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4567 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4568 bool addTest = true;
4569 SDOperand Cond = Op.getOperand(0);
4572 if (Cond.getOpcode() == ISD::SETCC)
4573 Cond = LowerSETCC(Cond, DAG);
4575 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4576 // setting operand in place of the X86ISD::SETCC.
4577 if (Cond.getOpcode() == X86ISD::SETCC) {
4578 CC = Cond.getOperand(0);
4580 SDOperand Cmp = Cond.getOperand(1);
4581 unsigned Opc = Cmp.getOpcode();
4582 MVT::ValueType VT = Op.getValueType();
4584 bool IllegalFPCMov = false;
4585 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4586 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4587 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4589 if ((Opc == X86ISD::CMP ||
4590 Opc == X86ISD::COMI ||
4591 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4598 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4599 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4602 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4604 SmallVector<SDOperand, 4> Ops;
4605 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4606 // condition is true.
4607 Ops.push_back(Op.getOperand(2));
4608 Ops.push_back(Op.getOperand(1));
4610 Ops.push_back(Cond);
4611 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4614 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4615 bool addTest = true;
4616 SDOperand Chain = Op.getOperand(0);
4617 SDOperand Cond = Op.getOperand(1);
4618 SDOperand Dest = Op.getOperand(2);
4621 if (Cond.getOpcode() == ISD::SETCC)
4622 Cond = LowerSETCC(Cond, DAG);
4624 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4625 // setting operand in place of the X86ISD::SETCC.
4626 if (Cond.getOpcode() == X86ISD::SETCC) {
4627 CC = Cond.getOperand(0);
4629 SDOperand Cmp = Cond.getOperand(1);
4630 unsigned Opc = Cmp.getOpcode();
4631 if (Opc == X86ISD::CMP ||
4632 Opc == X86ISD::COMI ||
4633 Opc == X86ISD::UCOMI) {
4640 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4641 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4643 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4644 Chain, Op.getOperand(2), CC, Cond);
4648 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4649 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4650 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4651 // that the guard pages used by the OS virtual memory manager are allocated in
4652 // correct sequence.
4654 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4655 SelectionDAG &DAG) {
4656 assert(Subtarget->isTargetCygMing() &&
4657 "This should be used only on Cygwin/Mingw targets");
4660 SDOperand Chain = Op.getOperand(0);
4661 SDOperand Size = Op.getOperand(1);
4662 // FIXME: Ensure alignment here
4666 MVT::ValueType IntPtr = getPointerTy();
4667 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4669 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4670 Flag = Chain.getValue(1);
4672 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4673 SDOperand Ops[] = { Chain,
4674 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4675 DAG.getRegister(X86::EAX, IntPtr),
4677 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4678 Flag = Chain.getValue(1);
4680 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4682 std::vector<MVT::ValueType> Tys;
4683 Tys.push_back(SPTy);
4684 Tys.push_back(MVT::Other);
4685 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4686 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4690 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4692 SDOperand Dst, SDOperand Src,
4693 SDOperand Size, unsigned Align,
4694 const Value *DstSV, uint64_t DstSVOff) {
4695 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4697 /// If not DWORD aligned or size is more than the threshold, call the library.
4698 /// The libc version is likely to be faster for these cases. It can use the
4699 /// address value and run time information about the CPU.
4700 if ((Align & 3) == 0 ||
4702 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4703 SDOperand InFlag(0, 0);
4705 // Check to see if there is a specialized entry-point for memory zeroing.
4706 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4707 if (const char *bzeroEntry =
4708 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4709 MVT::ValueType IntPtr = getPointerTy();
4710 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4711 TargetLowering::ArgListTy Args;
4712 TargetLowering::ArgListEntry Entry;
4714 Entry.Ty = IntPtrTy;
4715 Args.push_back(Entry);
4717 Args.push_back(Entry);
4718 std::pair<SDOperand,SDOperand> CallResult =
4719 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4720 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4722 return CallResult.second;
4725 // Otherwise have the target-independent code call memset.
4729 uint64_t SizeVal = ConstantSize->getValue();
4730 SDOperand InFlag(0, 0);
4733 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4734 unsigned BytesLeft = 0;
4735 bool TwoRepStos = false;
4738 uint64_t Val = ValC->getValue() & 255;
4740 // If the value is a constant, then we can potentially use larger sets.
4741 switch (Align & 3) {
4742 case 2: // WORD aligned
4745 Val = (Val << 8) | Val;
4747 case 0: // DWORD aligned
4750 Val = (Val << 8) | Val;
4751 Val = (Val << 16) | Val;
4752 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4755 Val = (Val << 32) | Val;
4758 default: // Byte aligned
4761 Count = DAG.getIntPtrConstant(SizeVal);
4765 if (AVT > MVT::i8) {
4766 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4767 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4768 BytesLeft = SizeVal % UBytes;
4771 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4773 InFlag = Chain.getValue(1);
4776 Count = DAG.getIntPtrConstant(SizeVal);
4777 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4778 InFlag = Chain.getValue(1);
4781 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4783 InFlag = Chain.getValue(1);
4784 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4786 InFlag = Chain.getValue(1);
4788 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4789 SmallVector<SDOperand, 8> Ops;
4790 Ops.push_back(Chain);
4791 Ops.push_back(DAG.getValueType(AVT));
4792 Ops.push_back(InFlag);
4793 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4796 InFlag = Chain.getValue(1);
4798 MVT::ValueType CVT = Count.getValueType();
4799 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4800 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4801 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4803 InFlag = Chain.getValue(1);
4804 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4806 Ops.push_back(Chain);
4807 Ops.push_back(DAG.getValueType(MVT::i8));
4808 Ops.push_back(InFlag);
4809 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4810 } else if (BytesLeft) {
4811 // Handle the last 1 - 7 bytes.
4812 unsigned Offset = SizeVal - BytesLeft;
4813 MVT::ValueType AddrVT = Dst.getValueType();
4814 MVT::ValueType SizeVT = Size.getValueType();
4816 Chain = DAG.getMemset(Chain,
4817 DAG.getNode(ISD::ADD, AddrVT, Dst,
4818 DAG.getConstant(Offset, AddrVT)),
4820 DAG.getConstant(BytesLeft, SizeVT),
4821 Align, DstSV, DstSVOff + Offset);
4824 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4829 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4831 SDOperand Dst, SDOperand Src,
4832 SDOperand Size, unsigned Align,
4834 const Value *DstSV, uint64_t DstSVOff,
4835 const Value *SrcSV, uint64_t SrcSVOff){
4837 // This requires the copy size to be a constant, preferrably
4838 // within a subtarget-specific limit.
4839 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4842 uint64_t SizeVal = ConstantSize->getValue();
4843 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4847 unsigned BytesLeft = 0;
4848 if (Align >= 8 && Subtarget->is64Bit())
4850 else if (Align >= 4)
4852 else if (Align >= 2)
4857 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4858 unsigned CountVal = SizeVal / UBytes;
4859 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4860 BytesLeft = SizeVal % UBytes;
4862 SDOperand InFlag(0, 0);
4863 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4865 InFlag = Chain.getValue(1);
4866 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4868 InFlag = Chain.getValue(1);
4869 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4871 InFlag = Chain.getValue(1);
4873 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4874 SmallVector<SDOperand, 8> Ops;
4875 Ops.push_back(Chain);
4876 Ops.push_back(DAG.getValueType(AVT));
4877 Ops.push_back(InFlag);
4878 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4880 SmallVector<SDOperand, 4> Results;
4881 Results.push_back(RepMovs);
4883 // Handle the last 1 - 7 bytes.
4884 unsigned Offset = SizeVal - BytesLeft;
4885 MVT::ValueType DstVT = Dst.getValueType();
4886 MVT::ValueType SrcVT = Src.getValueType();
4887 MVT::ValueType SizeVT = Size.getValueType();
4888 Results.push_back(DAG.getMemcpy(Chain,
4889 DAG.getNode(ISD::ADD, DstVT, Dst,
4890 DAG.getConstant(Offset, DstVT)),
4891 DAG.getNode(ISD::ADD, SrcVT, Src,
4892 DAG.getConstant(Offset, SrcVT)),
4893 DAG.getConstant(BytesLeft, SizeVT),
4894 Align, AlwaysInline,
4895 DstSV, DstSVOff + Offset,
4896 SrcSV, SrcSVOff + Offset));
4899 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4902 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4903 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4904 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4905 SDOperand TheChain = N->getOperand(0);
4906 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4907 if (Subtarget->is64Bit()) {
4908 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4909 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4910 MVT::i64, rax.getValue(2));
4911 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4912 DAG.getConstant(32, MVT::i8));
4914 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4917 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4918 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4921 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4922 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4923 MVT::i32, eax.getValue(2));
4924 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4925 SDOperand Ops[] = { eax, edx };
4926 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4928 // Use a MERGE_VALUES to return the value and chain.
4929 Ops[1] = edx.getValue(1);
4930 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4931 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4934 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4935 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4937 if (!Subtarget->is64Bit()) {
4938 // vastart just stores the address of the VarArgsFrameIndex slot into the
4939 // memory location argument.
4940 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4941 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4945 // gp_offset (0 - 6 * 8)
4946 // fp_offset (48 - 48 + 8 * 16)
4947 // overflow_arg_area (point to parameters coming in memory).
4949 SmallVector<SDOperand, 8> MemOps;
4950 SDOperand FIN = Op.getOperand(1);
4952 SDOperand Store = DAG.getStore(Op.getOperand(0),
4953 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4955 MemOps.push_back(Store);
4958 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4959 Store = DAG.getStore(Op.getOperand(0),
4960 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4962 MemOps.push_back(Store);
4964 // Store ptr to overflow_arg_area
4965 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4966 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4967 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4968 MemOps.push_back(Store);
4970 // Store ptr to reg_save_area.
4971 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4972 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4973 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4974 MemOps.push_back(Store);
4975 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4978 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4979 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4980 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
4981 SDOperand Chain = Op.getOperand(0);
4982 SDOperand DstPtr = Op.getOperand(1);
4983 SDOperand SrcPtr = Op.getOperand(2);
4984 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4985 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4987 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
4988 DAG.getIntPtrConstant(24), 8, false,
4989 DstSV, 0, SrcSV, 0);
4993 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4994 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4996 default: return SDOperand(); // Don't custom lower most intrinsics.
4997 // Comparison intrinsics.
4998 case Intrinsic::x86_sse_comieq_ss:
4999 case Intrinsic::x86_sse_comilt_ss:
5000 case Intrinsic::x86_sse_comile_ss:
5001 case Intrinsic::x86_sse_comigt_ss:
5002 case Intrinsic::x86_sse_comige_ss:
5003 case Intrinsic::x86_sse_comineq_ss:
5004 case Intrinsic::x86_sse_ucomieq_ss:
5005 case Intrinsic::x86_sse_ucomilt_ss:
5006 case Intrinsic::x86_sse_ucomile_ss:
5007 case Intrinsic::x86_sse_ucomigt_ss:
5008 case Intrinsic::x86_sse_ucomige_ss:
5009 case Intrinsic::x86_sse_ucomineq_ss:
5010 case Intrinsic::x86_sse2_comieq_sd:
5011 case Intrinsic::x86_sse2_comilt_sd:
5012 case Intrinsic::x86_sse2_comile_sd:
5013 case Intrinsic::x86_sse2_comigt_sd:
5014 case Intrinsic::x86_sse2_comige_sd:
5015 case Intrinsic::x86_sse2_comineq_sd:
5016 case Intrinsic::x86_sse2_ucomieq_sd:
5017 case Intrinsic::x86_sse2_ucomilt_sd:
5018 case Intrinsic::x86_sse2_ucomile_sd:
5019 case Intrinsic::x86_sse2_ucomigt_sd:
5020 case Intrinsic::x86_sse2_ucomige_sd:
5021 case Intrinsic::x86_sse2_ucomineq_sd: {
5023 ISD::CondCode CC = ISD::SETCC_INVALID;
5026 case Intrinsic::x86_sse_comieq_ss:
5027 case Intrinsic::x86_sse2_comieq_sd:
5031 case Intrinsic::x86_sse_comilt_ss:
5032 case Intrinsic::x86_sse2_comilt_sd:
5036 case Intrinsic::x86_sse_comile_ss:
5037 case Intrinsic::x86_sse2_comile_sd:
5041 case Intrinsic::x86_sse_comigt_ss:
5042 case Intrinsic::x86_sse2_comigt_sd:
5046 case Intrinsic::x86_sse_comige_ss:
5047 case Intrinsic::x86_sse2_comige_sd:
5051 case Intrinsic::x86_sse_comineq_ss:
5052 case Intrinsic::x86_sse2_comineq_sd:
5056 case Intrinsic::x86_sse_ucomieq_ss:
5057 case Intrinsic::x86_sse2_ucomieq_sd:
5058 Opc = X86ISD::UCOMI;
5061 case Intrinsic::x86_sse_ucomilt_ss:
5062 case Intrinsic::x86_sse2_ucomilt_sd:
5063 Opc = X86ISD::UCOMI;
5066 case Intrinsic::x86_sse_ucomile_ss:
5067 case Intrinsic::x86_sse2_ucomile_sd:
5068 Opc = X86ISD::UCOMI;
5071 case Intrinsic::x86_sse_ucomigt_ss:
5072 case Intrinsic::x86_sse2_ucomigt_sd:
5073 Opc = X86ISD::UCOMI;
5076 case Intrinsic::x86_sse_ucomige_ss:
5077 case Intrinsic::x86_sse2_ucomige_sd:
5078 Opc = X86ISD::UCOMI;
5081 case Intrinsic::x86_sse_ucomineq_ss:
5082 case Intrinsic::x86_sse2_ucomineq_sd:
5083 Opc = X86ISD::UCOMI;
5089 SDOperand LHS = Op.getOperand(1);
5090 SDOperand RHS = Op.getOperand(2);
5091 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5093 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5094 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5095 DAG.getConstant(X86CC, MVT::i8), Cond);
5096 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5099 // Fix vector shift instructions where the last operand is a non-immediate
5101 case Intrinsic::x86_sse2_pslli_w:
5102 case Intrinsic::x86_sse2_pslli_d:
5103 case Intrinsic::x86_sse2_pslli_q:
5104 case Intrinsic::x86_sse2_psrli_w:
5105 case Intrinsic::x86_sse2_psrli_d:
5106 case Intrinsic::x86_sse2_psrli_q:
5107 case Intrinsic::x86_sse2_psrai_w:
5108 case Intrinsic::x86_sse2_psrai_d:
5109 case Intrinsic::x86_mmx_pslli_w:
5110 case Intrinsic::x86_mmx_pslli_d:
5111 case Intrinsic::x86_mmx_pslli_q:
5112 case Intrinsic::x86_mmx_psrli_w:
5113 case Intrinsic::x86_mmx_psrli_d:
5114 case Intrinsic::x86_mmx_psrli_q:
5115 case Intrinsic::x86_mmx_psrai_w:
5116 case Intrinsic::x86_mmx_psrai_d: {
5117 SDOperand ShAmt = Op.getOperand(2);
5118 if (isa<ConstantSDNode>(ShAmt))
5121 unsigned NewIntNo = 0;
5122 MVT::ValueType ShAmtVT = MVT::v4i32;
5124 case Intrinsic::x86_sse2_pslli_w:
5125 NewIntNo = Intrinsic::x86_sse2_psll_w;
5127 case Intrinsic::x86_sse2_pslli_d:
5128 NewIntNo = Intrinsic::x86_sse2_psll_d;
5130 case Intrinsic::x86_sse2_pslli_q:
5131 NewIntNo = Intrinsic::x86_sse2_psll_q;
5133 case Intrinsic::x86_sse2_psrli_w:
5134 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5136 case Intrinsic::x86_sse2_psrli_d:
5137 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5139 case Intrinsic::x86_sse2_psrli_q:
5140 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5142 case Intrinsic::x86_sse2_psrai_w:
5143 NewIntNo = Intrinsic::x86_sse2_psra_w;
5145 case Intrinsic::x86_sse2_psrai_d:
5146 NewIntNo = Intrinsic::x86_sse2_psra_d;
5149 ShAmtVT = MVT::v2i32;
5151 case Intrinsic::x86_mmx_pslli_w:
5152 NewIntNo = Intrinsic::x86_mmx_psll_w;
5154 case Intrinsic::x86_mmx_pslli_d:
5155 NewIntNo = Intrinsic::x86_mmx_psll_d;
5157 case Intrinsic::x86_mmx_pslli_q:
5158 NewIntNo = Intrinsic::x86_mmx_psll_q;
5160 case Intrinsic::x86_mmx_psrli_w:
5161 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5163 case Intrinsic::x86_mmx_psrli_d:
5164 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5166 case Intrinsic::x86_mmx_psrli_q:
5167 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5169 case Intrinsic::x86_mmx_psrai_w:
5170 NewIntNo = Intrinsic::x86_mmx_psra_w;
5172 case Intrinsic::x86_mmx_psrai_d:
5173 NewIntNo = Intrinsic::x86_mmx_psra_d;
5175 default: abort(); // Can't reach here.
5180 MVT::ValueType VT = Op.getValueType();
5181 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5182 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5183 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5184 DAG.getConstant(NewIntNo, MVT::i32),
5185 Op.getOperand(1), ShAmt);
5190 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5191 // Depths > 0 not supported yet!
5192 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5195 // Just load the return address
5196 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5197 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5200 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5201 // Depths > 0 not supported yet!
5202 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5205 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5206 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5207 DAG.getIntPtrConstant(4));
5210 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5211 SelectionDAG &DAG) {
5212 // Is not yet supported on x86-64
5213 if (Subtarget->is64Bit())
5216 return DAG.getIntPtrConstant(8);
5219 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5221 assert(!Subtarget->is64Bit() &&
5222 "Lowering of eh_return builtin is not supported yet on x86-64");
5224 MachineFunction &MF = DAG.getMachineFunction();
5225 SDOperand Chain = Op.getOperand(0);
5226 SDOperand Offset = Op.getOperand(1);
5227 SDOperand Handler = Op.getOperand(2);
5229 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5232 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5233 DAG.getIntPtrConstant(-4UL));
5234 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5235 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5236 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5237 MF.getRegInfo().addLiveOut(X86::ECX);
5239 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5240 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5243 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5244 SelectionDAG &DAG) {
5245 SDOperand Root = Op.getOperand(0);
5246 SDOperand Trmp = Op.getOperand(1); // trampoline
5247 SDOperand FPtr = Op.getOperand(2); // nested function
5248 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5250 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5252 const X86InstrInfo *TII =
5253 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5255 if (Subtarget->is64Bit()) {
5256 SDOperand OutChains[6];
5258 // Large code-model.
5260 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5261 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5263 const unsigned char N86R10 =
5264 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5265 const unsigned char N86R11 =
5266 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5268 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5270 // Load the pointer to the nested function into R11.
5271 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5272 SDOperand Addr = Trmp;
5273 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5276 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5277 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5279 // Load the 'nest' parameter value into R10.
5280 // R10 is specified in X86CallingConv.td
5281 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5282 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5283 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5286 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5287 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5289 // Jump to the nested function.
5290 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5291 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5292 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5295 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5296 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5297 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5301 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5302 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5304 const Function *Func =
5305 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5306 unsigned CC = Func->getCallingConv();
5311 assert(0 && "Unsupported calling convention");
5312 case CallingConv::C:
5313 case CallingConv::X86_StdCall: {
5314 // Pass 'nest' parameter in ECX.
5315 // Must be kept in sync with X86CallingConv.td
5318 // Check that ECX wasn't needed by an 'inreg' parameter.
5319 const FunctionType *FTy = Func->getFunctionType();
5320 const PAListPtr &Attrs = Func->getParamAttrs();
5322 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5323 unsigned InRegCount = 0;
5326 for (FunctionType::param_iterator I = FTy->param_begin(),
5327 E = FTy->param_end(); I != E; ++I, ++Idx)
5328 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5329 // FIXME: should only count parameters that are lowered to integers.
5330 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5332 if (InRegCount > 2) {
5333 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5339 case CallingConv::X86_FastCall:
5340 // Pass 'nest' parameter in EAX.
5341 // Must be kept in sync with X86CallingConv.td
5346 SDOperand OutChains[4];
5347 SDOperand Addr, Disp;
5349 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5350 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5352 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5353 const unsigned char N86Reg =
5354 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5355 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5358 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5359 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5361 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5362 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5363 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5364 TrmpAddr, 5, false, 1);
5366 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5367 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5370 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5371 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5375 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5377 The rounding mode is in bits 11:10 of FPSR, and has the following
5384 FLT_ROUNDS, on the other hand, expects the following:
5391 To perform the conversion, we do:
5392 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5395 MachineFunction &MF = DAG.getMachineFunction();
5396 const TargetMachine &TM = MF.getTarget();
5397 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5398 unsigned StackAlignment = TFI.getStackAlignment();
5399 MVT::ValueType VT = Op.getValueType();
5401 // Save FP Control Word to stack slot
5402 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5403 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5405 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5406 DAG.getEntryNode(), StackSlot);
5408 // Load FP Control Word from stack slot
5409 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5411 // Transform as necessary
5413 DAG.getNode(ISD::SRL, MVT::i16,
5414 DAG.getNode(ISD::AND, MVT::i16,
5415 CWD, DAG.getConstant(0x800, MVT::i16)),
5416 DAG.getConstant(11, MVT::i8));
5418 DAG.getNode(ISD::SRL, MVT::i16,
5419 DAG.getNode(ISD::AND, MVT::i16,
5420 CWD, DAG.getConstant(0x400, MVT::i16)),
5421 DAG.getConstant(9, MVT::i8));
5424 DAG.getNode(ISD::AND, MVT::i16,
5425 DAG.getNode(ISD::ADD, MVT::i16,
5426 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5427 DAG.getConstant(1, MVT::i16)),
5428 DAG.getConstant(3, MVT::i16));
5431 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5432 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5435 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5436 MVT::ValueType VT = Op.getValueType();
5437 MVT::ValueType OpVT = VT;
5438 unsigned NumBits = MVT::getSizeInBits(VT);
5440 Op = Op.getOperand(0);
5441 if (VT == MVT::i8) {
5442 // Zero extend to i32 since there is not an i8 bsr.
5444 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5447 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5448 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5449 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5451 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5452 SmallVector<SDOperand, 4> Ops;
5454 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5455 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5456 Ops.push_back(Op.getValue(1));
5457 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5459 // Finally xor with NumBits-1.
5460 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5463 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5467 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5468 MVT::ValueType VT = Op.getValueType();
5469 MVT::ValueType OpVT = VT;
5470 unsigned NumBits = MVT::getSizeInBits(VT);
5472 Op = Op.getOperand(0);
5473 if (VT == MVT::i8) {
5475 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5478 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5479 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5480 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5482 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5483 SmallVector<SDOperand, 4> Ops;
5485 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5486 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5487 Ops.push_back(Op.getValue(1));
5488 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5491 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5495 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5496 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5500 case MVT::i8: Reg = X86::AL; size = 1; break;
5501 case MVT::i16: Reg = X86::AX; size = 2; break;
5502 case MVT::i32: Reg = X86::EAX; size = 4; break;
5504 if (Subtarget->is64Bit()) {
5505 Reg = X86::RAX; size = 8;
5506 } else //Should go away when LowerType stuff lands
5507 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5510 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5511 Op.getOperand(3), SDOperand());
5512 SDOperand Ops[] = { cpIn.getValue(0),
5515 DAG.getTargetConstant(size, MVT::i8),
5517 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5518 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5520 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5524 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5525 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5526 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5527 SDOperand cpInL, cpInH;
5528 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5529 DAG.getConstant(0, MVT::i32));
5530 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5531 DAG.getConstant(1, MVT::i32));
5532 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5533 cpInL, SDOperand());
5534 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5535 cpInH, cpInL.getValue(1));
5536 SDOperand swapInL, swapInH;
5537 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5538 DAG.getConstant(0, MVT::i32));
5539 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5540 DAG.getConstant(1, MVT::i32));
5541 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5542 swapInL, cpInH.getValue(1));
5543 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5544 swapInH, swapInL.getValue(1));
5545 SDOperand Ops[] = { swapInH.getValue(0),
5547 swapInH.getValue(1)};
5548 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5549 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5550 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5551 Result.getValue(1));
5552 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5553 cpOutL.getValue(2));
5554 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5555 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5556 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5557 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5560 SDNode* X86TargetLowering::ExpandATOMIC_LSS(SDNode* Op, SelectionDAG &DAG) {
5561 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5562 assert (T == MVT::i32 && "Only know how to expand i32 LSS");
5563 SDOperand negOp = DAG.getNode(ISD::SUB, T,
5564 DAG.getConstant(0, T), Op->getOperand(2));
5565 return DAG.getAtomic(ISD::ATOMIC_LAS, Op->getOperand(0),
5566 Op->getOperand(1), negOp, T).Val;
5569 /// LowerOperation - Provide custom lowering hooks for some operations.
5571 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5572 switch (Op.getOpcode()) {
5573 default: assert(0 && "Should not custom lower this!");
5574 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5575 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5576 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5577 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5578 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5579 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5580 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5581 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5582 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5583 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5584 case ISD::SHL_PARTS:
5585 case ISD::SRA_PARTS:
5586 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5587 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5588 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5589 case ISD::FABS: return LowerFABS(Op, DAG);
5590 case ISD::FNEG: return LowerFNEG(Op, DAG);
5591 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5592 case ISD::SETCC: return LowerSETCC(Op, DAG);
5593 case ISD::SELECT: return LowerSELECT(Op, DAG);
5594 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5595 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5596 case ISD::CALL: return LowerCALL(Op, DAG);
5597 case ISD::RET: return LowerRET(Op, DAG);
5598 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5599 case ISD::VASTART: return LowerVASTART(Op, DAG);
5600 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5601 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5602 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5603 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5604 case ISD::FRAME_TO_ARGS_OFFSET:
5605 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5606 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5607 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5608 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5609 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5610 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5611 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5613 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5614 case ISD::READCYCLECOUNTER:
5615 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5619 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5620 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5621 switch (N->getOpcode()) {
5622 default: assert(0 && "Should not custom lower this!");
5623 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5624 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5625 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5626 case ISD::ATOMIC_LSS: return ExpandATOMIC_LSS(N,DAG);
5630 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5632 default: return NULL;
5633 case X86ISD::BSF: return "X86ISD::BSF";
5634 case X86ISD::BSR: return "X86ISD::BSR";
5635 case X86ISD::SHLD: return "X86ISD::SHLD";
5636 case X86ISD::SHRD: return "X86ISD::SHRD";
5637 case X86ISD::FAND: return "X86ISD::FAND";
5638 case X86ISD::FOR: return "X86ISD::FOR";
5639 case X86ISD::FXOR: return "X86ISD::FXOR";
5640 case X86ISD::FSRL: return "X86ISD::FSRL";
5641 case X86ISD::FILD: return "X86ISD::FILD";
5642 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5643 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5644 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5645 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5646 case X86ISD::FLD: return "X86ISD::FLD";
5647 case X86ISD::FST: return "X86ISD::FST";
5648 case X86ISD::CALL: return "X86ISD::CALL";
5649 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5650 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5651 case X86ISD::CMP: return "X86ISD::CMP";
5652 case X86ISD::COMI: return "X86ISD::COMI";
5653 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5654 case X86ISD::SETCC: return "X86ISD::SETCC";
5655 case X86ISD::CMOV: return "X86ISD::CMOV";
5656 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5657 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5658 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5659 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5660 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5661 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5662 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5663 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5664 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5665 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5666 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5667 case X86ISD::FMAX: return "X86ISD::FMAX";
5668 case X86ISD::FMIN: return "X86ISD::FMIN";
5669 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5670 case X86ISD::FRCP: return "X86ISD::FRCP";
5671 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5672 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5673 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5674 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5675 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5676 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
5677 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
5678 case X86ISD::ZEXT_VMOVL: return "X86ISD::ZEXT_VMOVL";
5682 // isLegalAddressingMode - Return true if the addressing mode represented
5683 // by AM is legal for this target, for a load/store of the specified type.
5684 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5685 const Type *Ty) const {
5686 // X86 supports extremely general addressing modes.
5688 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5689 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5693 // We can only fold this if we don't need an extra load.
5694 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5697 // X86-64 only supports addr of globals in small code model.
5698 if (Subtarget->is64Bit()) {
5699 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5701 // If lower 4G is not available, then we must use rip-relative addressing.
5702 if (AM.BaseOffs || AM.Scale > 1)
5713 // These scales always work.
5718 // These scales are formed with basereg+scalereg. Only accept if there is
5723 default: // Other stuff never works.
5731 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5732 if (!Ty1->isInteger() || !Ty2->isInteger())
5734 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5735 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5736 if (NumBits1 <= NumBits2)
5738 return Subtarget->is64Bit() || NumBits1 < 64;
5741 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5742 MVT::ValueType VT2) const {
5743 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5745 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5746 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5747 if (NumBits1 <= NumBits2)
5749 return Subtarget->is64Bit() || NumBits1 < 64;
5752 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5753 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5754 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5755 /// are assumed to be legal.
5757 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5758 // Only do shuffles on 128-bit vector types for now.
5759 if (MVT::getSizeInBits(VT) == 64) return false;
5760 return (Mask.Val->getNumOperands() <= 4 ||
5761 isIdentityMask(Mask.Val) ||
5762 isIdentityMask(Mask.Val, true) ||
5763 isSplatMask(Mask.Val) ||
5764 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5765 X86::isUNPCKLMask(Mask.Val) ||
5766 X86::isUNPCKHMask(Mask.Val) ||
5767 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5768 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5772 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5774 SelectionDAG &DAG) const {
5775 unsigned NumElts = BVOps.size();
5776 // Only do shuffles on 128-bit vector types for now.
5777 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5778 if (NumElts == 2) return true;
5780 return (isMOVLMask(&BVOps[0], 4) ||
5781 isCommutedMOVL(&BVOps[0], 4, true) ||
5782 isSHUFPMask(&BVOps[0], 4) ||
5783 isCommutedSHUFP(&BVOps[0], 4));
5788 //===----------------------------------------------------------------------===//
5789 // X86 Scheduler Hooks
5790 //===----------------------------------------------------------------------===//
5792 // private utility function
5794 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
5795 MachineBasicBlock *MBB,
5798 // For the atomic bitwise operator, we generate
5801 // ld t1 = [bitinstr.addr]
5802 // op t2 = t1, [bitinstr.val]
5804 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5806 // fallthrough -->nextMBB
5807 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5808 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5809 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5812 /// First build the CFG
5813 MachineFunction *F = MBB->getParent();
5814 MachineBasicBlock *thisMBB = MBB;
5815 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5816 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5817 F->getBasicBlockList().insert(MBBIter, newMBB);
5818 F->getBasicBlockList().insert(MBBIter, nextMBB);
5820 // Move all successors to thisMBB to nextMBB
5821 nextMBB->transferSuccessors(thisMBB);
5823 // Update thisMBB to fall through to newMBB
5824 thisMBB->addSuccessor(newMBB);
5826 // newMBB jumps to itself and fall through to nextMBB
5827 newMBB->addSuccessor(nextMBB);
5828 newMBB->addSuccessor(newMBB);
5830 // Insert instructions into newMBB based on incoming instruction
5831 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
5832 MachineOperand& destOper = bInstr->getOperand(0);
5833 MachineOperand* argOpers[6];
5834 int numArgs = bInstr->getNumOperands() - 1;
5835 for (int i=0; i < numArgs; ++i)
5836 argOpers[i] = &bInstr->getOperand(i+1);
5838 // x86 address has 4 operands: base, index, scale, and displacement
5839 int lastAddrIndx = 3; // [0,3]
5842 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5843 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5844 for (int i=0; i <= lastAddrIndx; ++i)
5845 (*MIB).addOperand(*argOpers[i]);
5847 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5848 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5849 && "invalid operand");
5850 if (argOpers[valArgIndx]->isReg())
5851 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
5853 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
5855 (*MIB).addOperand(*argOpers[valArgIndx]);
5857 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5860 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5861 for (int i=0; i <= lastAddrIndx; ++i)
5862 (*MIB).addOperand(*argOpers[i]);
5865 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5866 MIB.addReg(X86::EAX);
5869 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5871 delete bInstr; // The pseudo instruction is gone now.
5875 // private utility function
5877 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
5878 MachineBasicBlock *MBB,
5880 // For the atomic min/max operator, we generate
5883 // ld t1 = [min/max.addr]
5884 // mov t2 = [min/max.val]
5886 // cmov[cond] t2 = t1
5888 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5890 // fallthrough -->nextMBB
5892 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5893 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5894 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5897 /// First build the CFG
5898 MachineFunction *F = MBB->getParent();
5899 MachineBasicBlock *thisMBB = MBB;
5900 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5901 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5902 F->getBasicBlockList().insert(MBBIter, newMBB);
5903 F->getBasicBlockList().insert(MBBIter, nextMBB);
5905 // Move all successors to thisMBB to nextMBB
5906 nextMBB->transferSuccessors(thisMBB);
5908 // Update thisMBB to fall through to newMBB
5909 thisMBB->addSuccessor(newMBB);
5911 // newMBB jumps to newMBB and fall through to nextMBB
5912 newMBB->addSuccessor(nextMBB);
5913 newMBB->addSuccessor(newMBB);
5915 // Insert instructions into newMBB based on incoming instruction
5916 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
5917 MachineOperand& destOper = mInstr->getOperand(0);
5918 MachineOperand* argOpers[6];
5919 int numArgs = mInstr->getNumOperands() - 1;
5920 for (int i=0; i < numArgs; ++i)
5921 argOpers[i] = &mInstr->getOperand(i+1);
5923 // x86 address has 4 operands: base, index, scale, and displacement
5924 int lastAddrIndx = 3; // [0,3]
5927 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5928 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5929 for (int i=0; i <= lastAddrIndx; ++i)
5930 (*MIB).addOperand(*argOpers[i]);
5932 // We only support register and immediate values
5933 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5934 && "invalid operand");
5936 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5937 if (argOpers[valArgIndx]->isReg())
5938 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5940 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5941 (*MIB).addOperand(*argOpers[valArgIndx]);
5943 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5946 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
5951 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5952 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
5956 // Cmp and exchange if none has modified the memory location
5957 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5958 for (int i=0; i <= lastAddrIndx; ++i)
5959 (*MIB).addOperand(*argOpers[i]);
5962 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5963 MIB.addReg(X86::EAX);
5966 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5968 delete mInstr; // The pseudo instruction is gone now.
5974 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5975 MachineBasicBlock *BB) {
5976 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5977 switch (MI->getOpcode()) {
5978 default: assert(false && "Unexpected instr type to insert");
5979 case X86::CMOV_FR32:
5980 case X86::CMOV_FR64:
5981 case X86::CMOV_V4F32:
5982 case X86::CMOV_V2F64:
5983 case X86::CMOV_V2I64: {
5984 // To "insert" a SELECT_CC instruction, we actually have to insert the
5985 // diamond control-flow pattern. The incoming instruction knows the
5986 // destination vreg to set, the condition code register to branch on, the
5987 // true/false values to select between, and a branch opcode to use.
5988 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5989 ilist<MachineBasicBlock>::iterator It = BB;
5995 // cmpTY ccX, r1, r2
5997 // fallthrough --> copy0MBB
5998 MachineBasicBlock *thisMBB = BB;
5999 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
6000 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
6002 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6003 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6004 MachineFunction *F = BB->getParent();
6005 F->getBasicBlockList().insert(It, copy0MBB);
6006 F->getBasicBlockList().insert(It, sinkMBB);
6007 // Update machine-CFG edges by transferring all successors of the current
6008 // block to the new block which will contain the Phi node for the select.
6009 sinkMBB->transferSuccessors(BB);
6011 // Add the true and fallthrough blocks as its successors.
6012 BB->addSuccessor(copy0MBB);
6013 BB->addSuccessor(sinkMBB);
6016 // %FalseValue = ...
6017 // # fallthrough to sinkMBB
6020 // Update machine-CFG edges
6021 BB->addSuccessor(sinkMBB);
6024 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6027 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6028 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6029 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6031 delete MI; // The pseudo instruction is gone now.
6035 case X86::FP32_TO_INT16_IN_MEM:
6036 case X86::FP32_TO_INT32_IN_MEM:
6037 case X86::FP32_TO_INT64_IN_MEM:
6038 case X86::FP64_TO_INT16_IN_MEM:
6039 case X86::FP64_TO_INT32_IN_MEM:
6040 case X86::FP64_TO_INT64_IN_MEM:
6041 case X86::FP80_TO_INT16_IN_MEM:
6042 case X86::FP80_TO_INT32_IN_MEM:
6043 case X86::FP80_TO_INT64_IN_MEM: {
6044 // Change the floating point control register to use "round towards zero"
6045 // mode when truncating to an integer value.
6046 MachineFunction *F = BB->getParent();
6047 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6048 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6050 // Load the old value of the high byte of the control word...
6052 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6053 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6055 // Set the high part to be round to zero...
6056 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6059 // Reload the modified control word now...
6060 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6062 // Restore the memory image of control word to original value
6063 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6066 // Get the X86 opcode to use.
6068 switch (MI->getOpcode()) {
6069 default: assert(0 && "illegal opcode!");
6070 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6071 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6072 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6073 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6074 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6075 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6076 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6077 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6078 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6082 MachineOperand &Op = MI->getOperand(0);
6083 if (Op.isRegister()) {
6084 AM.BaseType = X86AddressMode::RegBase;
6085 AM.Base.Reg = Op.getReg();
6087 AM.BaseType = X86AddressMode::FrameIndexBase;
6088 AM.Base.FrameIndex = Op.getIndex();
6090 Op = MI->getOperand(1);
6091 if (Op.isImmediate())
6092 AM.Scale = Op.getImm();
6093 Op = MI->getOperand(2);
6094 if (Op.isImmediate())
6095 AM.IndexReg = Op.getImm();
6096 Op = MI->getOperand(3);
6097 if (Op.isGlobalAddress()) {
6098 AM.GV = Op.getGlobal();
6100 AM.Disp = Op.getImm();
6102 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6103 .addReg(MI->getOperand(4).getReg());
6105 // Reload the original control word now.
6106 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6108 delete MI; // The pseudo instruction is gone now.
6111 case X86::ATOMAND32:
6112 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6115 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6117 case X86::ATOMXOR32:
6118 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6120 case X86::ATOMMIN32:
6121 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6122 case X86::ATOMMAX32:
6123 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6124 case X86::ATOMUMIN32:
6125 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6126 case X86::ATOMUMAX32:
6127 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6131 //===----------------------------------------------------------------------===//
6132 // X86 Optimization Hooks
6133 //===----------------------------------------------------------------------===//
6135 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
6139 const SelectionDAG &DAG,
6140 unsigned Depth) const {
6141 unsigned Opc = Op.getOpcode();
6142 assert((Opc >= ISD::BUILTIN_OP_END ||
6143 Opc == ISD::INTRINSIC_WO_CHAIN ||
6144 Opc == ISD::INTRINSIC_W_CHAIN ||
6145 Opc == ISD::INTRINSIC_VOID) &&
6146 "Should use MaskedValueIsZero if you don't know whether Op"
6147 " is a target node!");
6149 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6153 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6154 Mask.getBitWidth() - 1);
6159 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
6160 /// element of the result of the vector shuffle.
6161 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
6162 MVT::ValueType VT = N->getValueType(0);
6163 SDOperand PermMask = N->getOperand(2);
6164 unsigned NumElems = PermMask.getNumOperands();
6165 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
6167 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6169 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
6170 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
6171 SDOperand Idx = PermMask.getOperand(i);
6172 if (Idx.getOpcode() == ISD::UNDEF)
6173 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
6174 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
6179 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6180 /// node is a GlobalAddress + an offset.
6181 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
6182 unsigned Opc = N->getOpcode();
6183 if (Opc == X86ISD::Wrapper) {
6184 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
6185 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6188 } else if (Opc == ISD::ADD) {
6189 SDOperand N1 = N->getOperand(0);
6190 SDOperand N2 = N->getOperand(1);
6191 if (isGAPlusOffset(N1.Val, GA, Offset)) {
6192 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
6194 Offset += V->getSignExtended();
6197 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
6198 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
6200 Offset += V->getSignExtended();
6208 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
6210 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
6211 MachineFrameInfo *MFI) {
6212 if (N->getOperand(0).Val != Base->getOperand(0).Val)
6215 SDOperand Loc = N->getOperand(1);
6216 SDOperand BaseLoc = Base->getOperand(1);
6217 if (Loc.getOpcode() == ISD::FrameIndex) {
6218 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6220 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6221 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6222 int FS = MFI->getObjectSize(FI);
6223 int BFS = MFI->getObjectSize(BFI);
6224 if (FS != BFS || FS != Size) return false;
6225 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
6227 GlobalValue *GV1 = NULL;
6228 GlobalValue *GV2 = NULL;
6229 int64_t Offset1 = 0;
6230 int64_t Offset2 = 0;
6231 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
6232 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
6233 if (isGA1 && isGA2 && GV1 == GV2)
6234 return Offset1 == (Offset2 + Dist*Size);
6240 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base, MachineFrameInfo *MFI,
6241 const X86Subtarget *Subtarget) {
6244 if (isGAPlusOffset(Base, GV, Offset))
6245 return (GV->getAlignment() >= N && (Offset % N) == 0);
6246 // DAG combine handles the stack object case.
6250 static bool EltsFromConsecutiveLoads(SDNode *N, SDOperand PermMask,
6251 unsigned NumElems, MVT::ValueType EVT,
6252 MachineFrameInfo *MFI,
6253 SelectionDAG &DAG, SDNode *&Base) {
6255 for (unsigned i = 0; i < NumElems; ++i) {
6256 SDOperand Idx = PermMask.getOperand(i);
6257 if (Idx.getOpcode() == ISD::UNDEF) {
6263 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
6264 SDOperand Elt = getShuffleScalarElt(N, Index, DAG);
6266 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6272 if (Elt.getOpcode() == ISD::UNDEF)
6275 if (!isConsecutiveLoad(Elt.Val, Base, i, MVT::getSizeInBits(EVT)/8,MFI))
6281 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6282 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6283 /// if the load addresses are consecutive, non-overlapping, and in the right
6285 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6286 const X86Subtarget *Subtarget) {
6287 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6288 MVT::ValueType VT = N->getValueType(0);
6289 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6290 SDOperand PermMask = N->getOperand(2);
6291 unsigned NumElems = PermMask.getNumOperands();
6292 SDNode *Base = NULL;
6293 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, MFI, DAG, Base))
6296 LoadSDNode *LD = cast<LoadSDNode>(Base);
6297 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, MFI, Subtarget))
6298 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6299 LD->getSrcValueOffset(), LD->isVolatile());
6300 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6301 LD->getSrcValueOffset(), LD->isVolatile(),
6302 LD->getAlignment());
6305 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6306 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6307 const X86Subtarget *Subtarget) {
6308 SDOperand Cond = N->getOperand(0);
6310 // If we have SSE[12] support, try to form min/max nodes.
6311 if (Subtarget->hasSSE2() &&
6312 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6313 if (Cond.getOpcode() == ISD::SETCC) {
6314 // Get the LHS/RHS of the select.
6315 SDOperand LHS = N->getOperand(1);
6316 SDOperand RHS = N->getOperand(2);
6317 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6319 unsigned Opcode = 0;
6320 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6323 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6326 if (!UnsafeFPMath) break;
6328 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6330 Opcode = X86ISD::FMIN;
6333 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6336 if (!UnsafeFPMath) break;
6338 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6340 Opcode = X86ISD::FMAX;
6343 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6346 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6349 if (!UnsafeFPMath) break;
6351 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6353 Opcode = X86ISD::FMIN;
6356 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6359 if (!UnsafeFPMath) break;
6361 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6363 Opcode = X86ISD::FMAX;
6369 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6377 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6378 static SDOperand PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6379 const X86Subtarget *Subtarget) {
6380 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6381 // the FP state in cases where an emms may be missing.
6382 // A preferable solution to the general problem is to figure out the right
6383 // places to insert EMMS. This qualifies as a quick hack.
6384 StoreSDNode *St = cast<StoreSDNode>(N);
6385 if (MVT::isVector(St->getValue().getValueType()) &&
6386 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6387 isa<LoadSDNode>(St->getValue()) &&
6388 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6389 St->getChain().hasOneUse() && !St->isVolatile()) {
6390 SDNode* LdVal = St->getValue().Val;
6392 int TokenFactorIndex = -1;
6393 SmallVector<SDOperand, 8> Ops;
6394 SDNode* ChainVal = St->getChain().Val;
6395 // Must be a store of a load. We currently handle two cases: the load
6396 // is a direct child, and it's under an intervening TokenFactor. It is
6397 // possible to dig deeper under nested TokenFactors.
6398 if (ChainVal == LdVal)
6399 Ld = cast<LoadSDNode>(St->getChain());
6400 else if (St->getValue().hasOneUse() &&
6401 ChainVal->getOpcode() == ISD::TokenFactor) {
6402 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6403 if (ChainVal->getOperand(i).Val == LdVal) {
6404 TokenFactorIndex = i;
6405 Ld = cast<LoadSDNode>(St->getValue());
6407 Ops.push_back(ChainVal->getOperand(i));
6411 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6412 if (Subtarget->is64Bit()) {
6413 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6414 Ld->getBasePtr(), Ld->getSrcValue(),
6415 Ld->getSrcValueOffset(), Ld->isVolatile(),
6416 Ld->getAlignment());
6417 SDOperand NewChain = NewLd.getValue(1);
6418 if (TokenFactorIndex != -1) {
6419 Ops.push_back(NewChain);
6420 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6423 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6424 St->getSrcValue(), St->getSrcValueOffset(),
6425 St->isVolatile(), St->getAlignment());
6428 // Otherwise, lower to two 32-bit copies.
6429 SDOperand LoAddr = Ld->getBasePtr();
6430 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6431 DAG.getConstant(MVT::i32, 4));
6433 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6434 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6435 Ld->isVolatile(), Ld->getAlignment());
6436 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6437 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6439 MinAlign(Ld->getAlignment(), 4));
6441 SDOperand NewChain = LoLd.getValue(1);
6442 if (TokenFactorIndex != -1) {
6443 Ops.push_back(LoLd);
6444 Ops.push_back(HiLd);
6445 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6449 LoAddr = St->getBasePtr();
6450 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6451 DAG.getConstant(MVT::i32, 4));
6453 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6454 St->getSrcValue(), St->getSrcValueOffset(),
6455 St->isVolatile(), St->getAlignment());
6456 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6457 St->getSrcValue(), St->getSrcValueOffset()+4,
6459 MinAlign(St->getAlignment(), 4));
6460 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6466 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6467 /// X86ISD::FXOR nodes.
6468 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6469 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6470 // F[X]OR(0.0, x) -> x
6471 // F[X]OR(x, 0.0) -> x
6472 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6473 if (C->getValueAPF().isPosZero())
6474 return N->getOperand(1);
6475 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6476 if (C->getValueAPF().isPosZero())
6477 return N->getOperand(0);
6481 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6482 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6483 // FAND(0.0, x) -> 0.0
6484 // FAND(x, 0.0) -> 0.0
6485 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6486 if (C->getValueAPF().isPosZero())
6487 return N->getOperand(0);
6488 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6489 if (C->getValueAPF().isPosZero())
6490 return N->getOperand(1);
6495 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6496 DAGCombinerInfo &DCI) const {
6497 SelectionDAG &DAG = DCI.DAG;
6498 switch (N->getOpcode()) {
6500 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6501 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6502 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6504 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6505 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6511 //===----------------------------------------------------------------------===//
6512 // X86 Inline Assembly Support
6513 //===----------------------------------------------------------------------===//
6515 /// getConstraintType - Given a constraint letter, return the type of
6516 /// constraint it is for this target.
6517 X86TargetLowering::ConstraintType
6518 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6519 if (Constraint.size() == 1) {
6520 switch (Constraint[0]) {
6531 return C_RegisterClass;
6536 return TargetLowering::getConstraintType(Constraint);
6539 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6540 /// with another that has more specific requirements based on the type of the
6541 /// corresponding operand.
6542 const char *X86TargetLowering::
6543 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6544 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6545 // 'f' like normal targets.
6546 if (MVT::isFloatingPoint(ConstraintVT)) {
6547 if (Subtarget->hasSSE2())
6549 if (Subtarget->hasSSE1())
6553 return TargetLowering::LowerXConstraint(ConstraintVT);
6556 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6557 /// vector. If it is invalid, don't add anything to Ops.
6558 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6560 std::vector<SDOperand>&Ops,
6561 SelectionDAG &DAG) const {
6562 SDOperand Result(0, 0);
6564 switch (Constraint) {
6567 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6568 if (C->getValue() <= 31) {
6569 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6576 if (C->getValue() <= 255) {
6577 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6583 // Literal immediates are always ok.
6584 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6585 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6589 // If we are in non-pic codegen mode, we allow the address of a global (with
6590 // an optional displacement) to be used with 'i'.
6591 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6594 // Match either (GA) or (GA+C)
6596 Offset = GA->getOffset();
6597 } else if (Op.getOpcode() == ISD::ADD) {
6598 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6599 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6601 Offset = GA->getOffset()+C->getValue();
6603 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6604 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6606 Offset = GA->getOffset()+C->getValue();
6613 // If addressing this global requires a load (e.g. in PIC mode), we can't
6615 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6619 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6625 // Otherwise, not valid for this mode.
6631 Ops.push_back(Result);
6634 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6637 std::vector<unsigned> X86TargetLowering::
6638 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6639 MVT::ValueType VT) const {
6640 if (Constraint.size() == 1) {
6641 // FIXME: not handling fp-stack yet!
6642 switch (Constraint[0]) { // GCC X86 Constraint Letters
6643 default: break; // Unknown constraint letter
6644 case 'A': // EAX/EDX
6645 if (VT == MVT::i32 || VT == MVT::i64)
6646 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6648 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6651 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6652 else if (VT == MVT::i16)
6653 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6654 else if (VT == MVT::i8)
6655 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6656 else if (VT == MVT::i64)
6657 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6662 return std::vector<unsigned>();
6665 std::pair<unsigned, const TargetRegisterClass*>
6666 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6667 MVT::ValueType VT) const {
6668 // First, see if this is a constraint that directly corresponds to an LLVM
6670 if (Constraint.size() == 1) {
6671 // GCC Constraint Letters
6672 switch (Constraint[0]) {
6674 case 'r': // GENERAL_REGS
6675 case 'R': // LEGACY_REGS
6676 case 'l': // INDEX_REGS
6677 if (VT == MVT::i64 && Subtarget->is64Bit())
6678 return std::make_pair(0U, X86::GR64RegisterClass);
6680 return std::make_pair(0U, X86::GR32RegisterClass);
6681 else if (VT == MVT::i16)
6682 return std::make_pair(0U, X86::GR16RegisterClass);
6683 else if (VT == MVT::i8)
6684 return std::make_pair(0U, X86::GR8RegisterClass);
6686 case 'f': // FP Stack registers.
6687 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6688 // value to the correct fpstack register class.
6689 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6690 return std::make_pair(0U, X86::RFP32RegisterClass);
6691 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6692 return std::make_pair(0U, X86::RFP64RegisterClass);
6693 return std::make_pair(0U, X86::RFP80RegisterClass);
6694 case 'y': // MMX_REGS if MMX allowed.
6695 if (!Subtarget->hasMMX()) break;
6696 return std::make_pair(0U, X86::VR64RegisterClass);
6698 case 'Y': // SSE_REGS if SSE2 allowed
6699 if (!Subtarget->hasSSE2()) break;
6701 case 'x': // SSE_REGS if SSE1 allowed
6702 if (!Subtarget->hasSSE1()) break;
6706 // Scalar SSE types.
6709 return std::make_pair(0U, X86::FR32RegisterClass);
6712 return std::make_pair(0U, X86::FR64RegisterClass);
6720 return std::make_pair(0U, X86::VR128RegisterClass);
6726 // Use the default implementation in TargetLowering to convert the register
6727 // constraint into a member of a register class.
6728 std::pair<unsigned, const TargetRegisterClass*> Res;
6729 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6731 // Not found as a standard register?
6732 if (Res.second == 0) {
6733 // GCC calls "st(0)" just plain "st".
6734 if (StringsEqualNoCase("{st}", Constraint)) {
6735 Res.first = X86::ST0;
6736 Res.second = X86::RFP80RegisterClass;
6742 // Otherwise, check to see if this is a register class of the wrong value
6743 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6744 // turn into {ax},{dx}.
6745 if (Res.second->hasType(VT))
6746 return Res; // Correct type already, nothing to do.
6748 // All of the single-register GCC register classes map their values onto
6749 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6750 // really want an 8-bit or 32-bit register, map to the appropriate register
6751 // class and return the appropriate register.
6752 if (Res.second != X86::GR16RegisterClass)
6755 if (VT == MVT::i8) {
6756 unsigned DestReg = 0;
6757 switch (Res.first) {
6759 case X86::AX: DestReg = X86::AL; break;
6760 case X86::DX: DestReg = X86::DL; break;
6761 case X86::CX: DestReg = X86::CL; break;
6762 case X86::BX: DestReg = X86::BL; break;
6765 Res.first = DestReg;
6766 Res.second = Res.second = X86::GR8RegisterClass;
6768 } else if (VT == MVT::i32) {
6769 unsigned DestReg = 0;
6770 switch (Res.first) {
6772 case X86::AX: DestReg = X86::EAX; break;
6773 case X86::DX: DestReg = X86::EDX; break;
6774 case X86::CX: DestReg = X86::ECX; break;
6775 case X86::BX: DestReg = X86::EBX; break;
6776 case X86::SI: DestReg = X86::ESI; break;
6777 case X86::DI: DestReg = X86::EDI; break;
6778 case X86::BP: DestReg = X86::EBP; break;
6779 case X86::SP: DestReg = X86::ESP; break;
6782 Res.first = DestReg;
6783 Res.second = Res.second = X86::GR32RegisterClass;
6785 } else if (VT == MVT::i64) {
6786 unsigned DestReg = 0;
6787 switch (Res.first) {
6789 case X86::AX: DestReg = X86::RAX; break;
6790 case X86::DX: DestReg = X86::RDX; break;
6791 case X86::CX: DestReg = X86::RCX; break;
6792 case X86::BX: DestReg = X86::RBX; break;
6793 case X86::SI: DestReg = X86::RSI; break;
6794 case X86::DI: DestReg = X86::RDI; break;
6795 case X86::BP: DestReg = X86::RBP; break;
6796 case X86::SP: DestReg = X86::RSP; break;
6799 Res.first = DestReg;
6800 Res.second = Res.second = X86::GR64RegisterClass;